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