Explicitly pass ownership of the MemoryBuffer to AddNewSourceBuffer using std::unique_ptr
[oota-llvm.git] / lib / CodeGen / AsmPrinter / AsmPrinterInlineAsm.cpp
1 //===-- AsmPrinterInlineAsm.cpp - AsmPrinter Inline Asm Handling ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the inline assembler pieces of the AsmPrinter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/AsmPrinter.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/Twine.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineModuleInfo.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/InlineAsm.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/MC/MCTargetAsmParser.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/SourceMgr.h"
33 #include "llvm/Support/TargetRegistry.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 using namespace llvm;
38
39 #define DEBUG_TYPE "asm-printer"
40
41 namespace {
42   struct SrcMgrDiagInfo {
43     const MDNode *LocInfo;
44     LLVMContext::InlineAsmDiagHandlerTy DiagHandler;
45     void *DiagContext;
46   };
47 }
48
49 /// srcMgrDiagHandler - This callback is invoked when the SourceMgr for an
50 /// inline asm has an error in it.  diagInfo is a pointer to the SrcMgrDiagInfo
51 /// struct above.
52 static void srcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo) {
53   SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
54   assert(DiagInfo && "Diagnostic context not passed down?");
55
56   // If the inline asm had metadata associated with it, pull out a location
57   // cookie corresponding to which line the error occurred on.
58   unsigned LocCookie = 0;
59   if (const MDNode *LocInfo = DiagInfo->LocInfo) {
60     unsigned ErrorLine = Diag.getLineNo()-1;
61     if (ErrorLine >= LocInfo->getNumOperands())
62       ErrorLine = 0;
63
64     if (LocInfo->getNumOperands() != 0)
65       if (const ConstantInt *CI =
66           dyn_cast<ConstantInt>(LocInfo->getOperand(ErrorLine)))
67         LocCookie = CI->getZExtValue();
68   }
69
70   DiagInfo->DiagHandler(Diag, DiagInfo->DiagContext, LocCookie);
71 }
72
73 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
74 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode,
75                                InlineAsm::AsmDialect Dialect) const {
76   assert(!Str.empty() && "Can't emit empty inline asm block");
77
78   // Remember if the buffer is nul terminated or not so we can avoid a copy.
79   bool isNullTerminated = Str.back() == 0;
80   if (isNullTerminated)
81     Str = Str.substr(0, Str.size()-1);
82
83   // If the output streamer does not have mature MC support or the integrated
84   // assembler has been disabled, just emit the blob textually.
85   // Otherwise parse the asm and emit it via MC support.
86   // This is useful in case the asm parser doesn't handle something but the
87   // system assembler does.
88   const MCAsmInfo *MCAI = TM.getMCAsmInfo();
89   assert(MCAI && "No MCAsmInfo");
90   if (!MCAI->useIntegratedAssembler() &&
91       !OutStreamer.isIntegratedAssemblerRequired()) {
92     OutStreamer.EmitRawText(Str);
93     emitInlineAsmEnd(TM.getSubtarget<MCSubtargetInfo>(), nullptr);
94     return;
95   }
96
97   SourceMgr SrcMgr;
98   SrcMgrDiagInfo DiagInfo;
99
100   // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
101   LLVMContext &LLVMCtx = MMI->getModule()->getContext();
102   bool HasDiagHandler = false;
103   if (LLVMCtx.getInlineAsmDiagnosticHandler() != nullptr) {
104     // If the source manager has an issue, we arrange for srcMgrDiagHandler
105     // to be invoked, getting DiagInfo passed into it.
106     DiagInfo.LocInfo = LocMDNode;
107     DiagInfo.DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler();
108     DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
109     SrcMgr.setDiagHandler(srcMgrDiagHandler, &DiagInfo);
110     HasDiagHandler = true;
111   }
112
113   std::unique_ptr<MemoryBuffer> Buffer(
114       isNullTerminated ? MemoryBuffer::getMemBuffer(Str, "<inline asm>")
115                        : MemoryBuffer::getMemBufferCopy(Str, "<inline asm>"));
116
117   // Tell SrcMgr about this buffer, it takes ownership of the buffer.
118   SrcMgr.AddNewSourceBuffer(std::move(Buffer), SMLoc());
119
120   std::unique_ptr<MCAsmParser> Parser(
121       createMCAsmParser(SrcMgr, OutContext, OutStreamer, *MAI));
122
123   // Initialize the parser with a fresh subtarget info. It is better to use a
124   // new STI here because the parser may modify it and we do not want those
125   // modifications to persist after parsing the inlineasm. The modifications
126   // made by the parser will be seen by the code emitters because it passes
127   // the current STI down to the EncodeInstruction() method.
128   std::unique_ptr<MCSubtargetInfo> STI(TM.getTarget().createMCSubtargetInfo(
129       TM.getTargetTriple(), TM.getTargetCPU(), TM.getTargetFeatureString()));
130
131   // Preserve a copy of the original STI because the parser may modify it.  For
132   // example, when switching between arm and thumb mode. If the target needs to
133   // emit code to return to the original state it can do so in
134   // emitInlineAsmEnd().
135   MCSubtargetInfo STIOrig = *STI;
136
137   MCTargetOptions MCOptions;
138   if (MF)
139     MCOptions = MF->getTarget().Options.MCOptions;
140   std::unique_ptr<MCTargetAsmParser> TAP(
141       TM.getTarget().createMCAsmParser(*STI, *Parser, *MII, MCOptions));
142   if (!TAP)
143     report_fatal_error("Inline asm not supported by this streamer because"
144                        " we don't have an asm parser for this target\n");
145   Parser->setAssemblerDialect(Dialect);
146   Parser->setTargetParser(*TAP.get());
147
148   // Don't implicitly switch to the text section before the asm.
149   int Res = Parser->Run(/*NoInitialTextSection*/ true,
150                         /*NoFinalize*/ true);
151   emitInlineAsmEnd(STIOrig, STI.get());
152   if (Res && !HasDiagHandler)
153     report_fatal_error("Error parsing inline asm\n");
154 }
155
156 static void EmitMSInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
157                                MachineModuleInfo *MMI, int InlineAsmVariant,
158                                AsmPrinter *AP, unsigned LocCookie,
159                                raw_ostream &OS) {
160   // Switch to the inline assembly variant.
161   OS << "\t.intel_syntax\n\t";
162
163   const char *LastEmitted = AsmStr; // One past the last character emitted.
164   unsigned NumOperands = MI->getNumOperands();
165
166   while (*LastEmitted) {
167     switch (*LastEmitted) {
168     default: {
169       // Not a special case, emit the string section literally.
170       const char *LiteralEnd = LastEmitted+1;
171       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
172              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
173         ++LiteralEnd;
174
175       OS.write(LastEmitted, LiteralEnd-LastEmitted);
176       LastEmitted = LiteralEnd;
177       break;
178     }
179     case '\n':
180       ++LastEmitted;   // Consume newline character.
181       OS << '\n';      // Indent code with newline.
182       break;
183     case '$': {
184       ++LastEmitted;   // Consume '$' character.
185       bool Done = true;
186
187       // Handle escapes.
188       switch (*LastEmitted) {
189       default: Done = false; break;
190       case '$':
191         ++LastEmitted;  // Consume second '$' character.
192         break;
193       }
194       if (Done) break;
195
196       const char *IDStart = LastEmitted;
197       const char *IDEnd = IDStart;
198       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
199
200       unsigned Val;
201       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
202         report_fatal_error("Bad $ operand number in inline asm string: '" +
203                            Twine(AsmStr) + "'");
204       LastEmitted = IDEnd;
205
206       if (Val >= NumOperands-1)
207         report_fatal_error("Invalid $ operand number in inline asm string: '" +
208                            Twine(AsmStr) + "'");
209
210       // Okay, we finally have a value number.  Ask the target to print this
211       // operand!
212       unsigned OpNo = InlineAsm::MIOp_FirstOperand;
213
214       bool Error = false;
215
216       // Scan to find the machine operand number for the operand.
217       for (; Val; --Val) {
218         if (OpNo >= MI->getNumOperands()) break;
219         unsigned OpFlags = MI->getOperand(OpNo).getImm();
220         OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
221       }
222
223       // We may have a location metadata attached to the end of the
224       // instruction, and at no point should see metadata at any
225       // other point while processing. It's an error if so.
226       if (OpNo >= MI->getNumOperands() ||
227           MI->getOperand(OpNo).isMetadata()) {
228         Error = true;
229       } else {
230         unsigned OpFlags = MI->getOperand(OpNo).getImm();
231         ++OpNo;  // Skip over the ID number.
232
233         if (InlineAsm::isMemKind(OpFlags)) {
234           Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
235                                             /*Modifier*/ nullptr, OS);
236         } else {
237           Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
238                                       /*Modifier*/ nullptr, OS);
239         }
240       }
241       if (Error) {
242         std::string msg;
243         raw_string_ostream Msg(msg);
244         Msg << "invalid operand in inline asm: '" << AsmStr << "'";
245         MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
246       }
247       break;
248     }
249     }
250   }
251   OS << "\n\t.att_syntax\n" << (char)0;  // null terminate string.
252 }
253
254 static void EmitGCCInlineAsmStr(const char *AsmStr, const MachineInstr *MI,
255                                 MachineModuleInfo *MMI, int InlineAsmVariant,
256                                 int AsmPrinterVariant, AsmPrinter *AP,
257                                 unsigned LocCookie, raw_ostream &OS) {
258   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
259   const char *LastEmitted = AsmStr; // One past the last character emitted.
260   unsigned NumOperands = MI->getNumOperands();
261
262   OS << '\t';
263
264   while (*LastEmitted) {
265     switch (*LastEmitted) {
266     default: {
267       // Not a special case, emit the string section literally.
268       const char *LiteralEnd = LastEmitted+1;
269       while (*LiteralEnd && *LiteralEnd != '{' && *LiteralEnd != '|' &&
270              *LiteralEnd != '}' && *LiteralEnd != '$' && *LiteralEnd != '\n')
271         ++LiteralEnd;
272       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
273         OS.write(LastEmitted, LiteralEnd-LastEmitted);
274       LastEmitted = LiteralEnd;
275       break;
276     }
277     case '\n':
278       ++LastEmitted;   // Consume newline character.
279       OS << '\n';      // Indent code with newline.
280       break;
281     case '$': {
282       ++LastEmitted;   // Consume '$' character.
283       bool Done = true;
284
285       // Handle escapes.
286       switch (*LastEmitted) {
287       default: Done = false; break;
288       case '$':     // $$ -> $
289         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
290           OS << '$';
291         ++LastEmitted;  // Consume second '$' character.
292         break;
293       case '(':             // $( -> same as GCC's { character.
294         ++LastEmitted;      // Consume '(' character.
295         if (CurVariant != -1)
296           report_fatal_error("Nested variants found in inline asm string: '" +
297                              Twine(AsmStr) + "'");
298         CurVariant = 0;     // We're in the first variant now.
299         break;
300       case '|':
301         ++LastEmitted;  // consume '|' character.
302         if (CurVariant == -1)
303           OS << '|';       // this is gcc's behavior for | outside a variant
304         else
305           ++CurVariant;   // We're in the next variant.
306         break;
307       case ')':         // $) -> same as GCC's } char.
308         ++LastEmitted;  // consume ')' character.
309         if (CurVariant == -1)
310           OS << '}';     // this is gcc's behavior for } outside a variant
311         else
312           CurVariant = -1;
313         break;
314       }
315       if (Done) break;
316
317       bool HasCurlyBraces = false;
318       if (*LastEmitted == '{') {     // ${variable}
319         ++LastEmitted;               // Consume '{' character.
320         HasCurlyBraces = true;
321       }
322
323       // If we have ${:foo}, then this is not a real operand reference, it is a
324       // "magic" string reference, just like in .td files.  Arrange to call
325       // PrintSpecial.
326       if (HasCurlyBraces && *LastEmitted == ':') {
327         ++LastEmitted;
328         const char *StrStart = LastEmitted;
329         const char *StrEnd = strchr(StrStart, '}');
330         if (!StrEnd)
331           report_fatal_error("Unterminated ${:foo} operand in inline asm"
332                              " string: '" + Twine(AsmStr) + "'");
333
334         std::string Val(StrStart, StrEnd);
335         AP->PrintSpecial(MI, OS, Val.c_str());
336         LastEmitted = StrEnd+1;
337         break;
338       }
339
340       const char *IDStart = LastEmitted;
341       const char *IDEnd = IDStart;
342       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
343
344       unsigned Val;
345       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
346         report_fatal_error("Bad $ operand number in inline asm string: '" +
347                            Twine(AsmStr) + "'");
348       LastEmitted = IDEnd;
349
350       char Modifier[2] = { 0, 0 };
351
352       if (HasCurlyBraces) {
353         // If we have curly braces, check for a modifier character.  This
354         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
355         if (*LastEmitted == ':') {
356           ++LastEmitted;    // Consume ':' character.
357           if (*LastEmitted == 0)
358             report_fatal_error("Bad ${:} expression in inline asm string: '" +
359                                Twine(AsmStr) + "'");
360
361           Modifier[0] = *LastEmitted;
362           ++LastEmitted;    // Consume modifier character.
363         }
364
365         if (*LastEmitted != '}')
366           report_fatal_error("Bad ${} expression in inline asm string: '" +
367                              Twine(AsmStr) + "'");
368         ++LastEmitted;    // Consume '}' character.
369       }
370
371       if (Val >= NumOperands-1)
372         report_fatal_error("Invalid $ operand number in inline asm string: '" +
373                            Twine(AsmStr) + "'");
374
375       // Okay, we finally have a value number.  Ask the target to print this
376       // operand!
377       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
378         unsigned OpNo = InlineAsm::MIOp_FirstOperand;
379
380         bool Error = false;
381
382         // Scan to find the machine operand number for the operand.
383         for (; Val; --Val) {
384           if (OpNo >= MI->getNumOperands()) break;
385           unsigned OpFlags = MI->getOperand(OpNo).getImm();
386           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
387         }
388
389         // We may have a location metadata attached to the end of the
390         // instruction, and at no point should see metadata at any
391         // other point while processing. It's an error if so.
392         if (OpNo >= MI->getNumOperands() ||
393             MI->getOperand(OpNo).isMetadata()) {
394           Error = true;
395         } else {
396           unsigned OpFlags = MI->getOperand(OpNo).getImm();
397           ++OpNo;  // Skip over the ID number.
398
399           if (Modifier[0] == 'l')  // labels are target independent
400             // FIXME: What if the operand isn't an MBB, report error?
401             OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
402           else {
403             if (InlineAsm::isMemKind(OpFlags)) {
404               Error = AP->PrintAsmMemoryOperand(MI, OpNo, InlineAsmVariant,
405                                                 Modifier[0] ? Modifier : nullptr,
406                                                 OS);
407             } else {
408               Error = AP->PrintAsmOperand(MI, OpNo, InlineAsmVariant,
409                                           Modifier[0] ? Modifier : nullptr, OS);
410             }
411           }
412         }
413         if (Error) {
414           std::string msg;
415           raw_string_ostream Msg(msg);
416           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
417           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
418         }
419       }
420       break;
421     }
422     }
423   }
424   OS << '\n' << (char)0;  // null terminate string.
425 }
426
427 /// EmitInlineAsm - This method formats and emits the specified machine
428 /// instruction that is an inline asm.
429 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
430   assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
431
432   // Count the number of register definitions to find the asm string.
433   unsigned NumDefs = 0;
434   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
435        ++NumDefs)
436     assert(NumDefs != MI->getNumOperands()-2 && "No asm string?");
437
438   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
439
440   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
441   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
442
443   // If this asmstr is empty, just print the #APP/#NOAPP markers.
444   // These are useful to see where empty asm's wound up.
445   if (AsmStr[0] == 0) {
446     OutStreamer.emitRawComment(MAI->getInlineAsmStart());
447     OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
448     return;
449   }
450
451   // Emit the #APP start marker.  This has to happen even if verbose-asm isn't
452   // enabled, so we use emitRawComment.
453   OutStreamer.emitRawComment(MAI->getInlineAsmStart());
454
455   // Get the !srcloc metadata node if we have it, and decode the loc cookie from
456   // it.
457   unsigned LocCookie = 0;
458   const MDNode *LocMD = nullptr;
459   for (unsigned i = MI->getNumOperands(); i != 0; --i) {
460     if (MI->getOperand(i-1).isMetadata() &&
461         (LocMD = MI->getOperand(i-1).getMetadata()) &&
462         LocMD->getNumOperands() != 0) {
463       if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
464         LocCookie = CI->getZExtValue();
465         break;
466       }
467     }
468   }
469
470   // Emit the inline asm to a temporary string so we can emit it through
471   // EmitInlineAsm.
472   SmallString<256> StringData;
473   raw_svector_ostream OS(StringData);
474
475   // The variant of the current asmprinter.
476   int AsmPrinterVariant = MAI->getAssemblerDialect();
477   InlineAsm::AsmDialect InlineAsmVariant = MI->getInlineAsmDialect();
478   AsmPrinter *AP = const_cast<AsmPrinter*>(this);
479   if (InlineAsmVariant == InlineAsm::AD_ATT)
480     EmitGCCInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AsmPrinterVariant,
481                         AP, LocCookie, OS);
482   else
483     EmitMSInlineAsmStr(AsmStr, MI, MMI, InlineAsmVariant, AP, LocCookie, OS);
484
485   EmitInlineAsm(OS.str(), LocMD, MI->getInlineAsmDialect());
486
487   // Emit the #NOAPP end marker.  This has to happen even if verbose-asm isn't
488   // enabled, so we use emitRawComment.
489   OutStreamer.emitRawComment(MAI->getInlineAsmEnd());
490 }
491
492
493 /// PrintSpecial - Print information related to the specified machine instr
494 /// that is independent of the operand, and may be independent of the instr
495 /// itself.  This can be useful for portably encoding the comment character
496 /// or other bits of target-specific knowledge into the asmstrings.  The
497 /// syntax used is ${:comment}.  Targets can override this to add support
498 /// for their own strange codes.
499 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
500                               const char *Code) const {
501   const DataLayout *DL = TM.getSubtargetImpl()->getDataLayout();
502   if (!strcmp(Code, "private")) {
503     OS << DL->getPrivateGlobalPrefix();
504   } else if (!strcmp(Code, "comment")) {
505     OS << MAI->getCommentString();
506   } else if (!strcmp(Code, "uid")) {
507     // Comparing the address of MI isn't sufficient, because machineinstrs may
508     // be allocated to the same address across functions.
509
510     // If this is a new LastFn instruction, bump the counter.
511     if (LastMI != MI || LastFn != getFunctionNumber()) {
512       ++Counter;
513       LastMI = MI;
514       LastFn = getFunctionNumber();
515     }
516     OS << Counter;
517   } else {
518     std::string msg;
519     raw_string_ostream Msg(msg);
520     Msg << "Unknown special formatter '" << Code
521          << "' for machine instr: " << *MI;
522     report_fatal_error(Msg.str());
523   }
524 }
525
526 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
527 /// instruction, using the specified assembler variant.  Targets should
528 /// override this to format as appropriate.
529 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
530                                  unsigned AsmVariant, const char *ExtraCode,
531                                  raw_ostream &O) {
532   // Does this asm operand have a single letter operand modifier?
533   if (ExtraCode && ExtraCode[0]) {
534     if (ExtraCode[1] != 0) return true; // Unknown modifier.
535
536     const MachineOperand &MO = MI->getOperand(OpNo);
537     switch (ExtraCode[0]) {
538     default:
539       return true;  // Unknown modifier.
540     case 'c': // Substitute immediate value without immediate syntax
541       if (MO.getType() != MachineOperand::MO_Immediate)
542         return true;
543       O << MO.getImm();
544       return false;
545     case 'n':  // Negate the immediate constant.
546       if (MO.getType() != MachineOperand::MO_Immediate)
547         return true;
548       O << -MO.getImm();
549       return false;
550     }
551   }
552   return true;
553 }
554
555 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
556                                        unsigned AsmVariant,
557                                        const char *ExtraCode, raw_ostream &O) {
558   // Target doesn't support this yet!
559   return true;
560 }
561
562 void AsmPrinter::emitInlineAsmEnd(const MCSubtargetInfo &StartInfo,
563                                   const MCSubtargetInfo *EndInfo) const {}