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