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/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
41 #define DEBUG_TYPE "asm-printer"
44 struct SrcMgrDiagInfo {
45 const MDNode *LocInfo;
46 LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
51 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
52 /// inline asm has an error in it. diagInfo is a pointer to the SrcMgrDiagInfo
54 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
55 SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
56 assert(DiagInfo && "Diagnostic context not passed down?");
58 // If the inline asm had metadata associated with it, pull out a location
59 // cookie corresponding to which line the error occurred on.
60 unsigned LocCookie = 0;
61 if (const MDNode *LocInfo = DiagInfo->LocInfo) {
62 unsigned ErrorLine = Diag.getLineNo()-1;
63 if (ErrorLine >= LocInfo->getNumOperands())
66 if (LocInfo->getNumOperands() != 0)
67 if (const ConstantInt *CI =
68 mdconst::dyn_extract<ConstantInt>(LocInfo->getOperand(ErrorLine)))
69 LocCookie = CI->getZExtValue();
72 DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
75 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
76 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
77 InlineAsm::AsmDialect Dialect) const {
78 assert(!Str.empty() && "Can't emit empty inline asm block");
80 // Remember if the buffer is nul terminated or not so we can avoid a copy.
81 bool isNullTerminated = Str.back() == 0;
83 Str = Str.substr(0, Str.size()-1);
85 // If the output streamer does not have mature MC support or the integrated
86 // assembler has been disabled, just emit the blob textually.
87 // Otherwise parse the asm and emit it via MC support.
88 // This is useful in case the asm parser doesn't handle something but the
89 // system assembler does.
90 const MCAsmInfo *MCAI = TM.getMCAsmInfo();
91 assert(MCAI && "No MCAsmInfo");
92 if (!MCAI->useIntegratedAssembler() &&
93 !OutStreamer.isIntegratedAssemblerRequired()) {
95 OutStreamer.EmitRawText(Str);
96 // If we have a machine function then grab the MCSubtarget off of that,
97 // otherwise we're at the module level and want to construct one from
98 // the default CPU and target triple.
100 emitInlineAsmEnd(MF->getSubtarget<MCSubtargetInfo>(), nullptr);
102 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
103 TM.getTargetTriple(), TM.getTargetCPU(),
104 TM.getTargetFeatureString()));
105 emitInlineAsmEnd(*STI, nullptr);
111 SrcMgrDiagInfo DiagInfo;
113 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
114 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
115 bool HasDiagHandler = false;
116 if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) {
117 // If the source manager has an issue, we arrange for srcMgrDiagHandler
118 // to be invoked, getting DiagInfo passed into it.
119 DiagInfo.LocInfo = LocMDNode;
120 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
121 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
122 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
123 HasDiagHandler = true;
126 std::unique_ptr<MemoryBuffer> Buffer;
127 if (isNullTerminated)
128 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
130 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
132 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
133 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
135 std::unique_ptr<MCAsmParser> Parser(
136 createMCAsmParser(SrcMgr, OutContext, OutStreamer, *MAI));
138 // Initialize the parser with a fresh subtarget info. It is better to use a
139 // new STI here because the parser may modify it and we do not want those
140 // modifications to persist after parsing the inlineasm. The modifications
141 // made by the parser will be seen by the code emitters because it passes
142 // the current STI down to the EncodeInstruction() method.
143 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
144 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
146 // Preserve a copy of the original STI because the parser may modify it. For
147 // example, when switching between arm and thumb mode. If the target needs to
148 // emit code to return to the original state it can do so in
149 // emitInlineAsmEnd().
150 MCSubtargetInfo STIOrig = *STI;
152 // We create a new MCInstrInfo here since we might be at the module level
153 // and not have a MachineFunction to initialize the TargetInstrInfo from and
154 // we only need MCInstrInfo for asm parsing. We create one unconditionally
155 // because it's not subtarget dependent.
156 std::unique_ptr<MCInstrInfo> MII(TM.getTarget().createMCInstrInfo());
157 std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
158 *STI, *Parser, *MII, TM.Options.MCOptions));
160 report_fatal_error("Inline asm not supported by this streamer because"
161 " we don't have an asm parser for this target\n");
162 Parser->setAssemblerDialect(Dialect);
163 Parser->setTargetParser(*TAP.get());
165 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
166 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
169 emitInlineAsmStart();
170 // Don't implicitly switch to the text section before the asm.
171 int Res = Parser->Run(/*NoInitialTextSection*/ true,
172 /*NoFinalize*/ true);
173 emitInlineAsmEnd(STIOrig, STI.get());
174 if (Res && !HasDiagHandler)
175 report_fatal_error("Error parsing inline asm\n");
178 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
179 MachineModuleInfo *MMI, int InlineAsmVariant,
180 AsmPrinter *AP, unsigned LocCookie,
182 // Switch to the inline assembly variant.
183 OS << "\t.intel_syntax\n\t";
185 const char *LastEmitted = AsmStr; // One past the last character emitted.
186 unsigned NumOperands = MI->getNumOperands();
188 while (*LastEmitted) {
189 switch (*LastEmitted) {
191 // Not a special case, emit the string section literally.
192 const char *LiteralEnd = LastEmitted+1;
193 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
194 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
197 OS.write(LastEmitted, LiteralEnd-LastEmitted);
198 LastEmitted = LiteralEnd;
202 ++LastEmitted; // Consume newline character.
203 OS << '\n'; // Indent code with newline.
206 ++LastEmitted; // Consume '$' character.
210 switch (*LastEmitted) {
211 default: Done = false; break;
213 ++LastEmitted; // Consume second '$' character.
218 const char *IDStart = LastEmitted;
219 const char *IDEnd = IDStart;
220 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
223 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
224 report_fatal_error("Bad $ operand number in inline asm string: '" +
225 Twine(AsmStr) + "'");
228 if (Val >= NumOperands-1)
229 report_fatal_error("Invalid $ operand number in inline asm string: '" +
230 Twine(AsmStr) + "'");
232 // Okay, we finally have a value number. Ask the target to print this
234 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
238 // Scan to find the machine operand number for the operand.
240 if (OpNo >= MI->getNumOperands()) break;
241 unsigned OpFlags = MI->getOperand(OpNo).getImm();
242 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
245 // We may have a location metadata attached to the end of the
246 // instruction, and at no point should see metadata at any
247 // other point while processing. It's an error if so.
248 if (OpNo >= MI->getNumOperands() ||
249 MI->getOperand(OpNo).isMetadata()) {
252 unsigned OpFlags = MI->getOperand(OpNo).getImm();
253 ++OpNo; // Skip over the ID number.
255 if (InlineAsm::isMemKind(OpFlags)) {
256 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
257 /*Modifier*/ nullptr, OS);
259 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
260 /*Modifier*/ nullptr, OS);
265 raw_string_ostream Msg(msg);
266 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
267 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
273 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
276 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
277 MachineModuleInfo *MMI, int InlineAsmVariant,
278 int AsmPrinterVariant, AsmPrinter *AP,
279 unsigned LocCookie, raw_ostream &OS) {
280 int CurVariant = -1; // The number of the {.|.|.} region we are in.
281 const char *LastEmitted = AsmStr; // One past the last character emitted.
282 unsigned NumOperands = MI->getNumOperands();
286 while (*LastEmitted) {
287 switch (*LastEmitted) {
289 // Not a special case, emit the string section literally.
290 const char *LiteralEnd = LastEmitted+1;
291 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
292 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
294 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
295 OS.write(LastEmitted, LiteralEnd-LastEmitted);
296 LastEmitted = LiteralEnd;
300 ++LastEmitted; // Consume newline character.
301 OS << '\n'; // Indent code with newline.
304 ++LastEmitted; // Consume '$' character.
308 switch (*LastEmitted) {
309 default: Done = false; break;
311 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
313 ++LastEmitted; // Consume second '$' character.
315 case '(': // $( -> same as GCC's { character.
316 ++LastEmitted; // Consume '(' character.
317 if (CurVariant != -1)
318 report_fatal_error("Nested variants found in inline asm string: '" +
319 Twine(AsmStr) + "'");
320 CurVariant = 0; // We're in the first variant now.
323 ++LastEmitted; // consume '|' character.
324 if (CurVariant == -1)
325 OS << '|'; // this is gcc's behavior for | outside a variant
327 ++CurVariant; // We're in the next variant.
329 case ')': // $) -> same as GCC's } char.
330 ++LastEmitted; // consume ')' character.
331 if (CurVariant == -1)
332 OS << '}'; // this is gcc's behavior for } outside a variant
339 bool HasCurlyBraces = false;
340 if (*LastEmitted == '{') { // ${variable}
341 ++LastEmitted; // Consume '{' character.
342 HasCurlyBraces = true;
345 // If we have ${:foo}, then this is not a real operand reference, it is a
346 // "magic" string reference, just like in .td files. Arrange to call
348 if (HasCurlyBraces && *LastEmitted == ':') {
350 const char *StrStart = LastEmitted;
351 const char *StrEnd = strchr(StrStart, '}');
353 report_fatal_error("Unterminated ${:foo} operand in inline asm"
354 " string: '" + Twine(AsmStr) + "'");
356 std::string Val(StrStart, StrEnd);
357 AP->PrintSpecial(MI, OS, Val.c_str());
358 LastEmitted = StrEnd+1;
362 const char *IDStart = LastEmitted;
363 const char *IDEnd = IDStart;
364 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
367 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
368 report_fatal_error("Bad $ operand number in inline asm string: '" +
369 Twine(AsmStr) + "'");
372 char Modifier[2] = { 0, 0 };
374 if (HasCurlyBraces) {
375 // If we have curly braces, check for a modifier character. This
376 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
377 if (*LastEmitted == ':') {
378 ++LastEmitted; // Consume ':' character.
379 if (*LastEmitted == 0)
380 report_fatal_error("Bad ${:} expression in inline asm string: '" +
381 Twine(AsmStr) + "'");
383 Modifier[0] = *LastEmitted;
384 ++LastEmitted; // Consume modifier character.
387 if (*LastEmitted != '}')
388 report_fatal_error("Bad ${} expression in inline asm string: '" +
389 Twine(AsmStr) + "'");
390 ++LastEmitted; // Consume '}' character.
393 if (Val >= NumOperands-1)
394 report_fatal_error("Invalid $ operand number in inline asm string: '" +
395 Twine(AsmStr) + "'");
397 // Okay, we finally have a value number. Ask the target to print this
399 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
400 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
404 // Scan to find the machine operand number for the operand.
406 if (OpNo >= MI->getNumOperands()) break;
407 unsigned OpFlags = MI->getOperand(OpNo).getImm();
408 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
411 // We may have a location metadata attached to the end of the
412 // instruction, and at no point should see metadata at any
413 // other point while processing. It's an error if so.
414 if (OpNo >= MI->getNumOperands() ||
415 MI->getOperand(OpNo).isMetadata()) {
418 unsigned OpFlags = MI->getOperand(OpNo).getImm();
419 ++OpNo; // Skip over the ID number.
421 if (Modifier[0] == 'l') // labels are target independent
422 // FIXME: What if the operand isn't an MBB, report error?
423 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
425 if (InlineAsm::isMemKind(OpFlags)) {
426 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
427 Modifier[0] ? Modifier : nullptr,
430 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
431 Modifier[0] ? Modifier : nullptr, OS);
437 raw_string_ostream Msg(msg);
438 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
439 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
446 OS << '\n' << (char)0; // null terminate string.
449 /// EmitInlineAsm - This method formats and emits the specified machine
450 /// instruction that is an inline asm.
451 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
452 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
454 // Count the number of register definitions to find the asm string.
455 unsigned NumDefs = 0;
456 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
458 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
460 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
462 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
463 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
465 // If this asmstr is empty, just print the #APP/#NOAPP markers.
466 // These are useful to see where empty asm's wound up.
467 if (AsmStr[0] == 0) {
468 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
469 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
473 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
474 // enabled, so we use emitRawComment.
475 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
477 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
479 unsigned LocCookie = 0;
480 const MDNode *LocMD = nullptr;
481 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
482 if (MI->getOperand(i-1).isMetadata() &&
483 (LocMD = MI->getOperand(i-1).getMetadata()) &&
484 LocMD->getNumOperands() != 0) {
485 if (const ConstantInt *CI =
486 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
487 LocCookie = CI->getZExtValue();
493 // Emit the inline asm to a temporary string so we can emit it through
495 SmallString<256> StringData;
496 raw_svector_ostream OS(StringData);
498 // The variant of the current asmprinter.
499 int AsmPrinterVariant = MAI->getAssemblerDialect();
500 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
501 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
502 if (InlineAsmVariant == InlineAsm::AD_ATT)
503 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
506 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
508 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
510 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
511 // enabled, so we use emitRawComment.
512 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
516 /// PrintSpecial - Print information related to the specified machine instr
517 /// that is independent of the operand, and may be independent of the instr
518 /// itself. This can be useful for portably encoding the comment character
519 /// or other bits of target-specific knowledge into the asmstrings. The
520 /// syntax used is ${:comment}. Targets can override this to add support
521 /// for their own strange codes.
522 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
523 const char *Code) const {
524 const DataLayout *DL = TM.getDataLayout();
525 if (!strcmp(Code, "private")) {
526 OS << DL->getPrivateGlobalPrefix();
527 } else if (!strcmp(Code, "comment")) {
528 OS << MAI->getCommentString();
529 } else if (!strcmp(Code, "uid")) {
530 // Comparing the address of MI isn't sufficient, because machineinstrs may
531 // be allocated to the same address across functions.
533 // If this is a new LastFn instruction, bump the counter.
534 if (LastMI != MI || LastFn != getFunctionNumber()) {
537 LastFn = getFunctionNumber();
542 raw_string_ostream Msg(msg);
543 Msg << "Unknown special formatter '" << Code
544 << "' for machine instr: " << *MI;
545 report_fatal_error(Msg.str());
549 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
550 /// instruction, using the specified assembler variant. Targets should
551 /// override this to format as appropriate.
552 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
553 unsigned AsmVariant, const char *ExtraCode,
555 // Does this asm operand have a single letter operand modifier?
556 if (ExtraCode && ExtraCode[0]) {
557 if (ExtraCode[1] != 0) return true; // Unknown modifier.
559 const MachineOperand &MO = MI->getOperand(OpNo);
560 switch (ExtraCode[0]) {
562 return true; // Unknown modifier.
563 case 'c': // Substitute immediate value without immediate syntax
564 if (MO.getType() != MachineOperand::MO_Immediate)
568 case 'n': // Negate the immediate constant.
569 if (MO.getType() != MachineOperand::MO_Immediate)
578 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
580 const char *ExtraCode, raw_ostream &O) {
581 // Target doesn't support this yet!
585 void AsmPrinter::emitInlineAsmStart() const {}
587 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
588 const MCSubtargetInfo *EndInfo) const {}