StmtPrinter.cpp revision a59d20b135bfde058a5a69045bab5ec4e2553f74
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 "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "llvm/ADT/SmallString.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::VisitMSDependentExistsStmt(MSDependentExistsStmt *Node) {
309  Indent();
310  if (Node->isIfExists())
311    OS << "__if_exists (";
312  else
313    OS << "__if_not_exists (";
314
315  if (NestedNameSpecifier *Qualifier
316        = Node->getQualifierLoc().getNestedNameSpecifier())
317    Qualifier->print(OS, Policy);
318
319  OS << Node->getNameInfo() << ") ";
320
321  PrintRawCompoundStmt(Node->getSubStmt());
322}
323
324void StmtPrinter::VisitGotoStmt(GotoStmt *Node) {
325  Indent() << "goto " << Node->getLabel()->getName() << ";\n";
326}
327
328void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) {
329  Indent() << "goto *";
330  PrintExpr(Node->getTarget());
331  OS << ";\n";
332}
333
334void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) {
335  Indent() << "continue;\n";
336}
337
338void StmtPrinter::VisitBreakStmt(BreakStmt *Node) {
339  Indent() << "break;\n";
340}
341
342
343void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) {
344  Indent() << "return";
345  if (Node->getRetValue()) {
346    OS << " ";
347    PrintExpr(Node->getRetValue());
348  }
349  OS << ";\n";
350}
351
352
353void StmtPrinter::VisitAsmStmt(AsmStmt *Node) {
354  Indent() << "asm ";
355
356  if (Node->isVolatile())
357    OS << "volatile ";
358
359  OS << "(";
360  VisitStringLiteral(Node->getAsmString());
361
362  // Outputs
363  if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 ||
364      Node->getNumClobbers() != 0)
365    OS << " : ";
366
367  for (unsigned i = 0, e = Node->getNumOutputs(); i != e; ++i) {
368    if (i != 0)
369      OS << ", ";
370
371    if (!Node->getOutputName(i).empty()) {
372      OS << '[';
373      OS << Node->getOutputName(i);
374      OS << "] ";
375    }
376
377    VisitStringLiteral(Node->getOutputConstraintLiteral(i));
378    OS << " ";
379    Visit(Node->getOutputExpr(i));
380  }
381
382  // Inputs
383  if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0)
384    OS << " : ";
385
386  for (unsigned i = 0, e = Node->getNumInputs(); i != e; ++i) {
387    if (i != 0)
388      OS << ", ";
389
390    if (!Node->getInputName(i).empty()) {
391      OS << '[';
392      OS << Node->getInputName(i);
393      OS << "] ";
394    }
395
396    VisitStringLiteral(Node->getInputConstraintLiteral(i));
397    OS << " ";
398    Visit(Node->getInputExpr(i));
399  }
400
401  // Clobbers
402  if (Node->getNumClobbers() != 0)
403    OS << " : ";
404
405  for (unsigned i = 0, e = Node->getNumClobbers(); i != e; ++i) {
406    if (i != 0)
407      OS << ", ";
408
409    VisitStringLiteral(Node->getClobber(i));
410  }
411
412  OS << ");\n";
413}
414
415void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
416  Indent() << "@try";
417  if (CompoundStmt *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
418    PrintRawCompoundStmt(TS);
419    OS << "\n";
420  }
421
422  for (unsigned I = 0, N = Node->getNumCatchStmts(); I != N; ++I) {
423    ObjCAtCatchStmt *catchStmt = Node->getCatchStmt(I);
424    Indent() << "@catch(";
425    if (catchStmt->getCatchParamDecl()) {
426      if (Decl *DS = catchStmt->getCatchParamDecl())
427        PrintRawDecl(DS);
428    }
429    OS << ")";
430    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(catchStmt->getCatchBody())) {
431      PrintRawCompoundStmt(CS);
432      OS << "\n";
433    }
434  }
435
436  if (ObjCAtFinallyStmt *FS = static_cast<ObjCAtFinallyStmt *>(
437        Node->getFinallyStmt())) {
438    Indent() << "@finally";
439    PrintRawCompoundStmt(dyn_cast<CompoundStmt>(FS->getFinallyBody()));
440    OS << "\n";
441  }
442}
443
444void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {
445}
446
447void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) {
448  Indent() << "@catch (...) { /* todo */ } \n";
449}
450
451void StmtPrinter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *Node) {
452  Indent() << "@throw";
453  if (Node->getThrowExpr()) {
454    OS << " ";
455    PrintExpr(Node->getThrowExpr());
456  }
457  OS << ";\n";
458}
459
460void StmtPrinter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *Node) {
461  Indent() << "@synchronized (";
462  PrintExpr(Node->getSynchExpr());
463  OS << ")";
464  PrintRawCompoundStmt(Node->getSynchBody());
465  OS << "\n";
466}
467
468void StmtPrinter::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *Node) {
469  Indent() << "@autoreleasepool";
470  PrintRawCompoundStmt(dyn_cast<CompoundStmt>(Node->getSubStmt()));
471  OS << "\n";
472}
473
474void StmtPrinter::PrintRawCXXCatchStmt(CXXCatchStmt *Node) {
475  OS << "catch (";
476  if (Decl *ExDecl = Node->getExceptionDecl())
477    PrintRawDecl(ExDecl);
478  else
479    OS << "...";
480  OS << ") ";
481  PrintRawCompoundStmt(cast<CompoundStmt>(Node->getHandlerBlock()));
482}
483
484void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) {
485  Indent();
486  PrintRawCXXCatchStmt(Node);
487  OS << "\n";
488}
489
490void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) {
491  Indent() << "try ";
492  PrintRawCompoundStmt(Node->getTryBlock());
493  for (unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) {
494    OS << " ";
495    PrintRawCXXCatchStmt(Node->getHandler(i));
496  }
497  OS << "\n";
498}
499
500void StmtPrinter::VisitSEHTryStmt(SEHTryStmt *Node) {
501  Indent() << (Node->getIsCXXTry() ? "try " : "__try ");
502  PrintRawCompoundStmt(Node->getTryBlock());
503  SEHExceptStmt *E = Node->getExceptHandler();
504  SEHFinallyStmt *F = Node->getFinallyHandler();
505  if(E)
506    PrintRawSEHExceptHandler(E);
507  else {
508    assert(F && "Must have a finally block...");
509    PrintRawSEHFinallyStmt(F);
510  }
511  OS << "\n";
512}
513
514void StmtPrinter::PrintRawSEHFinallyStmt(SEHFinallyStmt *Node) {
515  OS << "__finally ";
516  PrintRawCompoundStmt(Node->getBlock());
517  OS << "\n";
518}
519
520void StmtPrinter::PrintRawSEHExceptHandler(SEHExceptStmt *Node) {
521  OS << "__except (";
522  VisitExpr(Node->getFilterExpr());
523  OS << ")\n";
524  PrintRawCompoundStmt(Node->getBlock());
525  OS << "\n";
526}
527
528void StmtPrinter::VisitSEHExceptStmt(SEHExceptStmt *Node) {
529  Indent();
530  PrintRawSEHExceptHandler(Node);
531  OS << "\n";
532}
533
534void StmtPrinter::VisitSEHFinallyStmt(SEHFinallyStmt *Node) {
535  Indent();
536  PrintRawSEHFinallyStmt(Node);
537  OS << "\n";
538}
539
540//===----------------------------------------------------------------------===//
541//  Expr printing methods.
542//===----------------------------------------------------------------------===//
543
544void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
545  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
546    Qualifier->print(OS, Policy);
547  if (Node->hasTemplateKeyword())
548    OS << "template ";
549  OS << Node->getNameInfo();
550  if (Node->hasExplicitTemplateArgs())
551    OS << TemplateSpecializationType::PrintTemplateArgumentList(
552                                                    Node->getTemplateArgs(),
553                                                    Node->getNumTemplateArgs(),
554                                                    Policy);
555}
556
557void StmtPrinter::VisitDependentScopeDeclRefExpr(
558                                           DependentScopeDeclRefExpr *Node) {
559  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
560    Qualifier->print(OS, Policy);
561  if (Node->hasTemplateKeyword())
562    OS << "template ";
563  OS << Node->getNameInfo();
564  if (Node->hasExplicitTemplateArgs())
565    OS << TemplateSpecializationType::PrintTemplateArgumentList(
566                                                   Node->getTemplateArgs(),
567                                                   Node->getNumTemplateArgs(),
568                                                   Policy);
569}
570
571void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
572  if (Node->getQualifier())
573    Node->getQualifier()->print(OS, Policy);
574  if (Node->hasTemplateKeyword())
575    OS << "template ";
576  OS << Node->getNameInfo();
577  if (Node->hasExplicitTemplateArgs())
578    OS << TemplateSpecializationType::PrintTemplateArgumentList(
579                                                   Node->getTemplateArgs(),
580                                                   Node->getNumTemplateArgs(),
581                                                   Policy);
582}
583
584void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
585  if (Node->getBase()) {
586    PrintExpr(Node->getBase());
587    OS << (Node->isArrow() ? "->" : ".");
588  }
589  OS << *Node->getDecl();
590}
591
592void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
593  if (Node->isSuperReceiver())
594    OS << "super.";
595  else if (Node->getBase()) {
596    PrintExpr(Node->getBase());
597    OS << ".";
598  }
599
600  if (Node->isImplicitProperty())
601    OS << Node->getImplicitPropertyGetter()->getSelector().getAsString();
602  else
603    OS << Node->getExplicitProperty()->getName();
604}
605
606void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
607  switch (Node->getIdentType()) {
608    default:
609      llvm_unreachable("unknown case");
610    case PredefinedExpr::Func:
611      OS << "__func__";
612      break;
613    case PredefinedExpr::Function:
614      OS << "__FUNCTION__";
615      break;
616    case PredefinedExpr::PrettyFunction:
617      OS << "__PRETTY_FUNCTION__";
618      break;
619  }
620}
621
622void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
623  unsigned value = Node->getValue();
624
625  switch (Node->getKind()) {
626  case CharacterLiteral::Ascii: break; // no prefix.
627  case CharacterLiteral::Wide:  OS << 'L'; break;
628  case CharacterLiteral::UTF16: OS << 'u'; break;
629  case CharacterLiteral::UTF32: OS << 'U'; break;
630  }
631
632  switch (value) {
633  case '\\':
634    OS << "'\\\\'";
635    break;
636  case '\'':
637    OS << "'\\''";
638    break;
639  case '\a':
640    // TODO: K&R: the meaning of '\\a' is different in traditional C
641    OS << "'\\a'";
642    break;
643  case '\b':
644    OS << "'\\b'";
645    break;
646  // Nonstandard escape sequence.
647  /*case '\e':
648    OS << "'\\e'";
649    break;*/
650  case '\f':
651    OS << "'\\f'";
652    break;
653  case '\n':
654    OS << "'\\n'";
655    break;
656  case '\r':
657    OS << "'\\r'";
658    break;
659  case '\t':
660    OS << "'\\t'";
661    break;
662  case '\v':
663    OS << "'\\v'";
664    break;
665  default:
666    if (value < 256 && isprint(value)) {
667      OS << "'" << (char)value << "'";
668    } else if (value < 256) {
669      OS << "'\\x";
670      OS.write_hex(value) << "'";
671    } else {
672      // FIXME what to really do here?
673      OS << value;
674    }
675  }
676}
677
678void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
679  bool isSigned = Node->getType()->isSignedIntegerType();
680  OS << Node->getValue().toString(10, isSigned);
681
682  // Emit suffixes.  Integer literals are always a builtin integer type.
683  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
684  default: llvm_unreachable("Unexpected type for integer literal!");
685  // FIXME: The Short and UShort cases are to handle cases where a short
686  // integeral literal is formed during template instantiation.  They should
687  // be removed when template instantiation no longer needs integer literals.
688  case BuiltinType::Short:
689  case BuiltinType::UShort:
690  case BuiltinType::Int:       break; // no suffix.
691  case BuiltinType::UInt:      OS << 'U'; break;
692  case BuiltinType::Long:      OS << 'L'; break;
693  case BuiltinType::ULong:     OS << "UL"; break;
694  case BuiltinType::LongLong:  OS << "LL"; break;
695  case BuiltinType::ULongLong: OS << "ULL"; break;
696  case BuiltinType::Int128:    OS << "i128"; break;
697  case BuiltinType::UInt128:   OS << "Ui128"; break;
698  }
699}
700void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
701  SmallString<16> Str;
702  Node->getValue().toString(Str);
703  OS << Str;
704}
705
706void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
707  PrintExpr(Node->getSubExpr());
708  OS << "i";
709}
710
711void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
712  switch (Str->getKind()) {
713  case StringLiteral::Ascii: break; // no prefix.
714  case StringLiteral::Wide:  OS << 'L'; break;
715  case StringLiteral::UTF8:  OS << "u8"; break;
716  case StringLiteral::UTF16: OS << 'u'; break;
717  case StringLiteral::UTF32: OS << 'U'; break;
718  }
719  OS << '"';
720  static char Hex[] = "0123456789ABCDEF";
721
722  for (unsigned I = 0, N = Str->getLength(); I != N; ++I) {
723    switch (uint32_t Char = Str->getCodeUnit(I)) {
724    default:
725      // FIXME: Is this the best way to print wchar_t?
726      if (Char > 0xff) {
727        assert(Char <= 0x10ffff && "invalid unicode codepoint");
728        if (Char > 0xffff)
729          OS << "\\U00"
730             << Hex[(Char >> 20) & 15]
731             << Hex[(Char >> 16) & 15];
732        else
733          OS << "\\u";
734        OS << Hex[(Char >> 12) & 15]
735           << Hex[(Char >>  8) & 15]
736           << Hex[(Char >>  4) & 15]
737           << Hex[(Char >>  0) & 15];
738        break;
739      }
740      if (Char <= 0xff && isprint(Char))
741        OS << (char)Char;
742      else  // Output anything hard as an octal escape.
743        OS << '\\'
744        << (char)('0'+ ((Char >> 6) & 7))
745        << (char)('0'+ ((Char >> 3) & 7))
746        << (char)('0'+ ((Char >> 0) & 7));
747      break;
748    // Handle some common non-printable cases to make dumps prettier.
749    case '\\': OS << "\\\\"; break;
750    case '"': OS << "\\\""; break;
751    case '\n': OS << "\\n"; break;
752    case '\t': OS << "\\t"; break;
753    case '\a': OS << "\\a"; break;
754    case '\b': OS << "\\b"; break;
755    }
756  }
757  OS << '"';
758}
759void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
760  OS << "(";
761  PrintExpr(Node->getSubExpr());
762  OS << ")";
763}
764void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
765  if (!Node->isPostfix()) {
766    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
767
768    // Print a space if this is an "identifier operator" like __real, or if
769    // it might be concatenated incorrectly like '+'.
770    switch (Node->getOpcode()) {
771    default: break;
772    case UO_Real:
773    case UO_Imag:
774    case UO_Extension:
775      OS << ' ';
776      break;
777    case UO_Plus:
778    case UO_Minus:
779      if (isa<UnaryOperator>(Node->getSubExpr()))
780        OS << ' ';
781      break;
782    }
783  }
784  PrintExpr(Node->getSubExpr());
785
786  if (Node->isPostfix())
787    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
788}
789
790void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
791  OS << "__builtin_offsetof(";
792  OS << Node->getTypeSourceInfo()->getType().getAsString(Policy) << ", ";
793  bool PrintedSomething = false;
794  for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
795    OffsetOfExpr::OffsetOfNode ON = Node->getComponent(i);
796    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Array) {
797      // Array node
798      OS << "[";
799      PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
800      OS << "]";
801      PrintedSomething = true;
802      continue;
803    }
804
805    // Skip implicit base indirections.
806    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Base)
807      continue;
808
809    // Field or identifier node.
810    IdentifierInfo *Id = ON.getFieldName();
811    if (!Id)
812      continue;
813
814    if (PrintedSomething)
815      OS << ".";
816    else
817      PrintedSomething = true;
818    OS << Id->getName();
819  }
820  OS << ")";
821}
822
823void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
824  switch(Node->getKind()) {
825  case UETT_SizeOf:
826    OS << "sizeof";
827    break;
828  case UETT_AlignOf:
829    OS << "__alignof";
830    break;
831  case UETT_VecStep:
832    OS << "vec_step";
833    break;
834  }
835  if (Node->isArgumentType())
836    OS << "(" << Node->getArgumentType().getAsString(Policy) << ")";
837  else {
838    OS << " ";
839    PrintExpr(Node->getArgumentExpr());
840  }
841}
842
843void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
844  OS << "_Generic(";
845  PrintExpr(Node->getControllingExpr());
846  for (unsigned i = 0; i != Node->getNumAssocs(); ++i) {
847    OS << ", ";
848    QualType T = Node->getAssocType(i);
849    if (T.isNull())
850      OS << "default";
851    else
852      OS << T.getAsString(Policy);
853    OS << ": ";
854    PrintExpr(Node->getAssocExpr(i));
855  }
856  OS << ")";
857}
858
859void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
860  PrintExpr(Node->getLHS());
861  OS << "[";
862  PrintExpr(Node->getRHS());
863  OS << "]";
864}
865
866void StmtPrinter::PrintCallArgs(CallExpr *Call) {
867  for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
868    if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
869      // Don't print any defaulted arguments
870      break;
871    }
872
873    if (i) OS << ", ";
874    PrintExpr(Call->getArg(i));
875  }
876}
877
878void StmtPrinter::VisitCallExpr(CallExpr *Call) {
879  PrintExpr(Call->getCallee());
880  OS << "(";
881  PrintCallArgs(Call);
882  OS << ")";
883}
884void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
885  // FIXME: Suppress printing implicit bases (like "this")
886  PrintExpr(Node->getBase());
887  if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
888    if (FD->isAnonymousStructOrUnion())
889      return;
890  OS << (Node->isArrow() ? "->" : ".");
891  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
892    Qualifier->print(OS, Policy);
893  if (Node->hasTemplateKeyword())
894    OS << "template ";
895  OS << Node->getMemberNameInfo();
896  if (Node->hasExplicitTemplateArgs())
897    OS << TemplateSpecializationType::PrintTemplateArgumentList(
898                                                    Node->getTemplateArgs(),
899                                                    Node->getNumTemplateArgs(),
900                                                                Policy);
901}
902void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
903  PrintExpr(Node->getBase());
904  OS << (Node->isArrow() ? "->isa" : ".isa");
905}
906
907void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
908  PrintExpr(Node->getBase());
909  OS << ".";
910  OS << Node->getAccessor().getName();
911}
912void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
913  OS << "(" << Node->getType().getAsString(Policy) << ")";
914  PrintExpr(Node->getSubExpr());
915}
916void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
917  OS << "(" << Node->getType().getAsString(Policy) << ")";
918  PrintExpr(Node->getInitializer());
919}
920void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
921  // No need to print anything, simply forward to the sub expression.
922  PrintExpr(Node->getSubExpr());
923}
924void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
925  PrintExpr(Node->getLHS());
926  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
927  PrintExpr(Node->getRHS());
928}
929void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
930  PrintExpr(Node->getLHS());
931  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
932  PrintExpr(Node->getRHS());
933}
934void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
935  PrintExpr(Node->getCond());
936  OS << " ? ";
937  PrintExpr(Node->getLHS());
938  OS << " : ";
939  PrintExpr(Node->getRHS());
940}
941
942// GNU extensions.
943
944void
945StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
946  PrintExpr(Node->getCommon());
947  OS << " ?: ";
948  PrintExpr(Node->getFalseExpr());
949}
950void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
951  OS << "&&" << Node->getLabel()->getName();
952}
953
954void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
955  OS << "(";
956  PrintRawCompoundStmt(E->getSubStmt());
957  OS << ")";
958}
959
960void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
961  OS << "__builtin_choose_expr(";
962  PrintExpr(Node->getCond());
963  OS << ", ";
964  PrintExpr(Node->getLHS());
965  OS << ", ";
966  PrintExpr(Node->getRHS());
967  OS << ")";
968}
969
970void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
971  OS << "__null";
972}
973
974void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
975  OS << "__builtin_shufflevector(";
976  for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
977    if (i) OS << ", ";
978    PrintExpr(Node->getExpr(i));
979  }
980  OS << ")";
981}
982
983void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
984  if (Node->getSyntacticForm()) {
985    Visit(Node->getSyntacticForm());
986    return;
987  }
988
989  OS << "{ ";
990  for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
991    if (i) OS << ", ";
992    if (Node->getInit(i))
993      PrintExpr(Node->getInit(i));
994    else
995      OS << "0";
996  }
997  OS << " }";
998}
999
1000void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
1001  OS << "( ";
1002  for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
1003    if (i) OS << ", ";
1004    PrintExpr(Node->getExpr(i));
1005  }
1006  OS << " )";
1007}
1008
1009void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
1010  for (DesignatedInitExpr::designators_iterator D = Node->designators_begin(),
1011                      DEnd = Node->designators_end();
1012       D != DEnd; ++D) {
1013    if (D->isFieldDesignator()) {
1014      if (D->getDotLoc().isInvalid())
1015        OS << D->getFieldName()->getName() << ":";
1016      else
1017        OS << "." << D->getFieldName()->getName();
1018    } else {
1019      OS << "[";
1020      if (D->isArrayDesignator()) {
1021        PrintExpr(Node->getArrayIndex(*D));
1022      } else {
1023        PrintExpr(Node->getArrayRangeStart(*D));
1024        OS << " ... ";
1025        PrintExpr(Node->getArrayRangeEnd(*D));
1026      }
1027      OS << "]";
1028    }
1029  }
1030
1031  OS << " = ";
1032  PrintExpr(Node->getInit());
1033}
1034
1035void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
1036  if (Policy.LangOpts.CPlusPlus)
1037    OS << "/*implicit*/" << Node->getType().getAsString(Policy) << "()";
1038  else {
1039    OS << "/*implicit*/(" << Node->getType().getAsString(Policy) << ")";
1040    if (Node->getType()->isRecordType())
1041      OS << "{}";
1042    else
1043      OS << 0;
1044  }
1045}
1046
1047void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1048  OS << "__builtin_va_arg(";
1049  PrintExpr(Node->getSubExpr());
1050  OS << ", ";
1051  OS << Node->getType().getAsString(Policy);
1052  OS << ")";
1053}
1054
1055void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
1056  PrintExpr(Node->getSyntacticForm());
1057}
1058
1059void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
1060  const char *Name = 0;
1061  switch (Node->getOp()) {
1062    case AtomicExpr::Init:
1063      Name = "__atomic_init(";
1064      break;
1065    case AtomicExpr::Load:
1066      Name = "__atomic_load(";
1067      break;
1068    case AtomicExpr::Store:
1069      Name = "__atomic_store(";
1070      break;
1071    case AtomicExpr::CmpXchgStrong:
1072      Name = "__atomic_compare_exchange_strong(";
1073      break;
1074    case AtomicExpr::CmpXchgWeak:
1075      Name = "__atomic_compare_exchange_weak(";
1076      break;
1077    case AtomicExpr::Xchg:
1078      Name = "__atomic_exchange(";
1079      break;
1080    case AtomicExpr::Add:
1081      Name = "__atomic_fetch_add(";
1082      break;
1083    case AtomicExpr::Sub:
1084      Name = "__atomic_fetch_sub(";
1085      break;
1086    case AtomicExpr::And:
1087      Name = "__atomic_fetch_and(";
1088      break;
1089    case AtomicExpr::Or:
1090      Name = "__atomic_fetch_or(";
1091      break;
1092    case AtomicExpr::Xor:
1093      Name = "__atomic_fetch_xor(";
1094      break;
1095  }
1096  OS << Name;
1097  PrintExpr(Node->getPtr());
1098  OS << ", ";
1099  if (Node->getOp() != AtomicExpr::Load) {
1100    PrintExpr(Node->getVal1());
1101    OS << ", ";
1102  }
1103  if (Node->isCmpXChg()) {
1104    PrintExpr(Node->getVal2());
1105    OS << ", ";
1106  }
1107  if (Node->getOp() != AtomicExpr::Init)
1108    PrintExpr(Node->getOrder());
1109  if (Node->isCmpXChg()) {
1110    OS << ", ";
1111    PrintExpr(Node->getOrderFail());
1112  }
1113  OS << ")";
1114}
1115
1116// C++
1117void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
1118  const char *OpStrings[NUM_OVERLOADED_OPERATORS] = {
1119    "",
1120#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1121    Spelling,
1122#include "clang/Basic/OperatorKinds.def"
1123  };
1124
1125  OverloadedOperatorKind Kind = Node->getOperator();
1126  if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1127    if (Node->getNumArgs() == 1) {
1128      OS << OpStrings[Kind] << ' ';
1129      PrintExpr(Node->getArg(0));
1130    } else {
1131      PrintExpr(Node->getArg(0));
1132      OS << ' ' << OpStrings[Kind];
1133    }
1134  } else if (Kind == OO_Call) {
1135    PrintExpr(Node->getArg(0));
1136    OS << '(';
1137    for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1138      if (ArgIdx > 1)
1139        OS << ", ";
1140      if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1141        PrintExpr(Node->getArg(ArgIdx));
1142    }
1143    OS << ')';
1144  } else if (Kind == OO_Subscript) {
1145    PrintExpr(Node->getArg(0));
1146    OS << '[';
1147    PrintExpr(Node->getArg(1));
1148    OS << ']';
1149  } else if (Node->getNumArgs() == 1) {
1150    OS << OpStrings[Kind] << ' ';
1151    PrintExpr(Node->getArg(0));
1152  } else if (Node->getNumArgs() == 2) {
1153    PrintExpr(Node->getArg(0));
1154    OS << ' ' << OpStrings[Kind] << ' ';
1155    PrintExpr(Node->getArg(1));
1156  } else {
1157    llvm_unreachable("unknown overloaded operator");
1158  }
1159}
1160
1161void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1162  VisitCallExpr(cast<CallExpr>(Node));
1163}
1164
1165void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1166  PrintExpr(Node->getCallee());
1167  OS << "<<<";
1168  PrintCallArgs(Node->getConfig());
1169  OS << ">>>(";
1170  PrintCallArgs(Node);
1171  OS << ")";
1172}
1173
1174void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1175  OS << Node->getCastName() << '<';
1176  OS << Node->getTypeAsWritten().getAsString(Policy) << ">(";
1177  PrintExpr(Node->getSubExpr());
1178  OS << ")";
1179}
1180
1181void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1182  VisitCXXNamedCastExpr(Node);
1183}
1184
1185void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1186  VisitCXXNamedCastExpr(Node);
1187}
1188
1189void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1190  VisitCXXNamedCastExpr(Node);
1191}
1192
1193void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1194  VisitCXXNamedCastExpr(Node);
1195}
1196
1197void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1198  OS << "typeid(";
1199  if (Node->isTypeOperand()) {
1200    OS << Node->getTypeOperand().getAsString(Policy);
1201  } else {
1202    PrintExpr(Node->getExprOperand());
1203  }
1204  OS << ")";
1205}
1206
1207void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1208  OS << "__uuidof(";
1209  if (Node->isTypeOperand()) {
1210    OS << Node->getTypeOperand().getAsString(Policy);
1211  } else {
1212    PrintExpr(Node->getExprOperand());
1213  }
1214  OS << ")";
1215}
1216
1217void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1218  OS << (Node->getValue() ? "true" : "false");
1219}
1220
1221void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1222  OS << "nullptr";
1223}
1224
1225void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1226  OS << "this";
1227}
1228
1229void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1230  if (Node->getSubExpr() == 0)
1231    OS << "throw";
1232  else {
1233    OS << "throw ";
1234    PrintExpr(Node->getSubExpr());
1235  }
1236}
1237
1238void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1239  // Nothing to print: we picked up the default argument
1240}
1241
1242void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1243  OS << Node->getType().getAsString(Policy);
1244  OS << "(";
1245  PrintExpr(Node->getSubExpr());
1246  OS << ")";
1247}
1248
1249void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1250  PrintExpr(Node->getSubExpr());
1251}
1252
1253void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1254  OS << Node->getType().getAsString(Policy);
1255  OS << "(";
1256  for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1257                                         ArgEnd = Node->arg_end();
1258       Arg != ArgEnd; ++Arg) {
1259    if (Arg != Node->arg_begin())
1260      OS << ", ";
1261    PrintExpr(*Arg);
1262  }
1263  OS << ")";
1264}
1265
1266void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
1267  OS << '[';
1268  bool NeedComma = false;
1269  switch (Node->getCaptureDefault()) {
1270  case LCD_None:
1271    break;
1272
1273  case LCD_ByCopy:
1274    OS << '=';
1275    NeedComma = true;
1276    break;
1277
1278  case LCD_ByRef:
1279    OS << '&';
1280    NeedComma = true;
1281    break;
1282  }
1283  for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(),
1284                                 CEnd = Node->explicit_capture_end();
1285       C != CEnd;
1286       ++C) {
1287    if (NeedComma)
1288      OS << ", ";
1289    NeedComma = true;
1290
1291    switch (C->getCaptureKind()) {
1292    case LCK_This:
1293      OS << "this";
1294      break;
1295
1296    case LCK_ByRef:
1297      if (Node->getCaptureDefault() != LCD_ByRef)
1298        OS << '&';
1299      OS << C->getCapturedVar()->getName();
1300      break;
1301
1302    case LCK_ByCopy:
1303      if (Node->getCaptureDefault() != LCD_ByCopy)
1304        OS << '=';
1305      OS << C->getCapturedVar()->getName();
1306      break;
1307    }
1308  }
1309  OS << ']';
1310
1311  if (Node->hasExplicitParameters()) {
1312    OS << " (";
1313    CXXMethodDecl *Method = Node->getCallOperator();
1314    NeedComma = false;
1315    for (CXXMethodDecl::param_iterator P = Method->param_begin(),
1316                                    PEnd = Method->param_end();
1317         P != PEnd; ++P) {
1318      if (NeedComma) {
1319        OS << ", ";
1320      } else {
1321        NeedComma = true;
1322      }
1323      std::string ParamStr = (*P)->getNameAsString();
1324      (*P)->getOriginalType().getAsStringInternal(ParamStr, Policy);
1325      OS << ParamStr;
1326    }
1327    if (Method->isVariadic()) {
1328      if (NeedComma)
1329        OS << ", ";
1330      OS << "...";
1331    }
1332    OS << ')';
1333
1334    if (Node->isMutable())
1335      OS << " mutable";
1336
1337    const FunctionProtoType *Proto
1338      = Method->getType()->getAs<FunctionProtoType>();
1339    {
1340      std::string ExceptionSpec;
1341      Proto->printExceptionSpecification(ExceptionSpec, Policy);
1342      OS << ExceptionSpec;
1343    }
1344
1345    // FIXME: Attributes
1346
1347    // FIXME: Suppress trailing return type if it wasn't specified in
1348    // the source.
1349    OS << " -> " << Proto->getResultType().getAsString(Policy);
1350  }
1351
1352  // Print the body.
1353  CompoundStmt *Body = Node->getBody();
1354  OS << ' ';
1355  PrintStmt(Body);
1356}
1357
1358void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1359  if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1360    OS << TSInfo->getType().getAsString(Policy) << "()";
1361  else
1362    OS << Node->getType().getAsString(Policy) << "()";
1363}
1364
1365void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1366  if (E->isGlobalNew())
1367    OS << "::";
1368  OS << "new ";
1369  unsigned NumPlace = E->getNumPlacementArgs();
1370  if (NumPlace > 0) {
1371    OS << "(";
1372    PrintExpr(E->getPlacementArg(0));
1373    for (unsigned i = 1; i < NumPlace; ++i) {
1374      OS << ", ";
1375      PrintExpr(E->getPlacementArg(i));
1376    }
1377    OS << ") ";
1378  }
1379  if (E->isParenTypeId())
1380    OS << "(";
1381  std::string TypeS;
1382  if (Expr *Size = E->getArraySize()) {
1383    llvm::raw_string_ostream s(TypeS);
1384    Size->printPretty(s, Context, Helper, Policy);
1385    s.flush();
1386    TypeS = "[" + TypeS + "]";
1387  }
1388  E->getAllocatedType().getAsStringInternal(TypeS, Policy);
1389  OS << TypeS;
1390  if (E->isParenTypeId())
1391    OS << ")";
1392
1393  if (E->hasInitializer()) {
1394    OS << "(";
1395    unsigned NumCons = E->getNumConstructorArgs();
1396    if (NumCons > 0) {
1397      PrintExpr(E->getConstructorArg(0));
1398      for (unsigned i = 1; i < NumCons; ++i) {
1399        OS << ", ";
1400        PrintExpr(E->getConstructorArg(i));
1401      }
1402    }
1403    OS << ")";
1404  }
1405}
1406
1407void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1408  if (E->isGlobalDelete())
1409    OS << "::";
1410  OS << "delete ";
1411  if (E->isArrayForm())
1412    OS << "[] ";
1413  PrintExpr(E->getArgument());
1414}
1415
1416void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1417  PrintExpr(E->getBase());
1418  if (E->isArrow())
1419    OS << "->";
1420  else
1421    OS << '.';
1422  if (E->getQualifier())
1423    E->getQualifier()->print(OS, Policy);
1424
1425  std::string TypeS;
1426  if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
1427    OS << II->getName();
1428  else
1429    E->getDestroyedType().getAsStringInternal(TypeS, Policy);
1430  OS << TypeS;
1431}
1432
1433void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
1434  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
1435    if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
1436      // Don't print any defaulted arguments
1437      break;
1438    }
1439
1440    if (i) OS << ", ";
1441    PrintExpr(E->getArg(i));
1442  }
1443}
1444
1445void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
1446  // Just forward to the sub expression.
1447  PrintExpr(E->getSubExpr());
1448}
1449
1450void
1451StmtPrinter::VisitCXXUnresolvedConstructExpr(
1452                                           CXXUnresolvedConstructExpr *Node) {
1453  OS << Node->getTypeAsWritten().getAsString(Policy);
1454  OS << "(";
1455  for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
1456                                             ArgEnd = Node->arg_end();
1457       Arg != ArgEnd; ++Arg) {
1458    if (Arg != Node->arg_begin())
1459      OS << ", ";
1460    PrintExpr(*Arg);
1461  }
1462  OS << ")";
1463}
1464
1465void StmtPrinter::VisitCXXDependentScopeMemberExpr(
1466                                         CXXDependentScopeMemberExpr *Node) {
1467  if (!Node->isImplicitAccess()) {
1468    PrintExpr(Node->getBase());
1469    OS << (Node->isArrow() ? "->" : ".");
1470  }
1471  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1472    Qualifier->print(OS, Policy);
1473  if (Node->hasTemplateKeyword())
1474    OS << "template ";
1475  OS << Node->getMemberNameInfo();
1476  if (Node->hasExplicitTemplateArgs()) {
1477    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1478                                                    Node->getTemplateArgs(),
1479                                                    Node->getNumTemplateArgs(),
1480                                                    Policy);
1481  }
1482}
1483
1484void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
1485  if (!Node->isImplicitAccess()) {
1486    PrintExpr(Node->getBase());
1487    OS << (Node->isArrow() ? "->" : ".");
1488  }
1489  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1490    Qualifier->print(OS, Policy);
1491  if (Node->hasTemplateKeyword())
1492    OS << "template ";
1493  OS << Node->getMemberNameInfo();
1494  if (Node->hasExplicitTemplateArgs()) {
1495    OS << TemplateSpecializationType::PrintTemplateArgumentList(
1496                                                    Node->getTemplateArgs(),
1497                                                    Node->getNumTemplateArgs(),
1498                                                    Policy);
1499  }
1500}
1501
1502static const char *getTypeTraitName(UnaryTypeTrait UTT) {
1503  switch (UTT) {
1504  case UTT_HasNothrowAssign:      return "__has_nothrow_assign";
1505  case UTT_HasNothrowConstructor: return "__has_nothrow_constructor";
1506  case UTT_HasNothrowCopy:          return "__has_nothrow_copy";
1507  case UTT_HasTrivialAssign:      return "__has_trivial_assign";
1508  case UTT_HasTrivialDefaultConstructor: return "__has_trivial_constructor";
1509  case UTT_HasTrivialCopy:          return "__has_trivial_copy";
1510  case UTT_HasTrivialDestructor:  return "__has_trivial_destructor";
1511  case UTT_HasVirtualDestructor:  return "__has_virtual_destructor";
1512  case UTT_IsAbstract:            return "__is_abstract";
1513  case UTT_IsArithmetic:            return "__is_arithmetic";
1514  case UTT_IsArray:                 return "__is_array";
1515  case UTT_IsClass:               return "__is_class";
1516  case UTT_IsCompleteType:          return "__is_complete_type";
1517  case UTT_IsCompound:              return "__is_compound";
1518  case UTT_IsConst:                 return "__is_const";
1519  case UTT_IsEmpty:               return "__is_empty";
1520  case UTT_IsEnum:                return "__is_enum";
1521  case UTT_IsFinal:                 return "__is_final";
1522  case UTT_IsFloatingPoint:         return "__is_floating_point";
1523  case UTT_IsFunction:              return "__is_function";
1524  case UTT_IsFundamental:           return "__is_fundamental";
1525  case UTT_IsIntegral:              return "__is_integral";
1526  case UTT_IsLiteral:               return "__is_literal";
1527  case UTT_IsLvalueReference:       return "__is_lvalue_reference";
1528  case UTT_IsMemberFunctionPointer: return "__is_member_function_pointer";
1529  case UTT_IsMemberObjectPointer:   return "__is_member_object_pointer";
1530  case UTT_IsMemberPointer:         return "__is_member_pointer";
1531  case UTT_IsObject:                return "__is_object";
1532  case UTT_IsPOD:                 return "__is_pod";
1533  case UTT_IsPointer:               return "__is_pointer";
1534  case UTT_IsPolymorphic:         return "__is_polymorphic";
1535  case UTT_IsReference:             return "__is_reference";
1536  case UTT_IsRvalueReference:       return "__is_rvalue_reference";
1537  case UTT_IsScalar:                return "__is_scalar";
1538  case UTT_IsSigned:                return "__is_signed";
1539  case UTT_IsStandardLayout:        return "__is_standard_layout";
1540  case UTT_IsTrivial:               return "__is_trivial";
1541  case UTT_IsTriviallyCopyable:     return "__is_trivially_copyable";
1542  case UTT_IsUnion:               return "__is_union";
1543  case UTT_IsUnsigned:              return "__is_unsigned";
1544  case UTT_IsVoid:                  return "__is_void";
1545  case UTT_IsVolatile:              return "__is_volatile";
1546  }
1547  llvm_unreachable("Type trait not covered by switch statement");
1548}
1549
1550static const char *getTypeTraitName(BinaryTypeTrait BTT) {
1551  switch (BTT) {
1552  case BTT_IsBaseOf:         return "__is_base_of";
1553  case BTT_IsConvertible:    return "__is_convertible";
1554  case BTT_IsSame:           return "__is_same";
1555  case BTT_TypeCompatible:   return "__builtin_types_compatible_p";
1556  case BTT_IsConvertibleTo:  return "__is_convertible_to";
1557  }
1558  llvm_unreachable("Binary type trait not covered by switch");
1559}
1560
1561static const char *getTypeTraitName(ArrayTypeTrait ATT) {
1562  switch (ATT) {
1563  case ATT_ArrayRank:        return "__array_rank";
1564  case ATT_ArrayExtent:      return "__array_extent";
1565  }
1566  llvm_unreachable("Array type trait not covered by switch");
1567}
1568
1569static const char *getExpressionTraitName(ExpressionTrait ET) {
1570  switch (ET) {
1571  case ET_IsLValueExpr:      return "__is_lvalue_expr";
1572  case ET_IsRValueExpr:      return "__is_rvalue_expr";
1573  }
1574  llvm_unreachable("Expression type trait not covered by switch");
1575}
1576
1577void StmtPrinter::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1578  OS << getTypeTraitName(E->getTrait()) << "("
1579     << E->getQueriedType().getAsString(Policy) << ")";
1580}
1581
1582void StmtPrinter::VisitBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
1583  OS << getTypeTraitName(E->getTrait()) << "("
1584     << E->getLhsType().getAsString(Policy) << ","
1585     << E->getRhsType().getAsString(Policy) << ")";
1586}
1587
1588void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
1589  OS << getTypeTraitName(E->getTrait()) << "("
1590     << E->getQueriedType().getAsString(Policy) << ")";
1591}
1592
1593void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
1594    OS << getExpressionTraitName(E->getTrait()) << "(";
1595    PrintExpr(E->getQueriedExpression());
1596    OS << ")";
1597}
1598
1599void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
1600  OS << "noexcept(";
1601  PrintExpr(E->getOperand());
1602  OS << ")";
1603}
1604
1605void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
1606  PrintExpr(E->getPattern());
1607  OS << "...";
1608}
1609
1610void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1611  OS << "sizeof...(" << *E->getPack() << ")";
1612}
1613
1614void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
1615                                       SubstNonTypeTemplateParmPackExpr *Node) {
1616  OS << *Node->getParameterPack();
1617}
1618
1619void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
1620                                       SubstNonTypeTemplateParmExpr *Node) {
1621  Visit(Node->getReplacement());
1622}
1623
1624void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
1625  PrintExpr(Node->GetTemporaryExpr());
1626}
1627
1628// Obj-C
1629
1630void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
1631  OS << "@";
1632  VisitStringLiteral(Node->getString());
1633}
1634
1635void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
1636  OS << "@encode(" << Node->getEncodedType().getAsString(Policy) << ')';
1637}
1638
1639void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
1640  OS << "@selector(" << Node->getSelector().getAsString() << ')';
1641}
1642
1643void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
1644  OS << "@protocol(" << *Node->getProtocol() << ')';
1645}
1646
1647void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
1648  OS << "[";
1649  switch (Mess->getReceiverKind()) {
1650  case ObjCMessageExpr::Instance:
1651    PrintExpr(Mess->getInstanceReceiver());
1652    break;
1653
1654  case ObjCMessageExpr::Class:
1655    OS << Mess->getClassReceiver().getAsString(Policy);
1656    break;
1657
1658  case ObjCMessageExpr::SuperInstance:
1659  case ObjCMessageExpr::SuperClass:
1660    OS << "Super";
1661    break;
1662  }
1663
1664  OS << ' ';
1665  Selector selector = Mess->getSelector();
1666  if (selector.isUnarySelector()) {
1667    OS << selector.getNameForSlot(0);
1668  } else {
1669    for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
1670      if (i < selector.getNumArgs()) {
1671        if (i > 0) OS << ' ';
1672        if (selector.getIdentifierInfoForSlot(i))
1673          OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
1674        else
1675           OS << ":";
1676      }
1677      else OS << ", "; // Handle variadic methods.
1678
1679      PrintExpr(Mess->getArg(i));
1680    }
1681  }
1682  OS << "]";
1683}
1684
1685void
1686StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
1687  PrintExpr(E->getSubExpr());
1688}
1689
1690void
1691StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
1692  OS << "(" << E->getBridgeKindName() << E->getType().getAsString(Policy)
1693     << ")";
1694  PrintExpr(E->getSubExpr());
1695}
1696
1697void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
1698  BlockDecl *BD = Node->getBlockDecl();
1699  OS << "^";
1700
1701  const FunctionType *AFT = Node->getFunctionType();
1702
1703  if (isa<FunctionNoProtoType>(AFT)) {
1704    OS << "()";
1705  } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
1706    OS << '(';
1707    std::string ParamStr;
1708    for (BlockDecl::param_iterator AI = BD->param_begin(),
1709         E = BD->param_end(); AI != E; ++AI) {
1710      if (AI != BD->param_begin()) OS << ", ";
1711      ParamStr = (*AI)->getNameAsString();
1712      (*AI)->getType().getAsStringInternal(ParamStr, Policy);
1713      OS << ParamStr;
1714    }
1715
1716    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
1717    if (FT->isVariadic()) {
1718      if (!BD->param_empty()) OS << ", ";
1719      OS << "...";
1720    }
1721    OS << ')';
1722  }
1723}
1724
1725void StmtPrinter::VisitBlockDeclRefExpr(BlockDeclRefExpr *Node) {
1726  OS << *Node->getDecl();
1727}
1728
1729void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
1730  PrintExpr(Node->getSourceExpr());
1731}
1732
1733void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
1734  OS << "__builtin_astype(";
1735  PrintExpr(Node->getSrcExpr());
1736  OS << ", " << Node->getType().getAsString();
1737  OS << ")";
1738}
1739
1740//===----------------------------------------------------------------------===//
1741// Stmt method implementations
1742//===----------------------------------------------------------------------===//
1743
1744void Stmt::dumpPretty(ASTContext& Context) const {
1745  printPretty(llvm::errs(), Context, 0,
1746              PrintingPolicy(Context.getLangOptions()));
1747}
1748
1749void Stmt::printPretty(raw_ostream &OS, ASTContext& Context,
1750                       PrinterHelper* Helper,
1751                       const PrintingPolicy &Policy,
1752                       unsigned Indentation) const {
1753  if (this == 0) {
1754    OS << "<NULL>";
1755    return;
1756  }
1757
1758  if (Policy.Dump && &Context) {
1759    dump(OS, Context.getSourceManager());
1760    return;
1761  }
1762
1763  StmtPrinter P(OS, Context, Helper, Policy, Indentation);
1764  P.Visit(const_cast<Stmt*>(this));
1765}
1766
1767//===----------------------------------------------------------------------===//
1768// PrinterHelper
1769//===----------------------------------------------------------------------===//
1770
1771// Implement virtual destructor.
1772PrinterHelper::~PrinterHelper() {}
1773