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/MCParser/MCTargetAsmParser.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/MC/MCSymbol.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 MCSubtargetInfo &STI,
77 const MCTargetOptions &MCOptions,
78 const MDNode *LocMDNode,
79 InlineAsm::AsmDialect Dialect) const {
80 assert(!Str.empty() && "Can't emit empty inline asm block");
82 // Remember if the buffer is nul terminated or not so we can avoid a copy.
83 bool isNullTerminated = Str.back() == 0;
85 Str = Str.substr(0, Str.size()-1);
87 // If the output streamer does not have mature MC support or the integrated
88 // assembler has been disabled, just emit the blob textually.
89 // Otherwise parse the asm and emit it via MC support.
90 // This is useful in case the asm parser doesn't handle something but the
91 // system assembler does.
92 const MCAsmInfo *MCAI = TM.getMCAsmInfo();
93 assert(MCAI && "No MCAsmInfo");
94 if (!MCAI->useIntegratedAssembler() &&
95 !OutStreamer->isIntegratedAssemblerRequired()) {
97 OutStreamer->EmitRawText(Str);
98 emitInlineAsmEnd(STI, nullptr);
103 SrcMgr.setIncludeDirs(MCOptions.IASSearchPaths);
105 SrcMgrDiagInfo DiagInfo;
107 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
108 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
109 bool HasDiagHandler = false;
110 if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) {
111 // If the source manager has an issue, we arrange for srcMgrDiagHandler
112 // to be invoked, getting DiagInfo passed into it.
113 DiagInfo.LocInfo = LocMDNode;
114 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
115 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
116 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
117 HasDiagHandler = true;
120 std::unique_ptr<MemoryBuffer> Buffer;
121 if (isNullTerminated)
122 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
124 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
126 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
127 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
129 std::unique_ptr<MCAsmParser> Parser(
130 createMCAsmParser(SrcMgr, OutContext, *OutStreamer, *MAI));
132 // We create a new MCInstrInfo here since we might be at the module level
133 // and not have a MachineFunction to initialize the TargetInstrInfo from and
134 // we only need MCInstrInfo for asm parsing. We create one unconditionally
135 // because it's not subtarget dependent.
136 std::unique_ptr<MCInstrInfo> MII(TM.getTarget().createMCInstrInfo());
137 std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
138 STI, *Parser, *MII, MCOptions));
140 report_fatal_error("Inline asm not supported by this streamer because"
141 " we don't have an asm parser for this target\n");
142 Parser->setAssemblerDialect(Dialect);
143 Parser->setTargetParser(*TAP.get());
145 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
146 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
149 emitInlineAsmStart();
150 // Don't implicitly switch to the text section before the asm.
151 int Res = Parser->Run(/*NoInitialTextSection*/ true,
152 /*NoFinalize*/ true);
153 emitInlineAsmEnd(STI, &TAP->getSTI());
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 // If we have ${:foo}, then this is not a real operand reference, it is a
199 // "magic" string reference, just like in .td files. Arrange to call
201 if (LastEmitted[0] == '{' && LastEmitted[1] == ':') {
203 const char *StrStart = LastEmitted;
204 const char *StrEnd = strchr(StrStart, '}');
206 report_fatal_error("Unterminated ${:foo} operand in inline asm"
207 " string: '" + Twine(AsmStr) + "'");
209 std::string Val(StrStart, StrEnd);
210 AP->PrintSpecial(MI, OS, Val.c_str());
211 LastEmitted = StrEnd+1;
215 const char *IDStart = LastEmitted;
216 const char *IDEnd = IDStart;
217 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
220 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
221 report_fatal_error("Bad $ operand number in inline asm string: '" +
222 Twine(AsmStr) + "'");
225 if (Val >= NumOperands-1)
226 report_fatal_error("Invalid $ operand number in inline asm string: '" +
227 Twine(AsmStr) + "'");
229 // Okay, we finally have a value number. Ask the target to print this
231 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
235 // Scan to find the machine operand number for the operand.
237 if (OpNo >= MI->getNumOperands()) break;
238 unsigned OpFlags = MI->getOperand(OpNo).getImm();
239 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
242 // We may have a location metadata attached to the end of the
243 // instruction, and at no point should see metadata at any
244 // other point while processing. It's an error if so.
245 if (OpNo >= MI->getNumOperands() ||
246 MI->getOperand(OpNo).isMetadata()) {
249 unsigned OpFlags = MI->getOperand(OpNo).getImm();
250 ++OpNo; // Skip over the ID number.
252 if (InlineAsm::isMemKind(OpFlags)) {
253 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
254 /*Modifier*/ nullptr, OS);
256 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
257 /*Modifier*/ nullptr, OS);
262 raw_string_ostream Msg(msg);
263 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
264 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
270 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
273 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
274 MachineModuleInfo *MMI, int InlineAsmVariant,
275 int AsmPrinterVariant, AsmPrinter *AP,
276 unsigned LocCookie, raw_ostream &OS) {
277 int CurVariant = -1; // The number of the {.|.|.} region we are in.
278 const char *LastEmitted = AsmStr; // One past the last character emitted.
279 unsigned NumOperands = MI->getNumOperands();
283 while (*LastEmitted) {
284 switch (*LastEmitted) {
286 // Not a special case, emit the string section literally.
287 const char *LiteralEnd = LastEmitted+1;
288 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
289 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
291 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
292 OS.write(LastEmitted, LiteralEnd-LastEmitted);
293 LastEmitted = LiteralEnd;
297 ++LastEmitted; // Consume newline character.
298 OS << '\n'; // Indent code with newline.
301 ++LastEmitted; // Consume '$' character.
305 switch (*LastEmitted) {
306 default: Done = false; break;
308 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
310 ++LastEmitted; // Consume second '$' character.
312 case '(': // $( -> same as GCC's { character.
313 ++LastEmitted; // Consume '(' character.
314 if (CurVariant != -1)
315 report_fatal_error("Nested variants found in inline asm string: '" +
316 Twine(AsmStr) + "'");
317 CurVariant = 0; // We're in the first variant now.
320 ++LastEmitted; // consume '|' character.
321 if (CurVariant == -1)
322 OS << '|'; // this is gcc's behavior for | outside a variant
324 ++CurVariant; // We're in the next variant.
326 case ')': // $) -> same as GCC's } char.
327 ++LastEmitted; // consume ')' character.
328 if (CurVariant == -1)
329 OS << '}'; // this is gcc's behavior for } outside a variant
336 bool HasCurlyBraces = false;
337 if (*LastEmitted == '{') { // ${variable}
338 ++LastEmitted; // Consume '{' character.
339 HasCurlyBraces = true;
342 // If we have ${:foo}, then this is not a real operand reference, it is a
343 // "magic" string reference, just like in .td files. Arrange to call
345 if (HasCurlyBraces && *LastEmitted == ':') {
347 const char *StrStart = LastEmitted;
348 const char *StrEnd = strchr(StrStart, '}');
350 report_fatal_error("Unterminated ${:foo} operand in inline asm"
351 " string: '" + Twine(AsmStr) + "'");
353 std::string Val(StrStart, StrEnd);
354 AP->PrintSpecial(MI, OS, Val.c_str());
355 LastEmitted = StrEnd+1;
359 const char *IDStart = LastEmitted;
360 const char *IDEnd = IDStart;
361 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
364 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
365 report_fatal_error("Bad $ operand number in inline asm string: '" +
366 Twine(AsmStr) + "'");
369 char Modifier[2] = { 0, 0 };
371 if (HasCurlyBraces) {
372 // If we have curly braces, check for a modifier character. This
373 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
374 if (*LastEmitted == ':') {
375 ++LastEmitted; // Consume ':' character.
376 if (*LastEmitted == 0)
377 report_fatal_error("Bad ${:} expression in inline asm string: '" +
378 Twine(AsmStr) + "'");
380 Modifier[0] = *LastEmitted;
381 ++LastEmitted; // Consume modifier character.
384 if (*LastEmitted != '}')
385 report_fatal_error("Bad ${} expression in inline asm string: '" +
386 Twine(AsmStr) + "'");
387 ++LastEmitted; // Consume '}' character.
390 if (Val >= NumOperands-1)
391 report_fatal_error("Invalid $ operand number in inline asm string: '" +
392 Twine(AsmStr) + "'");
394 // Okay, we finally have a value number. Ask the target to print this
396 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
397 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
401 // Scan to find the machine operand number for the operand.
403 if (OpNo >= MI->getNumOperands()) break;
404 unsigned OpFlags = MI->getOperand(OpNo).getImm();
405 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
408 // We may have a location metadata attached to the end of the
409 // instruction, and at no point should see metadata at any
410 // other point while processing. It's an error if so.
411 if (OpNo >= MI->getNumOperands() ||
412 MI->getOperand(OpNo).isMetadata()) {
415 unsigned OpFlags = MI->getOperand(OpNo).getImm();
416 ++OpNo; // Skip over the ID number.
418 if (Modifier[0] == 'l') { // Labels are target independent.
419 // FIXME: What if the operand isn't an MBB, report error?
420 const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol();
421 Sym->print(OS, AP->MAI);
423 if (InlineAsm::isMemKind(OpFlags)) {
424 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
425 Modifier[0] ? Modifier : nullptr,
428 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
429 Modifier[0] ? Modifier : nullptr, OS);
435 raw_string_ostream Msg(msg);
436 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
437 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
444 OS << '\n' << (char)0; // null terminate string.
447 /// EmitInlineAsm - This method formats and emits the specified machine
448 /// instruction that is an inline asm.
449 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
450 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
452 // Count the number of register definitions to find the asm string.
453 unsigned NumDefs = 0;
454 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
456 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
458 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
460 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
461 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
463 // If this asmstr is empty, just print the #APP/#NOAPP markers.
464 // These are useful to see where empty asm's wound up.
465 if (AsmStr[0] == 0) {
466 OutStreamer->emitRawComment(MAI->getInlineAsmStart());
467 OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
471 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
472 // enabled, so we use emitRawComment.
473 OutStreamer->emitRawComment(MAI->getInlineAsmStart());
475 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
477 unsigned LocCookie = 0;
478 const MDNode *LocMD = nullptr;
479 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
480 if (MI->getOperand(i-1).isMetadata() &&
481 (LocMD = MI->getOperand(i-1).getMetadata()) &&
482 LocMD->getNumOperands() != 0) {
483 if (const ConstantInt *CI =
484 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
485 LocCookie = CI->getZExtValue();
491 // Emit the inline asm to a temporary string so we can emit it through
493 SmallString<256> StringData;
494 raw_svector_ostream OS(StringData);
496 // The variant of the current asmprinter.
497 int AsmPrinterVariant = MAI->getAssemblerDialect();
498 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
499 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
500 if (InlineAsmVariant == InlineAsm::AD_ATT)
501 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
504 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
506 // Reset SanitizeAddress based on the function's attribute.
507 MCTargetOptions MCOptions = TM.Options.MCOptions;
508 MCOptions.SanitizeAddress =
509 MF->getFunction()->hasFnAttribute(Attribute::SanitizeAddress);
511 EmitInlineAsm(OS.str(), getSubtargetInfo(), MCOptions, LocMD,
512 MI->getInlineAsmDialect());
514 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
515 // enabled, so we use emitRawComment.
516 OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
520 /// PrintSpecial - Print information related to the specified machine instr
521 /// that is independent of the operand, and may be independent of the instr
522 /// itself. This can be useful for portably encoding the comment character
523 /// or other bits of target-specific knowledge into the asmstrings. The
524 /// syntax used is ${:comment}. Targets can override this to add support
525 /// for their own strange codes.
526 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
527 const char *Code) const {
528 if (!strcmp(Code, "private")) {
529 const DataLayout &DL = MF->getDataLayout();
530 OS << DL.getPrivateGlobalPrefix();
531 } else if (!strcmp(Code, "comment")) {
532 OS << MAI->getCommentString();
533 } else if (!strcmp(Code, "uid")) {
534 // Comparing the address of MI isn't sufficient, because machineinstrs may
535 // be allocated to the same address across functions.
537 // If this is a new LastFn instruction, bump the counter.
538 if (LastMI != MI || LastFn != getFunctionNumber()) {
541 LastFn = getFunctionNumber();
546 raw_string_ostream Msg(msg);
547 Msg << "Unknown special formatter '" << Code
548 << "' for machine instr: " << *MI;
549 report_fatal_error(Msg.str());
553 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
554 /// instruction, using the specified assembler variant. Targets should
555 /// override this to format as appropriate.
556 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
557 unsigned AsmVariant, const char *ExtraCode,
559 // Does this asm operand have a single letter operand modifier?
560 if (ExtraCode && ExtraCode[0]) {
561 if (ExtraCode[1] != 0) return true; // Unknown modifier.
563 const MachineOperand &MO = MI->getOperand(OpNo);
564 switch (ExtraCode[0]) {
566 return true; // Unknown modifier.
567 case 'c': // Substitute immediate value without immediate syntax
568 if (MO.getType() != MachineOperand::MO_Immediate)
572 case 'n': // Negate the immediate constant.
573 if (MO.getType() != MachineOperand::MO_Immediate)
577 case 's': // The GCC deprecated s modifier
578 if (MO.getType() != MachineOperand::MO_Immediate)
580 O << ((32 - MO.getImm()) & 31);
587 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
589 const char *ExtraCode, raw_ostream &O) {
590 // Target doesn't support this yet!
594 void AsmPrinter::emitInlineAsmStart() const {}
596 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
597 const MCSubtargetInfo *EndInfo) const {}