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