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::DiagHandlerTy 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 #ifndef ANDROID_TARGET_BUILD
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 a diagnostic handler, set it in SourceMgr.
93 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
94 bool HasDiagHandler = false;
95 if (LLVMCtx.getDiagnosticHandler() != 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.getDiagnosticHandler();
100 DiagInfo.DiagContext = LLVMCtx.getDiagnosticContext();
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));
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");
139 #endif // ANDROID_TARGET_BUILD
142 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
143 MachineModuleInfo *MMI, int InlineAsmVariant,
144 AsmPrinter *AP, unsigned LocCookie,
146 #ifndef ANDROID_TARGET_BUILD
147 // Switch to the inline assembly variant.
148 OS << "\t.intel_syntax\n\t";
150 const char *LastEmitted = AsmStr; // One past the last character emitted.
151 unsigned NumOperands = MI->getNumOperands();
153 while (*LastEmitted) {
154 switch (*LastEmitted) {
156 // Not a special case, emit the string section literally.
157 const char *LiteralEnd = LastEmitted+1;
158 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
159 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
162 OS.write(LastEmitted, LiteralEnd-LastEmitted);
163 LastEmitted = LiteralEnd;
167 ++LastEmitted; // Consume newline character.
168 OS << '\n'; // Indent code with newline.
171 ++LastEmitted; // Consume '$' character.
175 switch (*LastEmitted) {
176 default: Done = false; break;
178 ++LastEmitted; // Consume second '$' character.
183 const char *IDStart = LastEmitted;
184 const char *IDEnd = IDStart;
185 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
188 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
189 report_fatal_error("Bad $ operand number in inline asm string: '" +
190 Twine(AsmStr) + "'");
193 if (Val >= NumOperands-1)
194 report_fatal_error("Invalid $ operand number in inline asm string: '" +
195 Twine(AsmStr) + "'");
197 // Okay, we finally have a value number. Ask the target to print this
199 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
203 // Scan to find the machine operand number for the operand.
205 if (OpNo >= MI->getNumOperands()) break;
206 unsigned OpFlags = MI->getOperand(OpNo).getImm();
207 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
210 // We may have a location metadata attached to the end of the
211 // instruction, and at no point should see metadata at any
212 // other point while processing. It's an error if so.
213 if (OpNo >= MI->getNumOperands() ||
214 MI->getOperand(OpNo).isMetadata()) {
217 unsigned OpFlags = MI->getOperand(OpNo).getImm();
218 ++OpNo; // Skip over the ID number.
220 if (InlineAsm::isMemKind(OpFlags)) {
221 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
224 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
230 raw_string_ostream Msg(msg);
231 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
232 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
238 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
239 #endif // ANDROID_TARGET_BUILD
242 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
243 MachineModuleInfo *MMI, int InlineAsmVariant,
244 int AsmPrinterVariant, AsmPrinter *AP,
245 unsigned LocCookie, raw_ostream &OS) {
246 #ifndef ANDROID_TARGET_BUILD
247 int CurVariant = -1; // The number of the {.|.|.} region we are in.
248 const char *LastEmitted = AsmStr; // One past the last character emitted.
249 unsigned NumOperands = MI->getNumOperands();
253 while (*LastEmitted) {
254 switch (*LastEmitted) {
256 // Not a special case, emit the string section literally.
257 const char *LiteralEnd = LastEmitted+1;
258 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
259 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
261 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
262 OS.write(LastEmitted, LiteralEnd-LastEmitted);
263 LastEmitted = LiteralEnd;
267 ++LastEmitted; // Consume newline character.
268 OS << '\n'; // Indent code with newline.
271 ++LastEmitted; // Consume '$' character.
275 switch (*LastEmitted) {
276 default: Done = false; break;
278 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
280 ++LastEmitted; // Consume second '$' character.
282 case '(': // $( -> same as GCC's { character.
283 ++LastEmitted; // Consume '(' character.
284 if (CurVariant != -1)
285 report_fatal_error("Nested variants found in inline asm string: '" +
286 Twine(AsmStr) + "'");
287 CurVariant = 0; // We're in the first variant now.
290 ++LastEmitted; // consume '|' character.
291 if (CurVariant == -1)
292 OS << '|'; // this is gcc's behavior for | outside a variant
294 ++CurVariant; // We're in the next variant.
296 case ')': // $) -> same as GCC's } char.
297 ++LastEmitted; // consume ')' character.
298 if (CurVariant == -1)
299 OS << '}'; // this is gcc's behavior for } outside a variant
306 bool HasCurlyBraces = false;
307 if (*LastEmitted == '{') { // ${variable}
308 ++LastEmitted; // Consume '{' character.
309 HasCurlyBraces = true;
312 // If we have ${:foo}, then this is not a real operand reference, it is a
313 // "magic" string reference, just like in .td files. Arrange to call
315 if (HasCurlyBraces && *LastEmitted == ':') {
317 const char *StrStart = LastEmitted;
318 const char *StrEnd = strchr(StrStart, '}');
320 report_fatal_error("Unterminated ${:foo} operand in inline asm"
321 " string: '" + Twine(AsmStr) + "'");
323 std::string Val(StrStart, StrEnd);
324 AP->PrintSpecial(MI, OS, Val.c_str());
325 LastEmitted = StrEnd+1;
329 const char *IDStart = LastEmitted;
330 const char *IDEnd = IDStart;
331 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
334 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
335 report_fatal_error("Bad $ operand number in inline asm string: '" +
336 Twine(AsmStr) + "'");
339 char Modifier[2] = { 0, 0 };
341 if (HasCurlyBraces) {
342 // If we have curly braces, check for a modifier character. This
343 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
344 if (*LastEmitted == ':') {
345 ++LastEmitted; // Consume ':' character.
346 if (*LastEmitted == 0)
347 report_fatal_error("Bad ${:} expression in inline asm string: '" +
348 Twine(AsmStr) + "'");
350 Modifier[0] = *LastEmitted;
351 ++LastEmitted; // Consume modifier character.
354 if (*LastEmitted != '}')
355 report_fatal_error("Bad ${} expression in inline asm string: '" +
356 Twine(AsmStr) + "'");
357 ++LastEmitted; // Consume '}' character.
360 if (Val >= NumOperands-1)
361 report_fatal_error("Invalid $ operand number in inline asm string: '" +
362 Twine(AsmStr) + "'");
364 // Okay, we finally have a value number. Ask the target to print this
366 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
367 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
371 // Scan to find the machine operand number for the operand.
373 if (OpNo >= MI->getNumOperands()) break;
374 unsigned OpFlags = MI->getOperand(OpNo).getImm();
375 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
378 // We may have a location metadata attached to the end of the
379 // instruction, and at no point should see metadata at any
380 // other point while processing. It's an error if so.
381 if (OpNo >= MI->getNumOperands() ||
382 MI->getOperand(OpNo).isMetadata()) {
385 unsigned OpFlags = MI->getOperand(OpNo).getImm();
386 ++OpNo; // Skip over the ID number.
388 if (Modifier[0] == 'l') // labels are target independent
389 // FIXME: What if the operand isn't an MBB, report error?
390 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
392 if (InlineAsm::isMemKind(OpFlags)) {
393 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
394 Modifier[0] ? Modifier : 0,
397 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
398 Modifier[0] ? Modifier : 0, OS);
404 raw_string_ostream Msg(msg);
405 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
406 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
413 OS << '\n' << (char)0; // null terminate string.
414 #endif // ANDROID_TARGET_BUILD
417 /// EmitInlineAsm - This method formats and emits the specified machine
418 /// instruction that is an inline asm.
419 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
420 #ifndef ANDROID_TARGET_BUILD
421 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
423 // Count the number of register definitions to find the asm string.
424 unsigned NumDefs = 0;
425 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
427 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
429 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
431 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
432 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
434 // If this asmstr is empty, just print the #APP/#NOAPP markers.
435 // These are useful to see where empty asm's wound up.
436 if (AsmStr[0] == 0) {
437 // Don't emit the comments if writing to a .o file.
438 if (!OutStreamer.hasRawTextSupport()) return;
440 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
441 MAI->getInlineAsmStart());
442 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
443 MAI->getInlineAsmEnd());
447 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
448 // enabled, so we use EmitRawText.
449 if (OutStreamer.hasRawTextSupport())
450 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
451 MAI->getInlineAsmStart());
453 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
455 unsigned LocCookie = 0;
456 const MDNode *LocMD = 0;
457 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
458 if (MI->getOperand(i-1).isMetadata() &&
459 (LocMD = MI->getOperand(i-1).getMetadata()) &&
460 LocMD->getNumOperands() != 0) {
461 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
462 LocCookie = CI->getZExtValue();
468 // Emit the inline asm to a temporary string so we can emit it through
470 SmallString<256> StringData;
471 raw_svector_ostream OS(StringData);
473 // The variant of the current asmprinter.
474 int AsmPrinterVariant = MAI->getAssemblerDialect();
475 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
476 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
477 if (InlineAsmVariant == InlineAsm::AD_ATT)
478 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
481 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
483 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
485 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
486 // enabled, so we use EmitRawText.
487 if (OutStreamer.hasRawTextSupport())
488 OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
489 MAI->getInlineAsmEnd());
490 #endif // ANDROID_TARGET_BUILD
494 /// PrintSpecial - Print information related to the specified machine instr
495 /// that is independent of the operand, and may be independent of the instr
496 /// itself. This can be useful for portably encoding the comment character
497 /// or other bits of target-specific knowledge into the asmstrings. The
498 /// syntax used is ${:comment}. Targets can override this to add support
499 /// for their own strange codes.
500 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
501 const char *Code) const {
502 if (!strcmp(Code, "private")) {
503 OS << MAI->getPrivateGlobalPrefix();
504 } else if (!strcmp(Code, "comment")) {
505 OS << MAI->getCommentString();
506 } else if (!strcmp(Code, "uid")) {
507 // Comparing the address of MI isn't sufficient, because machineinstrs may
508 // be allocated to the same address across functions.
510 // If this is a new LastFn instruction, bump the counter.
511 if (LastMI != MI || LastFn != getFunctionNumber()) {
514 LastFn = getFunctionNumber();
519 raw_string_ostream Msg(msg);
520 Msg << "Unknown special formatter '" << Code
521 << "' for machine instr: " << *MI;
522 report_fatal_error(Msg.str());
526 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
527 /// instruction, using the specified assembler variant. Targets should
528 /// override this to format as appropriate.
529 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
530 unsigned AsmVariant, const char *ExtraCode,
532 // Does this asm operand have a single letter operand modifier?
533 if (ExtraCode && ExtraCode[0]) {
534 if (ExtraCode[1] != 0) return true; // Unknown modifier.
536 const MachineOperand &MO = MI->getOperand(OpNo);
537 switch (ExtraCode[0]) {
539 return true; // Unknown modifier.
540 case 'c': // Substitute immediate value without immediate syntax
541 if (MO.getType() != MachineOperand::MO_Immediate)
545 case 'n': // Negate the immediate constant.
546 if (MO.getType() != MachineOperand::MO_Immediate)
555 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
557 const char *ExtraCode, raw_ostream &O) {
558 // Target doesn't support this yet!