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