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 may 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.
155 const MCInstrInfo *MII = MF
156 ? MII = static_cast<const MCInstrInfo *>(
157 MF->getSubtarget().getInstrInfo())
158 : MII = static_cast<const MCInstrInfo *>(
159 TM.getTarget().createMCInstrInfo());
160 std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
161 *STI, *Parser, *MII, TM.Options.MCOptions));
163 report_fatal_error("Inline asm not supported by this streamer because"
164 " we don't have an asm parser for this target\n");
165 Parser->setAssemblerDialect(Dialect);
166 Parser->setTargetParser(*TAP.get());
168 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
169 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
172 emitInlineAsmStart();
173 // Don't implicitly switch to the text section before the asm.
174 int Res = Parser->Run(/*NoInitialTextSection*/ true,
175 /*NoFinalize*/ true);
176 emitInlineAsmEnd(STIOrig, STI.get());
177 if (Res && !HasDiagHandler)
178 report_fatal_error("Error parsing inline asm\n");
181 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
182 MachineModuleInfo *MMI, int InlineAsmVariant,
183 AsmPrinter *AP, unsigned LocCookie,
185 // Switch to the inline assembly variant.
186 OS << "\t.intel_syntax\n\t";
188 const char *LastEmitted = AsmStr; // One past the last character emitted.
189 unsigned NumOperands = MI->getNumOperands();
191 while (*LastEmitted) {
192 switch (*LastEmitted) {
194 // Not a special case, emit the string section literally.
195 const char *LiteralEnd = LastEmitted+1;
196 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
197 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
200 OS.write(LastEmitted, LiteralEnd-LastEmitted);
201 LastEmitted = LiteralEnd;
205 ++LastEmitted; // Consume newline character.
206 OS << '\n'; // Indent code with newline.
209 ++LastEmitted; // Consume '$' character.
213 switch (*LastEmitted) {
214 default: Done = false; break;
216 ++LastEmitted; // Consume second '$' character.
221 const char *IDStart = LastEmitted;
222 const char *IDEnd = IDStart;
223 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
226 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
227 report_fatal_error("Bad $ operand number in inline asm string: '" +
228 Twine(AsmStr) + "'");
231 if (Val >= NumOperands-1)
232 report_fatal_error("Invalid $ operand number in inline asm string: '" +
233 Twine(AsmStr) + "'");
235 // Okay, we finally have a value number. Ask the target to print this
237 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
241 // Scan to find the machine operand number for the operand.
243 if (OpNo >= MI->getNumOperands()) break;
244 unsigned OpFlags = MI->getOperand(OpNo).getImm();
245 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
248 // We may have a location metadata attached to the end of the
249 // instruction, and at no point should see metadata at any
250 // other point while processing. It's an error if so.
251 if (OpNo >= MI->getNumOperands() ||
252 MI->getOperand(OpNo).isMetadata()) {
255 unsigned OpFlags = MI->getOperand(OpNo).getImm();
256 ++OpNo; // Skip over the ID number.
258 if (InlineAsm::isMemKind(OpFlags)) {
259 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
260 /*Modifier*/ nullptr, OS);
262 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
263 /*Modifier*/ nullptr, OS);
268 raw_string_ostream Msg(msg);
269 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
270 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
276 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
279 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
280 MachineModuleInfo *MMI, int InlineAsmVariant,
281 int AsmPrinterVariant, AsmPrinter *AP,
282 unsigned LocCookie, raw_ostream &OS) {
283 int CurVariant = -1; // The number of the {.|.|.} region we are in.
284 const char *LastEmitted = AsmStr; // One past the last character emitted.
285 unsigned NumOperands = MI->getNumOperands();
289 while (*LastEmitted) {
290 switch (*LastEmitted) {
292 // Not a special case, emit the string section literally.
293 const char *LiteralEnd = LastEmitted+1;
294 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
295 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
297 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
298 OS.write(LastEmitted, LiteralEnd-LastEmitted);
299 LastEmitted = LiteralEnd;
303 ++LastEmitted; // Consume newline character.
304 OS << '\n'; // Indent code with newline.
307 ++LastEmitted; // Consume '$' character.
311 switch (*LastEmitted) {
312 default: Done = false; break;
314 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
316 ++LastEmitted; // Consume second '$' character.
318 case '(': // $( -> same as GCC's { character.
319 ++LastEmitted; // Consume '(' character.
320 if (CurVariant != -1)
321 report_fatal_error("Nested variants found in inline asm string: '" +
322 Twine(AsmStr) + "'");
323 CurVariant = 0; // We're in the first variant now.
326 ++LastEmitted; // consume '|' character.
327 if (CurVariant == -1)
328 OS << '|'; // this is gcc's behavior for | outside a variant
330 ++CurVariant; // We're in the next variant.
332 case ')': // $) -> same as GCC's } char.
333 ++LastEmitted; // consume ')' character.
334 if (CurVariant == -1)
335 OS << '}'; // this is gcc's behavior for } outside a variant
342 bool HasCurlyBraces = false;
343 if (*LastEmitted == '{') { // ${variable}
344 ++LastEmitted; // Consume '{' character.
345 HasCurlyBraces = true;
348 // If we have ${:foo}, then this is not a real operand reference, it is a
349 // "magic" string reference, just like in .td files. Arrange to call
351 if (HasCurlyBraces && *LastEmitted == ':') {
353 const char *StrStart = LastEmitted;
354 const char *StrEnd = strchr(StrStart, '}');
356 report_fatal_error("Unterminated ${:foo} operand in inline asm"
357 " string: '" + Twine(AsmStr) + "'");
359 std::string Val(StrStart, StrEnd);
360 AP->PrintSpecial(MI, OS, Val.c_str());
361 LastEmitted = StrEnd+1;
365 const char *IDStart = LastEmitted;
366 const char *IDEnd = IDStart;
367 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
370 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
371 report_fatal_error("Bad $ operand number in inline asm string: '" +
372 Twine(AsmStr) + "'");
375 char Modifier[2] = { 0, 0 };
377 if (HasCurlyBraces) {
378 // If we have curly braces, check for a modifier character. This
379 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
380 if (*LastEmitted == ':') {
381 ++LastEmitted; // Consume ':' character.
382 if (*LastEmitted == 0)
383 report_fatal_error("Bad ${:} expression in inline asm string: '" +
384 Twine(AsmStr) + "'");
386 Modifier[0] = *LastEmitted;
387 ++LastEmitted; // Consume modifier character.
390 if (*LastEmitted != '}')
391 report_fatal_error("Bad ${} expression in inline asm string: '" +
392 Twine(AsmStr) + "'");
393 ++LastEmitted; // Consume '}' character.
396 if (Val >= NumOperands-1)
397 report_fatal_error("Invalid $ operand number in inline asm string: '" +
398 Twine(AsmStr) + "'");
400 // Okay, we finally have a value number. Ask the target to print this
402 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
403 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
407 // Scan to find the machine operand number for the operand.
409 if (OpNo >= MI->getNumOperands()) break;
410 unsigned OpFlags = MI->getOperand(OpNo).getImm();
411 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
414 // We may have a location metadata attached to the end of the
415 // instruction, and at no point should see metadata at any
416 // other point while processing. It's an error if so.
417 if (OpNo >= MI->getNumOperands() ||
418 MI->getOperand(OpNo).isMetadata()) {
421 unsigned OpFlags = MI->getOperand(OpNo).getImm();
422 ++OpNo; // Skip over the ID number.
424 if (Modifier[0] == 'l') // labels are target independent
425 // FIXME: What if the operand isn't an MBB, report error?
426 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
428 if (InlineAsm::isMemKind(OpFlags)) {
429 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
430 Modifier[0] ? Modifier : nullptr,
433 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
434 Modifier[0] ? Modifier : nullptr, OS);
440 raw_string_ostream Msg(msg);
441 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
442 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
449 OS << '\n' << (char)0; // null terminate string.
452 /// EmitInlineAsm - This method formats and emits the specified machine
453 /// instruction that is an inline asm.
454 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
455 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
457 // Count the number of register definitions to find the asm string.
458 unsigned NumDefs = 0;
459 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
461 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
463 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
465 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
466 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
468 // If this asmstr is empty, just print the #APP/#NOAPP markers.
469 // These are useful to see where empty asm's wound up.
470 if (AsmStr[0] == 0) {
471 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
472 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
476 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
477 // enabled, so we use emitRawComment.
478 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
480 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
482 unsigned LocCookie = 0;
483 const MDNode *LocMD = nullptr;
484 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
485 if (MI->getOperand(i-1).isMetadata() &&
486 (LocMD = MI->getOperand(i-1).getMetadata()) &&
487 LocMD->getNumOperands() != 0) {
488 if (const ConstantInt *CI =
489 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
490 LocCookie = CI->getZExtValue();
496 // Emit the inline asm to a temporary string so we can emit it through
498 SmallString<256> StringData;
499 raw_svector_ostream OS(StringData);
501 // The variant of the current asmprinter.
502 int AsmPrinterVariant = MAI->getAssemblerDialect();
503 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
504 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
505 if (InlineAsmVariant == InlineAsm::AD_ATT)
506 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
509 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
511 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
513 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
514 // enabled, so we use emitRawComment.
515 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
519 /// PrintSpecial - Print information related to the specified machine instr
520 /// that is independent of the operand, and may be independent of the instr
521 /// itself. This can be useful for portably encoding the comment character
522 /// or other bits of target-specific knowledge into the asmstrings. The
523 /// syntax used is ${:comment}. Targets can override this to add support
524 /// for their own strange codes.
525 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
526 const char *Code) const {
527 const DataLayout *DL = TM.getDataLayout();
528 if (!strcmp(Code, "private")) {
529 OS << DL->getPrivateGlobalPrefix();
530 } else if (!strcmp(Code, "comment")) {
531 OS << MAI->getCommentString();
532 } else if (!strcmp(Code, "uid")) {
533 // Comparing the address of MI isn't sufficient, because machineinstrs may
534 // be allocated to the same address across functions.
536 // If this is a new LastFn instruction, bump the counter.
537 if (LastMI != MI || LastFn != getFunctionNumber()) {
540 LastFn = getFunctionNumber();
545 raw_string_ostream Msg(msg);
546 Msg << "Unknown special formatter '" << Code
547 << "' for machine instr: " << *MI;
548 report_fatal_error(Msg.str());
552 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
553 /// instruction, using the specified assembler variant. Targets should
554 /// override this to format as appropriate.
555 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
556 unsigned AsmVariant, const char *ExtraCode,
558 // Does this asm operand have a single letter operand modifier?
559 if (ExtraCode && ExtraCode[0]) {
560 if (ExtraCode[1] != 0) return true; // Unknown modifier.
562 const MachineOperand &MO = MI->getOperand(OpNo);
563 switch (ExtraCode[0]) {
565 return true; // Unknown modifier.
566 case 'c': // Substitute immediate value without immediate syntax
567 if (MO.getType() != MachineOperand::MO_Immediate)
571 case 'n': // Negate the immediate constant.
572 if (MO.getType() != MachineOperand::MO_Immediate)
581 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
583 const char *ExtraCode, raw_ostream &O) {
584 // Target doesn't support this yet!
588 void AsmPrinter::emitInlineAsmStart() const {}
590 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
591 const MCSubtargetInfo *EndInfo) const {}