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 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.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"
36 #include "llvm/Target/TargetSubtargetInfo.h"
39 #define DEBUG_TYPE "asm-printer"
42 struct SrcMgrDiagInfo {
43 const MDNode *LocInfo;
44 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
49 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
50 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
52 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
53 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
54 assert(DiagInfo && "Diagnostic context not passed down?");
56 // If the inline asm had metadata associated with it, pull out a location
57 // cookie corresponding to which line the error occurred on.
58 unsigned LocCookie = 0;
59 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
60 unsigned ErrorLine = Diag.getLineNo()-1;
61 if (ErrorLine >= LocInfo->getNumOperands())
64 if (LocInfo->getNumOperands() != 0)
65 if (const ConstantInt *CI =
66 dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
67 LocCookie = CI->getZExtValue();
70 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
73 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
74 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
75 InlineAsm::AsmDialect Dialect) const {
76 assert(!Str.empty() && "Can't emit empty inline asm block");
78 // Remember if the buffer is nul terminated or not so we can avoid a copy.
79 bool isNullTerminated = Str.back() == 0;
81 Str = Str.substr(0, Str.size()-1);
83 // If the output streamer does not have mature MC support or the integrated
84 // assembler has been disabled, just emit the blob textually.
85 // Otherwise parse the asm and emit it via MC support.
86 // This is useful in case the asm parser doesn't handle something but the
87 // system assembler does.
88 const MCAsmInfo *MCAI = TM.getMCAsmInfo();
89 assert(MCAI && "No MCAsmInfo");
90 if (!MCAI->useIntegratedAssembler() &&
91 !OutStreamer.isIntegratedAssemblerRequired()) {
92 OutStreamer.EmitRawText(Str);
93 emitInlineAsmEnd(TM.getSubtarget<MCSubtargetInfo>(), nullptr);
98 SrcMgrDiagInfo DiagInfo;
100 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
101 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
102 bool HasDiagHandler = false;
103 if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) {
104 // If the source manager has an issue, we arrange for srcMgrDiagHandler
105 // to be invoked, getting DiagInfo passed into it.
106 DiagInfo.LocInfo = LocMDNode;
107 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
108 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
109 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
110 HasDiagHandler = true;
113 std::unique_ptr<MemoryBuffer> Buffer;
114 if (isNullTerminated)
115 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
117 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
119 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
120 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
122 std::unique_ptr<MCAsmParser> Parser(
123 createMCAsmParser(SrcMgr, OutContext, OutStreamer, *MAI));
125 // Initialize the parser with a fresh subtarget info. It is better to use a
126 // new STI here because the parser may modify it and we do not want those
127 // modifications to persist after parsing the inlineasm. The modifications
128 // made by the parser will be seen by the code emitters because it passes
129 // the current STI down to the EncodeInstruction() method.
130 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
131 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
133 // Preserve a copy of the original STI because the parser may modify it. For
134 // example, when switching between arm and thumb mode. If the target needs to
135 // emit code to return to the original state it can do so in
136 // emitInlineAsmEnd().
137 MCSubtargetInfo STIOrig = *STI;
139 MCTargetOptions MCOptions;
141 MCOptions = MF->getTarget().Options.MCOptions;
142 std::unique_ptr<MCTargetAsmParser> TAP(
143 TM.getTarget().createMCAsmParser(*STI, *Parser, *MII, MCOptions));
145 report_fatal_error("Inline asm not supported by this streamer because"
146 " we don't have an asm parser for this target\n");
147 Parser->setAssemblerDialect(Dialect);
148 Parser->setTargetParser(*TAP.get());
150 // Don't implicitly switch to the text section before the asm.
151 int Res = Parser->Run(/*NoInitialTextSection*/ true,
152 /*NoFinalize*/ true);
153 emitInlineAsmEnd(STIOrig, STI.get());
154 if (Res && !HasDiagHandler)
155 report_fatal_error("Error parsing inline asm\n");
158 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
159 MachineModuleInfo *MMI, int InlineAsmVariant,
160 AsmPrinter *AP, unsigned LocCookie,
162 // Switch to the inline assembly variant.
163 OS << "\t.intel_syntax\n\t";
165 const char *LastEmitted = AsmStr; // One past the last character emitted.
166 unsigned NumOperands = MI->getNumOperands();
168 while (*LastEmitted) {
169 switch (*LastEmitted) {
171 // Not a special case, emit the string section literally.
172 const char *LiteralEnd = LastEmitted+1;
173 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
174 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
177 OS.write(LastEmitted, LiteralEnd-LastEmitted);
178 LastEmitted = LiteralEnd;
182 ++LastEmitted; // Consume newline character.
183 OS << '\n'; // Indent code with newline.
186 ++LastEmitted; // Consume '$' character.
190 switch (*LastEmitted) {
191 default: Done = false; break;
193 ++LastEmitted; // Consume second '$' character.
198 const char *IDStart = LastEmitted;
199 const char *IDEnd = IDStart;
200 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
203 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
204 report_fatal_error("Bad $ operand number in inline asm string: '" +
205 Twine(AsmStr) + "'");
208 if (Val >= NumOperands-1)
209 report_fatal_error("Invalid $ operand number in inline asm string: '" +
210 Twine(AsmStr) + "'");
212 // Okay, we finally have a value number. Ask the target to print this
214 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
218 // Scan to find the machine operand number for the operand.
220 if (OpNo >= MI->getNumOperands()) break;
221 unsigned OpFlags = MI->getOperand(OpNo).getImm();
222 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
225 // We may have a location metadata attached to the end of the
226 // instruction, and at no point should see metadata at any
227 // other point while processing. It's an error if so.
228 if (OpNo >= MI->getNumOperands() ||
229 MI->getOperand(OpNo).isMetadata()) {
232 unsigned OpFlags = MI->getOperand(OpNo).getImm();
233 ++OpNo; // Skip over the ID number.
235 if (InlineAsm::isMemKind(OpFlags)) {
236 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
237 /*Modifier*/ nullptr, OS);
239 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
240 /*Modifier*/ nullptr, OS);
245 raw_string_ostream Msg(msg);
246 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
247 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
253 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
256 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
257 MachineModuleInfo *MMI, int InlineAsmVariant,
258 int AsmPrinterVariant, AsmPrinter *AP,
259 unsigned LocCookie, raw_ostream &OS) {
260 int CurVariant = -1; // The number of the {.|.|.} region we are in.
261 const char *LastEmitted = AsmStr; // One past the last character emitted.
262 unsigned NumOperands = MI->getNumOperands();
266 while (*LastEmitted) {
267 switch (*LastEmitted) {
269 // Not a special case, emit the string section literally.
270 const char *LiteralEnd = LastEmitted+1;
271 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
272 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
274 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
275 OS.write(LastEmitted, LiteralEnd-LastEmitted);
276 LastEmitted = LiteralEnd;
280 ++LastEmitted; // Consume newline character.
281 OS << '\n'; // Indent code with newline.
284 ++LastEmitted; // Consume '$' character.
288 switch (*LastEmitted) {
289 default: Done = false; break;
291 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
293 ++LastEmitted; // Consume second '$' character.
295 case '(': // $( -> same as GCC's { character.
296 ++LastEmitted; // Consume '(' character.
297 if (CurVariant != -1)
298 report_fatal_error("Nested variants found in inline asm string: '" +
299 Twine(AsmStr) + "'");
300 CurVariant = 0; // We're in the first variant now.
303 ++LastEmitted; // consume '|' character.
304 if (CurVariant == -1)
305 OS << '|'; // this is gcc's behavior for | outside a variant
307 ++CurVariant; // We're in the next variant.
309 case ')': // $) -> same as GCC's } char.
310 ++LastEmitted; // consume ')' character.
311 if (CurVariant == -1)
312 OS << '}'; // this is gcc's behavior for } outside a variant
319 bool HasCurlyBraces = false;
320 if (*LastEmitted == '{') { // ${variable}
321 ++LastEmitted; // Consume '{' character.
322 HasCurlyBraces = true;
325 // If we have ${:foo}, then this is not a real operand reference, it is a
326 // "magic" string reference, just like in .td files. Arrange to call
328 if (HasCurlyBraces && *LastEmitted == ':') {
330 const char *StrStart = LastEmitted;
331 const char *StrEnd = strchr(StrStart, '}');
333 report_fatal_error("Unterminated ${:foo} operand in inline asm"
334 " string: '" + Twine(AsmStr) + "'");
336 std::string Val(StrStart, StrEnd);
337 AP->PrintSpecial(MI, OS, Val.c_str());
338 LastEmitted = StrEnd+1;
342 const char *IDStart = LastEmitted;
343 const char *IDEnd = IDStart;
344 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
347 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
348 report_fatal_error("Bad $ operand number in inline asm string: '" +
349 Twine(AsmStr) + "'");
352 char Modifier[2] = { 0, 0 };
354 if (HasCurlyBraces) {
355 // If we have curly braces, check for a modifier character. This
356 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
357 if (*LastEmitted == ':') {
358 ++LastEmitted; // Consume ':' character.
359 if (*LastEmitted == 0)
360 report_fatal_error("Bad ${:} expression in inline asm string: '" +
361 Twine(AsmStr) + "'");
363 Modifier[0] = *LastEmitted;
364 ++LastEmitted; // Consume modifier character.
367 if (*LastEmitted != '}')
368 report_fatal_error("Bad ${} expression in inline asm string: '" +
369 Twine(AsmStr) + "'");
370 ++LastEmitted; // Consume '}' character.
373 if (Val >= NumOperands-1)
374 report_fatal_error("Invalid $ operand number in inline asm string: '" +
375 Twine(AsmStr) + "'");
377 // Okay, we finally have a value number. Ask the target to print this
379 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
380 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
384 // Scan to find the machine operand number for the operand.
386 if (OpNo >= MI->getNumOperands()) break;
387 unsigned OpFlags = MI->getOperand(OpNo).getImm();
388 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
391 // We may have a location metadata attached to the end of the
392 // instruction, and at no point should see metadata at any
393 // other point while processing. It's an error if so.
394 if (OpNo >= MI->getNumOperands() ||
395 MI->getOperand(OpNo).isMetadata()) {
398 unsigned OpFlags = MI->getOperand(OpNo).getImm();
399 ++OpNo; // Skip over the ID number.
401 if (Modifier[0] == 'l') // labels are target independent
402 // FIXME: What if the operand isn't an MBB, report error?
403 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
405 if (InlineAsm::isMemKind(OpFlags)) {
406 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
407 Modifier[0] ? Modifier : nullptr,
410 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
411 Modifier[0] ? Modifier : nullptr, OS);
417 raw_string_ostream Msg(msg);
418 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
419 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
426 OS << '\n' << (char)0; // null terminate string.
429 /// EmitInlineAsm - This method formats and emits the specified machine
430 /// instruction that is an inline asm.
431 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
432 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
434 // Count the number of register definitions to find the asm string.
435 unsigned NumDefs = 0;
436 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
438 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
440 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
442 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
443 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
445 // If this asmstr is empty, just print the #APP/#NOAPP markers.
446 // These are useful to see where empty asm's wound up.
447 if (AsmStr[0] == 0) {
448 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
449 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
453 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
454 // enabled, so we use emitRawComment.
455 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
457 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
459 unsigned LocCookie = 0;
460 const MDNode *LocMD = nullptr;
461 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
462 if (MI->getOperand(i-1).isMetadata() &&
463 (LocMD = MI->getOperand(i-1).getMetadata()) &&
464 LocMD->getNumOperands() != 0) {
465 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
466 LocCookie = CI->getZExtValue();
472 // Emit the inline asm to a temporary string so we can emit it through
474 SmallString<256> StringData;
475 raw_svector_ostream OS(StringData);
477 // The variant of the current asmprinter.
478 int AsmPrinterVariant = MAI->getAssemblerDialect();
479 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
480 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
481 if (InlineAsmVariant == InlineAsm::AD_ATT)
482 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
485 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
487 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
489 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
490 // enabled, so we use emitRawComment.
491 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
495 /// PrintSpecial - Print information related to the specified machine instr
496 /// that is independent of the operand, and may be independent of the instr
497 /// itself. This can be useful for portably encoding the comment character
498 /// or other bits of target-specific knowledge into the asmstrings. The
499 /// syntax used is ${:comment}. Targets can override this to add support
500 /// for their own strange codes.
501 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
502 const char *Code) const {
503 const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
504 if (!strcmp(Code, "private")) {
505 OS << DL->getPrivateGlobalPrefix();
506 } else if (!strcmp(Code, "comment")) {
507 OS << MAI->getCommentString();
508 } else if (!strcmp(Code, "uid")) {
509 // Comparing the address of MI isn't sufficient, because machineinstrs may
510 // be allocated to the same address across functions.
512 // If this is a new LastFn instruction, bump the counter.
513 if (LastMI != MI || LastFn != getFunctionNumber()) {
516 LastFn = getFunctionNumber();
521 raw_string_ostream Msg(msg);
522 Msg << "Unknown special formatter '" << Code
523 << "' for machine instr: " << *MI;
524 report_fatal_error(Msg.str());
528 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
529 /// instruction, using the specified assembler variant. Targets should
530 /// override this to format as appropriate.
531 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
532 unsigned AsmVariant, const char *ExtraCode,
534 // Does this asm operand have a single letter operand modifier?
535 if (ExtraCode && ExtraCode[0]) {
536 if (ExtraCode[1] != 0) return true; // Unknown modifier.
538 const MachineOperand &MO = MI->getOperand(OpNo);
539 switch (ExtraCode[0]) {
541 return true; // Unknown modifier.
542 case 'c': // Substitute immediate value without immediate syntax
543 if (MO.getType() != MachineOperand::MO_Immediate)
547 case 'n': // Negate the immediate constant.
548 if (MO.getType() != MachineOperand::MO_Immediate)
557 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
559 const char *ExtraCode, raw_ostream &O) {
560 // Target doesn't support this yet!
564 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
565 const MCSubtargetInfo *EndInfo) const {}