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/ADT/OwningPtr.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/CodeGen/MachineBasicBlock.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCTargetAsmParser.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.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,
72 InlineAsm::AsmDialect Dialect) const {
73 assert(!Str.empty() && "Can't emit empty inline asm block");
75 // Remember if the buffer is nul terminated or not so we can avoid a copy.
76 bool isNullTerminated = Str.back() == 0;
78 Str = Str.substr(0, Str.size()-1);
80 // If the output streamer is actually a .s file, just emit the blob textually.
81 // This is useful in case the asm parser doesn't handle something but the
82 // system assembler does.
83 if (OutStreamer.hasRawTextSupport()) {
84 OutStreamer.EmitRawText(Str);
89 SrcMgrDiagInfo DiagInfo;
91 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
92 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
93 bool HasDiagHandler = false;
94 if (LLVMCtx.getInlineAsmDiagnosticHandler() != 0) {
95 // If the source manager has an issue, we arrange for srcMgrDiagHandler
96 // to be invoked, getting DiagInfo passed into it.
97 DiagInfo.LocInfo = LocMDNode;
98 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
99 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
100 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
101 HasDiagHandler = true;
104 MemoryBuffer *Buffer;
105 if (isNullTerminated)
106 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
108 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
110 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
111 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
113 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
114 OutContext, OutStreamer,
117 // FIXME: It would be nice if we can avoid createing a new instance of
118 // MCSubtargetInfo here given TargetSubtargetInfo is available. However,
119 // we have to watch out for asm directives which can change subtarget
120 // state. e.g. .code 16, .code 32.
121 OwningPtr<MCSubtargetInfo>
122 STI(TM.getTarget().createMCSubtargetInfo(TM.getTargetTriple(),
124 TM.getTargetFeatureString()));
125 OwningPtr<MCTargetAsmParser>
126 TAP(TM.getTarget().createMCAsmParser(*STI, *Parser));
128 report_fatal_error("Inline asm not supported by this streamer because"
129 " we don't have an asm parser for this target\n");
130 Parser->setAssemblerDialect(Dialect);
131 Parser->setTargetParser(*TAP.get());
133 // Don't implicitly switch to the text section before the asm.
134 int Res = Parser->Run(/*NoInitialTextSection*/ true,
135 /*NoFinalize*/ true);
136 if (Res && !HasDiagHandler)
137 report_fatal_error("Error parsing inline asm\n");
140 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
141 MachineModuleInfo *MMI, int InlineAsmVariant,
142 AsmPrinter *AP, unsigned LocCookie,
144 // Switch to the inline assembly variant.
145 OS << "\t.intel_syntax\n\t";
147 const char *LastEmitted = AsmStr; // One past the last character emitted.
148 unsigned NumOperands = MI->getNumOperands();
150 while (*LastEmitted) {
151 switch (*LastEmitted) {
153 // Not a special case, emit the string section literally.
154 const char *LiteralEnd = LastEmitted+1;
155 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
156 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
159 OS.write(LastEmitted, LiteralEnd-LastEmitted);
160 LastEmitted = LiteralEnd;
164 ++LastEmitted; // Consume newline character.
165 OS << '\n'; // Indent code with newline.
168 ++LastEmitted; // Consume '$' character.
172 switch (*LastEmitted) {
173 default: Done = false; break;
175 ++LastEmitted; // Consume second '$' character.
180 const char *IDStart = LastEmitted;
181 const char *IDEnd = IDStart;
182 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
185 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
186 report_fatal_error("Bad $ operand number in inline asm string: '" +
187 Twine(AsmStr) + "'");
190 if (Val >= NumOperands-1)
191 report_fatal_error("Invalid $ operand number in inline asm string: '" +
192 Twine(AsmStr) + "'");
194 // Okay, we finally have a value number. Ask the target to print this
196 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
200 // Scan to find the machine operand number for the operand.
202 if (OpNo >= MI->getNumOperands()) break;
203 unsigned OpFlags = MI->getOperand(OpNo).getImm();
204 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
207 // We may have a location metadata attached to the end of the
208 // instruction, and at no point should see metadata at any
209 // other point while processing. It's an error if so.
210 if (OpNo >= MI->getNumOperands() ||
211 MI->getOperand(OpNo).isMetadata()) {
214 unsigned OpFlags = MI->getOperand(OpNo).getImm();
215 ++OpNo; // Skip over the ID number.
217 if (InlineAsm::isMemKind(OpFlags)) {
218 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
221 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
227 raw_string_ostream Msg(msg);
228 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
229 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
235 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
238 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
239 MachineModuleInfo *MMI, int InlineAsmVariant,
240 int AsmPrinterVariant, AsmPrinter *AP,
241 unsigned LocCookie, raw_ostream &OS) {
242 int CurVariant = -1; // The number of the {.|.|.} region we are in.
243 const char *LastEmitted = AsmStr; // One past the last character emitted.
244 unsigned NumOperands = MI->getNumOperands();
248 while (*LastEmitted) {
249 switch (*LastEmitted) {
251 // Not a special case, emit the string section literally.
252 const char *LiteralEnd = LastEmitted+1;
253 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
254 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
256 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
257 OS.write(LastEmitted, LiteralEnd-LastEmitted);
258 LastEmitted = LiteralEnd;
262 ++LastEmitted; // Consume newline character.
263 OS << '\n'; // Indent code with newline.
266 ++LastEmitted; // Consume '$' character.
270 switch (*LastEmitted) {
271 default: Done = false; break;
273 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
275 ++LastEmitted; // Consume second '$' character.
277 case '(': // $( -> same as GCC's { character.
278 ++LastEmitted; // Consume '(' character.
279 if (CurVariant != -1)
280 report_fatal_error("Nested variants found in inline asm string: '" +
281 Twine(AsmStr) + "'");
282 CurVariant = 0; // We're in the first variant now.
285 ++LastEmitted; // consume '|' character.
286 if (CurVariant == -1)
287 OS << '|'; // this is gcc's behavior for | outside a variant
289 ++CurVariant; // We're in the next variant.
291 case ')': // $) -> same as GCC's } char.
292 ++LastEmitted; // consume ')' character.
293 if (CurVariant == -1)
294 OS << '}'; // this is gcc's behavior for } outside a variant
301 bool HasCurlyBraces = false;
302 if (*LastEmitted == '{') { // ${variable}
303 ++LastEmitted; // Consume '{' character.
304 HasCurlyBraces = true;
307 // If we have ${:foo}, then this is not a real operand reference, it is a
308 // "magic" string reference, just like in .td files. Arrange to call
310 if (HasCurlyBraces && *LastEmitted == ':') {
312 const char *StrStart = LastEmitted;
313 const char *StrEnd = strchr(StrStart, '}');
315 report_fatal_error("Unterminated ${:foo} operand in inline asm"
316 " string: '" + Twine(AsmStr) + "'");
318 std::string Val(StrStart, StrEnd);
319 AP->PrintSpecial(MI, OS, Val.c_str());
320 LastEmitted = StrEnd+1;
324 const char *IDStart = LastEmitted;
325 const char *IDEnd = IDStart;
326 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
329 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
330 report_fatal_error("Bad $ operand number in inline asm string: '" +
331 Twine(AsmStr) + "'");
334 char Modifier[2] = { 0, 0 };
336 if (HasCurlyBraces) {
337 // If we have curly braces, check for a modifier character. This
338 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
339 if (*LastEmitted == ':') {
340 ++LastEmitted; // Consume ':' character.
341 if (*LastEmitted == 0)
342 report_fatal_error("Bad ${:} expression in inline asm string: '" +
343 Twine(AsmStr) + "'");
345 Modifier[0] = *LastEmitted;
346 ++LastEmitted; // Consume modifier character.
349 if (*LastEmitted != '}')
350 report_fatal_error("Bad ${} expression in inline asm string: '" +
351 Twine(AsmStr) + "'");
352 ++LastEmitted; // Consume '}' character.
355 if (Val >= NumOperands-1)
356 report_fatal_error("Invalid $ operand number in inline asm string: '" +
357 Twine(AsmStr) + "'");
359 // Okay, we finally have a value number. Ask the target to print this
361 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
362 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
366 // Scan to find the machine operand number for the operand.
368 if (OpNo >= MI->getNumOperands()) break;
369 unsigned OpFlags = MI->getOperand(OpNo).getImm();
370 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
373 // We may have a location metadata attached to the end of the
374 // instruction, and at no point should see metadata at any
375 // other point while processing. It's an error if so.
376 if (OpNo >= MI->getNumOperands() ||
377 MI->getOperand(OpNo).isMetadata()) {
380 unsigned OpFlags = MI->getOperand(OpNo).getImm();
381 ++OpNo; // Skip over the ID number.
383 if (Modifier[0] == 'l') // labels are target independent
384 // FIXME: What if the operand isn't an MBB, report error?
385 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
387 if (InlineAsm::isMemKind(OpFlags)) {
388 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
389 Modifier[0] ? Modifier : 0,
392 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
393 Modifier[0] ? Modifier : 0, OS);
399 raw_string_ostream Msg(msg);
400 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
401 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
408 OS << '\n' << (char)0; // null terminate string.
411 /// EmitInlineAsm - This method formats and emits the specified machine
412 /// instruction that is an inline asm.
413 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
414 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
416 // Count the number of register definitions to find the asm string.
417 unsigned NumDefs = 0;
418 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
420 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
422 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
424 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
425 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
427 // If this asmstr is empty, just print the #APP/#NOAPP markers.
428 // These are useful to see where empty asm's wound up.
429 if (AsmStr[0] == 0) {
430 // Don't emit the comments if writing to a .o file.
431 if (!OutStreamer.hasRawTextSupport()) return;
433 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
434 MAI->getInlineAsmStart());
435 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
436 MAI->getInlineAsmEnd());
440 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
441 // enabled, so we use EmitRawText.
442 if (OutStreamer.hasRawTextSupport())
443 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
444 MAI->getInlineAsmStart());
446 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
448 unsigned LocCookie = 0;
449 const MDNode *LocMD = 0;
450 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
451 if (MI->getOperand(i-1).isMetadata() &&
452 (LocMD = MI->getOperand(i-1).getMetadata()) &&
453 LocMD->getNumOperands() != 0) {
454 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
455 LocCookie = CI->getZExtValue();
461 // Emit the inline asm to a temporary string so we can emit it through
463 SmallString<256> StringData;
464 raw_svector_ostream OS(StringData);
466 // The variant of the current asmprinter.
467 int AsmPrinterVariant = MAI->getAssemblerDialect();
468 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
469 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
470 if (InlineAsmVariant == InlineAsm::AD_ATT)
471 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
474 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
476 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
478 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
479 // enabled, so we use EmitRawText.
480 if (OutStreamer.hasRawTextSupport())
481 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
482 MAI->getInlineAsmEnd());
486 /// PrintSpecial - Print information related to the specified machine instr
487 /// that is independent of the operand, and may be independent of the instr
488 /// itself. This can be useful for portably encoding the comment character
489 /// or other bits of target-specific knowledge into the asmstrings. The
490 /// syntax used is ${:comment}. Targets can override this to add support
491 /// for their own strange codes.
492 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
493 const char *Code) const {
494 if (!strcmp(Code, "private")) {
495 OS << MAI->getPrivateGlobalPrefix();
496 } else if (!strcmp(Code, "comment")) {
497 OS << MAI->getCommentString();
498 } else if (!strcmp(Code, "uid")) {
499 // Comparing the address of MI isn't sufficient, because machineinstrs may
500 // be allocated to the same address across functions.
502 // If this is a new LastFn instruction, bump the counter.
503 if (LastMI != MI || LastFn != getFunctionNumber()) {
506 LastFn = getFunctionNumber();
511 raw_string_ostream Msg(msg);
512 Msg << "Unknown special formatter '" << Code
513 << "' for machine instr: " << *MI;
514 report_fatal_error(Msg.str());
518 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
519 /// instruction, using the specified assembler variant. Targets should
520 /// override this to format as appropriate.
521 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
522 unsigned AsmVariant, const char *ExtraCode,
524 // Does this asm operand have a single letter operand modifier?
525 if (ExtraCode && ExtraCode[0]) {
526 if (ExtraCode[1] != 0) return true; // Unknown modifier.
528 const MachineOperand &MO = MI->getOperand(OpNo);
529 switch (ExtraCode[0]) {
531 return true; // Unknown modifier.
532 case 'c': // Substitute immediate value without immediate syntax
533 if (MO.getType() != MachineOperand::MO_Immediate)
537 case 'n': // Negate the immediate constant.
538 if (MO.getType() != MachineOperand::MO_Immediate)
547 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
549 const char *ExtraCode, raw_ostream &O) {
550 // Target doesn't support this yet!