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 // We may create a new MCInstrInfo here since we might be at the module level
152 // and not have a MachineFunction to initialize the TargetInstrInfo from and
153 // we only need MCInstrInfo for asm parsing.
154 std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
155 *STI, *Parser, MII ? *MII : *TM.getTarget().createMCInstrInfo(),
156 TM.Options.MCOptions));
158 report_fatal_error("Inline asm not supported by this streamer because"
159 " we don't have an asm parser for this target\n");
160 Parser->setAssemblerDialect(Dialect);
161 Parser->setTargetParser(*TAP.get());
163 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
164 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
167 emitInlineAsmStart();
168 // Don't implicitly switch to the text section before the asm.
169 int Res = Parser->Run(/*NoInitialTextSection*/ true,
170 /*NoFinalize*/ true);
171 emitInlineAsmEnd(STIOrig, STI.get());
172 if (Res && !HasDiagHandler)
173 report_fatal_error("Error parsing inline asm\n");
176 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
177 MachineModuleInfo *MMI, int InlineAsmVariant,
178 AsmPrinter *AP, unsigned LocCookie,
180 // Switch to the inline assembly variant.
181 OS << "\t.intel_syntax\n\t";
183 const char *LastEmitted = AsmStr; // One past the last character emitted.
184 unsigned NumOperands = MI->getNumOperands();
186 while (*LastEmitted) {
187 switch (*LastEmitted) {
189 // Not a special case, emit the string section literally.
190 const char *LiteralEnd = LastEmitted+1;
191 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
192 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
195 OS.write(LastEmitted, LiteralEnd-LastEmitted);
196 LastEmitted = LiteralEnd;
200 ++LastEmitted; // Consume newline character.
201 OS << '\n'; // Indent code with newline.
204 ++LastEmitted; // Consume '$' character.
208 switch (*LastEmitted) {
209 default: Done = false; break;
211 ++LastEmitted; // Consume second '$' character.
216 const char *IDStart = LastEmitted;
217 const char *IDEnd = IDStart;
218 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
221 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
222 report_fatal_error("Bad $ operand number in inline asm string: '" +
223 Twine(AsmStr) + "'");
226 if (Val >= NumOperands-1)
227 report_fatal_error("Invalid $ operand number in inline asm string: '" +
228 Twine(AsmStr) + "'");
230 // Okay, we finally have a value number. Ask the target to print this
232 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
236 // Scan to find the machine operand number for the operand.
238 if (OpNo >= MI->getNumOperands()) break;
239 unsigned OpFlags = MI->getOperand(OpNo).getImm();
240 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
243 // We may have a location metadata attached to the end of the
244 // instruction, and at no point should see metadata at any
245 // other point while processing. It's an error if so.
246 if (OpNo >= MI->getNumOperands() ||
247 MI->getOperand(OpNo).isMetadata()) {
250 unsigned OpFlags = MI->getOperand(OpNo).getImm();
251 ++OpNo; // Skip over the ID number.
253 if (InlineAsm::isMemKind(OpFlags)) {
254 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
255 /*Modifier*/ nullptr, OS);
257 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
258 /*Modifier*/ nullptr, OS);
263 raw_string_ostream Msg(msg);
264 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
265 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
271 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
274 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
275 MachineModuleInfo *MMI, int InlineAsmVariant,
276 int AsmPrinterVariant, AsmPrinter *AP,
277 unsigned LocCookie, raw_ostream &OS) {
278 int CurVariant = -1; // The number of the {.|.|.} region we are in.
279 const char *LastEmitted = AsmStr; // One past the last character emitted.
280 unsigned NumOperands = MI->getNumOperands();
284 while (*LastEmitted) {
285 switch (*LastEmitted) {
287 // Not a special case, emit the string section literally.
288 const char *LiteralEnd = LastEmitted+1;
289 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
290 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
292 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
293 OS.write(LastEmitted, LiteralEnd-LastEmitted);
294 LastEmitted = LiteralEnd;
298 ++LastEmitted; // Consume newline character.
299 OS << '\n'; // Indent code with newline.
302 ++LastEmitted; // Consume '$' character.
306 switch (*LastEmitted) {
307 default: Done = false; break;
309 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
311 ++LastEmitted; // Consume second '$' character.
313 case '(': // $( -> same as GCC's { character.
314 ++LastEmitted; // Consume '(' character.
315 if (CurVariant != -1)
316 report_fatal_error("Nested variants found in inline asm string: '" +
317 Twine(AsmStr) + "'");
318 CurVariant = 0; // We're in the first variant now.
321 ++LastEmitted; // consume '|' character.
322 if (CurVariant == -1)
323 OS << '|'; // this is gcc's behavior for | outside a variant
325 ++CurVariant; // We're in the next variant.
327 case ')': // $) -> same as GCC's } char.
328 ++LastEmitted; // consume ')' character.
329 if (CurVariant == -1)
330 OS << '}'; // this is gcc's behavior for } outside a variant
337 bool HasCurlyBraces = false;
338 if (*LastEmitted == '{') { // ${variable}
339 ++LastEmitted; // Consume '{' character.
340 HasCurlyBraces = true;
343 // If we have ${:foo}, then this is not a real operand reference, it is a
344 // "magic" string reference, just like in .td files. Arrange to call
346 if (HasCurlyBraces && *LastEmitted == ':') {
348 const char *StrStart = LastEmitted;
349 const char *StrEnd = strchr(StrStart, '}');
351 report_fatal_error("Unterminated ${:foo} operand in inline asm"
352 " string: '" + Twine(AsmStr) + "'");
354 std::string Val(StrStart, StrEnd);
355 AP->PrintSpecial(MI, OS, Val.c_str());
356 LastEmitted = StrEnd+1;
360 const char *IDStart = LastEmitted;
361 const char *IDEnd = IDStart;
362 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
365 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
366 report_fatal_error("Bad $ operand number in inline asm string: '" +
367 Twine(AsmStr) + "'");
370 char Modifier[2] = { 0, 0 };
372 if (HasCurlyBraces) {
373 // If we have curly braces, check for a modifier character. This
374 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
375 if (*LastEmitted == ':') {
376 ++LastEmitted; // Consume ':' character.
377 if (*LastEmitted == 0)
378 report_fatal_error("Bad ${:} expression in inline asm string: '" +
379 Twine(AsmStr) + "'");
381 Modifier[0] = *LastEmitted;
382 ++LastEmitted; // Consume modifier character.
385 if (*LastEmitted != '}')
386 report_fatal_error("Bad ${} expression in inline asm string: '" +
387 Twine(AsmStr) + "'");
388 ++LastEmitted; // Consume '}' character.
391 if (Val >= NumOperands-1)
392 report_fatal_error("Invalid $ operand number in inline asm string: '" +
393 Twine(AsmStr) + "'");
395 // Okay, we finally have a value number. Ask the target to print this
397 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
398 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
402 // Scan to find the machine operand number for the operand.
404 if (OpNo >= MI->getNumOperands()) break;
405 unsigned OpFlags = MI->getOperand(OpNo).getImm();
406 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
409 // We may have a location metadata attached to the end of the
410 // instruction, and at no point should see metadata at any
411 // other point while processing. It's an error if so.
412 if (OpNo >= MI->getNumOperands() ||
413 MI->getOperand(OpNo).isMetadata()) {
416 unsigned OpFlags = MI->getOperand(OpNo).getImm();
417 ++OpNo; // Skip over the ID number.
419 if (Modifier[0] == 'l') // labels are target independent
420 // FIXME: What if the operand isn't an MBB, report error?
421 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
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 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
508 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
509 // enabled, so we use emitRawComment.
510 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
514 /// PrintSpecial - Print information related to the specified machine instr
515 /// that is independent of the operand, and may be independent of the instr
516 /// itself. This can be useful for portably encoding the comment character
517 /// or other bits of target-specific knowledge into the asmstrings. The
518 /// syntax used is ${:comment}. Targets can override this to add support
519 /// for their own strange codes.
520 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
521 const char *Code) const {
522 const DataLayout *DL = TM.getDataLayout();
523 if (!strcmp(Code, "private")) {
524 OS << DL->getPrivateGlobalPrefix();
525 } else if (!strcmp(Code, "comment")) {
526 OS << MAI->getCommentString();
527 } else if (!strcmp(Code, "uid")) {
528 // Comparing the address of MI isn't sufficient, because machineinstrs may
529 // be allocated to the same address across functions.
531 // If this is a new LastFn instruction, bump the counter.
532 if (LastMI != MI || LastFn != getFunctionNumber()) {
535 LastFn = getFunctionNumber();
540 raw_string_ostream Msg(msg);
541 Msg << "Unknown special formatter '" << Code
542 << "' for machine instr: " << *MI;
543 report_fatal_error(Msg.str());
547 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
548 /// instruction, using the specified assembler variant. Targets should
549 /// override this to format as appropriate.
550 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
551 unsigned AsmVariant, const char *ExtraCode,
553 // Does this asm operand have a single letter operand modifier?
554 if (ExtraCode && ExtraCode[0]) {
555 if (ExtraCode[1] != 0) return true; // Unknown modifier.
557 const MachineOperand &MO = MI->getOperand(OpNo);
558 switch (ExtraCode[0]) {
560 return true; // Unknown modifier.
561 case 'c': // Substitute immediate value without immediate syntax
562 if (MO.getType() != MachineOperand::MO_Immediate)
566 case 'n': // Negate the immediate constant.
567 if (MO.getType() != MachineOperand::MO_Immediate)
576 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
578 const char *ExtraCode, raw_ostream &O) {
579 // Target doesn't support this yet!
583 void AsmPrinter::emitInlineAsmStart() const {}
585 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
586 const MCSubtargetInfo *EndInfo) const {}