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 isNullTerminated ? MemoryBuffer::getMemBuffer(Str, "<inline asm>")
115 : MemoryBuffer::getMemBufferCopy(Str, "<inline asm>"));
117 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
118 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
120 std::unique_ptr<MCAsmParser> Parser(
121 createMCAsmParser(SrcMgr, OutContext, OutStreamer, *MAI));
123 // Initialize the parser with a fresh subtarget info. It is better to use a
124 // new STI here because the parser may modify it and we do not want those
125 // modifications to persist after parsing the inlineasm. The modifications
126 // made by the parser will be seen by the code emitters because it passes
127 // the current STI down to the EncodeInstruction() method.
128 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
129 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
131 // Preserve a copy of the original STI because the parser may modify it. For
132 // example, when switching between arm and thumb mode. If the target needs to
133 // emit code to return to the original state it can do so in
134 // emitInlineAsmEnd().
135 MCSubtargetInfo STIOrig = *STI;
137 MCTargetOptions MCOptions;
139 MCOptions = MF->getTarget().Options.MCOptions;
140 std::unique_ptr<MCTargetAsmParser> TAP(
141 TM.getTarget().createMCAsmParser(*STI, *Parser, *MII, MCOptions));
143 report_fatal_error("Inline asm not supported by this streamer because"
144 " we don't have an asm parser for this target\n");
145 Parser->setAssemblerDialect(Dialect);
146 Parser->setTargetParser(*TAP.get());
148 // Don't implicitly switch to the text section before the asm.
149 int Res = Parser->Run(/*NoInitialTextSection*/ true,
150 /*NoFinalize*/ true);
151 emitInlineAsmEnd(STIOrig, STI.get());
152 if (Res && !HasDiagHandler)
153 report_fatal_error("Error parsing inline asm\n");
156 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
157 MachineModuleInfo *MMI, int InlineAsmVariant,
158 AsmPrinter *AP, unsigned LocCookie,
160 // Switch to the inline assembly variant.
161 OS << "\t.intel_syntax\n\t";
163 const char *LastEmitted = AsmStr; // One past the last character emitted.
164 unsigned NumOperands = MI->getNumOperands();
166 while (*LastEmitted) {
167 switch (*LastEmitted) {
169 // Not a special case, emit the string section literally.
170 const char *LiteralEnd = LastEmitted+1;
171 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
172 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
175 OS.write(LastEmitted, LiteralEnd-LastEmitted);
176 LastEmitted = LiteralEnd;
180 ++LastEmitted; // Consume newline character.
181 OS << '\n'; // Indent code with newline.
184 ++LastEmitted; // Consume '$' character.
188 switch (*LastEmitted) {
189 default: Done = false; break;
191 ++LastEmitted; // Consume second '$' character.
196 const char *IDStart = LastEmitted;
197 const char *IDEnd = IDStart;
198 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
201 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
202 report_fatal_error("Bad $ operand number in inline asm string: '" +
203 Twine(AsmStr) + "'");
206 if (Val >= NumOperands-1)
207 report_fatal_error("Invalid $ operand number in inline asm string: '" +
208 Twine(AsmStr) + "'");
210 // Okay, we finally have a value number. Ask the target to print this
212 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
216 // Scan to find the machine operand number for the operand.
218 if (OpNo >= MI->getNumOperands()) break;
219 unsigned OpFlags = MI->getOperand(OpNo).getImm();
220 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
223 // We may have a location metadata attached to the end of the
224 // instruction, and at no point should see metadata at any
225 // other point while processing. It's an error if so.
226 if (OpNo >= MI->getNumOperands() ||
227 MI->getOperand(OpNo).isMetadata()) {
230 unsigned OpFlags = MI->getOperand(OpNo).getImm();
231 ++OpNo; // Skip over the ID number.
233 if (InlineAsm::isMemKind(OpFlags)) {
234 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
235 /*Modifier*/ nullptr, OS);
237 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
238 /*Modifier*/ nullptr, OS);
243 raw_string_ostream Msg(msg);
244 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
245 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
251 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
254 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
255 MachineModuleInfo *MMI, int InlineAsmVariant,
256 int AsmPrinterVariant, AsmPrinter *AP,
257 unsigned LocCookie, raw_ostream &OS) {
258 int CurVariant = -1; // The number of the {.|.|.} region we are in.
259 const char *LastEmitted = AsmStr; // One past the last character emitted.
260 unsigned NumOperands = MI->getNumOperands();
264 while (*LastEmitted) {
265 switch (*LastEmitted) {
267 // Not a special case, emit the string section literally.
268 const char *LiteralEnd = LastEmitted+1;
269 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
270 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
272 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
273 OS.write(LastEmitted, LiteralEnd-LastEmitted);
274 LastEmitted = LiteralEnd;
278 ++LastEmitted; // Consume newline character.
279 OS << '\n'; // Indent code with newline.
282 ++LastEmitted; // Consume '$' character.
286 switch (*LastEmitted) {
287 default: Done = false; break;
289 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
291 ++LastEmitted; // Consume second '$' character.
293 case '(': // $( -> same as GCC's { character.
294 ++LastEmitted; // Consume '(' character.
295 if (CurVariant != -1)
296 report_fatal_error("Nested variants found in inline asm string: '" +
297 Twine(AsmStr) + "'");
298 CurVariant = 0; // We're in the first variant now.
301 ++LastEmitted; // consume '|' character.
302 if (CurVariant == -1)
303 OS << '|'; // this is gcc's behavior for | outside a variant
305 ++CurVariant; // We're in the next variant.
307 case ')': // $) -> same as GCC's } char.
308 ++LastEmitted; // consume ')' character.
309 if (CurVariant == -1)
310 OS << '}'; // this is gcc's behavior for } outside a variant
317 bool HasCurlyBraces = false;
318 if (*LastEmitted == '{') { // ${variable}
319 ++LastEmitted; // Consume '{' character.
320 HasCurlyBraces = true;
323 // If we have ${:foo}, then this is not a real operand reference, it is a
324 // "magic" string reference, just like in .td files. Arrange to call
326 if (HasCurlyBraces && *LastEmitted == ':') {
328 const char *StrStart = LastEmitted;
329 const char *StrEnd = strchr(StrStart, '}');
331 report_fatal_error("Unterminated ${:foo} operand in inline asm"
332 " string: '" + Twine(AsmStr) + "'");
334 std::string Val(StrStart, StrEnd);
335 AP->PrintSpecial(MI, OS, Val.c_str());
336 LastEmitted = StrEnd+1;
340 const char *IDStart = LastEmitted;
341 const char *IDEnd = IDStart;
342 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
345 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
346 report_fatal_error("Bad $ operand number in inline asm string: '" +
347 Twine(AsmStr) + "'");
350 char Modifier[2] = { 0, 0 };
352 if (HasCurlyBraces) {
353 // If we have curly braces, check for a modifier character. This
354 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
355 if (*LastEmitted == ':') {
356 ++LastEmitted; // Consume ':' character.
357 if (*LastEmitted == 0)
358 report_fatal_error("Bad ${:} expression in inline asm string: '" +
359 Twine(AsmStr) + "'");
361 Modifier[0] = *LastEmitted;
362 ++LastEmitted; // Consume modifier character.
365 if (*LastEmitted != '}')
366 report_fatal_error("Bad ${} expression in inline asm string: '" +
367 Twine(AsmStr) + "'");
368 ++LastEmitted; // Consume '}' character.
371 if (Val >= NumOperands-1)
372 report_fatal_error("Invalid $ operand number in inline asm string: '" +
373 Twine(AsmStr) + "'");
375 // Okay, we finally have a value number. Ask the target to print this
377 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
378 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
382 // Scan to find the machine operand number for the operand.
384 if (OpNo >= MI->getNumOperands()) break;
385 unsigned OpFlags = MI->getOperand(OpNo).getImm();
386 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
389 // We may have a location metadata attached to the end of the
390 // instruction, and at no point should see metadata at any
391 // other point while processing. It's an error if so.
392 if (OpNo >= MI->getNumOperands() ||
393 MI->getOperand(OpNo).isMetadata()) {
396 unsigned OpFlags = MI->getOperand(OpNo).getImm();
397 ++OpNo; // Skip over the ID number.
399 if (Modifier[0] == 'l') // labels are target independent
400 // FIXME: What if the operand isn't an MBB, report error?
401 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
403 if (InlineAsm::isMemKind(OpFlags)) {
404 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
405 Modifier[0] ? Modifier : nullptr,
408 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
409 Modifier[0] ? Modifier : nullptr, OS);
415 raw_string_ostream Msg(msg);
416 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
417 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
424 OS << '\n' << (char)0; // null terminate string.
427 /// EmitInlineAsm - This method formats and emits the specified machine
428 /// instruction that is an inline asm.
429 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
430 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
432 // Count the number of register definitions to find the asm string.
433 unsigned NumDefs = 0;
434 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
436 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
438 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
440 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
441 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
443 // If this asmstr is empty, just print the #APP/#NOAPP markers.
444 // These are useful to see where empty asm's wound up.
445 if (AsmStr[0] == 0) {
446 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
447 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
451 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
452 // enabled, so we use emitRawComment.
453 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
455 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
457 unsigned LocCookie = 0;
458 const MDNode *LocMD = nullptr;
459 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
460 if (MI->getOperand(i-1).isMetadata() &&
461 (LocMD = MI->getOperand(i-1).getMetadata()) &&
462 LocMD->getNumOperands() != 0) {
463 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
464 LocCookie = CI->getZExtValue();
470 // Emit the inline asm to a temporary string so we can emit it through
472 SmallString<256> StringData;
473 raw_svector_ostream OS(StringData);
475 // The variant of the current asmprinter.
476 int AsmPrinterVariant = MAI->getAssemblerDialect();
477 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
478 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
479 if (InlineAsmVariant == InlineAsm::AD_ATT)
480 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
483 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
485 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
487 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
488 // enabled, so we use emitRawComment.
489 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
493 /// PrintSpecial - Print information related to the specified machine instr
494 /// that is independent of the operand, and may be independent of the instr
495 /// itself. This can be useful for portably encoding the comment character
496 /// or other bits of target-specific knowledge into the asmstrings. The
497 /// syntax used is ${:comment}. Targets can override this to add support
498 /// for their own strange codes.
499 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
500 const char *Code) const {
501 const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
502 if (!strcmp(Code, "private")) {
503 OS << DL->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!
562 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
563 const MCSubtargetInfo *EndInfo) const {}