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 MCTargetOptions MCOptions;
153 MCOptions = MF->getTarget().Options.MCOptions;
154 std::unique_ptr<MCTargetAsmParser> TAP(
155 TM.getTarget().createMCAsmParser(*STI, *Parser, *MII, MCOptions));
157 report_fatal_error("Inline asm not supported by this streamer because"
158 " we don't have an asm parser for this target\n");
159 Parser->setAssemblerDialect(Dialect);
160 Parser->setTargetParser(*TAP.get());
162 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
163 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
166 emitInlineAsmStart();
167 // Don't implicitly switch to the text section before the asm.
168 int Res = Parser->Run(/*NoInitialTextSection*/ true,
169 /*NoFinalize*/ true);
170 emitInlineAsmEnd(STIOrig, STI.get());
171 if (Res && !HasDiagHandler)
172 report_fatal_error("Error parsing inline asm\n");
175 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
176 MachineModuleInfo *MMI, int InlineAsmVariant,
177 AsmPrinter *AP, unsigned LocCookie,
179 // Switch to the inline assembly variant.
180 OS << "\t.intel_syntax\n\t";
182 const char *LastEmitted = AsmStr; // One past the last character emitted.
183 unsigned NumOperands = MI->getNumOperands();
185 while (*LastEmitted) {
186 switch (*LastEmitted) {
188 // Not a special case, emit the string section literally.
189 const char *LiteralEnd = LastEmitted+1;
190 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
191 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
194 OS.write(LastEmitted, LiteralEnd-LastEmitted);
195 LastEmitted = LiteralEnd;
199 ++LastEmitted; // Consume newline character.
200 OS << '\n'; // Indent code with newline.
203 ++LastEmitted; // Consume '$' character.
207 switch (*LastEmitted) {
208 default: Done = false; break;
210 ++LastEmitted; // Consume second '$' character.
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 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
422 if (InlineAsm::isMemKind(OpFlags)) {
423 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
424 Modifier[0] ? Modifier : nullptr,
427 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
428 Modifier[0] ? Modifier : nullptr, OS);
434 raw_string_ostream Msg(msg);
435 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
436 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
443 OS << '\n' << (char)0; // null terminate string.
446 /// EmitInlineAsm - This method formats and emits the specified machine
447 /// instruction that is an inline asm.
448 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
449 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
451 // Count the number of register definitions to find the asm string.
452 unsigned NumDefs = 0;
453 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
455 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
457 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
459 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
460 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
462 // If this asmstr is empty, just print the #APP/#NOAPP markers.
463 // These are useful to see where empty asm's wound up.
464 if (AsmStr[0] == 0) {
465 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
466 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
470 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
471 // enabled, so we use emitRawComment.
472 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
474 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
476 unsigned LocCookie = 0;
477 const MDNode *LocMD = nullptr;
478 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
479 if (MI->getOperand(i-1).isMetadata() &&
480 (LocMD = MI->getOperand(i-1).getMetadata()) &&
481 LocMD->getNumOperands() != 0) {
482 if (const ConstantInt *CI =
483 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
484 LocCookie = CI->getZExtValue();
490 // Emit the inline asm to a temporary string so we can emit it through
492 SmallString<256> StringData;
493 raw_svector_ostream OS(StringData);
495 // The variant of the current asmprinter.
496 int AsmPrinterVariant = MAI->getAssemblerDialect();
497 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
498 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
499 if (InlineAsmVariant == InlineAsm::AD_ATT)
500 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
503 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
505 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
507 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
508 // enabled, so we use emitRawComment.
509 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
513 /// PrintSpecial - Print information related to the specified machine instr
514 /// that is independent of the operand, and may be independent of the instr
515 /// itself. This can be useful for portably encoding the comment character
516 /// or other bits of target-specific knowledge into the asmstrings. The
517 /// syntax used is ${:comment}. Targets can override this to add support
518 /// for their own strange codes.
519 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
520 const char *Code) const {
521 const DataLayout *DL = TM.getDataLayout();
522 if (!strcmp(Code, "private")) {
523 OS << DL->getPrivateGlobalPrefix();
524 } else if (!strcmp(Code, "comment")) {
525 OS << MAI->getCommentString();
526 } else if (!strcmp(Code, "uid")) {
527 // Comparing the address of MI isn't sufficient, because machineinstrs may
528 // be allocated to the same address across functions.
530 // If this is a new LastFn instruction, bump the counter.
531 if (LastMI != MI || LastFn != getFunctionNumber()) {
534 LastFn = getFunctionNumber();
539 raw_string_ostream Msg(msg);
540 Msg << "Unknown special formatter '" << Code
541 << "' for machine instr: " << *MI;
542 report_fatal_error(Msg.str());
546 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
547 /// instruction, using the specified assembler variant. Targets should
548 /// override this to format as appropriate.
549 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
550 unsigned AsmVariant, const char *ExtraCode,
552 // Does this asm operand have a single letter operand modifier?
553 if (ExtraCode && ExtraCode[0]) {
554 if (ExtraCode[1] != 0) return true; // Unknown modifier.
556 const MachineOperand &MO = MI->getOperand(OpNo);
557 switch (ExtraCode[0]) {
559 return true; // Unknown modifier.
560 case 'c': // Substitute immediate value without immediate syntax
561 if (MO.getType() != MachineOperand::MO_Immediate)
565 case 'n': // Negate the immediate constant.
566 if (MO.getType() != MachineOperand::MO_Immediate)
575 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
577 const char *ExtraCode, raw_ostream &O) {
578 // Target doesn't support this yet!
582 void AsmPrinter::emitInlineAsmStart() const {}
584 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
585 const MCSubtargetInfo *EndInfo) const {}