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/ASTContext.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/PrettyPrinter.h"
23#include "clang/AST/StmtVisitor.h"
24#include "clang/Basic/CharInfo.h"
25#include "llvm/ADT/SmallString.h"
26#include "llvm/Support/Format.h"
27using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// StmtPrinter Visitor
31//===----------------------------------------------------------------------===//
32
33namespace  {
34  class StmtPrinter : public StmtVisitor<StmtPrinter> {
35    raw_ostream &OS;
36    unsigned IndentLevel;
37    clang::PrinterHelper* Helper;
38    PrintingPolicy Policy;
39
40  public:
41    StmtPrinter(raw_ostream &os, PrinterHelper* helper,
42                const PrintingPolicy &Policy,
43                unsigned Indentation = 0)
44      : OS(os), IndentLevel(Indentation), Helper(helper), Policy(Policy) {}
45
46    void PrintStmt(Stmt *S) {
47      PrintStmt(S, Policy.Indentation);
48    }
49
50    void PrintStmt(Stmt *S, int SubIndent) {
51      IndentLevel += SubIndent;
52      if (S && isa<Expr>(S)) {
53        // If this is an expr used in a stmt context, indent and newline it.
54        Indent();
55        Visit(S);
56        OS << ";\n";
57      } else if (S) {
58        Visit(S);
59      } else {
60        Indent() << "<<<NULL STATEMENT>>>\n";
61      }
62      IndentLevel -= SubIndent;
63    }
64
65    void PrintRawCompoundStmt(CompoundStmt *S);
66    void PrintRawDecl(Decl *D);
67    void PrintRawDeclStmt(const DeclStmt *S);
68    void PrintRawIfStmt(IfStmt *If);
69    void PrintRawCXXCatchStmt(CXXCatchStmt *Catch);
70    void PrintCallArgs(CallExpr *E);
71    void PrintRawSEHExceptHandler(SEHExceptStmt *S);
72    void PrintRawSEHFinallyStmt(SEHFinallyStmt *S);
73    void PrintOMPExecutableDirective(OMPExecutableDirective *S);
74
75    void PrintExpr(Expr *E) {
76      if (E)
77        Visit(E);
78      else
79        OS << "<null expr>";
80    }
81
82    raw_ostream &Indent(int Delta = 0) {
83      for (int i = 0, e = IndentLevel+Delta; i < e; ++i)
84        OS << "  ";
85      return OS;
86    }
87
88    void Visit(Stmt* S) {
89      if (Helper && Helper->handledStmt(S,OS))
90          return;
91      else StmtVisitor<StmtPrinter>::Visit(S);
92    }
93
94    void VisitStmt(Stmt *Node) LLVM_ATTRIBUTE_UNUSED {
95      Indent() << "<<unknown stmt type>>\n";
96    }
97    void VisitExpr(Expr *Node) LLVM_ATTRIBUTE_UNUSED {
98      OS << "<<unknown expr type>>";
99    }
100    void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node);
101
102#define ABSTRACT_STMT(CLASS)
103#define STMT(CLASS, PARENT) \
104    void Visit##CLASS(CLASS *Node);
105#include "clang/AST/StmtNodes.inc"
106  };
107}
108
109//===----------------------------------------------------------------------===//
110//  Stmt printing methods.
111//===----------------------------------------------------------------------===//
112
113/// PrintRawCompoundStmt - Print a compound stmt without indenting the {, and
114/// with no newline after the }.
115void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) {
116  OS << "{\n";
117  for (auto *I : Node->body())
118    PrintStmt(I);
119
120  Indent() << "}";
121}
122
123void StmtPrinter::PrintRawDecl(Decl *D) {
124  D->print(OS, Policy, IndentLevel);
125}
126
127void StmtPrinter::PrintRawDeclStmt(const DeclStmt *S) {
128  SmallVector<Decl*, 2> Decls(S->decls());
129  Decl::printGroup(Decls.data(), Decls.size(), OS, Policy, IndentLevel);
130}
131
132void StmtPrinter::VisitNullStmt(NullStmt *Node) {
133  Indent() << ";\n";
134}
135
136void StmtPrinter::VisitDeclStmt(DeclStmt *Node) {
137  Indent();
138  PrintRawDeclStmt(Node);
139  OS << ";\n";
140}
141
142void StmtPrinter::VisitCompoundStmt(CompoundStmt *Node) {
143  Indent();
144  PrintRawCompoundStmt(Node);
145  OS << "\n";
146}
147
148void StmtPrinter::VisitCaseStmt(CaseStmt *Node) {
149  Indent(-1) << "case ";
150  PrintExpr(Node->getLHS());
151  if (Node->getRHS()) {
152    OS << " ... ";
153    PrintExpr(Node->getRHS());
154  }
155  OS << ":\n";
156
157  PrintStmt(Node->getSubStmt(), 0);
158}
159
160void StmtPrinter::VisitDefaultStmt(DefaultStmt *Node) {
161  Indent(-1) << "default:\n";
162  PrintStmt(Node->getSubStmt(), 0);
163}
164
165void StmtPrinter::VisitLabelStmt(LabelStmt *Node) {
166  Indent(-1) << Node->getName() << ":\n";
167  PrintStmt(Node->getSubStmt(), 0);
168}
169
170void StmtPrinter::VisitAttributedStmt(AttributedStmt *Node) {
171  for (const auto *Attr : Node->getAttrs()) {
172    Attr->printPretty(OS, Policy);
173  }
174
175  PrintStmt(Node->getSubStmt(), 0);
176}
177
178void StmtPrinter::PrintRawIfStmt(IfStmt *If) {
179  OS << "if (";
180  if (const DeclStmt *DS = If->getConditionVariableDeclStmt())
181    PrintRawDeclStmt(DS);
182  else
183    PrintExpr(If->getCond());
184  OS << ')';
185
186  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(If->getThen())) {
187    OS << ' ';
188    PrintRawCompoundStmt(CS);
189    OS << (If->getElse() ? ' ' : '\n');
190  } else {
191    OS << '\n';
192    PrintStmt(If->getThen());
193    if (If->getElse()) Indent();
194  }
195
196  if (Stmt *Else = If->getElse()) {
197    OS << "else";
198
199    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Else)) {
200      OS << ' ';
201      PrintRawCompoundStmt(CS);
202      OS << '\n';
203    } else if (IfStmt *ElseIf = dyn_cast<IfStmt>(Else)) {
204      OS << ' ';
205      PrintRawIfStmt(ElseIf);
206    } else {
207      OS << '\n';
208      PrintStmt(If->getElse());
209    }
210  }
211}
212
213void StmtPrinter::VisitIfStmt(IfStmt *If) {
214  Indent();
215  PrintRawIfStmt(If);
216}
217
218void StmtPrinter::VisitSwitchStmt(SwitchStmt *Node) {
219  Indent() << "switch (";
220  if (const DeclStmt *DS = Node->getConditionVariableDeclStmt())
221    PrintRawDeclStmt(DS);
222  else
223    PrintExpr(Node->getCond());
224  OS << ")";
225
226  // Pretty print compoundstmt bodies (very common).
227  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
228    OS << " ";
229    PrintRawCompoundStmt(CS);
230    OS << "\n";
231  } else {
232    OS << "\n";
233    PrintStmt(Node->getBody());
234  }
235}
236
237void StmtPrinter::VisitWhileStmt(WhileStmt *Node) {
238  Indent() << "while (";
239  if (const DeclStmt *DS = Node->getConditionVariableDeclStmt())
240    PrintRawDeclStmt(DS);
241  else
242    PrintExpr(Node->getCond());
243  OS << ")\n";
244  PrintStmt(Node->getBody());
245}
246
247void StmtPrinter::VisitDoStmt(DoStmt *Node) {
248  Indent() << "do ";
249  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
250    PrintRawCompoundStmt(CS);
251    OS << " ";
252  } else {
253    OS << "\n";
254    PrintStmt(Node->getBody());
255    Indent();
256  }
257
258  OS << "while (";
259  PrintExpr(Node->getCond());
260  OS << ");\n";
261}
262
263void StmtPrinter::VisitForStmt(ForStmt *Node) {
264  Indent() << "for (";
265  if (Node->getInit()) {
266    if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getInit()))
267      PrintRawDeclStmt(DS);
268    else
269      PrintExpr(cast<Expr>(Node->getInit()));
270  }
271  OS << ";";
272  if (Node->getCond()) {
273    OS << " ";
274    PrintExpr(Node->getCond());
275  }
276  OS << ";";
277  if (Node->getInc()) {
278    OS << " ";
279    PrintExpr(Node->getInc());
280  }
281  OS << ") ";
282
283  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
284    PrintRawCompoundStmt(CS);
285    OS << "\n";
286  } else {
287    OS << "\n";
288    PrintStmt(Node->getBody());
289  }
290}
291
292void StmtPrinter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *Node) {
293  Indent() << "for (";
294  if (DeclStmt *DS = dyn_cast<DeclStmt>(Node->getElement()))
295    PrintRawDeclStmt(DS);
296  else
297    PrintExpr(cast<Expr>(Node->getElement()));
298  OS << " in ";
299  PrintExpr(Node->getCollection());
300  OS << ") ";
301
302  if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
303    PrintRawCompoundStmt(CS);
304    OS << "\n";
305  } else {
306    OS << "\n";
307    PrintStmt(Node->getBody());
308  }
309}
310
311void StmtPrinter::VisitCXXForRangeStmt(CXXForRangeStmt *Node) {
312  Indent() << "for (";
313  PrintingPolicy SubPolicy(Policy);
314  SubPolicy.SuppressInitializers = true;
315  Node->getLoopVariable()->print(OS, SubPolicy, IndentLevel);
316  OS << " : ";
317  PrintExpr(Node->getRangeInit());
318  OS << ") {\n";
319  PrintStmt(Node->getBody());
320  Indent() << "}";
321  if (Policy.IncludeNewlines) OS << "\n";
322}
323
324void StmtPrinter::VisitMSDependentExistsStmt(MSDependentExistsStmt *Node) {
325  Indent();
326  if (Node->isIfExists())
327    OS << "__if_exists (";
328  else
329    OS << "__if_not_exists (";
330
331  if (NestedNameSpecifier *Qualifier
332        = Node->getQualifierLoc().getNestedNameSpecifier())
333    Qualifier->print(OS, Policy);
334
335  OS << Node->getNameInfo() << ") ";
336
337  PrintRawCompoundStmt(Node->getSubStmt());
338}
339
340void StmtPrinter::VisitGotoStmt(GotoStmt *Node) {
341  Indent() << "goto " << Node->getLabel()->getName() << ";";
342  if (Policy.IncludeNewlines) OS << "\n";
343}
344
345void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) {
346  Indent() << "goto *";
347  PrintExpr(Node->getTarget());
348  OS << ";";
349  if (Policy.IncludeNewlines) OS << "\n";
350}
351
352void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) {
353  Indent() << "continue;";
354  if (Policy.IncludeNewlines) OS << "\n";
355}
356
357void StmtPrinter::VisitBreakStmt(BreakStmt *Node) {
358  Indent() << "break;";
359  if (Policy.IncludeNewlines) OS << "\n";
360}
361
362
363void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) {
364  Indent() << "return";
365  if (Node->getRetValue()) {
366    OS << " ";
367    PrintExpr(Node->getRetValue());
368  }
369  OS << ";";
370  if (Policy.IncludeNewlines) OS << "\n";
371}
372
373
374void StmtPrinter::VisitGCCAsmStmt(GCCAsmStmt *Node) {
375  Indent() << "asm ";
376
377  if (Node->isVolatile())
378    OS << "volatile ";
379
380  OS << "(";
381  VisitStringLiteral(Node->getAsmString());
382
383  // Outputs
384  if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 ||
385      Node->getNumClobbers() != 0)
386    OS << " : ";
387
388  for (unsigned i = 0, e = Node->getNumOutputs(); i != e; ++i) {
389    if (i != 0)
390      OS << ", ";
391
392    if (!Node->getOutputName(i).empty()) {
393      OS << '[';
394      OS << Node->getOutputName(i);
395      OS << "] ";
396    }
397
398    VisitStringLiteral(Node->getOutputConstraintLiteral(i));
399    OS << " ";
400    Visit(Node->getOutputExpr(i));
401  }
402
403  // Inputs
404  if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0)
405    OS << " : ";
406
407  for (unsigned i = 0, e = Node->getNumInputs(); i != e; ++i) {
408    if (i != 0)
409      OS << ", ";
410
411    if (!Node->getInputName(i).empty()) {
412      OS << '[';
413      OS << Node->getInputName(i);
414      OS << "] ";
415    }
416
417    VisitStringLiteral(Node->getInputConstraintLiteral(i));
418    OS << " ";
419    Visit(Node->getInputExpr(i));
420  }
421
422  // Clobbers
423  if (Node->getNumClobbers() != 0)
424    OS << " : ";
425
426  for (unsigned i = 0, e = Node->getNumClobbers(); i != e; ++i) {
427    if (i != 0)
428      OS << ", ";
429
430    VisitStringLiteral(Node->getClobberStringLiteral(i));
431  }
432
433  OS << ");";
434  if (Policy.IncludeNewlines) OS << "\n";
435}
436
437void StmtPrinter::VisitMSAsmStmt(MSAsmStmt *Node) {
438  // FIXME: Implement MS style inline asm statement printer.
439  Indent() << "__asm ";
440  if (Node->hasBraces())
441    OS << "{\n";
442  OS << Node->getAsmString() << "\n";
443  if (Node->hasBraces())
444    Indent() << "}\n";
445}
446
447void StmtPrinter::VisitCapturedStmt(CapturedStmt *Node) {
448  PrintStmt(Node->getCapturedDecl()->getBody());
449}
450
451void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
452  Indent() << "@try";
453  if (CompoundStmt *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
454    PrintRawCompoundStmt(TS);
455    OS << "\n";
456  }
457
458  for (unsigned I = 0, N = Node->getNumCatchStmts(); I != N; ++I) {
459    ObjCAtCatchStmt *catchStmt = Node->getCatchStmt(I);
460    Indent() << "@catch(";
461    if (catchStmt->getCatchParamDecl()) {
462      if (Decl *DS = catchStmt->getCatchParamDecl())
463        PrintRawDecl(DS);
464    }
465    OS << ")";
466    if (CompoundStmt *CS = dyn_cast<CompoundStmt>(catchStmt->getCatchBody())) {
467      PrintRawCompoundStmt(CS);
468      OS << "\n";
469    }
470  }
471
472  if (ObjCAtFinallyStmt *FS = static_cast<ObjCAtFinallyStmt *>(
473        Node->getFinallyStmt())) {
474    Indent() << "@finally";
475    PrintRawCompoundStmt(dyn_cast<CompoundStmt>(FS->getFinallyBody()));
476    OS << "\n";
477  }
478}
479
480void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {
481}
482
483void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) {
484  Indent() << "@catch (...) { /* todo */ } \n";
485}
486
487void StmtPrinter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *Node) {
488  Indent() << "@throw";
489  if (Node->getThrowExpr()) {
490    OS << " ";
491    PrintExpr(Node->getThrowExpr());
492  }
493  OS << ";\n";
494}
495
496void StmtPrinter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *Node) {
497  Indent() << "@synchronized (";
498  PrintExpr(Node->getSynchExpr());
499  OS << ")";
500  PrintRawCompoundStmt(Node->getSynchBody());
501  OS << "\n";
502}
503
504void StmtPrinter::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *Node) {
505  Indent() << "@autoreleasepool";
506  PrintRawCompoundStmt(dyn_cast<CompoundStmt>(Node->getSubStmt()));
507  OS << "\n";
508}
509
510void StmtPrinter::PrintRawCXXCatchStmt(CXXCatchStmt *Node) {
511  OS << "catch (";
512  if (Decl *ExDecl = Node->getExceptionDecl())
513    PrintRawDecl(ExDecl);
514  else
515    OS << "...";
516  OS << ") ";
517  PrintRawCompoundStmt(cast<CompoundStmt>(Node->getHandlerBlock()));
518}
519
520void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) {
521  Indent();
522  PrintRawCXXCatchStmt(Node);
523  OS << "\n";
524}
525
526void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) {
527  Indent() << "try ";
528  PrintRawCompoundStmt(Node->getTryBlock());
529  for (unsigned i = 0, e = Node->getNumHandlers(); i < e; ++i) {
530    OS << " ";
531    PrintRawCXXCatchStmt(Node->getHandler(i));
532  }
533  OS << "\n";
534}
535
536void StmtPrinter::VisitSEHTryStmt(SEHTryStmt *Node) {
537  Indent() << (Node->getIsCXXTry() ? "try " : "__try ");
538  PrintRawCompoundStmt(Node->getTryBlock());
539  SEHExceptStmt *E = Node->getExceptHandler();
540  SEHFinallyStmt *F = Node->getFinallyHandler();
541  if(E)
542    PrintRawSEHExceptHandler(E);
543  else {
544    assert(F && "Must have a finally block...");
545    PrintRawSEHFinallyStmt(F);
546  }
547  OS << "\n";
548}
549
550void StmtPrinter::PrintRawSEHFinallyStmt(SEHFinallyStmt *Node) {
551  OS << "__finally ";
552  PrintRawCompoundStmt(Node->getBlock());
553  OS << "\n";
554}
555
556void StmtPrinter::PrintRawSEHExceptHandler(SEHExceptStmt *Node) {
557  OS << "__except (";
558  VisitExpr(Node->getFilterExpr());
559  OS << ")\n";
560  PrintRawCompoundStmt(Node->getBlock());
561  OS << "\n";
562}
563
564void StmtPrinter::VisitSEHExceptStmt(SEHExceptStmt *Node) {
565  Indent();
566  PrintRawSEHExceptHandler(Node);
567  OS << "\n";
568}
569
570void StmtPrinter::VisitSEHFinallyStmt(SEHFinallyStmt *Node) {
571  Indent();
572  PrintRawSEHFinallyStmt(Node);
573  OS << "\n";
574}
575
576void StmtPrinter::VisitSEHLeaveStmt(SEHLeaveStmt *Node) {
577  Indent() << "__leave;";
578  if (Policy.IncludeNewlines) OS << "\n";
579}
580
581//===----------------------------------------------------------------------===//
582//  OpenMP clauses printing methods
583//===----------------------------------------------------------------------===//
584
585namespace {
586class OMPClausePrinter : public OMPClauseVisitor<OMPClausePrinter> {
587  raw_ostream &OS;
588  const PrintingPolicy &Policy;
589  /// \brief Process clauses with list of variables.
590  template <typename T>
591  void VisitOMPClauseList(T *Node, char StartSym);
592public:
593  OMPClausePrinter(raw_ostream &OS, const PrintingPolicy &Policy)
594    : OS(OS), Policy(Policy) { }
595#define OPENMP_CLAUSE(Name, Class)                              \
596  void Visit##Class(Class *S);
597#include "clang/Basic/OpenMPKinds.def"
598};
599
600void OMPClausePrinter::VisitOMPIfClause(OMPIfClause *Node) {
601  OS << "if(";
602  Node->getCondition()->printPretty(OS, nullptr, Policy, 0);
603  OS << ")";
604}
605
606void OMPClausePrinter::VisitOMPNumThreadsClause(OMPNumThreadsClause *Node) {
607  OS << "num_threads(";
608  Node->getNumThreads()->printPretty(OS, nullptr, Policy, 0);
609  OS << ")";
610}
611
612void OMPClausePrinter::VisitOMPSafelenClause(OMPSafelenClause *Node) {
613  OS << "safelen(";
614  Node->getSafelen()->printPretty(OS, nullptr, Policy, 0);
615  OS << ")";
616}
617
618void OMPClausePrinter::VisitOMPCollapseClause(OMPCollapseClause *Node) {
619  OS << "collapse(";
620  Node->getNumForLoops()->printPretty(OS, nullptr, Policy, 0);
621  OS << ")";
622}
623
624void OMPClausePrinter::VisitOMPDefaultClause(OMPDefaultClause *Node) {
625  OS << "default("
626     << getOpenMPSimpleClauseTypeName(OMPC_default, Node->getDefaultKind())
627     << ")";
628}
629
630void OMPClausePrinter::VisitOMPProcBindClause(OMPProcBindClause *Node) {
631  OS << "proc_bind("
632     << getOpenMPSimpleClauseTypeName(OMPC_proc_bind, Node->getProcBindKind())
633     << ")";
634}
635
636void OMPClausePrinter::VisitOMPScheduleClause(OMPScheduleClause *Node) {
637  OS << "schedule("
638     << getOpenMPSimpleClauseTypeName(OMPC_schedule, Node->getScheduleKind());
639  if (Node->getChunkSize()) {
640    OS << ", ";
641    Node->getChunkSize()->printPretty(OS, nullptr, Policy);
642  }
643  OS << ")";
644}
645
646void OMPClausePrinter::VisitOMPOrderedClause(OMPOrderedClause *) {
647  OS << "ordered";
648}
649
650void OMPClausePrinter::VisitOMPNowaitClause(OMPNowaitClause *) {
651  OS << "nowait";
652}
653
654template<typename T>
655void OMPClausePrinter::VisitOMPClauseList(T *Node, char StartSym) {
656  for (typename T::varlist_iterator I = Node->varlist_begin(),
657                                    E = Node->varlist_end();
658         I != E; ++I) {
659    assert(*I && "Expected non-null Stmt");
660    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*I)) {
661      OS << (I == Node->varlist_begin() ? StartSym : ',');
662      cast<NamedDecl>(DRE->getDecl())->printQualifiedName(OS);
663    } else {
664      OS << (I == Node->varlist_begin() ? StartSym : ',');
665      (*I)->printPretty(OS, nullptr, Policy, 0);
666    }
667  }
668}
669
670void OMPClausePrinter::VisitOMPPrivateClause(OMPPrivateClause *Node) {
671  if (!Node->varlist_empty()) {
672    OS << "private";
673    VisitOMPClauseList(Node, '(');
674    OS << ")";
675  }
676}
677
678void OMPClausePrinter::VisitOMPFirstprivateClause(OMPFirstprivateClause *Node) {
679  if (!Node->varlist_empty()) {
680    OS << "firstprivate";
681    VisitOMPClauseList(Node, '(');
682    OS << ")";
683  }
684}
685
686void OMPClausePrinter::VisitOMPLastprivateClause(OMPLastprivateClause *Node) {
687  if (!Node->varlist_empty()) {
688    OS << "lastprivate";
689    VisitOMPClauseList(Node, '(');
690    OS << ")";
691  }
692}
693
694void OMPClausePrinter::VisitOMPSharedClause(OMPSharedClause *Node) {
695  if (!Node->varlist_empty()) {
696    OS << "shared";
697    VisitOMPClauseList(Node, '(');
698    OS << ")";
699  }
700}
701
702void OMPClausePrinter::VisitOMPReductionClause(OMPReductionClause *Node) {
703  if (!Node->varlist_empty()) {
704    OS << "reduction(";
705    NestedNameSpecifier *QualifierLoc =
706        Node->getQualifierLoc().getNestedNameSpecifier();
707    OverloadedOperatorKind OOK =
708        Node->getNameInfo().getName().getCXXOverloadedOperator();
709    if (QualifierLoc == nullptr && OOK != OO_None) {
710      // Print reduction identifier in C format
711      OS << getOperatorSpelling(OOK);
712    } else {
713      // Use C++ format
714      if (QualifierLoc != nullptr)
715        QualifierLoc->print(OS, Policy);
716      OS << Node->getNameInfo();
717    }
718    OS << ":";
719    VisitOMPClauseList(Node, ' ');
720    OS << ")";
721  }
722}
723
724void OMPClausePrinter::VisitOMPLinearClause(OMPLinearClause *Node) {
725  if (!Node->varlist_empty()) {
726    OS << "linear";
727    VisitOMPClauseList(Node, '(');
728    if (Node->getStep() != nullptr) {
729      OS << ": ";
730      Node->getStep()->printPretty(OS, nullptr, Policy, 0);
731    }
732    OS << ")";
733  }
734}
735
736void OMPClausePrinter::VisitOMPAlignedClause(OMPAlignedClause *Node) {
737  if (!Node->varlist_empty()) {
738    OS << "aligned";
739    VisitOMPClauseList(Node, '(');
740    if (Node->getAlignment() != nullptr) {
741      OS << ": ";
742      Node->getAlignment()->printPretty(OS, nullptr, Policy, 0);
743    }
744    OS << ")";
745  }
746}
747
748void OMPClausePrinter::VisitOMPCopyinClause(OMPCopyinClause *Node) {
749  if (!Node->varlist_empty()) {
750    OS << "copyin";
751    VisitOMPClauseList(Node, '(');
752    OS << ")";
753  }
754}
755
756void OMPClausePrinter::VisitOMPCopyprivateClause(OMPCopyprivateClause *Node) {
757  if (!Node->varlist_empty()) {
758    OS << "copyprivate";
759    VisitOMPClauseList(Node, '(');
760    OS << ")";
761  }
762}
763
764}
765
766//===----------------------------------------------------------------------===//
767//  OpenMP directives printing methods
768//===----------------------------------------------------------------------===//
769
770void StmtPrinter::PrintOMPExecutableDirective(OMPExecutableDirective *S) {
771  OMPClausePrinter Printer(OS, Policy);
772  ArrayRef<OMPClause *> Clauses = S->clauses();
773  for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
774       I != E; ++I)
775    if (*I && !(*I)->isImplicit()) {
776      Printer.Visit(*I);
777      OS << ' ';
778    }
779  OS << "\n";
780  if (S->getAssociatedStmt()) {
781    assert(isa<CapturedStmt>(S->getAssociatedStmt()) &&
782           "Expected captured statement!");
783    Stmt *CS = cast<CapturedStmt>(S->getAssociatedStmt())->getCapturedStmt();
784    PrintStmt(CS);
785  }
786}
787
788void StmtPrinter::VisitOMPParallelDirective(OMPParallelDirective *Node) {
789  Indent() << "#pragma omp parallel ";
790  PrintOMPExecutableDirective(Node);
791}
792
793void StmtPrinter::VisitOMPSimdDirective(OMPSimdDirective *Node) {
794  Indent() << "#pragma omp simd ";
795  PrintOMPExecutableDirective(Node);
796}
797
798void StmtPrinter::VisitOMPForDirective(OMPForDirective *Node) {
799  Indent() << "#pragma omp for ";
800  PrintOMPExecutableDirective(Node);
801}
802
803void StmtPrinter::VisitOMPSectionsDirective(OMPSectionsDirective *Node) {
804  Indent() << "#pragma omp sections ";
805  PrintOMPExecutableDirective(Node);
806}
807
808void StmtPrinter::VisitOMPSectionDirective(OMPSectionDirective *Node) {
809  Indent() << "#pragma omp section";
810  PrintOMPExecutableDirective(Node);
811}
812
813void StmtPrinter::VisitOMPSingleDirective(OMPSingleDirective *Node) {
814  Indent() << "#pragma omp single ";
815  PrintOMPExecutableDirective(Node);
816}
817
818void StmtPrinter::VisitOMPParallelForDirective(OMPParallelForDirective *Node) {
819  Indent() << "#pragma omp parallel for ";
820  PrintOMPExecutableDirective(Node);
821}
822
823void StmtPrinter::VisitOMPParallelSectionsDirective(
824    OMPParallelSectionsDirective *Node) {
825  Indent() << "#pragma omp parallel sections ";
826  PrintOMPExecutableDirective(Node);
827}
828
829//===----------------------------------------------------------------------===//
830//  Expr printing methods.
831//===----------------------------------------------------------------------===//
832
833void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
834  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
835    Qualifier->print(OS, Policy);
836  if (Node->hasTemplateKeyword())
837    OS << "template ";
838  OS << Node->getNameInfo();
839  if (Node->hasExplicitTemplateArgs())
840    TemplateSpecializationType::PrintTemplateArgumentList(
841        OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
842}
843
844void StmtPrinter::VisitDependentScopeDeclRefExpr(
845                                           DependentScopeDeclRefExpr *Node) {
846  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
847    Qualifier->print(OS, Policy);
848  if (Node->hasTemplateKeyword())
849    OS << "template ";
850  OS << Node->getNameInfo();
851  if (Node->hasExplicitTemplateArgs())
852    TemplateSpecializationType::PrintTemplateArgumentList(
853        OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
854}
855
856void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
857  if (Node->getQualifier())
858    Node->getQualifier()->print(OS, Policy);
859  if (Node->hasTemplateKeyword())
860    OS << "template ";
861  OS << Node->getNameInfo();
862  if (Node->hasExplicitTemplateArgs())
863    TemplateSpecializationType::PrintTemplateArgumentList(
864        OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
865}
866
867void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
868  if (Node->getBase()) {
869    PrintExpr(Node->getBase());
870    OS << (Node->isArrow() ? "->" : ".");
871  }
872  OS << *Node->getDecl();
873}
874
875void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
876  if (Node->isSuperReceiver())
877    OS << "super.";
878  else if (Node->isObjectReceiver() && Node->getBase()) {
879    PrintExpr(Node->getBase());
880    OS << ".";
881  } else if (Node->isClassReceiver() && Node->getClassReceiver()) {
882    OS << Node->getClassReceiver()->getName() << ".";
883  }
884
885  if (Node->isImplicitProperty())
886    Node->getImplicitPropertyGetter()->getSelector().print(OS);
887  else
888    OS << Node->getExplicitProperty()->getName();
889}
890
891void StmtPrinter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node) {
892
893  PrintExpr(Node->getBaseExpr());
894  OS << "[";
895  PrintExpr(Node->getKeyExpr());
896  OS << "]";
897}
898
899void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
900  switch (Node->getIdentType()) {
901    default:
902      llvm_unreachable("unknown case");
903    case PredefinedExpr::Func:
904      OS << "__func__";
905      break;
906    case PredefinedExpr::Function:
907      OS << "__FUNCTION__";
908      break;
909    case PredefinedExpr::FuncDName:
910      OS << "__FUNCDNAME__";
911      break;
912    case PredefinedExpr::FuncSig:
913      OS << "__FUNCSIG__";
914      break;
915    case PredefinedExpr::LFunction:
916      OS << "L__FUNCTION__";
917      break;
918    case PredefinedExpr::PrettyFunction:
919      OS << "__PRETTY_FUNCTION__";
920      break;
921  }
922}
923
924void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
925  unsigned value = Node->getValue();
926
927  switch (Node->getKind()) {
928  case CharacterLiteral::Ascii: break; // no prefix.
929  case CharacterLiteral::Wide:  OS << 'L'; break;
930  case CharacterLiteral::UTF16: OS << 'u'; break;
931  case CharacterLiteral::UTF32: OS << 'U'; break;
932  }
933
934  switch (value) {
935  case '\\':
936    OS << "'\\\\'";
937    break;
938  case '\'':
939    OS << "'\\''";
940    break;
941  case '\a':
942    // TODO: K&R: the meaning of '\\a' is different in traditional C
943    OS << "'\\a'";
944    break;
945  case '\b':
946    OS << "'\\b'";
947    break;
948  // Nonstandard escape sequence.
949  /*case '\e':
950    OS << "'\\e'";
951    break;*/
952  case '\f':
953    OS << "'\\f'";
954    break;
955  case '\n':
956    OS << "'\\n'";
957    break;
958  case '\r':
959    OS << "'\\r'";
960    break;
961  case '\t':
962    OS << "'\\t'";
963    break;
964  case '\v':
965    OS << "'\\v'";
966    break;
967  default:
968    if (value < 256 && isPrintable((unsigned char)value))
969      OS << "'" << (char)value << "'";
970    else if (value < 256)
971      OS << "'\\x" << llvm::format("%02x", value) << "'";
972    else if (value <= 0xFFFF)
973      OS << "'\\u" << llvm::format("%04x", value) << "'";
974    else
975      OS << "'\\U" << llvm::format("%08x", value) << "'";
976  }
977}
978
979void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
980  bool isSigned = Node->getType()->isSignedIntegerType();
981  OS << Node->getValue().toString(10, isSigned);
982
983  // Emit suffixes.  Integer literals are always a builtin integer type.
984  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
985  default: llvm_unreachable("Unexpected type for integer literal!");
986  case BuiltinType::SChar:     OS << "i8"; break;
987  case BuiltinType::UChar:     OS << "Ui8"; break;
988  case BuiltinType::Short:     OS << "i16"; break;
989  case BuiltinType::UShort:    OS << "Ui16"; break;
990  case BuiltinType::Int:       break; // no suffix.
991  case BuiltinType::UInt:      OS << 'U'; break;
992  case BuiltinType::Long:      OS << 'L'; break;
993  case BuiltinType::ULong:     OS << "UL"; break;
994  case BuiltinType::LongLong:  OS << "LL"; break;
995  case BuiltinType::ULongLong: OS << "ULL"; break;
996  case BuiltinType::Int128:    OS << "i128"; break;
997  case BuiltinType::UInt128:   OS << "Ui128"; break;
998  }
999}
1000
1001static void PrintFloatingLiteral(raw_ostream &OS, FloatingLiteral *Node,
1002                                 bool PrintSuffix) {
1003  SmallString<16> Str;
1004  Node->getValue().toString(Str);
1005  OS << Str;
1006  if (Str.find_first_not_of("-0123456789") == StringRef::npos)
1007    OS << '.'; // Trailing dot in order to separate from ints.
1008
1009  if (!PrintSuffix)
1010    return;
1011
1012  // Emit suffixes.  Float literals are always a builtin float type.
1013  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
1014  default: llvm_unreachable("Unexpected type for float literal!");
1015  case BuiltinType::Half:       break; // FIXME: suffix?
1016  case BuiltinType::Double:     break; // no suffix.
1017  case BuiltinType::Float:      OS << 'F'; break;
1018  case BuiltinType::LongDouble: OS << 'L'; break;
1019  }
1020}
1021
1022void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
1023  PrintFloatingLiteral(OS, Node, /*PrintSuffix=*/true);
1024}
1025
1026void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
1027  PrintExpr(Node->getSubExpr());
1028  OS << "i";
1029}
1030
1031void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
1032  Str->outputString(OS);
1033}
1034void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
1035  OS << "(";
1036  PrintExpr(Node->getSubExpr());
1037  OS << ")";
1038}
1039void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
1040  if (!Node->isPostfix()) {
1041    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1042
1043    // Print a space if this is an "identifier operator" like __real, or if
1044    // it might be concatenated incorrectly like '+'.
1045    switch (Node->getOpcode()) {
1046    default: break;
1047    case UO_Real:
1048    case UO_Imag:
1049    case UO_Extension:
1050      OS << ' ';
1051      break;
1052    case UO_Plus:
1053    case UO_Minus:
1054      if (isa<UnaryOperator>(Node->getSubExpr()))
1055        OS << ' ';
1056      break;
1057    }
1058  }
1059  PrintExpr(Node->getSubExpr());
1060
1061  if (Node->isPostfix())
1062    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1063}
1064
1065void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
1066  OS << "__builtin_offsetof(";
1067  Node->getTypeSourceInfo()->getType().print(OS, Policy);
1068  OS << ", ";
1069  bool PrintedSomething = false;
1070  for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
1071    OffsetOfExpr::OffsetOfNode ON = Node->getComponent(i);
1072    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Array) {
1073      // Array node
1074      OS << "[";
1075      PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
1076      OS << "]";
1077      PrintedSomething = true;
1078      continue;
1079    }
1080
1081    // Skip implicit base indirections.
1082    if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Base)
1083      continue;
1084
1085    // Field or identifier node.
1086    IdentifierInfo *Id = ON.getFieldName();
1087    if (!Id)
1088      continue;
1089
1090    if (PrintedSomething)
1091      OS << ".";
1092    else
1093      PrintedSomething = true;
1094    OS << Id->getName();
1095  }
1096  OS << ")";
1097}
1098
1099void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
1100  switch(Node->getKind()) {
1101  case UETT_SizeOf:
1102    OS << "sizeof";
1103    break;
1104  case UETT_AlignOf:
1105    if (Policy.LangOpts.CPlusPlus)
1106      OS << "alignof";
1107    else if (Policy.LangOpts.C11)
1108      OS << "_Alignof";
1109    else
1110      OS << "__alignof";
1111    break;
1112  case UETT_VecStep:
1113    OS << "vec_step";
1114    break;
1115  }
1116  if (Node->isArgumentType()) {
1117    OS << '(';
1118    Node->getArgumentType().print(OS, Policy);
1119    OS << ')';
1120  } else {
1121    OS << " ";
1122    PrintExpr(Node->getArgumentExpr());
1123  }
1124}
1125
1126void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
1127  OS << "_Generic(";
1128  PrintExpr(Node->getControllingExpr());
1129  for (unsigned i = 0; i != Node->getNumAssocs(); ++i) {
1130    OS << ", ";
1131    QualType T = Node->getAssocType(i);
1132    if (T.isNull())
1133      OS << "default";
1134    else
1135      T.print(OS, Policy);
1136    OS << ": ";
1137    PrintExpr(Node->getAssocExpr(i));
1138  }
1139  OS << ")";
1140}
1141
1142void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
1143  PrintExpr(Node->getLHS());
1144  OS << "[";
1145  PrintExpr(Node->getRHS());
1146  OS << "]";
1147}
1148
1149void StmtPrinter::PrintCallArgs(CallExpr *Call) {
1150  for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
1151    if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
1152      // Don't print any defaulted arguments
1153      break;
1154    }
1155
1156    if (i) OS << ", ";
1157    PrintExpr(Call->getArg(i));
1158  }
1159}
1160
1161void StmtPrinter::VisitCallExpr(CallExpr *Call) {
1162  PrintExpr(Call->getCallee());
1163  OS << "(";
1164  PrintCallArgs(Call);
1165  OS << ")";
1166}
1167void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
1168  // FIXME: Suppress printing implicit bases (like "this")
1169  PrintExpr(Node->getBase());
1170
1171  MemberExpr *ParentMember = dyn_cast<MemberExpr>(Node->getBase());
1172  FieldDecl  *ParentDecl   = ParentMember
1173    ? dyn_cast<FieldDecl>(ParentMember->getMemberDecl()) : nullptr;
1174
1175  if (!ParentDecl || !ParentDecl->isAnonymousStructOrUnion())
1176    OS << (Node->isArrow() ? "->" : ".");
1177
1178  if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
1179    if (FD->isAnonymousStructOrUnion())
1180      return;
1181
1182  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1183    Qualifier->print(OS, Policy);
1184  if (Node->hasTemplateKeyword())
1185    OS << "template ";
1186  OS << Node->getMemberNameInfo();
1187  if (Node->hasExplicitTemplateArgs())
1188    TemplateSpecializationType::PrintTemplateArgumentList(
1189        OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
1190}
1191void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
1192  PrintExpr(Node->getBase());
1193  OS << (Node->isArrow() ? "->isa" : ".isa");
1194}
1195
1196void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
1197  PrintExpr(Node->getBase());
1198  OS << ".";
1199  OS << Node->getAccessor().getName();
1200}
1201void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
1202  OS << '(';
1203  Node->getTypeAsWritten().print(OS, Policy);
1204  OS << ')';
1205  PrintExpr(Node->getSubExpr());
1206}
1207void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
1208  OS << '(';
1209  Node->getType().print(OS, Policy);
1210  OS << ')';
1211  PrintExpr(Node->getInitializer());
1212}
1213void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
1214  // No need to print anything, simply forward to the subexpression.
1215  PrintExpr(Node->getSubExpr());
1216}
1217void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
1218  PrintExpr(Node->getLHS());
1219  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1220  PrintExpr(Node->getRHS());
1221}
1222void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
1223  PrintExpr(Node->getLHS());
1224  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1225  PrintExpr(Node->getRHS());
1226}
1227void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
1228  PrintExpr(Node->getCond());
1229  OS << " ? ";
1230  PrintExpr(Node->getLHS());
1231  OS << " : ";
1232  PrintExpr(Node->getRHS());
1233}
1234
1235// GNU extensions.
1236
1237void
1238StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
1239  PrintExpr(Node->getCommon());
1240  OS << " ?: ";
1241  PrintExpr(Node->getFalseExpr());
1242}
1243void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
1244  OS << "&&" << Node->getLabel()->getName();
1245}
1246
1247void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
1248  OS << "(";
1249  PrintRawCompoundStmt(E->getSubStmt());
1250  OS << ")";
1251}
1252
1253void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
1254  OS << "__builtin_choose_expr(";
1255  PrintExpr(Node->getCond());
1256  OS << ", ";
1257  PrintExpr(Node->getLHS());
1258  OS << ", ";
1259  PrintExpr(Node->getRHS());
1260  OS << ")";
1261}
1262
1263void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
1264  OS << "__null";
1265}
1266
1267void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
1268  OS << "__builtin_shufflevector(";
1269  for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
1270    if (i) OS << ", ";
1271    PrintExpr(Node->getExpr(i));
1272  }
1273  OS << ")";
1274}
1275
1276void StmtPrinter::VisitConvertVectorExpr(ConvertVectorExpr *Node) {
1277  OS << "__builtin_convertvector(";
1278  PrintExpr(Node->getSrcExpr());
1279  OS << ", ";
1280  Node->getType().print(OS, Policy);
1281  OS << ")";
1282}
1283
1284void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
1285  if (Node->getSyntacticForm()) {
1286    Visit(Node->getSyntacticForm());
1287    return;
1288  }
1289
1290  OS << "{ ";
1291  for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
1292    if (i) OS << ", ";
1293    if (Node->getInit(i))
1294      PrintExpr(Node->getInit(i));
1295    else
1296      OS << "0";
1297  }
1298  OS << " }";
1299}
1300
1301void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
1302  OS << "( ";
1303  for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
1304    if (i) OS << ", ";
1305    PrintExpr(Node->getExpr(i));
1306  }
1307  OS << " )";
1308}
1309
1310void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
1311  for (DesignatedInitExpr::designators_iterator D = Node->designators_begin(),
1312                      DEnd = Node->designators_end();
1313       D != DEnd; ++D) {
1314    if (D->isFieldDesignator()) {
1315      if (D->getDotLoc().isInvalid()) {
1316        if (IdentifierInfo *II = D->getFieldName())
1317          OS << II->getName() << ":";
1318      } else {
1319        OS << "." << D->getFieldName()->getName();
1320      }
1321    } else {
1322      OS << "[";
1323      if (D->isArrayDesignator()) {
1324        PrintExpr(Node->getArrayIndex(*D));
1325      } else {
1326        PrintExpr(Node->getArrayRangeStart(*D));
1327        OS << " ... ";
1328        PrintExpr(Node->getArrayRangeEnd(*D));
1329      }
1330      OS << "]";
1331    }
1332  }
1333
1334  OS << " = ";
1335  PrintExpr(Node->getInit());
1336}
1337
1338void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
1339  if (Policy.LangOpts.CPlusPlus) {
1340    OS << "/*implicit*/";
1341    Node->getType().print(OS, Policy);
1342    OS << "()";
1343  } else {
1344    OS << "/*implicit*/(";
1345    Node->getType().print(OS, Policy);
1346    OS << ')';
1347    if (Node->getType()->isRecordType())
1348      OS << "{}";
1349    else
1350      OS << 0;
1351  }
1352}
1353
1354void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1355  OS << "__builtin_va_arg(";
1356  PrintExpr(Node->getSubExpr());
1357  OS << ", ";
1358  Node->getType().print(OS, Policy);
1359  OS << ")";
1360}
1361
1362void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
1363  PrintExpr(Node->getSyntacticForm());
1364}
1365
1366void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
1367  const char *Name = nullptr;
1368  switch (Node->getOp()) {
1369#define BUILTIN(ID, TYPE, ATTRS)
1370#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1371  case AtomicExpr::AO ## ID: \
1372    Name = #ID "("; \
1373    break;
1374#include "clang/Basic/Builtins.def"
1375  }
1376  OS << Name;
1377
1378  // AtomicExpr stores its subexpressions in a permuted order.
1379  PrintExpr(Node->getPtr());
1380  if (Node->getOp() != AtomicExpr::AO__c11_atomic_load &&
1381      Node->getOp() != AtomicExpr::AO__atomic_load_n) {
1382    OS << ", ";
1383    PrintExpr(Node->getVal1());
1384  }
1385  if (Node->getOp() == AtomicExpr::AO__atomic_exchange ||
1386      Node->isCmpXChg()) {
1387    OS << ", ";
1388    PrintExpr(Node->getVal2());
1389  }
1390  if (Node->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1391      Node->getOp() == AtomicExpr::AO__atomic_compare_exchange_n) {
1392    OS << ", ";
1393    PrintExpr(Node->getWeak());
1394  }
1395  if (Node->getOp() != AtomicExpr::AO__c11_atomic_init) {
1396    OS << ", ";
1397    PrintExpr(Node->getOrder());
1398  }
1399  if (Node->isCmpXChg()) {
1400    OS << ", ";
1401    PrintExpr(Node->getOrderFail());
1402  }
1403  OS << ")";
1404}
1405
1406// C++
1407void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
1408  const char *OpStrings[NUM_OVERLOADED_OPERATORS] = {
1409    "",
1410#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1411    Spelling,
1412#include "clang/Basic/OperatorKinds.def"
1413  };
1414
1415  OverloadedOperatorKind Kind = Node->getOperator();
1416  if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1417    if (Node->getNumArgs() == 1) {
1418      OS << OpStrings[Kind] << ' ';
1419      PrintExpr(Node->getArg(0));
1420    } else {
1421      PrintExpr(Node->getArg(0));
1422      OS << ' ' << OpStrings[Kind];
1423    }
1424  } else if (Kind == OO_Arrow) {
1425    PrintExpr(Node->getArg(0));
1426  } else if (Kind == OO_Call) {
1427    PrintExpr(Node->getArg(0));
1428    OS << '(';
1429    for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1430      if (ArgIdx > 1)
1431        OS << ", ";
1432      if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1433        PrintExpr(Node->getArg(ArgIdx));
1434    }
1435    OS << ')';
1436  } else if (Kind == OO_Subscript) {
1437    PrintExpr(Node->getArg(0));
1438    OS << '[';
1439    PrintExpr(Node->getArg(1));
1440    OS << ']';
1441  } else if (Node->getNumArgs() == 1) {
1442    OS << OpStrings[Kind] << ' ';
1443    PrintExpr(Node->getArg(0));
1444  } else if (Node->getNumArgs() == 2) {
1445    PrintExpr(Node->getArg(0));
1446    OS << ' ' << OpStrings[Kind] << ' ';
1447    PrintExpr(Node->getArg(1));
1448  } else {
1449    llvm_unreachable("unknown overloaded operator");
1450  }
1451}
1452
1453void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1454  // If we have a conversion operator call only print the argument.
1455  CXXMethodDecl *MD = Node->getMethodDecl();
1456  if (MD && isa<CXXConversionDecl>(MD)) {
1457    PrintExpr(Node->getImplicitObjectArgument());
1458    return;
1459  }
1460  VisitCallExpr(cast<CallExpr>(Node));
1461}
1462
1463void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1464  PrintExpr(Node->getCallee());
1465  OS << "<<<";
1466  PrintCallArgs(Node->getConfig());
1467  OS << ">>>(";
1468  PrintCallArgs(Node);
1469  OS << ")";
1470}
1471
1472void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1473  OS << Node->getCastName() << '<';
1474  Node->getTypeAsWritten().print(OS, Policy);
1475  OS << ">(";
1476  PrintExpr(Node->getSubExpr());
1477  OS << ")";
1478}
1479
1480void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1481  VisitCXXNamedCastExpr(Node);
1482}
1483
1484void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1485  VisitCXXNamedCastExpr(Node);
1486}
1487
1488void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1489  VisitCXXNamedCastExpr(Node);
1490}
1491
1492void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1493  VisitCXXNamedCastExpr(Node);
1494}
1495
1496void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1497  OS << "typeid(";
1498  if (Node->isTypeOperand()) {
1499    Node->getTypeOperandSourceInfo()->getType().print(OS, Policy);
1500  } else {
1501    PrintExpr(Node->getExprOperand());
1502  }
1503  OS << ")";
1504}
1505
1506void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1507  OS << "__uuidof(";
1508  if (Node->isTypeOperand()) {
1509    Node->getTypeOperandSourceInfo()->getType().print(OS, Policy);
1510  } else {
1511    PrintExpr(Node->getExprOperand());
1512  }
1513  OS << ")";
1514}
1515
1516void StmtPrinter::VisitMSPropertyRefExpr(MSPropertyRefExpr *Node) {
1517  PrintExpr(Node->getBaseExpr());
1518  if (Node->isArrow())
1519    OS << "->";
1520  else
1521    OS << ".";
1522  if (NestedNameSpecifier *Qualifier =
1523      Node->getQualifierLoc().getNestedNameSpecifier())
1524    Qualifier->print(OS, Policy);
1525  OS << Node->getPropertyDecl()->getDeclName();
1526}
1527
1528void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
1529  switch (Node->getLiteralOperatorKind()) {
1530  case UserDefinedLiteral::LOK_Raw:
1531    OS << cast<StringLiteral>(Node->getArg(0)->IgnoreImpCasts())->getString();
1532    break;
1533  case UserDefinedLiteral::LOK_Template: {
1534    DeclRefExpr *DRE = cast<DeclRefExpr>(Node->getCallee()->IgnoreImpCasts());
1535    const TemplateArgumentList *Args =
1536      cast<FunctionDecl>(DRE->getDecl())->getTemplateSpecializationArgs();
1537    assert(Args);
1538    const TemplateArgument &Pack = Args->get(0);
1539    for (TemplateArgument::pack_iterator I = Pack.pack_begin(),
1540                                         E = Pack.pack_end(); I != E; ++I) {
1541      char C = (char)I->getAsIntegral().getZExtValue();
1542      OS << C;
1543    }
1544    break;
1545  }
1546  case UserDefinedLiteral::LOK_Integer: {
1547    // Print integer literal without suffix.
1548    IntegerLiteral *Int = cast<IntegerLiteral>(Node->getCookedLiteral());
1549    OS << Int->getValue().toString(10, /*isSigned*/false);
1550    break;
1551  }
1552  case UserDefinedLiteral::LOK_Floating: {
1553    // Print floating literal without suffix.
1554    FloatingLiteral *Float = cast<FloatingLiteral>(Node->getCookedLiteral());
1555    PrintFloatingLiteral(OS, Float, /*PrintSuffix=*/false);
1556    break;
1557  }
1558  case UserDefinedLiteral::LOK_String:
1559  case UserDefinedLiteral::LOK_Character:
1560    PrintExpr(Node->getCookedLiteral());
1561    break;
1562  }
1563  OS << Node->getUDSuffix()->getName();
1564}
1565
1566void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1567  OS << (Node->getValue() ? "true" : "false");
1568}
1569
1570void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1571  OS << "nullptr";
1572}
1573
1574void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1575  OS << "this";
1576}
1577
1578void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1579  if (!Node->getSubExpr())
1580    OS << "throw";
1581  else {
1582    OS << "throw ";
1583    PrintExpr(Node->getSubExpr());
1584  }
1585}
1586
1587void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1588  // Nothing to print: we picked up the default argument.
1589}
1590
1591void StmtPrinter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *Node) {
1592  // Nothing to print: we picked up the default initializer.
1593}
1594
1595void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1596  Node->getType().print(OS, Policy);
1597  OS << "(";
1598  PrintExpr(Node->getSubExpr());
1599  OS << ")";
1600}
1601
1602void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1603  PrintExpr(Node->getSubExpr());
1604}
1605
1606void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1607  Node->getType().print(OS, Policy);
1608  OS << "(";
1609  for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1610                                         ArgEnd = Node->arg_end();
1611       Arg != ArgEnd; ++Arg) {
1612    if (Arg->isDefaultArgument())
1613      break;
1614    if (Arg != Node->arg_begin())
1615      OS << ", ";
1616    PrintExpr(*Arg);
1617  }
1618  OS << ")";
1619}
1620
1621void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
1622  OS << '[';
1623  bool NeedComma = false;
1624  switch (Node->getCaptureDefault()) {
1625  case LCD_None:
1626    break;
1627
1628  case LCD_ByCopy:
1629    OS << '=';
1630    NeedComma = true;
1631    break;
1632
1633  case LCD_ByRef:
1634    OS << '&';
1635    NeedComma = true;
1636    break;
1637  }
1638  for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(),
1639                                 CEnd = Node->explicit_capture_end();
1640       C != CEnd;
1641       ++C) {
1642    if (NeedComma)
1643      OS << ", ";
1644    NeedComma = true;
1645
1646    switch (C->getCaptureKind()) {
1647    case LCK_This:
1648      OS << "this";
1649      break;
1650
1651    case LCK_ByRef:
1652      if (Node->getCaptureDefault() != LCD_ByRef || C->isInitCapture())
1653        OS << '&';
1654      OS << C->getCapturedVar()->getName();
1655      break;
1656
1657    case LCK_ByCopy:
1658      OS << C->getCapturedVar()->getName();
1659      break;
1660    }
1661
1662    if (C->isInitCapture())
1663      PrintExpr(C->getCapturedVar()->getInit());
1664  }
1665  OS << ']';
1666
1667  if (Node->hasExplicitParameters()) {
1668    OS << " (";
1669    CXXMethodDecl *Method = Node->getCallOperator();
1670    NeedComma = false;
1671    for (auto P : Method->params()) {
1672      if (NeedComma) {
1673        OS << ", ";
1674      } else {
1675        NeedComma = true;
1676      }
1677      std::string ParamStr = P->getNameAsString();
1678      P->getOriginalType().print(OS, Policy, ParamStr);
1679    }
1680    if (Method->isVariadic()) {
1681      if (NeedComma)
1682        OS << ", ";
1683      OS << "...";
1684    }
1685    OS << ')';
1686
1687    if (Node->isMutable())
1688      OS << " mutable";
1689
1690    const FunctionProtoType *Proto
1691      = Method->getType()->getAs<FunctionProtoType>();
1692    Proto->printExceptionSpecification(OS, Policy);
1693
1694    // FIXME: Attributes
1695
1696    // Print the trailing return type if it was specified in the source.
1697    if (Node->hasExplicitResultType()) {
1698      OS << " -> ";
1699      Proto->getReturnType().print(OS, Policy);
1700    }
1701  }
1702
1703  // Print the body.
1704  CompoundStmt *Body = Node->getBody();
1705  OS << ' ';
1706  PrintStmt(Body);
1707}
1708
1709void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1710  if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1711    TSInfo->getType().print(OS, Policy);
1712  else
1713    Node->getType().print(OS, Policy);
1714  OS << "()";
1715}
1716
1717void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1718  if (E->isGlobalNew())
1719    OS << "::";
1720  OS << "new ";
1721  unsigned NumPlace = E->getNumPlacementArgs();
1722  if (NumPlace > 0 && !isa<CXXDefaultArgExpr>(E->getPlacementArg(0))) {
1723    OS << "(";
1724    PrintExpr(E->getPlacementArg(0));
1725    for (unsigned i = 1; i < NumPlace; ++i) {
1726      if (isa<CXXDefaultArgExpr>(E->getPlacementArg(i)))
1727        break;
1728      OS << ", ";
1729      PrintExpr(E->getPlacementArg(i));
1730    }
1731    OS << ") ";
1732  }
1733  if (E->isParenTypeId())
1734    OS << "(";
1735  std::string TypeS;
1736  if (Expr *Size = E->getArraySize()) {
1737    llvm::raw_string_ostream s(TypeS);
1738    s << '[';
1739    Size->printPretty(s, Helper, Policy);
1740    s << ']';
1741  }
1742  E->getAllocatedType().print(OS, Policy, TypeS);
1743  if (E->isParenTypeId())
1744    OS << ")";
1745
1746  CXXNewExpr::InitializationStyle InitStyle = E->getInitializationStyle();
1747  if (InitStyle) {
1748    if (InitStyle == CXXNewExpr::CallInit)
1749      OS << "(";
1750    PrintExpr(E->getInitializer());
1751    if (InitStyle == CXXNewExpr::CallInit)
1752      OS << ")";
1753  }
1754}
1755
1756void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1757  if (E->isGlobalDelete())
1758    OS << "::";
1759  OS << "delete ";
1760  if (E->isArrayForm())
1761    OS << "[] ";
1762  PrintExpr(E->getArgument());
1763}
1764
1765void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1766  PrintExpr(E->getBase());
1767  if (E->isArrow())
1768    OS << "->";
1769  else
1770    OS << '.';
1771  if (E->getQualifier())
1772    E->getQualifier()->print(OS, Policy);
1773  OS << "~";
1774
1775  if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
1776    OS << II->getName();
1777  else
1778    E->getDestroyedType().print(OS, Policy);
1779}
1780
1781void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
1782  if (E->isListInitialization())
1783    OS << "{ ";
1784
1785  for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
1786    if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
1787      // Don't print any defaulted arguments
1788      break;
1789    }
1790
1791    if (i) OS << ", ";
1792    PrintExpr(E->getArg(i));
1793  }
1794
1795  if (E->isListInitialization())
1796    OS << " }";
1797}
1798
1799void StmtPrinter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
1800  PrintExpr(E->getSubExpr());
1801}
1802
1803void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
1804  // Just forward to the subexpression.
1805  PrintExpr(E->getSubExpr());
1806}
1807
1808void
1809StmtPrinter::VisitCXXUnresolvedConstructExpr(
1810                                           CXXUnresolvedConstructExpr *Node) {
1811  Node->getTypeAsWritten().print(OS, Policy);
1812  OS << "(";
1813  for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
1814                                             ArgEnd = Node->arg_end();
1815       Arg != ArgEnd; ++Arg) {
1816    if (Arg != Node->arg_begin())
1817      OS << ", ";
1818    PrintExpr(*Arg);
1819  }
1820  OS << ")";
1821}
1822
1823void StmtPrinter::VisitCXXDependentScopeMemberExpr(
1824                                         CXXDependentScopeMemberExpr *Node) {
1825  if (!Node->isImplicitAccess()) {
1826    PrintExpr(Node->getBase());
1827    OS << (Node->isArrow() ? "->" : ".");
1828  }
1829  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1830    Qualifier->print(OS, Policy);
1831  if (Node->hasTemplateKeyword())
1832    OS << "template ";
1833  OS << Node->getMemberNameInfo();
1834  if (Node->hasExplicitTemplateArgs())
1835    TemplateSpecializationType::PrintTemplateArgumentList(
1836        OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
1837}
1838
1839void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
1840  if (!Node->isImplicitAccess()) {
1841    PrintExpr(Node->getBase());
1842    OS << (Node->isArrow() ? "->" : ".");
1843  }
1844  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1845    Qualifier->print(OS, Policy);
1846  if (Node->hasTemplateKeyword())
1847    OS << "template ";
1848  OS << Node->getMemberNameInfo();
1849  if (Node->hasExplicitTemplateArgs())
1850    TemplateSpecializationType::PrintTemplateArgumentList(
1851        OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
1852}
1853
1854static const char *getTypeTraitName(TypeTrait TT) {
1855  switch (TT) {
1856#define TYPE_TRAIT_1(Spelling, Name, Key) \
1857case clang::UTT_##Name: return #Spelling;
1858#define TYPE_TRAIT_2(Spelling, Name, Key) \
1859case clang::BTT_##Name: return #Spelling;
1860#define TYPE_TRAIT_N(Spelling, Name, Key) \
1861  case clang::TT_##Name: return #Spelling;
1862#include "clang/Basic/TokenKinds.def"
1863  }
1864  llvm_unreachable("Type trait not covered by switch");
1865}
1866
1867static const char *getTypeTraitName(ArrayTypeTrait ATT) {
1868  switch (ATT) {
1869  case ATT_ArrayRank:        return "__array_rank";
1870  case ATT_ArrayExtent:      return "__array_extent";
1871  }
1872  llvm_unreachable("Array type trait not covered by switch");
1873}
1874
1875static const char *getExpressionTraitName(ExpressionTrait ET) {
1876  switch (ET) {
1877  case ET_IsLValueExpr:      return "__is_lvalue_expr";
1878  case ET_IsRValueExpr:      return "__is_rvalue_expr";
1879  }
1880  llvm_unreachable("Expression type trait not covered by switch");
1881}
1882
1883void StmtPrinter::VisitTypeTraitExpr(TypeTraitExpr *E) {
1884  OS << getTypeTraitName(E->getTrait()) << "(";
1885  for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
1886    if (I > 0)
1887      OS << ", ";
1888    E->getArg(I)->getType().print(OS, Policy);
1889  }
1890  OS << ")";
1891}
1892
1893void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
1894  OS << getTypeTraitName(E->getTrait()) << '(';
1895  E->getQueriedType().print(OS, Policy);
1896  OS << ')';
1897}
1898
1899void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
1900  OS << getExpressionTraitName(E->getTrait()) << '(';
1901  PrintExpr(E->getQueriedExpression());
1902  OS << ')';
1903}
1904
1905void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
1906  OS << "noexcept(";
1907  PrintExpr(E->getOperand());
1908  OS << ")";
1909}
1910
1911void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
1912  PrintExpr(E->getPattern());
1913  OS << "...";
1914}
1915
1916void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
1917  OS << "sizeof...(" << *E->getPack() << ")";
1918}
1919
1920void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
1921                                       SubstNonTypeTemplateParmPackExpr *Node) {
1922  OS << *Node->getParameterPack();
1923}
1924
1925void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
1926                                       SubstNonTypeTemplateParmExpr *Node) {
1927  Visit(Node->getReplacement());
1928}
1929
1930void StmtPrinter::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) {
1931  OS << *E->getParameterPack();
1932}
1933
1934void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
1935  PrintExpr(Node->GetTemporaryExpr());
1936}
1937
1938// Obj-C
1939
1940void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
1941  OS << "@";
1942  VisitStringLiteral(Node->getString());
1943}
1944
1945void StmtPrinter::VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
1946  OS << "@";
1947  Visit(E->getSubExpr());
1948}
1949
1950void StmtPrinter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
1951  OS << "@[ ";
1952  StmtRange ch = E->children();
1953  if (ch.first != ch.second) {
1954    while (1) {
1955      Visit(*ch.first);
1956      ++ch.first;
1957      if (ch.first == ch.second) break;
1958      OS << ", ";
1959    }
1960  }
1961  OS << " ]";
1962}
1963
1964void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
1965  OS << "@{ ";
1966  for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
1967    if (I > 0)
1968      OS << ", ";
1969
1970    ObjCDictionaryElement Element = E->getKeyValueElement(I);
1971    Visit(Element.Key);
1972    OS << " : ";
1973    Visit(Element.Value);
1974    if (Element.isPackExpansion())
1975      OS << "...";
1976  }
1977  OS << " }";
1978}
1979
1980void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
1981  OS << "@encode(";
1982  Node->getEncodedType().print(OS, Policy);
1983  OS << ')';
1984}
1985
1986void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
1987  OS << "@selector(";
1988  Node->getSelector().print(OS);
1989  OS << ')';
1990}
1991
1992void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
1993  OS << "@protocol(" << *Node->getProtocol() << ')';
1994}
1995
1996void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
1997  OS << "[";
1998  switch (Mess->getReceiverKind()) {
1999  case ObjCMessageExpr::Instance:
2000    PrintExpr(Mess->getInstanceReceiver());
2001    break;
2002
2003  case ObjCMessageExpr::Class:
2004    Mess->getClassReceiver().print(OS, Policy);
2005    break;
2006
2007  case ObjCMessageExpr::SuperInstance:
2008  case ObjCMessageExpr::SuperClass:
2009    OS << "Super";
2010    break;
2011  }
2012
2013  OS << ' ';
2014  Selector selector = Mess->getSelector();
2015  if (selector.isUnarySelector()) {
2016    OS << selector.getNameForSlot(0);
2017  } else {
2018    for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
2019      if (i < selector.getNumArgs()) {
2020        if (i > 0) OS << ' ';
2021        if (selector.getIdentifierInfoForSlot(i))
2022          OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
2023        else
2024           OS << ":";
2025      }
2026      else OS << ", "; // Handle variadic methods.
2027
2028      PrintExpr(Mess->getArg(i));
2029    }
2030  }
2031  OS << "]";
2032}
2033
2034void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
2035  OS << (Node->getValue() ? "__objc_yes" : "__objc_no");
2036}
2037
2038void
2039StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
2040  PrintExpr(E->getSubExpr());
2041}
2042
2043void
2044StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
2045  OS << '(' << E->getBridgeKindName();
2046  E->getType().print(OS, Policy);
2047  OS << ')';
2048  PrintExpr(E->getSubExpr());
2049}
2050
2051void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
2052  BlockDecl *BD = Node->getBlockDecl();
2053  OS << "^";
2054
2055  const FunctionType *AFT = Node->getFunctionType();
2056
2057  if (isa<FunctionNoProtoType>(AFT)) {
2058    OS << "()";
2059  } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
2060    OS << '(';
2061    for (BlockDecl::param_iterator AI = BD->param_begin(),
2062         E = BD->param_end(); AI != E; ++AI) {
2063      if (AI != BD->param_begin()) OS << ", ";
2064      std::string ParamStr = (*AI)->getNameAsString();
2065      (*AI)->getType().print(OS, Policy, ParamStr);
2066    }
2067
2068    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
2069    if (FT->isVariadic()) {
2070      if (!BD->param_empty()) OS << ", ";
2071      OS << "...";
2072    }
2073    OS << ')';
2074  }
2075  OS << "{ }";
2076}
2077
2078void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
2079  PrintExpr(Node->getSourceExpr());
2080}
2081
2082void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
2083  OS << "__builtin_astype(";
2084  PrintExpr(Node->getSrcExpr());
2085  OS << ", ";
2086  Node->getType().print(OS, Policy);
2087  OS << ")";
2088}
2089
2090//===----------------------------------------------------------------------===//
2091// Stmt method implementations
2092//===----------------------------------------------------------------------===//
2093
2094void Stmt::dumpPretty(const ASTContext &Context) const {
2095  printPretty(llvm::errs(), nullptr, PrintingPolicy(Context.getLangOpts()));
2096}
2097
2098void Stmt::printPretty(raw_ostream &OS,
2099                       PrinterHelper *Helper,
2100                       const PrintingPolicy &Policy,
2101                       unsigned Indentation) const {
2102  StmtPrinter P(OS, Helper, Policy, Indentation);
2103  P.Visit(const_cast<Stmt*>(this));
2104}
2105
2106//===----------------------------------------------------------------------===//
2107// PrinterHelper
2108//===----------------------------------------------------------------------===//
2109
2110// Implement virtual destructor.
2111PrinterHelper::~PrinterHelper() {}
2112