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"
37 #include "llvm/Target/TargetSubtargetInfo.h"
41 struct SrcMgrDiagInfo {
42 const MDNode *LocInfo;
43 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
48 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
49 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
51 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
52 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
53 assert(DiagInfo && "Diagnostic context not passed down?");
55 // If the inline asm had metadata associated with it, pull out a location
56 // cookie corresponding to which line the error occurred on.
57 unsigned LocCookie = 0;
58 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
59 unsigned ErrorLine = Diag.getLineNo()-1;
60 if (ErrorLine >= LocInfo->getNumOperands())
63 if (LocInfo->getNumOperands() != 0)
64 if (const ConstantInt *CI =
65 dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
66 LocCookie = CI->getZExtValue();
69 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
72 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
73 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
74 InlineAsm::AsmDialect Dialect) const {
75 assert(!Str.empty() && "Can't emit empty inline asm block");
77 // Remember if the buffer is nul terminated or not so we can avoid a copy.
78 bool isNullTerminated = Str.back() == 0;
80 Str = Str.substr(0, Str.size()-1);
82 // If the output streamer is actually a .s file, just emit the blob textually.
83 // This is useful in case the asm parser doesn't handle something but the
84 // system assembler does.
85 if (OutStreamer.hasRawTextSupport()) {
86 OutStreamer.EmitRawText(Str);
87 emitInlineAsmEnd(TM.getSubtarget<MCSubtargetInfo>(), 0);
92 SrcMgrDiagInfo DiagInfo;
94 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
95 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
96 bool HasDiagHandler = false;
97 if (LLVMCtx.getInlineAsmDiagnosticHandler() != 0) {
98 // If the source manager has an issue, we arrange for srcMgrDiagHandler
99 // to be invoked, getting DiagInfo passed into it.
100 DiagInfo.LocInfo = LocMDNode;
101 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
102 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
103 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
104 HasDiagHandler = true;
107 MemoryBuffer *Buffer;
108 if (isNullTerminated)
109 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
111 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
113 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
114 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
116 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr,
117 OutContext, OutStreamer,
120 // Initialize the parser with a fresh subtarget info. It is better to use a
121 // new STI here because the parser may modify it and we do not want those
122 // modifications to persist after parsing the inlineasm. The modifications
123 // made by the parser will be seen by the code emitters because it passes
124 // the current STI down to the EncodeInstruction() method.
125 OwningPtr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
126 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
128 // Preserve a copy of the original STI because the parser may modify it. For
129 // example, when switching between arm and thumb mode. If the target needs to
130 // emit code to return to the original state it can do so in emitInlineAsmEnd().
131 MCSubtargetInfo STIOrig = *STI;
133 OwningPtr<MCTargetAsmParser>
134 TAP(TM.getTarget().createMCAsmParser(*STI, *Parser, *MII));
136 report_fatal_error("Inline asm not supported by this streamer because"
137 " we don't have an asm parser for this target\n");
138 Parser->setAssemblerDialect(Dialect);
139 Parser->setTargetParser(*TAP.get());
141 // Don't implicitly switch to the text section before the asm.
142 int Res = Parser->Run(/*NoInitialTextSection*/ true,
143 /*NoFinalize*/ true);
144 emitInlineAsmEnd(STIOrig, STI.get());
145 if (Res && !HasDiagHandler)
146 report_fatal_error("Error parsing inline asm\n");
149 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
150 MachineModuleInfo *MMI, int InlineAsmVariant,
151 AsmPrinter *AP, unsigned LocCookie,
153 // Switch to the inline assembly variant.
154 OS << "\t.intel_syntax\n\t";
156 const char *LastEmitted = AsmStr; // One past the last character emitted.
157 unsigned NumOperands = MI->getNumOperands();
159 while (*LastEmitted) {
160 switch (*LastEmitted) {
162 // Not a special case, emit the string section literally.
163 const char *LiteralEnd = LastEmitted+1;
164 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
165 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
168 OS.write(LastEmitted, LiteralEnd-LastEmitted);
169 LastEmitted = LiteralEnd;
173 ++LastEmitted; // Consume newline character.
174 OS << '\n'; // Indent code with newline.
177 ++LastEmitted; // Consume '$' character.
181 switch (*LastEmitted) {
182 default: Done = false; break;
184 ++LastEmitted; // Consume second '$' character.
189 const char *IDStart = LastEmitted;
190 const char *IDEnd = IDStart;
191 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
194 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
195 report_fatal_error("Bad $ operand number in inline asm string: '" +
196 Twine(AsmStr) + "'");
199 if (Val >= NumOperands-1)
200 report_fatal_error("Invalid $ operand number in inline asm string: '" +
201 Twine(AsmStr) + "'");
203 // Okay, we finally have a value number. Ask the target to print this
205 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
209 // Scan to find the machine operand number for the operand.
211 if (OpNo >= MI->getNumOperands()) break;
212 unsigned OpFlags = MI->getOperand(OpNo).getImm();
213 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
216 // We may have a location metadata attached to the end of the
217 // instruction, and at no point should see metadata at any
218 // other point while processing. It's an error if so.
219 if (OpNo >= MI->getNumOperands() ||
220 MI->getOperand(OpNo).isMetadata()) {
223 unsigned OpFlags = MI->getOperand(OpNo).getImm();
224 ++OpNo; // Skip over the ID number.
226 if (InlineAsm::isMemKind(OpFlags)) {
227 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
230 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
236 raw_string_ostream Msg(msg);
237 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
238 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
244 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
247 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
248 MachineModuleInfo *MMI, int InlineAsmVariant,
249 int AsmPrinterVariant, AsmPrinter *AP,
250 unsigned LocCookie, raw_ostream &OS) {
251 int CurVariant = -1; // The number of the {.|.|.} region we are in.
252 const char *LastEmitted = AsmStr; // One past the last character emitted.
253 unsigned NumOperands = MI->getNumOperands();
257 while (*LastEmitted) {
258 switch (*LastEmitted) {
260 // Not a special case, emit the string section literally.
261 const char *LiteralEnd = LastEmitted+1;
262 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
263 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
265 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
266 OS.write(LastEmitted, LiteralEnd-LastEmitted);
267 LastEmitted = LiteralEnd;
271 ++LastEmitted; // Consume newline character.
272 OS << '\n'; // Indent code with newline.
275 ++LastEmitted; // Consume '$' character.
279 switch (*LastEmitted) {
280 default: Done = false; break;
282 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
284 ++LastEmitted; // Consume second '$' character.
286 case '(': // $( -> same as GCC's { character.
287 ++LastEmitted; // Consume '(' character.
288 if (CurVariant != -1)
289 report_fatal_error("Nested variants found in inline asm string: '" +
290 Twine(AsmStr) + "'");
291 CurVariant = 0; // We're in the first variant now.
294 ++LastEmitted; // consume '|' character.
295 if (CurVariant == -1)
296 OS << '|'; // this is gcc's behavior for | outside a variant
298 ++CurVariant; // We're in the next variant.
300 case ')': // $) -> same as GCC's } char.
301 ++LastEmitted; // consume ')' character.
302 if (CurVariant == -1)
303 OS << '}'; // this is gcc's behavior for } outside a variant
310 bool HasCurlyBraces = false;
311 if (*LastEmitted == '{') { // ${variable}
312 ++LastEmitted; // Consume '{' character.
313 HasCurlyBraces = true;
316 // If we have ${:foo}, then this is not a real operand reference, it is a
317 // "magic" string reference, just like in .td files. Arrange to call
319 if (HasCurlyBraces && *LastEmitted == ':') {
321 const char *StrStart = LastEmitted;
322 const char *StrEnd = strchr(StrStart, '}');
324 report_fatal_error("Unterminated ${:foo} operand in inline asm"
325 " string: '" + Twine(AsmStr) + "'");
327 std::string Val(StrStart, StrEnd);
328 AP->PrintSpecial(MI, OS, Val.c_str());
329 LastEmitted = StrEnd+1;
333 const char *IDStart = LastEmitted;
334 const char *IDEnd = IDStart;
335 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
338 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
339 report_fatal_error("Bad $ operand number in inline asm string: '" +
340 Twine(AsmStr) + "'");
343 char Modifier[2] = { 0, 0 };
345 if (HasCurlyBraces) {
346 // If we have curly braces, check for a modifier character. This
347 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
348 if (*LastEmitted == ':') {
349 ++LastEmitted; // Consume ':' character.
350 if (*LastEmitted == 0)
351 report_fatal_error("Bad ${:} expression in inline asm string: '" +
352 Twine(AsmStr) + "'");
354 Modifier[0] = *LastEmitted;
355 ++LastEmitted; // Consume modifier character.
358 if (*LastEmitted != '}')
359 report_fatal_error("Bad ${} expression in inline asm string: '" +
360 Twine(AsmStr) + "'");
361 ++LastEmitted; // Consume '}' character.
364 if (Val >= NumOperands-1)
365 report_fatal_error("Invalid $ operand number in inline asm string: '" +
366 Twine(AsmStr) + "'");
368 // Okay, we finally have a value number. Ask the target to print this
370 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
371 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
375 // Scan to find the machine operand number for the operand.
377 if (OpNo >= MI->getNumOperands()) break;
378 unsigned OpFlags = MI->getOperand(OpNo).getImm();
379 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
382 // We may have a location metadata attached to the end of the
383 // instruction, and at no point should see metadata at any
384 // other point while processing. It's an error if so.
385 if (OpNo >= MI->getNumOperands() ||
386 MI->getOperand(OpNo).isMetadata()) {
389 unsigned OpFlags = MI->getOperand(OpNo).getImm();
390 ++OpNo; // Skip over the ID number.
392 if (Modifier[0] == 'l') // labels are target independent
393 // FIXME: What if the operand isn't an MBB, report error?
394 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
396 if (InlineAsm::isMemKind(OpFlags)) {
397 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
398 Modifier[0] ? Modifier : 0,
401 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
402 Modifier[0] ? Modifier : 0, OS);
408 raw_string_ostream Msg(msg);
409 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
410 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
417 OS << '\n' << (char)0; // null terminate string.
420 /// EmitInlineAsm - This method formats and emits the specified machine
421 /// instruction that is an inline asm.
422 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
423 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
425 // Count the number of register definitions to find the asm string.
426 unsigned NumDefs = 0;
427 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
429 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
431 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
433 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
434 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
436 // If this asmstr is empty, just print the #APP/#NOAPP markers.
437 // These are useful to see where empty asm's wound up.
438 if (AsmStr[0] == 0) {
439 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
440 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
444 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
445 // enabled, so we use emitRawComment.
446 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
448 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
450 unsigned LocCookie = 0;
451 const MDNode *LocMD = 0;
452 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
453 if (MI->getOperand(i-1).isMetadata() &&
454 (LocMD = MI->getOperand(i-1).getMetadata()) &&
455 LocMD->getNumOperands() != 0) {
456 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
457 LocCookie = CI->getZExtValue();
463 // Emit the inline asm to a temporary string so we can emit it through
465 SmallString<256> StringData;
466 raw_svector_ostream OS(StringData);
468 // The variant of the current asmprinter.
469 int AsmPrinterVariant = MAI->getAssemblerDialect();
470 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
471 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
472 if (InlineAsmVariant == InlineAsm::AD_ATT)
473 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
476 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
478 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
480 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
481 // enabled, so we use emitRawComment.
482 OutStreamer.emitRawComment(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 const DataLayout *DL = TM.getDataLayout();
495 if (!strcmp(Code, "private")) {
496 OS << DL->getPrivateGlobalPrefix();
497 } else if (!strcmp(Code, "comment")) {
498 OS << MAI->getCommentString();
499 } else if (!strcmp(Code, "uid")) {
500 // Comparing the address of MI isn't sufficient, because machineinstrs may
501 // be allocated to the same address across functions.
503 // If this is a new LastFn instruction, bump the counter.
504 if (LastMI != MI || LastFn != getFunctionNumber()) {
507 LastFn = getFunctionNumber();
512 raw_string_ostream Msg(msg);
513 Msg << "Unknown special formatter '" << Code
514 << "' for machine instr: " << *MI;
515 report_fatal_error(Msg.str());
519 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
520 /// instruction, using the specified assembler variant. Targets should
521 /// override this to format as appropriate.
522 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
523 unsigned AsmVariant, const char *ExtraCode,
525 // Does this asm operand have a single letter operand modifier?
526 if (ExtraCode && ExtraCode[0]) {
527 if (ExtraCode[1] != 0) return true; // Unknown modifier.
529 const MachineOperand &MO = MI->getOperand(OpNo);
530 switch (ExtraCode[0]) {
532 return true; // Unknown modifier.
533 case 'c': // Substitute immediate value without immediate syntax
534 if (MO.getType() != MachineOperand::MO_Immediate)
538 case 'n': // Negate the immediate constant.
539 if (MO.getType() != MachineOperand::MO_Immediate)
548 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
550 const char *ExtraCode, raw_ostream &O) {
551 // Target doesn't support this yet!
555 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
556 const MCSubtargetInfo *EndInfo) const {}