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/DataLayout.h"
23 #include "llvm/IR/InlineAsm.h"
24 #include "llvm/IR/LLVMContext.h"
25 #include "llvm/IR/Module.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/MC/MCTargetAsmParser.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetMachine.h"
40 struct SrcMgrDiagInfo {
41 const MDNode *LocInfo;
42 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
47 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
48 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
50 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
51 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
52 assert(DiagInfo && "Diagnostic context not passed down?");
54 // If the inline asm had metadata associated with it, pull out a location
55 // cookie corresponding to which line the error occurred on.
56 unsigned LocCookie = 0;
57 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
58 unsigned ErrorLine = Diag.getLineNo()-1;
59 if (ErrorLine >= LocInfo->getNumOperands())
62 if (LocInfo->getNumOperands() != 0)
63 if (const ConstantInt *CI =
64 dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
65 LocCookie = CI->getZExtValue();
68 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
71 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
72 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
73 InlineAsm::AsmDialect Dialect) const {
74 assert(!Str.empty() && "Can't emit empty inline asm block");
76 // Remember if the buffer is nul terminated or not so we can avoid a copy.
77 bool isNullTerminated = Str.back() == 0;
79 Str = Str.substr(0, Str.size()-1);
81 // If the output streamer is actually a .s file, just emit the blob textually.
82 // This is useful in case the asm parser doesn't handle something but the
83 // system assembler does.
84 if (OutStreamer.hasRawTextSupport()) {
85 OutStreamer.EmitRawText(Str);
90 SrcMgrDiagInfo DiagInfo;
92 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
93 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
94 bool HasDiagHandler = false;
95 if (LLVMCtx.getInlineAsmDiagnosticHandler() != 0) {
96 // If the source manager has an issue, we arrange for srcMgrDiagHandler
97 // to be invoked, getting DiagInfo passed into it.
98 DiagInfo.LocInfo = LocMDNode;
99 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
100 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
101 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
102 HasDiagHandler = true;
105 MemoryBuffer *Buffer;
106 if (isNullTerminated)
107 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
109 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
111 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
112 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
114 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
115 OutContext, OutStreamer,
118 // FIXME: It would be nice if we can avoid createing a new instance of
119 // MCSubtargetInfo here given TargetSubtargetInfo is available. However,
120 // we have to watch out for asm directives which can change subtarget
121 // state. e.g. .code 16, .code 32.
122 OwningPtr<MCSubtargetInfo>
123 STI(TM.getTarget().createMCSubtargetInfo(TM.getTargetTriple(),
125 TM.getTargetFeatureString()));
126 OwningPtr<MCTargetAsmParser>
127 TAP(TM.getTarget().createMCAsmParser(*STI, *Parser, *MII));
129 report_fatal_error("Inline asm not supported by this streamer because"
130 " we don't have an asm parser for this target\n");
131 Parser->setAssemblerDialect(Dialect);
132 Parser->setTargetParser(*TAP.get());
134 // Don't implicitly switch to the text section before the asm.
135 int Res = Parser->Run(/*NoInitialTextSection*/ true,
136 /*NoFinalize*/ true);
137 if (Res && !HasDiagHandler)
138 report_fatal_error("Error parsing inline asm\n");
141 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
142 MachineModuleInfo *MMI, int InlineAsmVariant,
143 AsmPrinter *AP, unsigned LocCookie,
145 // Switch to the inline assembly variant.
146 OS << "\t.intel_syntax\n\t";
148 const char *LastEmitted = AsmStr; // One past the last character emitted.
149 unsigned NumOperands = MI->getNumOperands();
151 while (*LastEmitted) {
152 switch (*LastEmitted) {
154 // Not a special case, emit the string section literally.
155 const char *LiteralEnd = LastEmitted+1;
156 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
157 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
160 OS.write(LastEmitted, LiteralEnd-LastEmitted);
161 LastEmitted = LiteralEnd;
165 ++LastEmitted; // Consume newline character.
166 OS << '\n'; // Indent code with newline.
169 ++LastEmitted; // Consume '$' character.
173 switch (*LastEmitted) {
174 default: Done = false; break;
176 ++LastEmitted; // Consume second '$' character.
181 const char *IDStart = LastEmitted;
182 const char *IDEnd = IDStart;
183 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
186 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
187 report_fatal_error("Bad $ operand number in inline asm string: '" +
188 Twine(AsmStr) + "'");
191 if (Val >= NumOperands-1)
192 report_fatal_error("Invalid $ operand number in inline asm string: '" +
193 Twine(AsmStr) + "'");
195 // Okay, we finally have a value number. Ask the target to print this
197 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
201 // Scan to find the machine operand number for the operand.
203 if (OpNo >= MI->getNumOperands()) break;
204 unsigned OpFlags = MI->getOperand(OpNo).getImm();
205 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
208 // We may have a location metadata attached to the end of the
209 // instruction, and at no point should see metadata at any
210 // other point while processing. It's an error if so.
211 if (OpNo >= MI->getNumOperands() ||
212 MI->getOperand(OpNo).isMetadata()) {
215 unsigned OpFlags = MI->getOperand(OpNo).getImm();
216 ++OpNo; // Skip over the ID number.
218 if (InlineAsm::isMemKind(OpFlags)) {
219 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
222 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
228 raw_string_ostream Msg(msg);
229 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
230 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
236 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
239 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
240 MachineModuleInfo *MMI, int InlineAsmVariant,
241 int AsmPrinterVariant, AsmPrinter *AP,
242 unsigned LocCookie, raw_ostream &OS) {
243 int CurVariant = -1; // The number of the {.|.|.} region we are in.
244 const char *LastEmitted = AsmStr; // One past the last character emitted.
245 unsigned NumOperands = MI->getNumOperands();
249 while (*LastEmitted) {
250 switch (*LastEmitted) {
252 // Not a special case, emit the string section literally.
253 const char *LiteralEnd = LastEmitted+1;
254 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
255 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
257 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
258 OS.write(LastEmitted, LiteralEnd-LastEmitted);
259 LastEmitted = LiteralEnd;
263 ++LastEmitted; // Consume newline character.
264 OS << '\n'; // Indent code with newline.
267 ++LastEmitted; // Consume '$' character.
271 switch (*LastEmitted) {
272 default: Done = false; break;
274 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
276 ++LastEmitted; // Consume second '$' character.
278 case '(': // $( -> same as GCC's { character.
279 ++LastEmitted; // Consume '(' character.
280 if (CurVariant != -1)
281 report_fatal_error("Nested variants found in inline asm string: '" +
282 Twine(AsmStr) + "'");
283 CurVariant = 0; // We're in the first variant now.
286 ++LastEmitted; // consume '|' character.
287 if (CurVariant == -1)
288 OS << '|'; // this is gcc's behavior for | outside a variant
290 ++CurVariant; // We're in the next variant.
292 case ')': // $) -> same as GCC's } char.
293 ++LastEmitted; // consume ')' character.
294 if (CurVariant == -1)
295 OS << '}'; // this is gcc's behavior for } outside a variant
302 bool HasCurlyBraces = false;
303 if (*LastEmitted == '{') { // ${variable}
304 ++LastEmitted; // Consume '{' character.
305 HasCurlyBraces = true;
308 // If we have ${:foo}, then this is not a real operand reference, it is a
309 // "magic" string reference, just like in .td files. Arrange to call
311 if (HasCurlyBraces && *LastEmitted == ':') {
313 const char *StrStart = LastEmitted;
314 const char *StrEnd = strchr(StrStart, '}');
316 report_fatal_error("Unterminated ${:foo} operand in inline asm"
317 " string: '" + Twine(AsmStr) + "'");
319 std::string Val(StrStart, StrEnd);
320 AP->PrintSpecial(MI, OS, Val.c_str());
321 LastEmitted = StrEnd+1;
325 const char *IDStart = LastEmitted;
326 const char *IDEnd = IDStart;
327 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
330 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
331 report_fatal_error("Bad $ operand number in inline asm string: '" +
332 Twine(AsmStr) + "'");
335 char Modifier[2] = { 0, 0 };
337 if (HasCurlyBraces) {
338 // If we have curly braces, check for a modifier character. This
339 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
340 if (*LastEmitted == ':') {
341 ++LastEmitted; // Consume ':' character.
342 if (*LastEmitted == 0)
343 report_fatal_error("Bad ${:} expression in inline asm string: '" +
344 Twine(AsmStr) + "'");
346 Modifier[0] = *LastEmitted;
347 ++LastEmitted; // Consume modifier character.
350 if (*LastEmitted != '}')
351 report_fatal_error("Bad ${} expression in inline asm string: '" +
352 Twine(AsmStr) + "'");
353 ++LastEmitted; // Consume '}' character.
356 if (Val >= NumOperands-1)
357 report_fatal_error("Invalid $ operand number in inline asm string: '" +
358 Twine(AsmStr) + "'");
360 // Okay, we finally have a value number. Ask the target to print this
362 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
363 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
367 // Scan to find the machine operand number for the operand.
369 if (OpNo >= MI->getNumOperands()) break;
370 unsigned OpFlags = MI->getOperand(OpNo).getImm();
371 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
374 // We may have a location metadata attached to the end of the
375 // instruction, and at no point should see metadata at any
376 // other point while processing. It's an error if so.
377 if (OpNo >= MI->getNumOperands() ||
378 MI->getOperand(OpNo).isMetadata()) {
381 unsigned OpFlags = MI->getOperand(OpNo).getImm();
382 ++OpNo; // Skip over the ID number.
384 if (Modifier[0] == 'l') // labels are target independent
385 // FIXME: What if the operand isn't an MBB, report error?
386 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
388 if (InlineAsm::isMemKind(OpFlags)) {
389 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
390 Modifier[0] ? Modifier : 0,
393 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
394 Modifier[0] ? Modifier : 0, OS);
400 raw_string_ostream Msg(msg);
401 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
402 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
409 OS << '\n' << (char)0; // null terminate string.
412 /// EmitInlineAsm - This method formats and emits the specified machine
413 /// instruction that is an inline asm.
414 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
415 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
417 // Count the number of register definitions to find the asm string.
418 unsigned NumDefs = 0;
419 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
421 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
423 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
425 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
426 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
428 // If this asmstr is empty, just print the #APP/#NOAPP markers.
429 // These are useful to see where empty asm's wound up.
430 if (AsmStr[0] == 0) {
431 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
432 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
436 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
437 // enabled, so we use emitRawComment.
438 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
440 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
442 unsigned LocCookie = 0;
443 const MDNode *LocMD = 0;
444 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
445 if (MI->getOperand(i-1).isMetadata() &&
446 (LocMD = MI->getOperand(i-1).getMetadata()) &&
447 LocMD->getNumOperands() != 0) {
448 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
449 LocCookie = CI->getZExtValue();
455 // Emit the inline asm to a temporary string so we can emit it through
457 SmallString<256> StringData;
458 raw_svector_ostream OS(StringData);
460 // The variant of the current asmprinter.
461 int AsmPrinterVariant = MAI->getAssemblerDialect();
462 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
463 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
464 if (InlineAsmVariant == InlineAsm::AD_ATT)
465 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
468 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
470 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
472 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
473 // enabled, so we use emitRawComment.
474 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
478 /// PrintSpecial - Print information related to the specified machine instr
479 /// that is independent of the operand, and may be independent of the instr
480 /// itself. This can be useful for portably encoding the comment character
481 /// or other bits of target-specific knowledge into the asmstrings. The
482 /// syntax used is ${:comment}. Targets can override this to add support
483 /// for their own strange codes.
484 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
485 const char *Code) const {
486 const DataLayout *DL = TM.getDataLayout();
487 if (!strcmp(Code, "private")) {
488 OS << DL->getPrivateGlobalPrefix();
489 } else if (!strcmp(Code, "comment")) {
490 OS << MAI->getCommentString();
491 } else if (!strcmp(Code, "uid")) {
492 // Comparing the address of MI isn't sufficient, because machineinstrs may
493 // be allocated to the same address across functions.
495 // If this is a new LastFn instruction, bump the counter.
496 if (LastMI != MI || LastFn != getFunctionNumber()) {
499 LastFn = getFunctionNumber();
504 raw_string_ostream Msg(msg);
505 Msg << "Unknown special formatter '" << Code
506 << "' for machine instr: " << *MI;
507 report_fatal_error(Msg.str());
511 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
512 /// instruction, using the specified assembler variant. Targets should
513 /// override this to format as appropriate.
514 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
515 unsigned AsmVariant, const char *ExtraCode,
517 // Does this asm operand have a single letter operand modifier?
518 if (ExtraCode && ExtraCode[0]) {
519 if (ExtraCode[1] != 0) return true; // Unknown modifier.
521 const MachineOperand &MO = MI->getOperand(OpNo);
522 switch (ExtraCode[0]) {
524 return true; // Unknown modifier.
525 case 'c': // Substitute immediate value without immediate syntax
526 if (MO.getType() != MachineOperand::MO_Immediate)
530 case 'n': // Negate the immediate constant.
531 if (MO.getType() != MachineOperand::MO_Immediate)
540 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
542 const char *ExtraCode, raw_ostream &O) {
543 // Target doesn't support this yet!