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 dyn_cast<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 OutStreamer.EmitRawText(Str);
94 emitInlineAsmEnd(TM.getSubtarget<MCSubtargetInfo>(), nullptr);
99 SrcMgrDiagInfo DiagInfo;
101 // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
102 LLVMContext &LLVMCtx = MMI->getModule()->getContext();
103 bool HasDiagHandler = false;
104 if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) {
105 // If the source manager has an issue, we arrange for srcMgrDiagHandler
106 // to be invoked, getting DiagInfo passed into it.
107 DiagInfo.LocInfo = LocMDNode;
108 DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
109 DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
110 SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
111 HasDiagHandler = true;
114 std::unique_ptr<MemoryBuffer> Buffer;
115 if (isNullTerminated)
116 Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
118 Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
120 // Tell SrcMgr about this buffer, it takes ownership of the buffer.
121 SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
123 std::unique_ptr<MCAsmParser> Parser(
124 createMCAsmParser(SrcMgr, OutContext, OutStreamer, *MAI));
126 // Initialize the parser with a fresh subtarget info. It is better to use a
127 // new STI here because the parser may modify it and we do not want those
128 // modifications to persist after parsing the inlineasm. The modifications
129 // made by the parser will be seen by the code emitters because it passes
130 // the current STI down to the EncodeInstruction() method.
131 std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
132 TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
134 // Preserve a copy of the original STI because the parser may modify it. For
135 // example, when switching between arm and thumb mode. If the target needs to
136 // emit code to return to the original state it can do so in
137 // emitInlineAsmEnd().
138 MCSubtargetInfo STIOrig = *STI;
140 MCTargetOptions MCOptions;
142 MCOptions = MF->getTarget().Options.MCOptions;
143 std::unique_ptr<MCTargetAsmParser> TAP(
144 TM.getTarget().createMCAsmParser(*STI, *Parser, *MII, MCOptions));
146 report_fatal_error("Inline asm not supported by this streamer because"
147 " we don't have an asm parser for this target\n");
148 Parser->setAssemblerDialect(Dialect);
149 Parser->setTargetParser(*TAP.get());
151 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
152 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
155 // Don't implicitly switch to the text section before the asm.
156 int Res = Parser->Run(/*NoInitialTextSection*/ true,
157 /*NoFinalize*/ true);
158 emitInlineAsmEnd(STIOrig, STI.get());
159 if (Res && !HasDiagHandler)
160 report_fatal_error("Error parsing inline asm\n");
163 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
164 MachineModuleInfo *MMI, int InlineAsmVariant,
165 AsmPrinter *AP, unsigned LocCookie,
167 // Switch to the inline assembly variant.
168 OS << "\t.intel_syntax\n\t";
170 const char *LastEmitted = AsmStr; // One past the last character emitted.
171 unsigned NumOperands = MI->getNumOperands();
173 while (*LastEmitted) {
174 switch (*LastEmitted) {
176 // Not a special case, emit the string section literally.
177 const char *LiteralEnd = LastEmitted+1;
178 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
179 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
182 OS.write(LastEmitted, LiteralEnd-LastEmitted);
183 LastEmitted = LiteralEnd;
187 ++LastEmitted; // Consume newline character.
188 OS << '\n'; // Indent code with newline.
191 ++LastEmitted; // Consume '$' character.
195 switch (*LastEmitted) {
196 default: Done = false; break;
198 ++LastEmitted; // Consume second '$' character.
203 const char *IDStart = LastEmitted;
204 const char *IDEnd = IDStart;
205 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
208 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
209 report_fatal_error("Bad $ operand number in inline asm string: '" +
210 Twine(AsmStr) + "'");
213 if (Val >= NumOperands-1)
214 report_fatal_error("Invalid $ operand number in inline asm string: '" +
215 Twine(AsmStr) + "'");
217 // Okay, we finally have a value number. Ask the target to print this
219 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
223 // Scan to find the machine operand number for the operand.
225 if (OpNo >= MI->getNumOperands()) break;
226 unsigned OpFlags = MI->getOperand(OpNo).getImm();
227 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
230 // We may have a location metadata attached to the end of the
231 // instruction, and at no point should see metadata at any
232 // other point while processing. It's an error if so.
233 if (OpNo >= MI->getNumOperands() ||
234 MI->getOperand(OpNo).isMetadata()) {
237 unsigned OpFlags = MI->getOperand(OpNo).getImm();
238 ++OpNo; // Skip over the ID number.
240 if (InlineAsm::isMemKind(OpFlags)) {
241 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
242 /*Modifier*/ nullptr, OS);
244 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
245 /*Modifier*/ nullptr, OS);
250 raw_string_ostream Msg(msg);
251 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
252 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
258 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
261 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
262 MachineModuleInfo *MMI, int InlineAsmVariant,
263 int AsmPrinterVariant, AsmPrinter *AP,
264 unsigned LocCookie, raw_ostream &OS) {
265 int CurVariant = -1; // The number of the {.|.|.} region we are in.
266 const char *LastEmitted = AsmStr; // One past the last character emitted.
267 unsigned NumOperands = MI->getNumOperands();
271 while (*LastEmitted) {
272 switch (*LastEmitted) {
274 // Not a special case, emit the string section literally.
275 const char *LiteralEnd = LastEmitted+1;
276 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
277 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
279 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
280 OS.write(LastEmitted, LiteralEnd-LastEmitted);
281 LastEmitted = LiteralEnd;
285 ++LastEmitted; // Consume newline character.
286 OS << '\n'; // Indent code with newline.
289 ++LastEmitted; // Consume '$' character.
293 switch (*LastEmitted) {
294 default: Done = false; break;
296 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
298 ++LastEmitted; // Consume second '$' character.
300 case '(': // $( -> same as GCC's { character.
301 ++LastEmitted; // Consume '(' character.
302 if (CurVariant != -1)
303 report_fatal_error("Nested variants found in inline asm string: '" +
304 Twine(AsmStr) + "'");
305 CurVariant = 0; // We're in the first variant now.
308 ++LastEmitted; // consume '|' character.
309 if (CurVariant == -1)
310 OS << '|'; // this is gcc's behavior for | outside a variant
312 ++CurVariant; // We're in the next variant.
314 case ')': // $) -> same as GCC's } char.
315 ++LastEmitted; // consume ')' character.
316 if (CurVariant == -1)
317 OS << '}'; // this is gcc's behavior for } outside a variant
324 bool HasCurlyBraces = false;
325 if (*LastEmitted == '{') { // ${variable}
326 ++LastEmitted; // Consume '{' character.
327 HasCurlyBraces = true;
330 // If we have ${:foo}, then this is not a real operand reference, it is a
331 // "magic" string reference, just like in .td files. Arrange to call
333 if (HasCurlyBraces && *LastEmitted == ':') {
335 const char *StrStart = LastEmitted;
336 const char *StrEnd = strchr(StrStart, '}');
338 report_fatal_error("Unterminated ${:foo} operand in inline asm"
339 " string: '" + Twine(AsmStr) + "'");
341 std::string Val(StrStart, StrEnd);
342 AP->PrintSpecial(MI, OS, Val.c_str());
343 LastEmitted = StrEnd+1;
347 const char *IDStart = LastEmitted;
348 const char *IDEnd = IDStart;
349 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
352 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
353 report_fatal_error("Bad $ operand number in inline asm string: '" +
354 Twine(AsmStr) + "'");
357 char Modifier[2] = { 0, 0 };
359 if (HasCurlyBraces) {
360 // If we have curly braces, check for a modifier character. This
361 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
362 if (*LastEmitted == ':') {
363 ++LastEmitted; // Consume ':' character.
364 if (*LastEmitted == 0)
365 report_fatal_error("Bad ${:} expression in inline asm string: '" +
366 Twine(AsmStr) + "'");
368 Modifier[0] = *LastEmitted;
369 ++LastEmitted; // Consume modifier character.
372 if (*LastEmitted != '}')
373 report_fatal_error("Bad ${} expression in inline asm string: '" +
374 Twine(AsmStr) + "'");
375 ++LastEmitted; // Consume '}' character.
378 if (Val >= NumOperands-1)
379 report_fatal_error("Invalid $ operand number in inline asm string: '" +
380 Twine(AsmStr) + "'");
382 // Okay, we finally have a value number. Ask the target to print this
384 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
385 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
389 // Scan to find the machine operand number for the operand.
391 if (OpNo >= MI->getNumOperands()) break;
392 unsigned OpFlags = MI->getOperand(OpNo).getImm();
393 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
396 // We may have a location metadata attached to the end of the
397 // instruction, and at no point should see metadata at any
398 // other point while processing. It's an error if so.
399 if (OpNo >= MI->getNumOperands() ||
400 MI->getOperand(OpNo).isMetadata()) {
403 unsigned OpFlags = MI->getOperand(OpNo).getImm();
404 ++OpNo; // Skip over the ID number.
406 if (Modifier[0] == 'l') // labels are target independent
407 // FIXME: What if the operand isn't an MBB, report error?
408 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
410 if (InlineAsm::isMemKind(OpFlags)) {
411 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
412 Modifier[0] ? Modifier : nullptr,
415 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
416 Modifier[0] ? Modifier : nullptr, OS);
422 raw_string_ostream Msg(msg);
423 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
424 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
431 OS << '\n' << (char)0; // null terminate string.
434 /// EmitInlineAsm - This method formats and emits the specified machine
435 /// instruction that is an inline asm.
436 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
437 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
439 // Count the number of register definitions to find the asm string.
440 unsigned NumDefs = 0;
441 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
443 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
445 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
447 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
448 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
450 // If this asmstr is empty, just print the #APP/#NOAPP markers.
451 // These are useful to see where empty asm's wound up.
452 if (AsmStr[0] == 0) {
453 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
454 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
458 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
459 // enabled, so we use emitRawComment.
460 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
462 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
464 unsigned LocCookie = 0;
465 const MDNode *LocMD = nullptr;
466 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
467 if (MI->getOperand(i-1).isMetadata() &&
468 (LocMD = MI->getOperand(i-1).getMetadata()) &&
469 LocMD->getNumOperands() != 0) {
470 if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
471 LocCookie = CI->getZExtValue();
477 // Emit the inline asm to a temporary string so we can emit it through
479 SmallString<256> StringData;
480 raw_svector_ostream OS(StringData);
482 // The variant of the current asmprinter.
483 int AsmPrinterVariant = MAI->getAssemblerDialect();
484 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
485 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
486 if (InlineAsmVariant == InlineAsm::AD_ATT)
487 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
490 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
492 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
494 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
495 // enabled, so we use emitRawComment.
496 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
500 /// PrintSpecial - Print information related to the specified machine instr
501 /// that is independent of the operand, and may be independent of the instr
502 /// itself. This can be useful for portably encoding the comment character
503 /// or other bits of target-specific knowledge into the asmstrings. The
504 /// syntax used is ${:comment}. Targets can override this to add support
505 /// for their own strange codes.
506 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
507 const char *Code) const {
508 const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
509 if (!strcmp(Code, "private")) {
510 OS << DL->getPrivateGlobalPrefix();
511 } else if (!strcmp(Code, "comment")) {
512 OS << MAI->getCommentString();
513 } else if (!strcmp(Code, "uid")) {
514 // Comparing the address of MI isn't sufficient, because machineinstrs may
515 // be allocated to the same address across functions.
517 // If this is a new LastFn instruction, bump the counter.
518 if (LastMI != MI || LastFn != getFunctionNumber()) {
521 LastFn = getFunctionNumber();
526 raw_string_ostream Msg(msg);
527 Msg << "Unknown special formatter '" << Code
528 << "' for machine instr: " << *MI;
529 report_fatal_error(Msg.str());
533 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
534 /// instruction, using the specified assembler variant. Targets should
535 /// override this to format as appropriate.
536 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
537 unsigned AsmVariant, const char *ExtraCode,
539 // Does this asm operand have a single letter operand modifier?
540 if (ExtraCode && ExtraCode[0]) {
541 if (ExtraCode[1] != 0) return true; // Unknown modifier.
543 const MachineOperand &MO = MI->getOperand(OpNo);
544 switch (ExtraCode[0]) {
546 return true; // Unknown modifier.
547 case 'c': // Substitute immediate value without immediate syntax
548 if (MO.getType() != MachineOperand::MO_Immediate)
552 case 'n': // Negate the immediate constant.
553 if (MO.getType() != MachineOperand::MO_Immediate)
562 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
564 const char *ExtraCode, raw_ostream &O) {
565 // Target doesn't support this yet!
569 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
570 const MCSubtargetInfo *EndInfo) const {}