1 //===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the inline assembler pieces of the AsmPrinter class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/ADT/SmallString.h"
14 #include "llvm/ADT/SmallVector.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/CodeGen/TargetInstrInfo.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DiagnosticInfo.h"
25 #include "llvm/IR/InlineAsm.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/MC/TargetRegistry.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetMachine.h"
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "asm-printer"
42 
43 unsigned AsmPrinter::addInlineAsmDiagBuffer(StringRef AsmStr,
44                                             const MDNode *LocMDNode) const {
45   MCContext &Context = MMI->getContext();
46   Context.initInlineSourceManager();
47   SourceMgr &SrcMgr = *Context.getInlineSourceManager();
48   std::vector<const MDNode *> &LocInfos = Context.getLocInfos();
49 
50   std::unique_ptr<MemoryBuffer> Buffer;
51   // The inline asm source manager will outlive AsmStr, so make a copy of the
52   // string for SourceMgr to own.
53   Buffer = MemoryBuffer::getMemBufferCopy(AsmStr, "<inline asm>");
54 
55   // Tell SrcMgr about this buffer, it takes ownership of the buffer.
56   unsigned BufNum = SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
57 
58   // Store LocMDNode in DiagInfo, using BufNum as an identifier.
59   if (LocMDNode) {
60     LocInfos.resize(BufNum);
61     LocInfos[BufNum - 1] = LocMDNode;
62   }
63 
64   return BufNum;
65 }
66 
67 
68 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
69 void AsmPrinter::emitInlineAsm(StringRef Str, const MCSubtargetInfo &STI,
70                                const MCTargetOptions &MCOptions,
71                                const MDNode *LocMDNode,
72                                InlineAsm::AsmDialect Dialect) const {
73   assert(!Str.empty() && "Can't emit empty inline asm block");
74 
75   // Remember if the buffer is nul terminated or not so we can avoid a copy.
76   bool isNullTerminated = Str.back() == 0;
77   if (isNullTerminated)
78     Str = Str.substr(0, Str.size()-1);
79 
80   // If the output streamer does not have mature MC support or the integrated
81   // assembler has been disabled or not required, just emit the blob textually.
82   // Otherwise parse the asm and emit it via MC support.
83   // This is useful in case the asm parser doesn't handle something but the
84   // system assembler does.
85   const MCAsmInfo *MCAI = TM.getMCAsmInfo();
86   assert(MCAI && "No MCAsmInfo");
87   if (!MCAI->useIntegratedAssembler() &&
88       !MCAI->parseInlineAsmUsingAsmParser() &&
89       !OutStreamer->isIntegratedAssemblerRequired()) {
90     emitInlineAsmStart();
91     OutStreamer->emitRawText(Str);
92     emitInlineAsmEnd(STI, nullptr);
93     return;
94   }
95 
96   unsigned BufNum = addInlineAsmDiagBuffer(Str, LocMDNode);
97   SourceMgr &SrcMgr = *MMI->getContext().getInlineSourceManager();
98   SrcMgr.setIncludeDirs(MCOptions.IASSearchPaths);
99 
100   std::unique_ptr<MCAsmParser> Parser(
101       createMCAsmParser(SrcMgr, OutContext, *OutStreamer, *MAI, BufNum));
102 
103   // Do not use assembler-level information for parsing inline assembly.
104   OutStreamer->setUseAssemblerInfoForParsing(false);
105 
106   // We create a new MCInstrInfo here since we might be at the module level
107   // and not have a MachineFunction to initialize the TargetInstrInfo from and
108   // we only need MCInstrInfo for asm parsing. We create one unconditionally
109   // because it's not subtarget dependent.
110   std::unique_ptr<MCInstrInfo> MII(TM.getTarget().createMCInstrInfo());
111   assert(MII && "Failed to create instruction info");
112   std::unique_ptr<MCTargetAsmParser> TAP(TM.getTarget().createMCAsmParser(
113       STI, *Parser, *MII, MCOptions));
114   if (!TAP)
115     report_fatal_error("Inline asm not supported by this streamer because"
116                        " we don't have an asm parser for this target\n");
117   Parser->setAssemblerDialect(Dialect);
118   Parser->setTargetParser(*TAP.get());
119   // Enable lexing Masm binary and hex integer literals in intel inline
120   // assembly.
121   if (Dialect == InlineAsm::AD_Intel)
122     Parser->getLexer().setLexMasmIntegers(true);
123 
124   emitInlineAsmStart();
125   // Don't implicitly switch to the text section before the asm.
126   (void)Parser->Run(/*NoInitialTextSection*/ true,
127                     /*NoFinalize*/ true);
128   emitInlineAsmEnd(STI, &TAP->getSTI());
129 }
130 
131 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
132                                MachineModuleInfo *MMI, const MCAsmInfo *MAI,
133                                AsmPrinter *AP, uint64_t LocCookie,
134                                raw_ostream &OS) {
135   // Switch to the inline assembly variant.
136   OS << "\t.intel_syntax\n\t";
137 
138   int CurVariant = -1; // The number of the {.|.|.} region we are in.
139   const char *LastEmitted = AsmStr; // One past the last character emitted.
140   unsigned NumOperands = MI->getNumOperands();
141   int AsmPrinterVariant = 1; // X86MCAsmInfo.cpp's AsmWriterFlavorTy::Intel.
142 
143   while (*LastEmitted) {
144     switch (*LastEmitted) {
145     default: {
146       // Not a special case, emit the string section literally.
147       const char *LiteralEnd = LastEmitted+1;
148       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
149              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
150         ++LiteralEnd;
151       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
152         OS.write(LastEmitted, LiteralEnd - LastEmitted);
153       LastEmitted = LiteralEnd;
154       break;
155     }
156     case '\n':
157       ++LastEmitted;   // Consume newline character.
158       OS << '\n';      // Indent code with newline.
159       break;
160     case '$': {
161       ++LastEmitted;   // Consume '$' character.
162       bool Done = true;
163 
164       // Handle escapes.
165       switch (*LastEmitted) {
166       default: Done = false; break;
167       case '$':
168         ++LastEmitted;  // Consume second '$' character.
169         break;
170       case '(':        // $( -> same as GCC's { character.
171         ++LastEmitted; // Consume '(' character.
172         if (CurVariant != -1)
173           report_fatal_error("Nested variants found in inline asm string: '" +
174                              Twine(AsmStr) + "'");
175         CurVariant = 0; // We're in the first variant now.
176         break;
177       case '|':
178         ++LastEmitted; // Consume '|' character.
179         if (CurVariant == -1)
180           OS << '|'; // This is gcc's behavior for | outside a variant.
181         else
182           ++CurVariant; // We're in the next variant.
183         break;
184       case ')':        // $) -> same as GCC's } char.
185         ++LastEmitted; // Consume ')' character.
186         if (CurVariant == -1)
187           OS << '}'; // This is gcc's behavior for } outside a variant.
188         else
189           CurVariant = -1;
190         break;
191       }
192       if (Done) break;
193 
194       bool HasCurlyBraces = false;
195       if (*LastEmitted == '{') {     // ${variable}
196         ++LastEmitted;               // Consume '{' character.
197         HasCurlyBraces = true;
198       }
199 
200       // If we have ${:foo}, then this is not a real operand reference, it is a
201       // "magic" string reference, just like in .td files.  Arrange to call
202       // PrintSpecial.
203       if (HasCurlyBraces && *LastEmitted == ':') {
204         ++LastEmitted;
205         const char *StrStart = LastEmitted;
206         const char *StrEnd = strchr(StrStart, '}');
207         if (!StrEnd)
208           report_fatal_error("Unterminated ${:foo} operand in inline asm"
209                              " string: '" + Twine(AsmStr) + "'");
210         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
211           AP->PrintSpecial(MI, OS, StringRef(StrStart, StrEnd - StrStart));
212         LastEmitted = StrEnd+1;
213         break;
214       }
215 
216       const char *IDStart = LastEmitted;
217       const char *IDEnd = IDStart;
218       while (isDigit(*IDEnd))
219         ++IDEnd;
220 
221       unsigned Val;
222       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
223         report_fatal_error("Bad $ operand number in inline asm string: '" +
224                            Twine(AsmStr) + "'");
225       LastEmitted = IDEnd;
226 
227       if (Val >= NumOperands - 1)
228         report_fatal_error("Invalid $ operand number in inline asm string: '" +
229                            Twine(AsmStr) + "'");
230 
231       char Modifier[2] = { 0, 0 };
232 
233       if (HasCurlyBraces) {
234         // If we have curly braces, check for a modifier character.  This
235         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
236         if (*LastEmitted == ':') {
237           ++LastEmitted;    // Consume ':' character.
238           if (*LastEmitted == 0)
239             report_fatal_error("Bad ${:} expression in inline asm string: '" +
240                                Twine(AsmStr) + "'");
241 
242           Modifier[0] = *LastEmitted;
243           ++LastEmitted;    // Consume modifier character.
244         }
245 
246         if (*LastEmitted != '}')
247           report_fatal_error("Bad ${} expression in inline asm string: '" +
248                              Twine(AsmStr) + "'");
249         ++LastEmitted;    // Consume '}' character.
250       }
251 
252       // Okay, we finally have a value number.  Ask the target to print this
253       // operand!
254       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
255         unsigned OpNo = InlineAsm::MIOp_FirstOperand;
256 
257         bool Error = false;
258 
259         // Scan to find the machine operand number for the operand.
260         for (; Val; --Val) {
261           if (OpNo >= MI->getNumOperands())
262             break;
263           unsigned OpFlags = MI->getOperand(OpNo).getImm();
264           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
265         }
266 
267         // We may have a location metadata attached to the end of the
268         // instruction, and at no point should see metadata at any
269         // other point while processing. It's an error if so.
270         if (OpNo >= MI->getNumOperands() || MI->getOperand(OpNo).isMetadata()) {
271           Error = true;
272         } else {
273           unsigned OpFlags = MI->getOperand(OpNo).getImm();
274           ++OpNo; // Skip over the ID number.
275 
276           if (InlineAsm::isMemKind(OpFlags)) {
277             Error = AP->PrintAsmMemoryOperand(
278                 MI, OpNo, Modifier[0] ? Modifier : nullptr, OS);
279           } else {
280             Error = AP->PrintAsmOperand(MI, OpNo,
281                                         Modifier[0] ? Modifier : nullptr, OS);
282           }
283         }
284         if (Error) {
285           std::string msg;
286           raw_string_ostream Msg(msg);
287           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
288           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
289         }
290       }
291       break;
292     }
293     }
294   }
295   OS << "\n\t.att_syntax\n" << (char)0;  // null terminate string.
296 }
297 
298 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
299                                 MachineModuleInfo *MMI, const MCAsmInfo *MAI,
300                                 AsmPrinter *AP, uint64_t LocCookie,
301                                 raw_ostream &OS) {
302   int CurVariant = -1; // The number of the {.|.|.} region we are in.
303   const char *LastEmitted = AsmStr; // One past the last character emitted.
304   unsigned NumOperands = MI->getNumOperands();
305   int AsmPrinterVariant = MMI->getTarget().unqualifiedInlineAsmVariant();
306 
307   if (MAI->getEmitGNUAsmStartIndentationMarker())
308     OS << '\t';
309 
310   while (*LastEmitted) {
311     switch (*LastEmitted) {
312     default: {
313       // Not a special case, emit the string section literally.
314       const char *LiteralEnd = LastEmitted+1;
315       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
316              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
317         ++LiteralEnd;
318       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
319         OS.write(LastEmitted, LiteralEnd - LastEmitted);
320       LastEmitted = LiteralEnd;
321       break;
322     }
323     case '\n':
324       ++LastEmitted;   // Consume newline character.
325       OS << '\n';      // Indent code with newline.
326       break;
327     case '$': {
328       ++LastEmitted;   // Consume '$' character.
329       bool Done = true;
330 
331       // Handle escapes.
332       switch (*LastEmitted) {
333       default: Done = false; break;
334       case '$':     // $$ -> $
335         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
336           OS << '$';
337         ++LastEmitted;  // Consume second '$' character.
338         break;
339       case '(':        // $( -> same as GCC's { character.
340         ++LastEmitted; // Consume '(' character.
341         if (CurVariant != -1)
342           report_fatal_error("Nested variants found in inline asm string: '" +
343                              Twine(AsmStr) + "'");
344         CurVariant = 0; // We're in the first variant now.
345         break;
346       case '|':
347         ++LastEmitted; // Consume '|' character.
348         if (CurVariant == -1)
349           OS << '|'; // This is gcc's behavior for | outside a variant.
350         else
351           ++CurVariant; // We're in the next variant.
352         break;
353       case ')':        // $) -> same as GCC's } char.
354         ++LastEmitted; // Consume ')' character.
355         if (CurVariant == -1)
356           OS << '}'; // This is gcc's behavior for } outside a variant.
357         else
358           CurVariant = -1;
359         break;
360       }
361       if (Done) break;
362 
363       bool HasCurlyBraces = false;
364       if (*LastEmitted == '{') {     // ${variable}
365         ++LastEmitted;               // Consume '{' character.
366         HasCurlyBraces = true;
367       }
368 
369       // If we have ${:foo}, then this is not a real operand reference, it is a
370       // "magic" string reference, just like in .td files.  Arrange to call
371       // PrintSpecial.
372       if (HasCurlyBraces && *LastEmitted == ':') {
373         ++LastEmitted;
374         const char *StrStart = LastEmitted;
375         const char *StrEnd = strchr(StrStart, '}');
376         if (!StrEnd)
377           report_fatal_error("Unterminated ${:foo} operand in inline asm"
378                              " string: '" + Twine(AsmStr) + "'");
379         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
380           AP->PrintSpecial(MI, OS, StringRef(StrStart, StrEnd - StrStart));
381         LastEmitted = StrEnd+1;
382         break;
383       }
384 
385       const char *IDStart = LastEmitted;
386       const char *IDEnd = IDStart;
387       while (isDigit(*IDEnd))
388         ++IDEnd;
389 
390       unsigned Val;
391       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
392         report_fatal_error("Bad $ operand number in inline asm string: '" +
393                            Twine(AsmStr) + "'");
394       LastEmitted = IDEnd;
395 
396       if (Val >= NumOperands - 1)
397         report_fatal_error("Invalid $ operand number in inline asm string: '" +
398                            Twine(AsmStr) + "'");
399 
400       char Modifier[2] = { 0, 0 };
401 
402       if (HasCurlyBraces) {
403         // If we have curly braces, check for a modifier character.  This
404         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
405         if (*LastEmitted == ':') {
406           ++LastEmitted;    // Consume ':' character.
407           if (*LastEmitted == 0)
408             report_fatal_error("Bad ${:} expression in inline asm string: '" +
409                                Twine(AsmStr) + "'");
410 
411           Modifier[0] = *LastEmitted;
412           ++LastEmitted;    // Consume modifier character.
413         }
414 
415         if (*LastEmitted != '}')
416           report_fatal_error("Bad ${} expression in inline asm string: '" +
417                              Twine(AsmStr) + "'");
418         ++LastEmitted;    // Consume '}' character.
419       }
420 
421       // Okay, we finally have a value number.  Ask the target to print this
422       // operand!
423       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
424         unsigned OpNo = InlineAsm::MIOp_FirstOperand;
425 
426         bool Error = false;
427 
428         // Scan to find the machine operand number for the operand.
429         for (; Val; --Val) {
430           if (OpNo >= MI->getNumOperands())
431             break;
432           unsigned OpFlags = MI->getOperand(OpNo).getImm();
433           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
434         }
435 
436         // We may have a location metadata attached to the end of the
437         // instruction, and at no point should see metadata at any
438         // other point while processing. It's an error if so.
439         if (OpNo >= MI->getNumOperands() || MI->getOperand(OpNo).isMetadata()) {
440           Error = true;
441         } else {
442           unsigned OpFlags = MI->getOperand(OpNo).getImm();
443           ++OpNo; // Skip over the ID number.
444 
445           // FIXME: Shouldn't arch-independent output template handling go into
446           // PrintAsmOperand?
447           // Labels are target independent.
448           if (MI->getOperand(OpNo).isBlockAddress()) {
449             const BlockAddress *BA = MI->getOperand(OpNo).getBlockAddress();
450             MCSymbol *Sym = AP->GetBlockAddressSymbol(BA);
451             Sym->print(OS, AP->MAI);
452             MMI->getContext().registerInlineAsmLabel(Sym);
453           } else if (MI->getOperand(OpNo).isMBB()) {
454             const MCSymbol *Sym = MI->getOperand(OpNo).getMBB()->getSymbol();
455             Sym->print(OS, AP->MAI);
456           } else if (Modifier[0] == 'l') {
457             Error = true;
458           } else if (InlineAsm::isMemKind(OpFlags)) {
459             Error = AP->PrintAsmMemoryOperand(
460                 MI, OpNo, Modifier[0] ? Modifier : nullptr, OS);
461           } else {
462             Error = AP->PrintAsmOperand(MI, OpNo,
463                                         Modifier[0] ? Modifier : nullptr, OS);
464           }
465         }
466         if (Error) {
467           std::string msg;
468           raw_string_ostream Msg(msg);
469           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
470           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
471         }
472       }
473       break;
474     }
475     }
476   }
477   OS << '\n' << (char)0;  // null terminate string.
478 }
479 
480 /// This method formats and emits the specified machine instruction that is an
481 /// inline asm.
482 void AsmPrinter::emitInlineAsm(const MachineInstr *MI) const {
483   assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
484 
485   // Count the number of register definitions to find the asm string.
486   unsigned NumDefs = 0;
487   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
488        ++NumDefs)
489     assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
490 
491   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
492 
493   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
494   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
495 
496   // If this asmstr is empty, just print the #APP/#NOAPP markers.
497   // These are useful to see where empty asm's wound up.
498   if (AsmStr[0] == 0) {
499     OutStreamer->emitRawComment(MAI->getInlineAsmStart());
500     OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
501     return;
502   }
503 
504   // Emit the #APP start marker.  This has to happen even if verbose-asm isn't
505   // enabled, so we use emitRawComment.
506   OutStreamer->emitRawComment(MAI->getInlineAsmStart());
507 
508   // Get the !srcloc metadata node if we have it, and decode the loc cookie from
509   // it.
510   uint64_t LocCookie = 0;
511   const MDNode *LocMD = nullptr;
512   for (unsigned i = MI->getNumOperands(); i != 0; --i) {
513     if (MI->getOperand(i-1).isMetadata() &&
514         (LocMD = MI->getOperand(i-1).getMetadata()) &&
515         LocMD->getNumOperands() != 0) {
516       if (const ConstantInt *CI =
517               mdconst::dyn_extract<ConstantInt>(LocMD->getOperand(0))) {
518         LocCookie = CI->getZExtValue();
519         break;
520       }
521     }
522   }
523 
524   // Emit the inline asm to a temporary string so we can emit it through
525   // EmitInlineAsm.
526   SmallString<256> StringData;
527   raw_svector_ostream OS(StringData);
528 
529   AsmPrinter *AP = const_cast<AsmPrinter*>(this);
530   if (MI->getInlineAsmDialect() == InlineAsm::AD_ATT)
531     EmitGCCInlineAsmStr(AsmStr, MI, MMI, MAI, AP, LocCookie, OS);
532   else
533     EmitMSInlineAsmStr(AsmStr, MI, MMI, MAI, AP, LocCookie, OS);
534 
535   // Emit warnings if we use reserved registers on the clobber list, as
536   // that might lead to undefined behaviour.
537   SmallVector<Register, 8> RestrRegs;
538   const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
539   // Start with the first operand descriptor, and iterate over them.
540   for (unsigned I = InlineAsm::MIOp_FirstOperand, NumOps = MI->getNumOperands();
541        I < NumOps; ++I) {
542     const MachineOperand &MO = MI->getOperand(I);
543     if (!MO.isImm())
544       continue;
545     unsigned Flags = MO.getImm();
546     if (InlineAsm::getKind(Flags) == InlineAsm::Kind_Clobber) {
547       Register Reg = MI->getOperand(I + 1).getReg();
548       if (!TRI->isAsmClobberable(*MF, Reg))
549         RestrRegs.push_back(Reg);
550     }
551     // Skip to one before the next operand descriptor, if it exists.
552     I += InlineAsm::getNumOperandRegisters(Flags);
553   }
554 
555   if (!RestrRegs.empty()) {
556     std::string Msg = "inline asm clobber list contains reserved registers: ";
557     ListSeparator LS;
558     for (const Register &RR : RestrRegs) {
559       Msg += LS;
560       Msg += TRI->getName(RR);
561     }
562     const char *Note =
563         "Reserved registers on the clobber list may not be "
564         "preserved across the asm statement, and clobbering them may "
565         "lead to undefined behaviour.";
566     MMI->getModule()->getContext().diagnose(DiagnosticInfoInlineAsm(
567         LocCookie, Msg, DiagnosticSeverity::DS_Warning));
568     MMI->getModule()->getContext().diagnose(
569         DiagnosticInfoInlineAsm(LocCookie, Note, DiagnosticSeverity::DS_Note));
570   }
571 
572   emitInlineAsm(OS.str(), getSubtargetInfo(), TM.Options.MCOptions, LocMD,
573                 MI->getInlineAsmDialect());
574 
575   // Emit the #NOAPP end marker.  This has to happen even if verbose-asm isn't
576   // enabled, so we use emitRawComment.
577   OutStreamer->emitRawComment(MAI->getInlineAsmEnd());
578 }
579 
580 /// PrintSpecial - Print information related to the specified machine instr
581 /// that is independent of the operand, and may be independent of the instr
582 /// itself.  This can be useful for portably encoding the comment character
583 /// or other bits of target-specific knowledge into the asmstrings.  The
584 /// syntax used is ${:comment}.  Targets can override this to add support
585 /// for their own strange codes.
586 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
587                               StringRef Code) const {
588   if (Code == "private") {
589     const DataLayout &DL = MF->getDataLayout();
590     OS << DL.getPrivateGlobalPrefix();
591   } else if (Code == "comment") {
592     OS << MAI->getCommentString();
593   } else if (Code == "uid") {
594     // Comparing the address of MI isn't sufficient, because machineinstrs may
595     // be allocated to the same address across functions.
596 
597     // If this is a new LastFn instruction, bump the counter.
598     if (LastMI != MI || LastFn != getFunctionNumber()) {
599       ++Counter;
600       LastMI = MI;
601       LastFn = getFunctionNumber();
602     }
603     OS << Counter;
604   } else {
605     std::string msg;
606     raw_string_ostream Msg(msg);
607     Msg << "Unknown special formatter '" << Code
608          << "' for machine instr: " << *MI;
609     report_fatal_error(Twine(Msg.str()));
610   }
611 }
612 
613 void AsmPrinter::PrintSymbolOperand(const MachineOperand &MO, raw_ostream &OS) {
614   assert(MO.isGlobal() && "caller should check MO.isGlobal");
615   getSymbolPreferLocal(*MO.getGlobal())->print(OS, MAI);
616   printOffset(MO.getOffset(), OS);
617 }
618 
619 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
620 /// instruction, using the specified assembler variant.  Targets should
621 /// override this to format as appropriate for machine specific ExtraCodes
622 /// or when the arch-independent handling would be too complex otherwise.
623 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
624                                  const char *ExtraCode, raw_ostream &O) {
625   // Does this asm operand have a single letter operand modifier?
626   if (ExtraCode && ExtraCode[0]) {
627     if (ExtraCode[1] != 0) return true; // Unknown modifier.
628 
629     // https://gcc.gnu.org/onlinedocs/gccint/Output-Template.html
630     const MachineOperand &MO = MI->getOperand(OpNo);
631     switch (ExtraCode[0]) {
632     default:
633       return true;  // Unknown modifier.
634     case 'a': // Print as memory address.
635       if (MO.isReg()) {
636         PrintAsmMemoryOperand(MI, OpNo, nullptr, O);
637         return false;
638       }
639       LLVM_FALLTHROUGH; // GCC allows '%a' to behave like '%c' with immediates.
640     case 'c': // Substitute immediate value without immediate syntax
641       if (MO.isImm()) {
642         O << MO.getImm();
643         return false;
644       }
645       if (MO.isGlobal()) {
646         PrintSymbolOperand(MO, O);
647         return false;
648       }
649       return true;
650     case 'n':  // Negate the immediate constant.
651       if (!MO.isImm())
652         return true;
653       O << -MO.getImm();
654       return false;
655     case 's':  // The GCC deprecated s modifier
656       if (!MO.isImm())
657         return true;
658       O << ((32 - MO.getImm()) & 31);
659       return false;
660     }
661   }
662   return true;
663 }
664 
665 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
666                                        const char *ExtraCode, raw_ostream &O) {
667   // Target doesn't support this yet!
668   return true;
669 }
670 
671 void AsmPrinter::emitInlineAsmStart() const {}
672 
673 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
674                                   const MCSubtargetInfo *EndInfo) const {}
675