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()) {
93 emitInlineAsmStart(TM.getSubtarget<MCSubtargetInfo>());
94 OutStreamer.EmitRawText(Str);
95 emitInlineAsmEnd(TM.getSubtarget<MCSubtargetInfo>(), nullptr);
100 SrcMgrDiagInfo DiagInfo;
102 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
103 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
104 bool HasDiagHandler = false;
105 if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) {
106 // If the source manager has an issue, we arrange for srcMgrDiagHandler
107 // to be invoked, getting DiagInfo passed into it.
108 DiagInfo.LocInfo = LocMDNode;
109 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
110 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
111 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
112 HasDiagHandler = true;
115 std::unique_ptr<MemoryBuffer> Buffer;
116 if (isNullTerminated)
117 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
119 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
121 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
122 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
124 std::unique_ptr<MCAsmParser> Parser(
125 createMCAsmParser(SrcMgr, OutContext, OutStreamer, *MAI));
127 // Initialize the parser with a fresh subtarget info. It is better to use a
128 // new STI here because the parser may modify it and we do not want those
129 // modifications to persist after parsing the inlineasm. The modifications
130 // made by the parser will be seen by the code emitters because it passes
131 // the current STI down to the EncodeInstruction() method.
132 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
133 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
135 // Preserve a copy of the original STI because the parser may modify it. For
136 // example, when switching between arm and thumb mode. If the target needs to
137 // emit code to return to the original state it can do so in
138 // emitInlineAsmEnd().
139 MCSubtargetInfo STIOrig = *STI;
141 MCTargetOptions MCOptions;
143 MCOptions = MF->getTarget().Options.MCOptions;
144 std::unique_ptr<MCTargetAsmParser> TAP(
145 TM.getTarget().createMCAsmParser(*STI, *Parser, *MII, MCOptions));
147 report_fatal_error("Inline asm not supported by this streamer because"
148 " we don't have an asm parser for this target\n");
149 Parser->setAssemblerDialect(Dialect);
150 Parser->setTargetParser(*TAP.get());
152 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
153 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
156 emitInlineAsmStart(STIOrig);
157 // Don't implicitly switch to the text section before the asm.
158 int Res = Parser->Run(/*NoInitialTextSection*/ true,
159 /*NoFinalize*/ true);
160 emitInlineAsmEnd(STIOrig, STI.get());
161 if (Res && !HasDiagHandler)
162 report_fatal_error("Error parsing inline asm\n");
165 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
166 MachineModuleInfo *MMI, int InlineAsmVariant,
167 AsmPrinter *AP, unsigned LocCookie,
169 // Switch to the inline assembly variant.
170 OS << "\t.intel_syntax\n\t";
172 const char *LastEmitted = AsmStr; // One past the last character emitted.
173 unsigned NumOperands = MI->getNumOperands();
175 while (*LastEmitted) {
176 switch (*LastEmitted) {
178 // Not a special case, emit the string section literally.
179 const char *LiteralEnd = LastEmitted+1;
180 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
181 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
184 OS.write(LastEmitted, LiteralEnd-LastEmitted);
185 LastEmitted = LiteralEnd;
189 ++LastEmitted; // Consume newline character.
190 OS << '\n'; // Indent code with newline.
193 ++LastEmitted; // Consume '$' character.
197 switch (*LastEmitted) {
198 default: Done = false; break;
200 ++LastEmitted; // Consume second '$' character.
205 const char *IDStart = LastEmitted;
206 const char *IDEnd = IDStart;
207 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
210 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
211 report_fatal_error("Bad $ operand number in inline asm string: '" +
212 Twine(AsmStr) + "'");
215 if (Val >= NumOperands-1)
216 report_fatal_error("Invalid $ operand number in inline asm string: '" +
217 Twine(AsmStr) + "'");
219 // Okay, we finally have a value number. Ask the target to print this
221 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
225 // Scan to find the machine operand number for the operand.
227 if (OpNo >= MI->getNumOperands()) break;
228 unsigned OpFlags = MI->getOperand(OpNo).getImm();
229 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
232 // We may have a location metadata attached to the end of the
233 // instruction, and at no point should see metadata at any
234 // other point while processing. It's an error if so.
235 if (OpNo >= MI->getNumOperands() ||
236 MI->getOperand(OpNo).isMetadata()) {
239 unsigned OpFlags = MI->getOperand(OpNo).getImm();
240 ++OpNo; // Skip over the ID number.
242 if (InlineAsm::isMemKind(OpFlags)) {
243 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
244 /*Modifier*/ nullptr, OS);
246 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
247 /*Modifier*/ nullptr, OS);
252 raw_string_ostream Msg(msg);
253 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
254 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
260 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
263 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
264 MachineModuleInfo *MMI, int InlineAsmVariant,
265 int AsmPrinterVariant, AsmPrinter *AP,
266 unsigned LocCookie, raw_ostream &OS) {
267 int CurVariant = -1; // The number of the {.|.|.} region we are in.
268 const char *LastEmitted = AsmStr; // One past the last character emitted.
269 unsigned NumOperands = MI->getNumOperands();
273 while (*LastEmitted) {
274 switch (*LastEmitted) {
276 // Not a special case, emit the string section literally.
277 const char *LiteralEnd = LastEmitted+1;
278 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
279 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
281 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
282 OS.write(LastEmitted, LiteralEnd-LastEmitted);
283 LastEmitted = LiteralEnd;
287 ++LastEmitted; // Consume newline character.
288 OS << '\n'; // Indent code with newline.
291 ++LastEmitted; // Consume '$' character.
295 switch (*LastEmitted) {
296 default: Done = false; break;
298 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
300 ++LastEmitted; // Consume second '$' character.
302 case '(': // $( -> same as GCC's { character.
303 ++LastEmitted; // Consume '(' character.
304 if (CurVariant != -1)
305 report_fatal_error("Nested variants found in inline asm string: '" +
306 Twine(AsmStr) + "'");
307 CurVariant = 0; // We're in the first variant now.
310 ++LastEmitted; // consume '|' character.
311 if (CurVariant == -1)
312 OS << '|'; // this is gcc's behavior for | outside a variant
314 ++CurVariant; // We're in the next variant.
316 case ')': // $) -> same as GCC's } char.
317 ++LastEmitted; // consume ')' character.
318 if (CurVariant == -1)
319 OS << '}'; // this is gcc's behavior for } outside a variant
326 bool HasCurlyBraces = false;
327 if (*LastEmitted == '{') { // ${variable}
328 ++LastEmitted; // Consume '{' character.
329 HasCurlyBraces = true;
332 // If we have ${:foo}, then this is not a real operand reference, it is a
333 // "magic" string reference, just like in .td files. Arrange to call
335 if (HasCurlyBraces && *LastEmitted == ':') {
337 const char *StrStart = LastEmitted;
338 const char *StrEnd = strchr(StrStart, '}');
340 report_fatal_error("Unterminated ${:foo} operand in inline asm"
341 " string: '" + Twine(AsmStr) + "'");
343 std::string Val(StrStart, StrEnd);
344 AP->PrintSpecial(MI, OS, Val.c_str());
345 LastEmitted = StrEnd+1;
349 const char *IDStart = LastEmitted;
350 const char *IDEnd = IDStart;
351 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
354 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
355 report_fatal_error("Bad $ operand number in inline asm string: '" +
356 Twine(AsmStr) + "'");
359 char Modifier[2] = { 0, 0 };
361 if (HasCurlyBraces) {
362 // If we have curly braces, check for a modifier character. This
363 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
364 if (*LastEmitted == ':') {
365 ++LastEmitted; // Consume ':' character.
366 if (*LastEmitted == 0)
367 report_fatal_error("Bad ${:} expression in inline asm string: '" +
368 Twine(AsmStr) + "'");
370 Modifier[0] = *LastEmitted;
371 ++LastEmitted; // Consume modifier character.
374 if (*LastEmitted != '}')
375 report_fatal_error("Bad ${} expression in inline asm string: '" +
376 Twine(AsmStr) + "'");
377 ++LastEmitted; // Consume '}' character.
380 if (Val >= NumOperands-1)
381 report_fatal_error("Invalid $ operand number in inline asm string: '" +
382 Twine(AsmStr) + "'");
384 // Okay, we finally have a value number. Ask the target to print this
386 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
387 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
391 // Scan to find the machine operand number for the operand.
393 if (OpNo >= MI->getNumOperands()) break;
394 unsigned OpFlags = MI->getOperand(OpNo).getImm();
395 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
398 // We may have a location metadata attached to the end of the
399 // instruction, and at no point should see metadata at any
400 // other point while processing. It's an error if so.
401 if (OpNo >= MI->getNumOperands() ||
402 MI->getOperand(OpNo).isMetadata()) {
405 unsigned OpFlags = MI->getOperand(OpNo).getImm();
406 ++OpNo; // Skip over the ID number.
408 if (Modifier[0] == 'l') // labels are target independent
409 // FIXME: What if the operand isn't an MBB, report error?
410 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
412 if (InlineAsm::isMemKind(OpFlags)) {
413 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
414 Modifier[0] ? Modifier : nullptr,
417 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
418 Modifier[0] ? Modifier : nullptr, OS);
424 raw_string_ostream Msg(msg);
425 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
426 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
433 OS << '\n' << (char)0; // null terminate string.
436 /// EmitInlineAsm - This method formats and emits the specified machine
437 /// instruction that is an inline asm.
438 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
439 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
441 // Count the number of register definitions to find the asm string.
442 unsigned NumDefs = 0;
443 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
445 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
447 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
449 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
450 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
452 // If this asmstr is empty, just print the #APP/#NOAPP markers.
453 // These are useful to see where empty asm's wound up.
454 if (AsmStr[0] == 0) {
455 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
456 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
460 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
461 // enabled, so we use emitRawComment.
462 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
464 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
466 unsigned LocCookie = 0;
467 const MDNode *LocMD = nullptr;
468 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
469 if (MI->getOperand(i-1).isMetadata() &&
470 (LocMD = MI->getOperand(i-1).getMetadata()) &&
471 LocMD->getNumOperands() != 0) {
472 if (const ConstantInt *CI =
473 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
474 LocCookie = CI->getZExtValue();
480 // Emit the inline asm to a temporary string so we can emit it through
482 SmallString<256> StringData;
483 raw_svector_ostream OS(StringData);
485 // The variant of the current asmprinter.
486 int AsmPrinterVariant = MAI->getAssemblerDialect();
487 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
488 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
489 if (InlineAsmVariant == InlineAsm::AD_ATT)
490 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
493 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
495 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
497 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
498 // enabled, so we use emitRawComment.
499 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
503 /// PrintSpecial - Print information related to the specified machine instr
504 /// that is independent of the operand, and may be independent of the instr
505 /// itself. This can be useful for portably encoding the comment character
506 /// or other bits of target-specific knowledge into the asmstrings. The
507 /// syntax used is ${:comment}. Targets can override this to add support
508 /// for their own strange codes.
509 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
510 const char *Code) const {
511 const DataLayout *DL = TM.getDataLayout();
512 if (!strcmp(Code, "private")) {
513 OS << DL->getPrivateGlobalPrefix();
514 } else if (!strcmp(Code, "comment")) {
515 OS << MAI->getCommentString();
516 } else if (!strcmp(Code, "uid")) {
517 // Comparing the address of MI isn't sufficient, because machineinstrs may
518 // be allocated to the same address across functions.
520 // If this is a new LastFn instruction, bump the counter.
521 if (LastMI != MI || LastFn != getFunctionNumber()) {
524 LastFn = getFunctionNumber();
529 raw_string_ostream Msg(msg);
530 Msg << "Unknown special formatter '" << Code
531 << "' for machine instr: " << *MI;
532 report_fatal_error(Msg.str());
536 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
537 /// instruction, using the specified assembler variant. Targets should
538 /// override this to format as appropriate.
539 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
540 unsigned AsmVariant, const char *ExtraCode,
542 // Does this asm operand have a single letter operand modifier?
543 if (ExtraCode && ExtraCode[0]) {
544 if (ExtraCode[1] != 0) return true; // Unknown modifier.
546 const MachineOperand &MO = MI->getOperand(OpNo);
547 switch (ExtraCode[0]) {
549 return true; // Unknown modifier.
550 case 'c': // Substitute immediate value without immediate syntax
551 if (MO.getType() != MachineOperand::MO_Immediate)
555 case 'n': // Negate the immediate constant.
556 if (MO.getType() != MachineOperand::MO_Immediate)
565 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
567 const char *ExtraCode, raw_ostream &O) {
568 // Target doesn't support this yet!
572 void AsmPrinter::emitInlineAsmStart(const MCSubtargetInfo &StartInfo) const {}
574 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
575 const MCSubtargetInfo *EndInfo) const {}