StmtPrinter.cpp revision b390921e55db36ee0ab1ca203c166f0f8c96f631
1//===--- StmtPrinter.cpp - Printing implementation for Stmt ASTs ----------===//
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 Stmt::dumpPretty/Stmt::printPretty methods, which
11// pretty print the AST back out to C code.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/StmtVisitor.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/PrettyPrinter.h"
20#include "llvm/Support/Format.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23using namespace clang;
24
25//===----------------------------------------------------------------------===//
26// StmtPrinter Visitor
27//===----------------------------------------------------------------------===//
28
29namespace  {
30  class StmtPrinter : public StmtVisitor<StmtPrinter> {
31    raw_ostream &OS;
32    ASTContext &Context;
33    unsigned IndentLevel;
34    clang::PrinterHelper* Helper;
35    PrintingPolicy Policy;
36
37  public:
38    StmtPrinter(raw_ostream &os, ASTContext &C, PrinterHelper* helper,
39                const PrintingPolicy &Policy,
40                unsigned Indentation = 0)
41      : OS(os), Context(C), IndentLevel(Indentation), Helper(helper),
42        Policy(Policy) {}
43
44    void PrintStmt(Stmt *S) {
45      PrintStmt(S, Policy.Indentation);
46    }
47
48    void PrintStmt(Stmt *S, int SubIndent) {
49      IndentLevel += SubIndent;
50      if (S && isa<Expr>(S)) {
51        // If this is an expr used in a stmt context, indent and newline it.
52        Indent();
53        Visit(S);
54        OS << ";\n";
55      } else if (S) {
56        Visit(S);
57      } else {
58        Indent() << "<<<NULL STATEMENT>>>\n";
59      }
60      IndentLevel -= SubIndent;
61    }
62
63    void PrintRawCompoundStmt(CompoundStmt *S);
64    void PrintRawDecl(Decl *D);
65    void PrintRawDeclStmt(DeclStmt *S);
66    void PrintRawIfStmt(IfStmt *If);
67    void PrintRawCXXCatchStmt(CXXCatchStmt *Catch);
68    void PrintCallArgs(CallExpr *E);
69    void PrintRawSEHExceptHandler(SEHExceptStmt *S);
70    void PrintRawSEHFinallyStmt(SEHFinallyStmt *S);
71
72    void PrintExpr(Expr *E) {
73      if (E)
74        Visit(E);
75      else
76        OS << "<null expr>";
77    }
78
79    raw_ostream &Indent(int Delta = 0) {
80      for (int i = 0, e = IndentLevel+Delta; i < e; ++i)
81        OS << "  ";
82      return OS;
83    }
84
85    void Visit(Stmt* S) {
86      if (Helper && Helper->handledStmt(S,OS))
87          return;
88      else StmtVisitor<StmtPrinter>::Visit(S);
89    }
90
91    void VisitStmt(Stmt *Node) LLVM_ATTRIBUTE_UNUSED {
92      Indent() << "<<unknown stmt type>>\n";
93    }
94    void VisitExpr(Expr *Node) LLVM_ATTRIBUTE_UNUSED {
95      OS << "<<unknown expr type>>";
96    }
97    void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node);
98
99#define ABSTRACT_STMT(CLASS)
100#define STMT(CLASS, PARENT) \
101    void Visit##CLASS(CLASS *Node);
102#include "clang/AST/StmtNodes.inc"
103  };
104}
105
106//===----------------------------------------------------------------------===//
107//  Stmt printing methods.
108//===----------------------------------------------------------------------===//
109
110/// PrintRawCompoundStmt - Print a compound stmt without indenting the {, and
111/// with no newline after the }.
112void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) {
113  OS << "{\n";
114  for (CompoundStmt::body_iterator I = Node->body_begin(), E = Node->body_end();
115       I != E; ++I)
116    PrintStmt(*I);
117
118  Indent() << "}";
119}
120
121void StmtPrinter::PrintRawDecl(Decl *D) {
122  D->print(OS, Policy, IndentLevel);
123}
124
125void StmtPrinter::PrintRawDeclStmt(DeclStmt *S) {
126  DeclStmt::decl_iterator Begin = S->decl_begin(), End = S->decl_end();
127  SmallVector<Decl*, 2> Decls;
128  for ( ; Begin != End; ++Begin)
129    Decls.push_back(*Begin);
130
131  Decl::printGroup(Decls.data(), Decls.size(), OS, Policy, IndentLevel);
132}
133
134void StmtPrinter::VisitNullStmt(NullStmt *Node) {
135  Indent() << ";\n";
136}
137
138void StmtPrinter::VisitDeclStmt(DeclStmt *Node) {
139  Indent();
140  PrintRawDeclStmt(Node);
141  OS << ";\n";
142}
143
144void StmtPrinter::VisitCompoundStmt(CompoundStmt *Node) {
145  Indent();
146  PrintRawCompoundStmt(Node);
147  OS << "\n";
148}
149
150void StmtPrinter::VisitCaseStmt(CaseStmt *Node) {
151  Indent(-1) << "case ";
152  PrintExpr(Node->getLHS());
153  if (Node->getRHS()) {
154    OS << " ... ";
155    PrintExpr(Node->getRHS());
156  }
157  OS << ":\n";
158
159  PrintStmt(Node->getSubStmt(), 0);
160}
161
162void StmtPrinter::VisitDefaultStmt(DefaultStmt *Node) {
163  Indent(-1) << "default:\n";
164  PrintStmt(Node->getSubStmt(), 0);
165}
166
167void StmtPrinter::VisitLabelStmt(LabelStmt *Node) {
168  Indent(-1) << Node->getName() << ":\n";
169  PrintStmt(Node->getSubStmt(), 0);
170}
171
172void StmtPrinter::PrintRawIfStmt(IfStmt *If) {
173  OS << "if (";
174  PrintExpr(If->getCond());
175  OS << ')';
176
177  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(If->getThen())) {
178    OS << ' ';
179    PrintRawCompoundStmt(CS);
180    OS << (If->getElse() ? ' ' : '\n');
181  } else {
182    OS << '\n';
183    PrintStmt(If->getThen());
184    if (If->getElse()) Indent();
185  }
186
187  if (Stmt *Else = If->getElse()) {
188    OS << "else";
189
190    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Else)) {
191      OS << ' ';
192      PrintRawCompoundStmt(CS);
193      OS << '\n';
194    } else if (IfStmt *ElseIf = dyn_cast<IfStmt>(Else)) {
195      OS << ' ';
196      PrintRawIfStmt(ElseIf);
197    } else {
198      OS << '\n';
199      PrintStmt(If->getElse());
200    }
201  }
202}
203
204void StmtPrinter::VisitIfStmt(IfStmt *If) {
205  Indent();
206  PrintRawIfStmt(If);
207}
208
209void StmtPrinter::VisitSwitchStmt(SwitchStmt *Node) {
210  Indent() << "switch (";
211  PrintExpr(Node->getCond());
212  OS << ")";
213
214  // Pretty print compoundstmt bodies (very common).
215  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
216    OS << " ";
217    PrintRawCompoundStmt(CS);
218    OS << "\n";
219  } else {
220    OS << "\n";
221    PrintStmt(Node->getBody());
222  }
223}
224
225void StmtPrinter::VisitWhileStmt(WhileStmt *Node) {
226  Indent() << "while (";
227  PrintExpr(Node->getCond());
228  OS << ")\n";
229  PrintStmt(Node->getBody());
230}
231
232void StmtPrinter::VisitDoStmt(DoStmt *Node) {
233  Indent() << "do ";
234  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
235    PrintRawCompoundStmt(CS);
236    OS << " ";
237  } else {
238    OS << "\n";
239    PrintStmt(Node->getBody());
240    Indent();
241  }
242
243  OS << "while (";
244  PrintExpr(Node->getCond());
245  OS << ");\n";
246}
247
248void StmtPrinter::VisitForStmt(ForStmt *Node) {
249  Indent() << "for (";
250  if (Node->getInit()) {
251    if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getInit()))
252      PrintRawDeclStmt(DS);
253    else
254      PrintExpr(cast<Expr>(Node->getInit()));
255  }
256  OS << ";";
257  if (Node->getCond()) {
258    OS << " ";
259    PrintExpr(Node->getCond());
260  }
261  OS << ";";
262  if (Node->getInc()) {
263    OS << " ";
264    PrintExpr(Node->getInc());
265  }
266  OS << ") ";
267
268  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
269    PrintRawCompoundStmt(CS);
270    OS << "\n";
271  } else {
272    OS << "\n";
273    PrintStmt(Node->getBody());
274  }
275}
276
277void StmtPrinter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *Node) {
278  Indent() << "for (";
279  if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getElement()))
280    PrintRawDeclStmt(DS);
281  else
282    PrintExpr(cast<Expr>(Node->getElement()));
283  OS << " in ";
284  PrintExpr(Node->getCollection());
285  OS << ") ";
286
287  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
288    PrintRawCompoundStmt(CS);
289    OS << "\n";
290  } else {
291    OS << "\n";
292    PrintStmt(Node->getBody());
293  }
294}
295
296void StmtPrinter::VisitCXXForRangeStmt(CXXForRangeStmt *Node) {
297  Indent() << "for (";
298  PrintingPolicy SubPolicy(Policy);
299  SubPolicy.SuppressInitializers = true;
300  Node->getLoopVariable()->print(OS, SubPolicy, IndentLevel);
301  OS << " : ";
302  PrintExpr(Node->getRangeInit());
303  OS << ") {\n";
304  PrintStmt(Node->getBody());
305  Indent() << "}\n";
306}
307
308void StmtPrinter::VisitGotoStmt(GotoStmt *Node) {
309  Indent() << "goto " << Node->getLabel()->getName() << ";\n";
310}
311
312void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) {
313  Indent() << "goto *";
314  PrintExpr(Node->getTarget());
315  OS << ";\n";
316}
317
318void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) {
319  Indent() << "continue;\n";
320}
321
322void StmtPrinter::VisitBreakStmt(BreakStmt *Node) {
323  Indent() << "break;\n";
324}
325
326
327void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) {
328  Indent() << "return";
329  if (Node->getRetValue()) {
330    OS << " ";
331    PrintExpr(Node->getRetValue());
332  }
333  OS << ";\n";
334}
335
336
337void StmtPrinter::VisitAsmStmt(AsmStmt *Node) {
338  Indent() << "asm ";
339
340  if (Node->isVolatile())
341    OS << "volatile ";
342
343  OS << "(";
344  VisitStringLiteral(Node->getAsmString());
345
346  // Outputs
347  if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 ||
348      Node->getNumClobbers() != 0)
349    OS << " : ";
350
351  for (unsigned i = 0, e = Node->getNumOutputs(); i != e; ++i) {
352    if (i != 0)
353      OS << ", ";
354
355    if (!Node->getOutputName(i).empty()) {
356      OS << '[';
357      OS << Node->getOutputName(i);
358      OS << "] ";
359    }
360
361    VisitStringLiteral(Node->getOutputConstraintLiteral(i));
362    OS << " ";
363    Visit(Node->getOutputExpr(i));
364  }
365
366  // Inputs
367  if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0)
368    OS << " : ";
369
370  for (unsigned i = 0, e = Node->getNumInputs(); i != e; ++i) {
371    if (i != 0)
372      OS << ", ";
373
374    if (!Node->getInputName(i).empty()) {
375      OS << '[';
376      OS << Node->getInputName(i);
377      OS << "] ";
378    }
379
380    VisitStringLiteral(Node->getInputConstraintLiteral(i));
381    OS << " ";
382    Visit(Node->getInputExpr(i));
383  }
384
385  // Clobbers
386  if (Node->getNumClobbers() != 0)
387    OS << " : ";
388
389  for (unsigned i = 0, e = Node->getNumClobbers(); i != e; ++i) {
390    if (i != 0)
391      OS << ", ";
392
393    VisitStringLiteral(Node->getClobber(i));
394  }
395
396  OS << ");\n";
397}
398
399void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
400  Indent() << "@try";
401  if (CompoundStmt *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
402    PrintRawCompoundStmt(TS);
403    OS << "\n";
404  }
405
406  for (unsigned I = 0, N = Node->getNumCatchStmts(); I != N; ++I) {
407    ObjCAtCatchStmt *catchStmt = Node->getCatchStmt(I);
408    Indent() << "@catch(";
409    if (catchStmt->getCatchParamDecl()) {
410      if (Decl *DS = catchStmt->getCatchParamDecl())
411        PrintRawDecl(DS);
412    }
413    OS << ")";
414    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(catchStmt->getCatchBody())) {
415      PrintRawCompoundStmt(CS);
416      OS << "\n";
417    }
418  }
419
420  if (ObjCAtFinallyStmt *FS = static_cast<ObjCAtFinallyStmt *>(
421        Node->getFinallyStmt())) {
422    Indent() << "@finally";
423    PrintRawCompoundStmt(dyn_cast<CompoundStmt>(FS->getFinallyBody()));
424    OS << "\n";
425  }
426}
427
428void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {
429}
430
431void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) {
432  Indent() << "@catch (...) { /* todo */ } \n";
433}
434
435void StmtPrinter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *Node) {
436  Indent() << "@throw";
437  if (Node->getThrowExpr()) {
438    OS << " ";
439    PrintExpr(Node->getThrowExpr());
440  }
441  OS << ";\n";
442}
443
444void StmtPrinter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *Node) {
445  Indent() << "@synchronized (";
446  PrintExpr(Node->getSynchExpr());
447  OS << ")";
448  PrintRawCompoundStmt(Node->getSynchBody());
449  OS << "\n";
450}
451
452void StmtPrinter::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *Node) {
453  Indent() << "@autoreleasepool";
454  PrintRawCompoundStmt(dyn_cast<CompoundStmt>(Node->getSubStmt()));
455  OS << "\n";
456}
457
458void StmtPrinter::PrintRawCXXCatchStmt(CXXCatchStmt *Node) {
459  OS << "catch (";
460  if (Decl *ExDecl = Node->getExceptionDecl())
461    PrintRawDecl(ExDecl);
462  else
463    OS << "...";
464  OS << ") ";
465  PrintRawCompoundStmt(cast<CompoundStmt>(Node->getHandlerBlock()));
466}
467
468void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) {
469  Indent();
470  PrintRawCXXCatchStmt(Node);
471  OS << "\n";
472}
473
474void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) {
475  Indent() << "try ";
476  PrintRawCompoundStmt(Node->getTryBlock());
477  for (unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) {
478    OS << " ";
479    PrintRawCXXCatchStmt(Node->getHandler(i));
480  }
481  OS << "\n";
482}
483
484void StmtPrinter::VisitSEHTryStmt(SEHTryStmt *Node) {
485  Indent() << (Node->getIsCXXTry() ? "try " : "__try ");
486  PrintRawCompoundStmt(Node->getTryBlock());
487  SEHExceptStmt *E = Node->getExceptHandler();
488  SEHFinallyStmt *F = Node->getFinallyHandler();
489  if(E)
490    PrintRawSEHExceptHandler(E);
491  else {
492    assert(F && "Must have a finally block...");
493    PrintRawSEHFinallyStmt(F);
494  }
495  OS << "\n";
496}
497
498void StmtPrinter::PrintRawSEHFinallyStmt(SEHFinallyStmt *Node) {
499  OS << "__finally ";
500  PrintRawCompoundStmt(Node->getBlock());
501  OS << "\n";
502}
503
504void StmtPrinter::PrintRawSEHExceptHandler(SEHExceptStmt *Node) {
505  OS << "__except (";
506  VisitExpr(Node->getFilterExpr());
507  OS << ")\n";
508  PrintRawCompoundStmt(Node->getBlock());
509  OS << "\n";
510}
511
512void StmtPrinter::VisitSEHExceptStmt(SEHExceptStmt *Node) {
513  Indent();
514  PrintRawSEHExceptHandler(Node);
515  OS << "\n";
516}
517
518void StmtPrinter::VisitSEHFinallyStmt(SEHFinallyStmt *Node) {
519  Indent();
520  PrintRawSEHFinallyStmt(Node);
521  OS << "\n";
522}
523
524//===----------------------------------------------------------------------===//
525//  Expr printing methods.
526//===----------------------------------------------------------------------===//
527
528void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
529  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
530    Qualifier->print(OS, Policy);
531  OS << Node->getNameInfo();
532  if (Node->hasExplicitTemplateArgs())
533    OS << TemplateSpecializationType::PrintTemplateArgumentList(
534                                                    Node->getTemplateArgs(),
535                                                    Node->getNumTemplateArgs(),
536                                                    Policy);
537}
538
539void StmtPrinter::VisitDependentScopeDeclRefExpr(
540                                           DependentScopeDeclRefExpr *Node) {
541  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
542    Qualifier->print(OS, Policy);
543  OS << Node->getNameInfo();
544  if (Node->hasExplicitTemplateArgs())
545    OS << TemplateSpecializationType::PrintTemplateArgumentList(
546                                                   Node->getTemplateArgs(),
547                                                   Node->getNumTemplateArgs(),
548                                                   Policy);
549}
550
551void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
552  if (Node->getQualifier())
553    Node->getQualifier()->print(OS, Policy);
554  OS << Node->getNameInfo();
555  if (Node->hasExplicitTemplateArgs())
556    OS << TemplateSpecializationType::PrintTemplateArgumentList(
557                                                   Node->getTemplateArgs(),
558                                                   Node->getNumTemplateArgs(),
559                                                   Policy);
560}
561
562void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
563  if (Node->getBase()) {
564    PrintExpr(Node->getBase());
565    OS << (Node->isArrow() ? "->" : ".");
566  }
567  OS << Node->getDecl();
568}
569
570void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
571  if (Node->isSuperReceiver())
572    OS << "super.";
573  else if (Node->getBase()) {
574    PrintExpr(Node->getBase());
575    OS << ".";
576  }
577
578  if (Node->isImplicitProperty())
579    OS << Node->getImplicitPropertyGetter()->getSelector().getAsString();
580  else
581    OS << Node->getExplicitProperty()->getName();
582}
583
584void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
585  switch (Node->getIdentType()) {
586    default:
587      llvm_unreachable("unknown case");
588    case PredefinedExpr::Func:
589      OS << "__func__";
590      break;
591    case PredefinedExpr::Function:
592      OS << "__FUNCTION__";
593      break;
594    case PredefinedExpr::PrettyFunction:
595      OS << "__PRETTY_FUNCTION__";
596      break;
597  }
598}
599
600void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
601  unsigned value = Node->getValue();
602
603  switch (Node->getKind()) {
604  case CharacterLiteral::Ascii: break; // no prefix.
605  case CharacterLiteral::Wide:  OS << 'L'; break;
606  case CharacterLiteral::UTF16: OS << 'u'; break;
607  case CharacterLiteral::UTF32: OS << 'U'; break;
608  }
609
610  switch (value) {
611  case '\\':
612    OS << "'\\\\'";
613    break;
614  case '\'':
615    OS << "'\\''";
616    break;
617  case '\a':
618    // TODO: K&R: the meaning of '\\a' is different in traditional C
619    OS << "'\\a'";
620    break;
621  case '\b':
622    OS << "'\\b'";
623    break;
624  // Nonstandard escape sequence.
625  /*case '\e':
626    OS << "'\\e'";
627    break;*/
628  case '\f':
629    OS << "'\\f'";
630    break;
631  case '\n':
632    OS << "'\\n'";
633    break;
634  case '\r':
635    OS << "'\\r'";
636    break;
637  case '\t':
638    OS << "'\\t'";
639    break;
640  case '\v':
641    OS << "'\\v'";
642    break;
643  default:
644    if (value < 256 && isprint(value)) {
645      OS << "'" << (char)value << "'";
646    } else if (value < 256) {
647      OS << "'\\x" << llvm::format("%x", value) << "'";
648    } else {
649      // FIXME what to really do here?
650      OS << value;
651    }
652  }
653}
654
655void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
656  bool isSigned = Node->getType()->isSignedIntegerType();
657  OS << Node->getValue().toString(10, isSigned);
658
659  // Emit suffixes.  Integer literals are always a builtin integer type.
660  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
661  default: llvm_unreachable("Unexpected type for integer literal!");
662  case BuiltinType::Int:       break; // no suffix.
663  case BuiltinType::UInt:      OS << 'U'; break;
664  case BuiltinType::Long:      OS << 'L'; break;
665  case BuiltinType::ULong:     OS << "UL"; break;
666  case BuiltinType::LongLong:  OS << "LL"; break;
667  case BuiltinType::ULongLong: OS << "ULL"; break;
668  }
669}
670void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
671  llvm::SmallString<16> Str;
672  Node->getValue().toString(Str);
673  OS << Str;
674}
675
676void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
677  PrintExpr(Node->getSubExpr());
678  OS << "i";
679}
680
681void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
682  switch (Str->getKind()) {
683  case StringLiteral::Ascii: break; // no prefix.
684  case StringLiteral::Wide:  OS << 'L'; break;
685  case StringLiteral::UTF8:  OS << "u8"; break;
686  case StringLiteral::UTF16: OS << 'u'; break;
687  case StringLiteral::UTF32: OS << 'U'; break;
688  }
689  OS << '"';
690
691  // FIXME: this doesn't print wstrings right.
692  StringRef StrData = Str->getString();
693  for (StringRef::iterator I = StrData.begin(), E = StrData.end();
694                                                             I != E; ++I) {
695    unsigned char Char = *I;
696
697    switch (Char) {
698    default:
699      if (isprint(Char))
700        OS << (char)Char;
701      else  // Output anything hard as an octal escape.
702        OS << '\\'
703        << (char)('0'+ ((Char >> 6) & 7))
704        << (char)('0'+ ((Char >> 3) & 7))
705        << (char)('0'+ ((Char >> 0) & 7));
706      break;
707    // Handle some common non-printable cases to make dumps prettier.
708    case '\\': OS << "\\\\"; break;
709    case '"': OS << "\\\""; break;
710    case '\n': OS << "\\n"; break;
711    case '\t': OS << "\\t"; break;
712    case '\a': OS << "\\a"; break;
713    case '\b': OS << "\\b"; break;
714    }
715  }
716  OS << '"';
717}
718void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
719  OS << "(";
720  PrintExpr(Node->getSubExpr());
721  OS << ")";
722}
723void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
724  if (!Node->isPostfix()) {
725    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
726
727    // Print a space if this is an "identifier operator" like __real, or if
728    // it might be concatenated incorrectly like '+'.
729    switch (Node->getOpcode()) {
730    default: break;
731    case UO_Real:
732    case UO_Imag:
733    case UO_Extension:
734      OS << ' ';
735      break;
736    case UO_Plus:
737    case UO_Minus:
738      if (isa<UnaryOperator>(Node->getSubExpr()))
739        OS << ' ';
740      break;
741    }
742  }
743  PrintExpr(Node->getSubExpr());
744
745  if (Node->isPostfix())
746    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
747}
748
749void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
750  OS << "__builtin_offsetof(";
751  OS << Node->getTypeSourceInfo()->getType().getAsString(Policy) << ", ";
752  bool PrintedSomething = false;
753  for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
754    OffsetOfExpr::OffsetOfNode ON = Node->getComponent(i);
755    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Array) {
756      // Array node
757      OS << "[";
758      PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
759      OS << "]";
760      PrintedSomething = true;
761      continue;
762    }
763
764    // Skip implicit base indirections.
765    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Base)
766      continue;
767
768    // Field or identifier node.
769    IdentifierInfo *Id = ON.getFieldName();
770    if (!Id)
771      continue;
772
773    if (PrintedSomething)
774      OS << ".";
775    else
776      PrintedSomething = true;
777    OS << Id->getName();
778  }
779  OS << ")";
780}
781
782void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
783  switch(Node->getKind()) {
784  case UETT_SizeOf:
785    OS << "sizeof";
786    break;
787  case UETT_AlignOf:
788    OS << "__alignof";
789    break;
790  case UETT_VecStep:
791    OS << "vec_step";
792    break;
793  }
794  if (Node->isArgumentType())
795    OS << "(" << Node->getArgumentType().getAsString(Policy) << ")";
796  else {
797    OS << " ";
798    PrintExpr(Node->getArgumentExpr());
799  }
800}
801
802void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
803  OS << "_Generic(";
804  PrintExpr(Node->getControllingExpr());
805  for (unsigned i = 0; i != Node->getNumAssocs(); ++i) {
806    OS << ", ";
807    QualType T = Node->getAssocType(i);
808    if (T.isNull())
809      OS << "default";
810    else
811      OS << T.getAsString(Policy);
812    OS << ": ";
813    PrintExpr(Node->getAssocExpr(i));
814  }
815  OS << ")";
816}
817
818void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
819  PrintExpr(Node->getLHS());
820  OS << "[";
821  PrintExpr(Node->getRHS());
822  OS << "]";
823}
824
825void StmtPrinter::PrintCallArgs(CallExpr *Call) {
826  for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
827    if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
828      // Don't print any defaulted arguments
829      break;
830    }
831
832    if (i) OS << ", ";
833    PrintExpr(Call->getArg(i));
834  }
835}
836
837void StmtPrinter::VisitCallExpr(CallExpr *Call) {
838  PrintExpr(Call->getCallee());
839  OS << "(";
840  PrintCallArgs(Call);
841  OS << ")";
842}
843void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
844  // FIXME: Suppress printing implicit bases (like "this")
845  PrintExpr(Node->getBase());
846  if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
847    if (FD->isAnonymousStructOrUnion())
848      return;
849  OS << (Node->isArrow() ? "->" : ".");
850  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
851    Qualifier->print(OS, Policy);
852
853  OS << Node->getMemberNameInfo();
854
855  if (Node->hasExplicitTemplateArgs())
856    OS << TemplateSpecializationType::PrintTemplateArgumentList(
857                                                    Node->getTemplateArgs(),
858                                                    Node->getNumTemplateArgs(),
859                                                                Policy);
860}
861void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
862  PrintExpr(Node->getBase());
863  OS << (Node->isArrow() ? "->isa" : ".isa");
864}
865
866void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
867  PrintExpr(Node->getBase());
868  OS << ".";
869  OS << Node->getAccessor().getName();
870}
871void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
872  OS << "(" << Node->getType().getAsString(Policy) << ")";
873  PrintExpr(Node->getSubExpr());
874}
875void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
876  OS << "(" << Node->getType().getAsString(Policy) << ")";
877  PrintExpr(Node->getInitializer());
878}
879void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
880  // No need to print anything, simply forward to the sub expression.
881  PrintExpr(Node->getSubExpr());
882}
883void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
884  PrintExpr(Node->getLHS());
885  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
886  PrintExpr(Node->getRHS());
887}
888void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
889  PrintExpr(Node->getLHS());
890  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
891  PrintExpr(Node->getRHS());
892}
893void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
894  PrintExpr(Node->getCond());
895  OS << " ? ";
896  PrintExpr(Node->getLHS());
897  OS << " : ";
898  PrintExpr(Node->getRHS());
899}
900
901// GNU extensions.
902
903void
904StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
905  PrintExpr(Node->getCommon());
906  OS << " ?: ";
907  PrintExpr(Node->getFalseExpr());
908}
909void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
910  OS << "&&" << Node->getLabel()->getName();
911}
912
913void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
914  OS << "(";
915  PrintRawCompoundStmt(E->getSubStmt());
916  OS << ")";
917}
918
919void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
920  OS << "__builtin_choose_expr(";
921  PrintExpr(Node->getCond());
922  OS << ", ";
923  PrintExpr(Node->getLHS());
924  OS << ", ";
925  PrintExpr(Node->getRHS());
926  OS << ")";
927}
928
929void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
930  OS << "__null";
931}
932
933void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
934  OS << "__builtin_shufflevector(";
935  for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
936    if (i) OS << ", ";
937    PrintExpr(Node->getExpr(i));
938  }
939  OS << ")";
940}
941
942void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
943  if (Node->getSyntacticForm()) {
944    Visit(Node->getSyntacticForm());
945    return;
946  }
947
948  OS << "{ ";
949  for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
950    if (i) OS << ", ";
951    if (Node->getInit(i))
952      PrintExpr(Node->getInit(i));
953    else
954      OS << "0";
955  }
956  OS << " }";
957}
958
959void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
960  OS << "( ";
961  for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
962    if (i) OS << ", ";
963    PrintExpr(Node->getExpr(i));
964  }
965  OS << " )";
966}
967
968void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
969  for (DesignatedInitExpr::designators_iterator D = Node->designators_begin(),
970                      DEnd = Node->designators_end();
971       D != DEnd; ++D) {
972    if (D->isFieldDesignator()) {
973      if (D->getDotLoc().isInvalid())
974        OS << D->getFieldName()->getName() << ":";
975      else
976        OS << "." << D->getFieldName()->getName();
977    } else {
978      OS << "[";
979      if (D->isArrayDesignator()) {
980        PrintExpr(Node->getArrayIndex(*D));
981      } else {
982        PrintExpr(Node->getArrayRangeStart(*D));
983        OS << " ... ";
984        PrintExpr(Node->getArrayRangeEnd(*D));
985      }
986      OS << "]";
987    }
988  }
989
990  OS << " = ";
991  PrintExpr(Node->getInit());
992}
993
994void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
995  if (Policy.LangOpts.CPlusPlus)
996    OS << "/*implicit*/" << Node->getType().getAsString(Policy) << "()";
997  else {
998    OS << "/*implicit*/(" << Node->getType().getAsString(Policy) << ")";
999    if (Node->getType()->isRecordType())
1000      OS << "{}";
1001    else
1002      OS << 0;
1003  }
1004}
1005
1006void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1007  OS << "__builtin_va_arg(";
1008  PrintExpr(Node->getSubExpr());
1009  OS << ", ";
1010  OS << Node->getType().getAsString(Policy);
1011  OS << ")";
1012}
1013
1014// C++
1015void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
1016  const char *OpStrings[NUM_OVERLOADED_OPERATORS] = {
1017    "",
1018#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1019    Spelling,
1020#include "clang/Basic/OperatorKinds.def"
1021  };
1022
1023  OverloadedOperatorKind Kind = Node->getOperator();
1024  if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1025    if (Node->getNumArgs() == 1) {
1026      OS << OpStrings[Kind] << ' ';
1027      PrintExpr(Node->getArg(0));
1028    } else {
1029      PrintExpr(Node->getArg(0));
1030      OS << ' ' << OpStrings[Kind];
1031    }
1032  } else if (Kind == OO_Call) {
1033    PrintExpr(Node->getArg(0));
1034    OS << '(';
1035    for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1036      if (ArgIdx > 1)
1037        OS << ", ";
1038      if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1039        PrintExpr(Node->getArg(ArgIdx));
1040    }
1041    OS << ')';
1042  } else if (Kind == OO_Subscript) {
1043    PrintExpr(Node->getArg(0));
1044    OS << '[';
1045    PrintExpr(Node->getArg(1));
1046    OS << ']';
1047  } else if (Node->getNumArgs() == 1) {
1048    OS << OpStrings[Kind] << ' ';
1049    PrintExpr(Node->getArg(0));
1050  } else if (Node->getNumArgs() == 2) {
1051    PrintExpr(Node->getArg(0));
1052    OS << ' ' << OpStrings[Kind] << ' ';
1053    PrintExpr(Node->getArg(1));
1054  } else {
1055    llvm_unreachable("unknown overloaded operator");
1056  }
1057}
1058
1059void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1060  VisitCallExpr(cast<CallExpr>(Node));
1061}
1062
1063void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1064  PrintExpr(Node->getCallee());
1065  OS << "<<<";
1066  PrintCallArgs(Node->getConfig());
1067  OS << ">>>(";
1068  PrintCallArgs(Node);
1069  OS << ")";
1070}
1071
1072void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1073  OS << Node->getCastName() << '<';
1074  OS << Node->getTypeAsWritten().getAsString(Policy) << ">(";
1075  PrintExpr(Node->getSubExpr());
1076  OS << ")";
1077}
1078
1079void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1080  VisitCXXNamedCastExpr(Node);
1081}
1082
1083void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1084  VisitCXXNamedCastExpr(Node);
1085}
1086
1087void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1088  VisitCXXNamedCastExpr(Node);
1089}
1090
1091void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1092  VisitCXXNamedCastExpr(Node);
1093}
1094
1095void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1096  OS << "typeid(";
1097  if (Node->isTypeOperand()) {
1098    OS << Node->getTypeOperand().getAsString(Policy);
1099  } else {
1100    PrintExpr(Node->getExprOperand());
1101  }
1102  OS << ")";
1103}
1104
1105void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1106  OS << "__uuidof(";
1107  if (Node->isTypeOperand()) {
1108    OS << Node->getTypeOperand().getAsString(Policy);
1109  } else {
1110    PrintExpr(Node->getExprOperand());
1111  }
1112  OS << ")";
1113}
1114
1115void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1116  OS << (Node->getValue() ? "true" : "false");
1117}
1118
1119void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1120  OS << "nullptr";
1121}
1122
1123void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1124  OS << "this";
1125}
1126
1127void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1128  if (Node->getSubExpr() == 0)
1129    OS << "throw";
1130  else {
1131    OS << "throw ";
1132    PrintExpr(Node->getSubExpr());
1133  }
1134}
1135
1136void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1137  // Nothing to print: we picked up the default argument
1138}
1139
1140void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1141  OS << Node->getType().getAsString(Policy);
1142  OS << "(";
1143  PrintExpr(Node->getSubExpr());
1144  OS << ")";
1145}
1146
1147void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1148  PrintExpr(Node->getSubExpr());
1149}
1150
1151void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1152  OS << Node->getType().getAsString(Policy);
1153  OS << "(";
1154  for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1155                                         ArgEnd = Node->arg_end();
1156       Arg != ArgEnd; ++Arg) {
1157    if (Arg != Node->arg_begin())
1158      OS << ", ";
1159    PrintExpr(*Arg);
1160  }
1161  OS << ")";
1162}
1163
1164void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1165  if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1166    OS << TSInfo->getType().getAsString(Policy) << "()";
1167  else
1168    OS << Node->getType().getAsString(Policy) << "()";
1169}
1170
1171void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1172  if (E->isGlobalNew())
1173    OS << "::";
1174  OS << "new ";
1175  unsigned NumPlace = E->getNumPlacementArgs();
1176  if (NumPlace > 0) {
1177    OS << "(";
1178    PrintExpr(E->getPlacementArg(0));
1179    for (unsigned i = 1; i < NumPlace; ++i) {
1180      OS << ", ";
1181      PrintExpr(E->getPlacementArg(i));
1182    }
1183    OS << ") ";
1184  }
1185  if (E->isParenTypeId())
1186    OS << "(";
1187  std::string TypeS;
1188  if (Expr *Size = E->getArraySize()) {
1189    llvm::raw_string_ostream s(TypeS);
1190    Size->printPretty(s, Context, Helper, Policy);
1191    s.flush();
1192    TypeS = "[" + TypeS + "]";
1193  }
1194  E->getAllocatedType().getAsStringInternal(TypeS, Policy);
1195  OS << TypeS;
1196  if (E->isParenTypeId())
1197    OS << ")";
1198
1199  if (E->hasInitializer()) {
1200    OS << "(";
1201    unsigned NumCons = E->getNumConstructorArgs();
1202    if (NumCons > 0) {
1203      PrintExpr(E->getConstructorArg(0));
1204      for (unsigned i = 1; i < NumCons; ++i) {
1205        OS << ", ";
1206        PrintExpr(E->getConstructorArg(i));
1207      }
1208    }
1209    OS << ")";
1210  }
1211}
1212
1213void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1214  if (E->isGlobalDelete())
1215    OS << "::";
1216  OS << "delete ";
1217  if (E->isArrayForm())
1218    OS << "[] ";
1219  PrintExpr(E->getArgument());
1220}
1221
1222void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1223  PrintExpr(E->getBase());
1224  if (E->isArrow())
1225    OS << "->";
1226  else
1227    OS << '.';
1228  if (E->getQualifier())
1229    E->getQualifier()->print(OS, Policy);
1230
1231  std::string TypeS;
1232  if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
1233    OS << II->getName();
1234  else
1235    E->getDestroyedType().getAsStringInternal(TypeS, Policy);
1236  OS << TypeS;
1237}
1238
1239void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
1240  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
1241    if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
1242      // Don't print any defaulted arguments
1243      break;
1244    }
1245
1246    if (i) OS << ", ";
1247    PrintExpr(E->getArg(i));
1248  }
1249}
1250
1251void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
1252  // Just forward to the sub expression.
1253  PrintExpr(E->getSubExpr());
1254}
1255
1256void
1257StmtPrinter::VisitCXXUnresolvedConstructExpr(
1258                                           CXXUnresolvedConstructExpr *Node) {
1259  OS << Node->getTypeAsWritten().getAsString(Policy);
1260  OS << "(";
1261  for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
1262                                             ArgEnd = Node->arg_end();
1263       Arg != ArgEnd; ++Arg) {
1264    if (Arg != Node->arg_begin())
1265      OS << ", ";
1266    PrintExpr(*Arg);
1267  }
1268  OS << ")";
1269}
1270
1271void StmtPrinter::VisitCXXDependentScopeMemberExpr(
1272                                         CXXDependentScopeMemberExpr *Node) {
1273  if (!Node->isImplicitAccess()) {
1274    PrintExpr(Node->getBase());
1275    OS << (Node->isArrow() ? "->" : ".");
1276  }
1277  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1278    Qualifier->print(OS, Policy);
1279  else if (Node->hasExplicitTemplateArgs())
1280    // FIXME: Track use of "template" keyword explicitly?
1281    OS << "template ";
1282
1283  OS << Node->getMemberNameInfo();
1284
1285  if (Node->hasExplicitTemplateArgs()) {
1286    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1287                                                    Node->getTemplateArgs(),
1288                                                    Node->getNumTemplateArgs(),
1289                                                    Policy);
1290  }
1291}
1292
1293void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
1294  if (!Node->isImplicitAccess()) {
1295    PrintExpr(Node->getBase());
1296    OS << (Node->isArrow() ? "->" : ".");
1297  }
1298  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1299    Qualifier->print(OS, Policy);
1300
1301  // FIXME: this might originally have been written with 'template'
1302
1303  OS << Node->getMemberNameInfo();
1304
1305  if (Node->hasExplicitTemplateArgs()) {
1306    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1307                                                    Node->getTemplateArgs(),
1308                                                    Node->getNumTemplateArgs(),
1309                                                    Policy);
1310  }
1311}
1312
1313static const char *getTypeTraitName(UnaryTypeTrait UTT) {
1314  switch (UTT) {
1315  case UTT_HasNothrowAssign:      return "__has_nothrow_assign";
1316  case UTT_HasNothrowConstructor: return "__has_nothrow_constructor";
1317  case UTT_HasNothrowCopy:          return "__has_nothrow_copy";
1318  case UTT_HasTrivialAssign:      return "__has_trivial_assign";
1319  case UTT_HasTrivialDefaultConstructor: return "__has_trivial_constructor";
1320  case UTT_HasTrivialCopy:          return "__has_trivial_copy";
1321  case UTT_HasTrivialDestructor:  return "__has_trivial_destructor";
1322  case UTT_HasVirtualDestructor:  return "__has_virtual_destructor";
1323  case UTT_IsAbstract:            return "__is_abstract";
1324  case UTT_IsArithmetic:            return "__is_arithmetic";
1325  case UTT_IsArray:                 return "__is_array";
1326  case UTT_IsClass:               return "__is_class";
1327  case UTT_IsCompleteType:          return "__is_complete_type";
1328  case UTT_IsCompound:              return "__is_compound";
1329  case UTT_IsConst:                 return "__is_const";
1330  case UTT_IsEmpty:               return "__is_empty";
1331  case UTT_IsEnum:                return "__is_enum";
1332  case UTT_IsFloatingPoint:         return "__is_floating_point";
1333  case UTT_IsFunction:              return "__is_function";
1334  case UTT_IsFundamental:           return "__is_fundamental";
1335  case UTT_IsIntegral:              return "__is_integral";
1336  case UTT_IsLiteral:               return "__is_literal";
1337  case UTT_IsLvalueReference:       return "__is_lvalue_reference";
1338  case UTT_IsMemberFunctionPointer: return "__is_member_function_pointer";
1339  case UTT_IsMemberObjectPointer:   return "__is_member_object_pointer";
1340  case UTT_IsMemberPointer:         return "__is_member_pointer";
1341  case UTT_IsObject:                return "__is_object";
1342  case UTT_IsPOD:                 return "__is_pod";
1343  case UTT_IsPointer:               return "__is_pointer";
1344  case UTT_IsPolymorphic:         return "__is_polymorphic";
1345  case UTT_IsReference:             return "__is_reference";
1346  case UTT_IsRvalueReference:       return "__is_rvalue_reference";
1347  case UTT_IsScalar:                return "__is_scalar";
1348  case UTT_IsSigned:                return "__is_signed";
1349  case UTT_IsStandardLayout:        return "__is_standard_layout";
1350  case UTT_IsTrivial:               return "__is_trivial";
1351  case UTT_IsTriviallyCopyable:     return "__is_trivially_copyable";
1352  case UTT_IsUnion:               return "__is_union";
1353  case UTT_IsUnsigned:              return "__is_unsigned";
1354  case UTT_IsVoid:                  return "__is_void";
1355  case UTT_IsVolatile:              return "__is_volatile";
1356  }
1357  llvm_unreachable("Type trait not covered by switch statement");
1358}
1359
1360static const char *getTypeTraitName(BinaryTypeTrait BTT) {
1361  switch (BTT) {
1362  case BTT_IsBaseOf:         return "__is_base_of";
1363  case BTT_IsConvertible:    return "__is_convertible";
1364  case BTT_IsSame:           return "__is_same";
1365  case BTT_TypeCompatible:   return "__builtin_types_compatible_p";
1366  case BTT_IsConvertibleTo:  return "__is_convertible_to";
1367  }
1368  llvm_unreachable("Binary type trait not covered by switch");
1369}
1370
1371static const char *getTypeTraitName(ArrayTypeTrait ATT) {
1372  switch (ATT) {
1373  case ATT_ArrayRank:        return "__array_rank";
1374  case ATT_ArrayExtent:      return "__array_extent";
1375  }
1376  llvm_unreachable("Array type trait not covered by switch");
1377}
1378
1379static const char *getExpressionTraitName(ExpressionTrait ET) {
1380  switch (ET) {
1381  case ET_IsLValueExpr:      return "__is_lvalue_expr";
1382  case ET_IsRValueExpr:      return "__is_rvalue_expr";
1383  }
1384  llvm_unreachable("Expression type trait not covered by switch");
1385}
1386
1387void StmtPrinter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1388  OS << getTypeTraitName(E->getTrait()) << "("
1389     << E->getQueriedType().getAsString(Policy) << ")";
1390}
1391
1392void StmtPrinter::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
1393  OS << getTypeTraitName(E->getTrait()) << "("
1394     << E->getLhsType().getAsString(Policy) << ","
1395     << E->getRhsType().getAsString(Policy) << ")";
1396}
1397
1398void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
1399  OS << getTypeTraitName(E->getTrait()) << "("
1400     << E->getQueriedType().getAsString(Policy) << ")";
1401}
1402
1403void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
1404    OS << getExpressionTraitName(E->getTrait()) << "(";
1405    PrintExpr(E->getQueriedExpression());
1406    OS << ")";
1407}
1408
1409void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
1410  OS << "noexcept(";
1411  PrintExpr(E->getOperand());
1412  OS << ")";
1413}
1414
1415void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
1416  PrintExpr(E->getPattern());
1417  OS << "...";
1418}
1419
1420void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1421  OS << "sizeof...(" << E->getPack()->getNameAsString() << ")";
1422}
1423
1424void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
1425                                       SubstNonTypeTemplateParmPackExpr *Node) {
1426  OS << Node->getParameterPack()->getNameAsString();
1427}
1428
1429void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
1430                                       SubstNonTypeTemplateParmExpr *Node) {
1431  Visit(Node->getReplacement());
1432}
1433
1434void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
1435  PrintExpr(Node->GetTemporaryExpr());
1436}
1437
1438// Obj-C
1439
1440void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
1441  OS << "@";
1442  VisitStringLiteral(Node->getString());
1443}
1444
1445void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
1446  OS << "@encode(" << Node->getEncodedType().getAsString(Policy) << ')';
1447}
1448
1449void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
1450  OS << "@selector(" << Node->getSelector().getAsString() << ')';
1451}
1452
1453void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
1454  OS << "@protocol(" << Node->getProtocol() << ')';
1455}
1456
1457void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
1458  OS << "[";
1459  switch (Mess->getReceiverKind()) {
1460  case ObjCMessageExpr::Instance:
1461    PrintExpr(Mess->getInstanceReceiver());
1462    break;
1463
1464  case ObjCMessageExpr::Class:
1465    OS << Mess->getClassReceiver().getAsString(Policy);
1466    break;
1467
1468  case ObjCMessageExpr::SuperInstance:
1469  case ObjCMessageExpr::SuperClass:
1470    OS << "Super";
1471    break;
1472  }
1473
1474  OS << ' ';
1475  Selector selector = Mess->getSelector();
1476  if (selector.isUnarySelector()) {
1477    OS << selector.getNameForSlot(0);
1478  } else {
1479    for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
1480      if (i < selector.getNumArgs()) {
1481        if (i > 0) OS << ' ';
1482        if (selector.getIdentifierInfoForSlot(i))
1483          OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
1484        else
1485           OS << ":";
1486      }
1487      else OS << ", "; // Handle variadic methods.
1488
1489      PrintExpr(Mess->getArg(i));
1490    }
1491  }
1492  OS << "]";
1493}
1494
1495void
1496StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
1497  PrintExpr(E->getSubExpr());
1498}
1499
1500void
1501StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
1502  OS << "(" << E->getBridgeKindName() << E->getType().getAsString(Policy)
1503     << ")";
1504  PrintExpr(E->getSubExpr());
1505}
1506
1507void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
1508  BlockDecl *BD = Node->getBlockDecl();
1509  OS << "^";
1510
1511  const FunctionType *AFT = Node->getFunctionType();
1512
1513  if (isa<FunctionNoProtoType>(AFT)) {
1514    OS << "()";
1515  } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
1516    OS << '(';
1517    std::string ParamStr;
1518    for (BlockDecl::param_iterator AI = BD->param_begin(),
1519         E = BD->param_end(); AI != E; ++AI) {
1520      if (AI != BD->param_begin()) OS << ", ";
1521      ParamStr = (*AI)->getNameAsString();
1522      (*AI)->getType().getAsStringInternal(ParamStr, Policy);
1523      OS << ParamStr;
1524    }
1525
1526    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
1527    if (FT->isVariadic()) {
1528      if (!BD->param_empty()) OS << ", ";
1529      OS << "...";
1530    }
1531    OS << ')';
1532  }
1533}
1534
1535void StmtPrinter::VisitBlockDeclRefExpr(BlockDeclRefExpr *Node) {
1536  OS << Node->getDecl();
1537}
1538
1539void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {}
1540
1541void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
1542  OS << "__builtin_astype(";
1543  PrintExpr(Node->getSrcExpr());
1544  OS << ", " << Node->getType().getAsString();
1545  OS << ")";
1546}
1547
1548//===----------------------------------------------------------------------===//
1549// Stmt method implementations
1550//===----------------------------------------------------------------------===//
1551
1552void Stmt::dumpPretty(ASTContext& Context) const {
1553  printPretty(llvm::errs(), Context, 0,
1554              PrintingPolicy(Context.getLangOptions()));
1555}
1556
1557void Stmt::printPretty(raw_ostream &OS, ASTContext& Context,
1558                       PrinterHelper* Helper,
1559                       const PrintingPolicy &Policy,
1560                       unsigned Indentation) const {
1561  if (this == 0) {
1562    OS << "<NULL>";
1563    return;
1564  }
1565
1566  if (Policy.Dump && &Context) {
1567    dump(OS, Context.getSourceManager());
1568    return;
1569  }
1570
1571  StmtPrinter P(OS, Context, Helper, Policy, Indentation);
1572  P.Visit(const_cast<Stmt*>(this));
1573}
1574
1575//===----------------------------------------------------------------------===//
1576// PrinterHelper
1577//===----------------------------------------------------------------------===//
1578
1579// Implement virtual destructor.
1580PrinterHelper::~PrinterHelper() {}
1581