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/TargetRegisterInfo.h"
37 #include "llvm/Target/TargetSubtargetInfo.h"
40 #define DEBUG_TYPE "asm-printer"
43 struct SrcMgrDiagInfo {
44 const MDNode *LocInfo;
45 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
50 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
51 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
53 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
54 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
55 assert(DiagInfo && "Diagnostic context not passed down?");
57 // If the inline asm had metadata associated with it, pull out a location
58 // cookie corresponding to which line the error occurred on.
59 unsigned LocCookie = 0;
60 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
61 unsigned ErrorLine = Diag.getLineNo()-1;
62 if (ErrorLine >= LocInfo->getNumOperands())
65 if (LocInfo->getNumOperands() != 0)
66 if (const ConstantInt *CI =
67 mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine)))
68 LocCookie = CI->getZExtValue();
71 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
74 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
75 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
76 InlineAsm::AsmDialect Dialect) const {
77 assert(!Str.empty() && "Can't emit empty inline asm block");
79 // Remember if the buffer is nul terminated or not so we can avoid a copy.
80 bool isNullTerminated = Str.back() == 0;
82 Str = Str.substr(0, Str.size()-1);
84 // If the output streamer does not have mature MC support or the integrated
85 // assembler has been disabled, just emit the blob textually.
86 // Otherwise parse the asm and emit it via MC support.
87 // This is useful in case the asm parser doesn't handle something but the
88 // system assembler does.
89 const MCAsmInfo *MCAI = TM.getMCAsmInfo();
90 assert(MCAI && "No MCAsmInfo");
91 if (!MCAI->useIntegratedAssembler() &&
92 !OutStreamer.isIntegratedAssemblerRequired()) {
94 OutStreamer.EmitRawText(Str);
95 // If we have a machine function then grab the MCSubtarget off of that,
96 // otherwise we're at the module level and want to construct one from
97 // the default CPU and target triple.
99 emitInlineAsmEnd(MF->getSubtarget<MCSubtargetInfo>(), nullptr);
101 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
102 TM.getTargetTriple(), TM.getTargetCPU(),
103 TM.getTargetFeatureString()));
104 emitInlineAsmEnd(*STI, nullptr);
110 SrcMgrDiagInfo DiagInfo;
112 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
113 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
114 bool HasDiagHandler = false;
115 if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) {
116 // If the source manager has an issue, we arrange for srcMgrDiagHandler
117 // to be invoked, getting DiagInfo passed into it.
118 DiagInfo.LocInfo = LocMDNode;
119 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
120 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
121 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
122 HasDiagHandler = true;
125 std::unique_ptr<MemoryBuffer> Buffer;
126 if (isNullTerminated)
127 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
129 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
131 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
132 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
134 std::unique_ptr<MCAsmParser> Parser(
135 createMCAsmParser(SrcMgr, OutContext, OutStreamer, *MAI));
137 // Initialize the parser with a fresh subtarget info. It is better to use a
138 // new STI here because the parser may modify it and we do not want those
139 // modifications to persist after parsing the inlineasm. The modifications
140 // made by the parser will be seen by the code emitters because it passes
141 // the current STI down to the EncodeInstruction() method.
142 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
143 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
145 // Preserve a copy of the original STI because the parser may modify it. For
146 // example, when switching between arm and thumb mode. If the target needs to
147 // emit code to return to the original state it can do so in
148 // emitInlineAsmEnd().
149 MCSubtargetInfo STIOrig = *STI;
151 std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
152 *STI, *Parser, *MII, TM.Options.MCOptions));
154 report_fatal_error("Inline asm not supported by this streamer because"
155 " we don't have an asm parser for this target\n");
156 Parser->setAssemblerDialect(Dialect);
157 Parser->setTargetParser(*TAP.get());
159 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
160 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
163 emitInlineAsmStart();
164 // Don't implicitly switch to the text section before the asm.
165 int Res = Parser->Run(/*NoInitialTextSection*/ true,
166 /*NoFinalize*/ true);
167 emitInlineAsmEnd(STIOrig, STI.get());
168 if (Res && !HasDiagHandler)
169 report_fatal_error("Error parsing inline asm\n");
172 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
173 MachineModuleInfo *MMI, int InlineAsmVariant,
174 AsmPrinter *AP, unsigned LocCookie,
176 // Switch to the inline assembly variant.
177 OS << "\t.intel_syntax\n\t";
179 const char *LastEmitted = AsmStr; // One past the last character emitted.
180 unsigned NumOperands = MI->getNumOperands();
182 while (*LastEmitted) {
183 switch (*LastEmitted) {
185 // Not a special case, emit the string section literally.
186 const char *LiteralEnd = LastEmitted+1;
187 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
188 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
191 OS.write(LastEmitted, LiteralEnd-LastEmitted);
192 LastEmitted = LiteralEnd;
196 ++LastEmitted; // Consume newline character.
197 OS << '\n'; // Indent code with newline.
200 ++LastEmitted; // Consume '$' character.
204 switch (*LastEmitted) {
205 default: Done = false; break;
207 ++LastEmitted; // Consume second '$' character.
212 const char *IDStart = LastEmitted;
213 const char *IDEnd = IDStart;
214 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
217 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
218 report_fatal_error("Bad $ operand number in inline asm string: '" +
219 Twine(AsmStr) + "'");
222 if (Val >= NumOperands-1)
223 report_fatal_error("Invalid $ operand number in inline asm string: '" +
224 Twine(AsmStr) + "'");
226 // Okay, we finally have a value number. Ask the target to print this
228 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
232 // Scan to find the machine operand number for the operand.
234 if (OpNo >= MI->getNumOperands()) break;
235 unsigned OpFlags = MI->getOperand(OpNo).getImm();
236 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
239 // We may have a location metadata attached to the end of the
240 // instruction, and at no point should see metadata at any
241 // other point while processing. It's an error if so.
242 if (OpNo >= MI->getNumOperands() ||
243 MI->getOperand(OpNo).isMetadata()) {
246 unsigned OpFlags = MI->getOperand(OpNo).getImm();
247 ++OpNo; // Skip over the ID number.
249 if (InlineAsm::isMemKind(OpFlags)) {
250 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
251 /*Modifier*/ nullptr, OS);
253 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
254 /*Modifier*/ nullptr, OS);
259 raw_string_ostream Msg(msg);
260 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
261 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
267 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
270 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
271 MachineModuleInfo *MMI, int InlineAsmVariant,
272 int AsmPrinterVariant, AsmPrinter *AP,
273 unsigned LocCookie, raw_ostream &OS) {
274 int CurVariant = -1; // The number of the {.|.|.} region we are in.
275 const char *LastEmitted = AsmStr; // One past the last character emitted.
276 unsigned NumOperands = MI->getNumOperands();
280 while (*LastEmitted) {
281 switch (*LastEmitted) {
283 // Not a special case, emit the string section literally.
284 const char *LiteralEnd = LastEmitted+1;
285 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
286 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
288 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
289 OS.write(LastEmitted, LiteralEnd-LastEmitted);
290 LastEmitted = LiteralEnd;
294 ++LastEmitted; // Consume newline character.
295 OS << '\n'; // Indent code with newline.
298 ++LastEmitted; // Consume '$' character.
302 switch (*LastEmitted) {
303 default: Done = false; break;
305 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
307 ++LastEmitted; // Consume second '$' character.
309 case '(': // $( -> same as GCC's { character.
310 ++LastEmitted; // Consume '(' character.
311 if (CurVariant != -1)
312 report_fatal_error("Nested variants found in inline asm string: '" +
313 Twine(AsmStr) + "'");
314 CurVariant = 0; // We're in the first variant now.
317 ++LastEmitted; // consume '|' character.
318 if (CurVariant == -1)
319 OS << '|'; // this is gcc's behavior for | outside a variant
321 ++CurVariant; // We're in the next variant.
323 case ')': // $) -> same as GCC's } char.
324 ++LastEmitted; // consume ')' character.
325 if (CurVariant == -1)
326 OS << '}'; // this is gcc's behavior for } outside a variant
333 bool HasCurlyBraces = false;
334 if (*LastEmitted == '{') { // ${variable}
335 ++LastEmitted; // Consume '{' character.
336 HasCurlyBraces = true;
339 // If we have ${:foo}, then this is not a real operand reference, it is a
340 // "magic" string reference, just like in .td files. Arrange to call
342 if (HasCurlyBraces && *LastEmitted == ':') {
344 const char *StrStart = LastEmitted;
345 const char *StrEnd = strchr(StrStart, '}');
347 report_fatal_error("Unterminated ${:foo} operand in inline asm"
348 " string: '" + Twine(AsmStr) + "'");
350 std::string Val(StrStart, StrEnd);
351 AP->PrintSpecial(MI, OS, Val.c_str());
352 LastEmitted = StrEnd+1;
356 const char *IDStart = LastEmitted;
357 const char *IDEnd = IDStart;
358 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
361 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
362 report_fatal_error("Bad $ operand number in inline asm string: '" +
363 Twine(AsmStr) + "'");
366 char Modifier[2] = { 0, 0 };
368 if (HasCurlyBraces) {
369 // If we have curly braces, check for a modifier character. This
370 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
371 if (*LastEmitted == ':') {
372 ++LastEmitted; // Consume ':' character.
373 if (*LastEmitted == 0)
374 report_fatal_error("Bad ${:} expression in inline asm string: '" +
375 Twine(AsmStr) + "'");
377 Modifier[0] = *LastEmitted;
378 ++LastEmitted; // Consume modifier character.
381 if (*LastEmitted != '}')
382 report_fatal_error("Bad ${} expression in inline asm string: '" +
383 Twine(AsmStr) + "'");
384 ++LastEmitted; // Consume '}' character.
387 if (Val >= NumOperands-1)
388 report_fatal_error("Invalid $ operand number in inline asm string: '" +
389 Twine(AsmStr) + "'");
391 // Okay, we finally have a value number. Ask the target to print this
393 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
394 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
398 // Scan to find the machine operand number for the operand.
400 if (OpNo >= MI->getNumOperands()) break;
401 unsigned OpFlags = MI->getOperand(OpNo).getImm();
402 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
405 // We may have a location metadata attached to the end of the
406 // instruction, and at no point should see metadata at any
407 // other point while processing. It's an error if so.
408 if (OpNo >= MI->getNumOperands() ||
409 MI->getOperand(OpNo).isMetadata()) {
412 unsigned OpFlags = MI->getOperand(OpNo).getImm();
413 ++OpNo; // Skip over the ID number.
415 if (Modifier[0] == 'l') // labels are target independent
416 // FIXME: What if the operand isn't an MBB, report error?
417 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
419 if (InlineAsm::isMemKind(OpFlags)) {
420 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
421 Modifier[0] ? Modifier : nullptr,
424 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
425 Modifier[0] ? Modifier : nullptr, OS);
431 raw_string_ostream Msg(msg);
432 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
433 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
440 OS << '\n' << (char)0; // null terminate string.
443 /// EmitInlineAsm - This method formats and emits the specified machine
444 /// instruction that is an inline asm.
445 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
446 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
448 // Count the number of register definitions to find the asm string.
449 unsigned NumDefs = 0;
450 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
452 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
454 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
456 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
457 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
459 // If this asmstr is empty, just print the #APP/#NOAPP markers.
460 // These are useful to see where empty asm's wound up.
461 if (AsmStr[0] == 0) {
462 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
463 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
467 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
468 // enabled, so we use emitRawComment.
469 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
471 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
473 unsigned LocCookie = 0;
474 const MDNode *LocMD = nullptr;
475 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
476 if (MI->getOperand(i-1).isMetadata() &&
477 (LocMD = MI->getOperand(i-1).getMetadata()) &&
478 LocMD->getNumOperands() != 0) {
479 if (const ConstantInt *CI =
480 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
481 LocCookie = CI->getZExtValue();
487 // Emit the inline asm to a temporary string so we can emit it through
489 SmallString<256> StringData;
490 raw_svector_ostream OS(StringData);
492 // The variant of the current asmprinter.
493 int AsmPrinterVariant = MAI->getAssemblerDialect();
494 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
495 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
496 if (InlineAsmVariant == InlineAsm::AD_ATT)
497 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
500 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
502 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
504 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
505 // enabled, so we use emitRawComment.
506 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
510 /// PrintSpecial - Print information related to the specified machine instr
511 /// that is independent of the operand, and may be independent of the instr
512 /// itself. This can be useful for portably encoding the comment character
513 /// or other bits of target-specific knowledge into the asmstrings. The
514 /// syntax used is ${:comment}. Targets can override this to add support
515 /// for their own strange codes.
516 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
517 const char *Code) const {
518 const DataLayout *DL = TM.getDataLayout();
519 if (!strcmp(Code, "private")) {
520 OS << DL->getPrivateGlobalPrefix();
521 } else if (!strcmp(Code, "comment")) {
522 OS << MAI->getCommentString();
523 } else if (!strcmp(Code, "uid")) {
524 // Comparing the address of MI isn't sufficient, because machineinstrs may
525 // be allocated to the same address across functions.
527 // If this is a new LastFn instruction, bump the counter.
528 if (LastMI != MI || LastFn != getFunctionNumber()) {
531 LastFn = getFunctionNumber();
536 raw_string_ostream Msg(msg);
537 Msg << "Unknown special formatter '" << Code
538 << "' for machine instr: " << *MI;
539 report_fatal_error(Msg.str());
543 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
544 /// instruction, using the specified assembler variant. Targets should
545 /// override this to format as appropriate.
546 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
547 unsigned AsmVariant, const char *ExtraCode,
549 // Does this asm operand have a single letter operand modifier?
550 if (ExtraCode && ExtraCode[0]) {
551 if (ExtraCode[1] != 0) return true; // Unknown modifier.
553 const MachineOperand &MO = MI->getOperand(OpNo);
554 switch (ExtraCode[0]) {
556 return true; // Unknown modifier.
557 case 'c': // Substitute immediate value without immediate syntax
558 if (MO.getType() != MachineOperand::MO_Immediate)
562 case 'n': // Negate the immediate constant.
563 if (MO.getType() != MachineOperand::MO_Immediate)
572 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
574 const char *ExtraCode, raw_ostream &O) {
575 // Target doesn't support this yet!
579 void AsmPrinter::emitInlineAsmStart() const {}
581 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
582 const MCSubtargetInfo *EndInfo) const {}