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 =
156 MF ? static_cast<const MCInstrInfo *>(MF->getSubtarget().getInstrInfo())
157 : static_cast<const MCInstrInfo *>(TM.getTarget().createMCInstrInfo());
158 std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
159 *STI, *Parser, *MII, TM.Options.MCOptions));
161 report_fatal_error("Inline asm not supported by this streamer because"
162 " we don't have an asm parser for this target\n");
163 Parser->setAssemblerDialect(Dialect);
164 Parser->setTargetParser(*TAP.get());
166 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
167 TAP->SetFrameRegister(TRI->getFrameRegister(*MF));
170 emitInlineAsmStart();
171 // Don't implicitly switch to the text section before the asm.
172 int Res = Parser->Run(/*NoInitialTextSection*/ true,
173 /*NoFinalize*/ true);
174 emitInlineAsmEnd(STIOrig, STI.get());
175 if (Res && !HasDiagHandler)
176 report_fatal_error("Error parsing inline asm\n");
179 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
180 MachineModuleInfo *MMI, int InlineAsmVariant,
181 AsmPrinter *AP, unsigned LocCookie,
183 // Switch to the inline assembly variant.
184 OS << "\t.intel_syntax\n\t";
186 const char *LastEmitted = AsmStr; // One past the last character emitted.
187 unsigned NumOperands = MI->getNumOperands();
189 while (*LastEmitted) {
190 switch (*LastEmitted) {
192 // Not a special case, emit the string section literally.
193 const char *LiteralEnd = LastEmitted+1;
194 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
195 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
198 OS.write(LastEmitted, LiteralEnd-LastEmitted);
199 LastEmitted = LiteralEnd;
203 ++LastEmitted; // Consume newline character.
204 OS << '\n'; // Indent code with newline.
207 ++LastEmitted; // Consume '$' character.
211 switch (*LastEmitted) {
212 default: Done = false; break;
214 ++LastEmitted; // Consume second '$' character.
219 const char *IDStart = LastEmitted;
220 const char *IDEnd = IDStart;
221 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
224 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
225 report_fatal_error("Bad $ operand number in inline asm string: '" +
226 Twine(AsmStr) + "'");
229 if (Val >= NumOperands-1)
230 report_fatal_error("Invalid $ operand number in inline asm string: '" +
231 Twine(AsmStr) + "'");
233 // Okay, we finally have a value number. Ask the target to print this
235 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
239 // Scan to find the machine operand number for the operand.
241 if (OpNo >= MI->getNumOperands()) break;
242 unsigned OpFlags = MI->getOperand(OpNo).getImm();
243 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
246 // We may have a location metadata attached to the end of the
247 // instruction, and at no point should see metadata at any
248 // other point while processing. It's an error if so.
249 if (OpNo >= MI->getNumOperands() ||
250 MI->getOperand(OpNo).isMetadata()) {
253 unsigned OpFlags = MI->getOperand(OpNo).getImm();
254 ++OpNo; // Skip over the ID number.
256 if (InlineAsm::isMemKind(OpFlags)) {
257 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
258 /*Modifier*/ nullptr, OS);
260 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
261 /*Modifier*/ nullptr, OS);
266 raw_string_ostream Msg(msg);
267 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
268 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
274 OS << "\n\t.att_syntax\n" << (char)0; // null terminate string.
277 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
278 MachineModuleInfo *MMI, int InlineAsmVariant,
279 int AsmPrinterVariant, AsmPrinter *AP,
280 unsigned LocCookie, raw_ostream &OS) {
281 int CurVariant = -1; // The number of the {.|.|.} region we are in.
282 const char *LastEmitted = AsmStr; // One past the last character emitted.
283 unsigned NumOperands = MI->getNumOperands();
287 while (*LastEmitted) {
288 switch (*LastEmitted) {
290 // Not a special case, emit the string section literally.
291 const char *LiteralEnd = LastEmitted+1;
292 while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
293 *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
295 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
296 OS.write(LastEmitted, LiteralEnd-LastEmitted);
297 LastEmitted = LiteralEnd;
301 ++LastEmitted; // Consume newline character.
302 OS << '\n'; // Indent code with newline.
305 ++LastEmitted; // Consume '$' character.
309 switch (*LastEmitted) {
310 default: Done = false; break;
312 if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
314 ++LastEmitted; // Consume second '$' character.
316 case '(': // $( -> same as GCC's { character.
317 ++LastEmitted; // Consume '(' character.
318 if (CurVariant != -1)
319 report_fatal_error("Nested variants found in inline asm string: '" +
320 Twine(AsmStr) + "'");
321 CurVariant = 0; // We're in the first variant now.
324 ++LastEmitted; // consume '|' character.
325 if (CurVariant == -1)
326 OS << '|'; // this is gcc's behavior for | outside a variant
328 ++CurVariant; // We're in the next variant.
330 case ')': // $) -> same as GCC's } char.
331 ++LastEmitted; // consume ')' character.
332 if (CurVariant == -1)
333 OS << '}'; // this is gcc's behavior for } outside a variant
340 bool HasCurlyBraces = false;
341 if (*LastEmitted == '{') { // ${variable}
342 ++LastEmitted; // Consume '{' character.
343 HasCurlyBraces = true;
346 // If we have ${:foo}, then this is not a real operand reference, it is a
347 // "magic" string reference, just like in .td files. Arrange to call
349 if (HasCurlyBraces && *LastEmitted == ':') {
351 const char *StrStart = LastEmitted;
352 const char *StrEnd = strchr(StrStart, '}');
354 report_fatal_error("Unterminated ${:foo} operand in inline asm"
355 " string: '" + Twine(AsmStr) + "'");
357 std::string Val(StrStart, StrEnd);
358 AP->PrintSpecial(MI, OS, Val.c_str());
359 LastEmitted = StrEnd+1;
363 const char *IDStart = LastEmitted;
364 const char *IDEnd = IDStart;
365 while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
368 if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
369 report_fatal_error("Bad $ operand number in inline asm string: '" +
370 Twine(AsmStr) + "'");
373 char Modifier[2] = { 0, 0 };
375 if (HasCurlyBraces) {
376 // If we have curly braces, check for a modifier character. This
377 // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
378 if (*LastEmitted == ':') {
379 ++LastEmitted; // Consume ':' character.
380 if (*LastEmitted == 0)
381 report_fatal_error("Bad ${:} expression in inline asm string: '" +
382 Twine(AsmStr) + "'");
384 Modifier[0] = *LastEmitted;
385 ++LastEmitted; // Consume modifier character.
388 if (*LastEmitted != '}')
389 report_fatal_error("Bad ${} expression in inline asm string: '" +
390 Twine(AsmStr) + "'");
391 ++LastEmitted; // Consume '}' character.
394 if (Val >= NumOperands-1)
395 report_fatal_error("Invalid $ operand number in inline asm string: '" +
396 Twine(AsmStr) + "'");
398 // Okay, we finally have a value number. Ask the target to print this
400 if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
401 unsigned OpNo = InlineAsm::MIOp_FirstOperand;
405 // Scan to find the machine operand number for the operand.
407 if (OpNo >= MI->getNumOperands()) break;
408 unsigned OpFlags = MI->getOperand(OpNo).getImm();
409 OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
412 // We may have a location metadata attached to the end of the
413 // instruction, and at no point should see metadata at any
414 // other point while processing. It's an error if so.
415 if (OpNo >= MI->getNumOperands() ||
416 MI->getOperand(OpNo).isMetadata()) {
419 unsigned OpFlags = MI->getOperand(OpNo).getImm();
420 ++OpNo; // Skip over the ID number.
422 if (Modifier[0] == 'l') // labels are target independent
423 // FIXME: What if the operand isn't an MBB, report error?
424 OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
426 if (InlineAsm::isMemKind(OpFlags)) {
427 Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
428 Modifier[0] ? Modifier : nullptr,
431 Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
432 Modifier[0] ? Modifier : nullptr, OS);
438 raw_string_ostream Msg(msg);
439 Msg << "invalid operand in inline asm: '" << AsmStr << "'";
440 MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
447 OS << '\n' << (char)0; // null terminate string.
450 /// EmitInlineAsm - This method formats and emits the specified machine
451 /// instruction that is an inline asm.
452 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
453 assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
455 // Count the number of register definitions to find the asm string.
456 unsigned NumDefs = 0;
457 for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
459 assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
461 assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
463 // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
464 const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
466 // If this asmstr is empty, just print the #APP/#NOAPP markers.
467 // These are useful to see where empty asm's wound up.
468 if (AsmStr[0] == 0) {
469 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
470 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
474 // Emit the #APP start marker. This has to happen even if verbose-asm isn't
475 // enabled, so we use emitRawComment.
476 OutStreamer.emitRawComment(MAI->getInlineAsmStart());
478 // Get the !srcloc metadata node if we have it, and decode the loc cookie from
480 unsigned LocCookie = 0;
481 const MDNode *LocMD = nullptr;
482 for (unsigned i = MI->getNumOperands(); i != 0; --i) {
483 if (MI->getOperand(i-1).isMetadata() &&
484 (LocMD = MI->getOperand(i-1).getMetadata()) &&
485 LocMD->getNumOperands() != 0) {
486 if (const ConstantInt *CI =
487 mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
488 LocCookie = CI->getZExtValue();
494 // Emit the inline asm to a temporary string so we can emit it through
496 SmallString<256> StringData;
497 raw_svector_ostream OS(StringData);
499 // The variant of the current asmprinter.
500 int AsmPrinterVariant = MAI->getAssemblerDialect();
501 InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
502 AsmPrinter *AP = const_cast<AsmPrinter*>(this);
503 if (InlineAsmVariant == InlineAsm::AD_ATT)
504 EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
507 EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
509 EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
511 // Emit the #NOAPP end marker. This has to happen even if verbose-asm isn't
512 // enabled, so we use emitRawComment.
513 OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
517 /// PrintSpecial - Print information related to the specified machine instr
518 /// that is independent of the operand, and may be independent of the instr
519 /// itself. This can be useful for portably encoding the comment character
520 /// or other bits of target-specific knowledge into the asmstrings. The
521 /// syntax used is ${:comment}. Targets can override this to add support
522 /// for their own strange codes.
523 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
524 const char *Code) const {
525 const DataLayout *DL = TM.getDataLayout();
526 if (!strcmp(Code, "private")) {
527 OS << DL->getPrivateGlobalPrefix();
528 } else if (!strcmp(Code, "comment")) {
529 OS << MAI->getCommentString();
530 } else if (!strcmp(Code, "uid")) {
531 // Comparing the address of MI isn't sufficient, because machineinstrs may
532 // be allocated to the same address across functions.
534 // If this is a new LastFn instruction, bump the counter.
535 if (LastMI != MI || LastFn != getFunctionNumber()) {
538 LastFn = getFunctionNumber();
543 raw_string_ostream Msg(msg);
544 Msg << "Unknown special formatter '" << Code
545 << "' for machine instr: " << *MI;
546 report_fatal_error(Msg.str());
550 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
551 /// instruction, using the specified assembler variant. Targets should
552 /// override this to format as appropriate.
553 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
554 unsigned AsmVariant, const char *ExtraCode,
556 // Does this asm operand have a single letter operand modifier?
557 if (ExtraCode && ExtraCode[0]) {
558 if (ExtraCode[1] != 0) return true; // Unknown modifier.
560 const MachineOperand &MO = MI->getOperand(OpNo);
561 switch (ExtraCode[0]) {
563 return true; // Unknown modifier.
564 case 'c': // Substitute immediate value without immediate syntax
565 if (MO.getType() != MachineOperand::MO_Immediate)
569 case 'n': // Negate the immediate constant.
570 if (MO.getType() != MachineOperand::MO_Immediate)
579 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
581 const char *ExtraCode, raw_ostream &O) {
582 // Target doesn't support this yet!
586 void AsmPrinter::emitInlineAsmStart() const {}
588 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
589 const MCSubtargetInfo *EndInfo) const {}