25ce25c325ef0670fdc0c5c3a30603f23862f9e3
[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 #define DEBUG_TYPE "asm-printer"
15 #include "llvm/CodeGen/AsmPrinter.h"
16 #include "llvm/Constants.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/LLVMContext.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCStreamer.h"
24 #include "llvm/MC/MCSymbol.h"
25 #include "llvm/Target/TargetAsmParser.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/raw_ostream.h"
35 using namespace llvm;
36
37 namespace {
38   struct SrcMgrDiagInfo {
39     const MDNode *LocInfo;
40     void *DiagHandler;
41     void *DiagContext;
42   };
43 }
44
45 /// SrcMgrDiagHandler - This callback is invoked when the SourceMgr for an
46 /// inline asm has an error in it.  diagInfo is a pointer to the SrcMgrDiagInfo
47 /// struct above.
48 static void SrcMgrDiagHandler(const SMDiagnostic &Diag, void *diagInfo,
49                               unsigned locCookie) {
50   SrcMgrDiagInfo *DiagInfo = static_cast<SrcMgrDiagInfo *>(diagInfo);
51   assert(DiagInfo && "Diagnostic context not passed down?");
52   
53   unsigned LocCookie = 0;
54   if (const MDNode *LocInfo = DiagInfo->LocInfo) 
55     if (LocInfo->getNumOperands() > 0)
56       if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocInfo->getOperand(0)))
57         LocCookie = CI->getZExtValue();
58   
59   SourceMgr::DiagHandlerTy ChainHandler = 
60     (SourceMgr::DiagHandlerTy)(intptr_t)DiagInfo->DiagHandler;
61   
62   ChainHandler(Diag, DiagInfo->DiagContext, LocCookie);
63 }
64
65 /// EmitInlineAsm - Emit a blob of inline asm to the output streamer.
66 void AsmPrinter::EmitInlineAsm(StringRef Str, const MDNode *LocMDNode) const {
67   assert(!Str.empty() && "Can't emit empty inline asm block");
68
69   // Remember if the buffer is nul terminated or not so we can avoid a copy.
70   bool isNullTerminated = Str.back() == 0;
71   if (isNullTerminated)
72     Str = Str.substr(0, Str.size()-1);
73
74   // If the output streamer is actually a .s file, just emit the blob textually.
75   // This is useful in case the asm parser doesn't handle something but the
76   // system assembler does.
77   if (OutStreamer.hasRawTextSupport()) {
78     OutStreamer.EmitRawText(Str);
79     return;
80   }
81
82   SourceMgr SrcMgr;
83   SrcMgrDiagInfo DiagInfo;
84
85   // If the current LLVMContext has an inline asm handler, set it in SourceMgr.
86   LLVMContext &LLVMCtx = MMI->getModule()->getContext();
87   bool HasDiagHandler = false;
88   if (void *DiagHandler = LLVMCtx.getInlineAsmDiagnosticHandler()) {
89     // If the source manager has an issue, we arrange for SrcMgrDiagHandler
90     // to be invoked, getting DiagInfo passed into it.
91     DiagInfo.LocInfo = LocMDNode;
92     DiagInfo.DiagHandler = DiagHandler;
93     DiagInfo.DiagContext = LLVMCtx.getInlineAsmDiagnosticContext();
94     SrcMgr.setDiagHandler(SrcMgrDiagHandler, &DiagInfo);
95     HasDiagHandler = true;
96   }
97
98   MemoryBuffer *Buffer;
99   if (isNullTerminated)
100     Buffer = MemoryBuffer::getMemBuffer(Str, "<inline asm>");
101   else
102     Buffer = MemoryBuffer::getMemBufferCopy(Str, "<inline asm>");
103
104   // Tell SrcMgr about this buffer, it takes ownership of the buffer.
105   SrcMgr.AddNewSourceBuffer(Buffer, SMLoc());
106
107   OwningPtr<MCAsmParser> Parser(createMCAsmParser(TM.getTarget(), SrcMgr,
108                                                   OutContext, OutStreamer,
109                                                   *MAI));
110   OwningPtr<TargetAsmParser> TAP(TM.getTarget().createAsmParser(*Parser, TM));
111   if (!TAP)
112     report_fatal_error("Inline asm not supported by this streamer because"
113                        " we don't have an asm parser for this target\n");
114   Parser->setTargetParser(*TAP.get());
115
116   // Don't implicitly switch to the text section before the asm.
117   int Res = Parser->Run(/*NoInitialTextSection*/ true,
118                         /*NoFinalize*/ true);
119   if (Res && !HasDiagHandler)
120     report_fatal_error("Error parsing inline asm\n");
121 }
122
123
124 /// EmitInlineAsm - This method formats and emits the specified machine
125 /// instruction that is an inline asm.
126 void AsmPrinter::EmitInlineAsm(const MachineInstr *MI) const {
127   assert(MI->isInlineAsm() && "printInlineAsm only works on inline asms");
128
129   unsigned NumOperands = MI->getNumOperands();
130
131   // Count the number of register definitions to find the asm string.
132   unsigned NumDefs = 0;
133   for (; MI->getOperand(NumDefs).isReg() && MI->getOperand(NumDefs).isDef();
134        ++NumDefs)
135     assert(NumDefs != NumOperands-2 && "No asm string?");
136
137   assert(MI->getOperand(NumDefs).isSymbol() && "No asm string?");
138
139   // Disassemble the AsmStr, printing out the literal pieces, the operands, etc.
140   const char *AsmStr = MI->getOperand(NumDefs).getSymbolName();
141
142   // If this asmstr is empty, just print the #APP/#NOAPP markers.
143   // These are useful to see where empty asm's wound up.
144   if (AsmStr[0] == 0) {
145     // Don't emit the comments if writing to a .o file.
146     if (!OutStreamer.hasRawTextSupport()) return;
147
148     OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
149                             MAI->getInlineAsmStart());
150     OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
151                             MAI->getInlineAsmEnd());
152     return;
153   }
154
155   // Emit the #APP start marker.  This has to happen even if verbose-asm isn't
156   // enabled, so we use EmitRawText.
157   if (OutStreamer.hasRawTextSupport())
158     OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
159                             MAI->getInlineAsmStart());
160
161   // Get the !srcloc metadata node if we have it, and decode the loc cookie from
162   // it.
163   unsigned LocCookie = 0;
164   const MDNode *LocMD = 0;
165   for (unsigned i = MI->getNumOperands(); i != 0; --i) {
166     if (MI->getOperand(i-1).isMetadata() &&
167         (LocMD = MI->getOperand(i-1).getMetadata()) &&
168         LocMD->getNumOperands() != 0) {
169       if (const ConstantInt *CI = dyn_cast<ConstantInt>(LocMD->getOperand(0))) {
170         LocCookie = CI->getZExtValue();
171         break;
172       }
173     }
174   }
175
176   // Emit the inline asm to a temporary string so we can emit it through
177   // EmitInlineAsm.
178   SmallString<256> StringData;
179   raw_svector_ostream OS(StringData);
180
181   OS << '\t';
182
183   // The variant of the current asmprinter.
184   int AsmPrinterVariant = MAI->getAssemblerDialect();
185
186   int CurVariant = -1;            // The number of the {.|.|.} region we are in.
187   const char *LastEmitted = AsmStr; // One past the last character emitted.
188
189   while (*LastEmitted) {
190     switch (*LastEmitted) {
191     default: {
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')
196         ++LiteralEnd;
197       if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
198         OS.write(LastEmitted, LiteralEnd-LastEmitted);
199       LastEmitted = LiteralEnd;
200       break;
201     }
202     case '\n':
203       ++LastEmitted;   // Consume newline character.
204       OS << '\n';      // Indent code with newline.
205       break;
206     case '$': {
207       ++LastEmitted;   // Consume '$' character.
208       bool Done = true;
209
210       // Handle escapes.
211       switch (*LastEmitted) {
212       default: Done = false; break;
213       case '$':     // $$ -> $
214         if (CurVariant == -1 || CurVariant == AsmPrinterVariant)
215           OS << '$';
216         ++LastEmitted;  // Consume second '$' character.
217         break;
218       case '(':             // $( -> same as GCC's { character.
219         ++LastEmitted;      // Consume '(' character.
220         if (CurVariant != -1)
221           report_fatal_error("Nested variants found in inline asm string: '" +
222                              Twine(AsmStr) + "'");
223         CurVariant = 0;     // We're in the first variant now.
224         break;
225       case '|':
226         ++LastEmitted;  // consume '|' character.
227         if (CurVariant == -1)
228           OS << '|';       // this is gcc's behavior for | outside a variant
229         else
230           ++CurVariant;   // We're in the next variant.
231         break;
232       case ')':         // $) -> same as GCC's } char.
233         ++LastEmitted;  // consume ')' character.
234         if (CurVariant == -1)
235           OS << '}';     // this is gcc's behavior for } outside a variant
236         else
237           CurVariant = -1;
238         break;
239       }
240       if (Done) break;
241
242       bool HasCurlyBraces = false;
243       if (*LastEmitted == '{') {     // ${variable}
244         ++LastEmitted;               // Consume '{' character.
245         HasCurlyBraces = true;
246       }
247
248       // If we have ${:foo}, then this is not a real operand reference, it is a
249       // "magic" string reference, just like in .td files.  Arrange to call
250       // PrintSpecial.
251       if (HasCurlyBraces && *LastEmitted == ':') {
252         ++LastEmitted;
253         const char *StrStart = LastEmitted;
254         const char *StrEnd = strchr(StrStart, '}');
255         if (StrEnd == 0)
256           report_fatal_error("Unterminated ${:foo} operand in inline asm"
257                              " string: '" + Twine(AsmStr) + "'");
258
259         std::string Val(StrStart, StrEnd);
260         PrintSpecial(MI, OS, Val.c_str());
261         LastEmitted = StrEnd+1;
262         break;
263       }
264
265       const char *IDStart = LastEmitted;
266       const char *IDEnd = IDStart;
267       while (*IDEnd >= '0' && *IDEnd <= '9') ++IDEnd;
268
269       unsigned Val;
270       if (StringRef(IDStart, IDEnd-IDStart).getAsInteger(10, Val))
271         report_fatal_error("Bad $ operand number in inline asm string: '" +
272                            Twine(AsmStr) + "'");
273       LastEmitted = IDEnd;
274
275       char Modifier[2] = { 0, 0 };
276
277       if (HasCurlyBraces) {
278         // If we have curly braces, check for a modifier character.  This
279         // supports syntax like ${0:u}, which correspond to "%u0" in GCC asm.
280         if (*LastEmitted == ':') {
281           ++LastEmitted;    // Consume ':' character.
282           if (*LastEmitted == 0)
283             report_fatal_error("Bad ${:} expression in inline asm string: '" +
284                                Twine(AsmStr) + "'");
285
286           Modifier[0] = *LastEmitted;
287           ++LastEmitted;    // Consume modifier character.
288         }
289
290         if (*LastEmitted != '}')
291           report_fatal_error("Bad ${} expression in inline asm string: '" +
292                              Twine(AsmStr) + "'");
293         ++LastEmitted;    // Consume '}' character.
294       }
295
296       if (Val >= NumOperands-1)
297         report_fatal_error("Invalid $ operand number in inline asm string: '" +
298                            Twine(AsmStr) + "'");
299
300       // Okay, we finally have a value number.  Ask the target to print this
301       // operand!
302       if (CurVariant == -1 || CurVariant == AsmPrinterVariant) {
303         unsigned OpNo = 2;
304
305         bool Error = false;
306
307         // Scan to find the machine operand number for the operand.
308         for (; Val; --Val) {
309           if (OpNo >= MI->getNumOperands()) break;
310           unsigned OpFlags = MI->getOperand(OpNo).getImm();
311           OpNo += InlineAsm::getNumOperandRegisters(OpFlags) + 1;
312         }
313
314         if (OpNo >= MI->getNumOperands()) {
315           Error = true;
316         } else {
317           unsigned OpFlags = MI->getOperand(OpNo).getImm();
318           ++OpNo;  // Skip over the ID number.
319
320           if (Modifier[0] == 'l')  // labels are target independent
321             // FIXME: What if the operand isn't an MBB, report error?
322             OS << *MI->getOperand(OpNo).getMBB()->getSymbol();
323           else {
324             AsmPrinter *AP = const_cast<AsmPrinter*>(this);
325             if (InlineAsm::isMemKind(OpFlags)) {
326               Error = AP->PrintAsmMemoryOperand(MI, OpNo, AsmPrinterVariant,
327                                                 Modifier[0] ? Modifier : 0,
328                                                 OS);
329             } else {
330               Error = AP->PrintAsmOperand(MI, OpNo, AsmPrinterVariant,
331                                           Modifier[0] ? Modifier : 0, OS);
332             }
333           }
334         }
335         if (Error) {
336           std::string msg;
337           raw_string_ostream Msg(msg);
338           Msg << "invalid operand in inline asm: '" << AsmStr << "'";
339           MMI->getModule()->getContext().emitError(LocCookie, Msg.str());
340         }
341       }
342       break;
343     }
344     }
345   }
346   OS << '\n' << (char)0;  // null terminate string.
347   EmitInlineAsm(OS.str(), LocMD);
348
349   // Emit the #NOAPP end marker.  This has to happen even if verbose-asm isn't
350   // enabled, so we use EmitRawText.
351   if (OutStreamer.hasRawTextSupport())
352     OutStreamer.EmitRawText(Twine("\t")+MAI->getCommentString()+
353                             MAI->getInlineAsmEnd());
354 }
355
356
357 /// PrintSpecial - Print information related to the specified machine instr
358 /// that is independent of the operand, and may be independent of the instr
359 /// itself.  This can be useful for portably encoding the comment character
360 /// or other bits of target-specific knowledge into the asmstrings.  The
361 /// syntax used is ${:comment}.  Targets can override this to add support
362 /// for their own strange codes.
363 void AsmPrinter::PrintSpecial(const MachineInstr *MI, raw_ostream &OS,
364                               const char *Code) const {
365   if (!strcmp(Code, "private")) {
366     OS << MAI->getPrivateGlobalPrefix();
367   } else if (!strcmp(Code, "comment")) {
368     OS << MAI->getCommentString();
369   } else if (!strcmp(Code, "uid")) {
370     // Comparing the address of MI isn't sufficient, because machineinstrs may
371     // be allocated to the same address across functions.
372
373     // If this is a new LastFn instruction, bump the counter.
374     if (LastMI != MI || LastFn != getFunctionNumber()) {
375       ++Counter;
376       LastMI = MI;
377       LastFn = getFunctionNumber();
378     }
379     OS << Counter;
380   } else {
381     std::string msg;
382     raw_string_ostream Msg(msg);
383     Msg << "Unknown special formatter '" << Code
384          << "' for machine instr: " << *MI;
385     report_fatal_error(Msg.str());
386   }
387 }
388
389 /// PrintAsmOperand - Print the specified operand of MI, an INLINEASM
390 /// instruction, using the specified assembler variant.  Targets should
391 /// override this to format as appropriate.
392 bool AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
393                                  unsigned AsmVariant, const char *ExtraCode,
394                                  raw_ostream &O) {
395   // Target doesn't support this yet!
396   return true;
397 }
398
399 bool AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
400                                        unsigned AsmVariant,
401                                        const char *ExtraCode, raw_ostream &O) {
402   // Target doesn't support this yet!
403   return true;
404 }
405