Clang Project

clang_source_code/lib/AST/StmtPrinter.cpp
1//===- StmtPrinter.cpp - Printing implementation for Stmt ASTs ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Stmt::dumpPretty/Stmt::printPretty methods, which
10// pretty print the AST back out to C code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Attr.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclBase.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclOpenMP.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprOpenMP.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/OpenMPClause.h"
28#include "clang/AST/PrettyPrinter.h"
29#include "clang/AST/Stmt.h"
30#include "clang/AST/StmtCXX.h"
31#include "clang/AST/StmtObjC.h"
32#include "clang/AST/StmtOpenMP.h"
33#include "clang/AST/StmtVisitor.h"
34#include "clang/AST/TemplateBase.h"
35#include "clang/AST/Type.h"
36#include "clang/Basic/CharInfo.h"
37#include "clang/Basic/ExpressionTraits.h"
38#include "clang/Basic/IdentifierTable.h"
39#include "clang/Basic/LLVM.h"
40#include "clang/Basic/Lambda.h"
41#include "clang/Basic/OpenMPKinds.h"
42#include "clang/Basic/OperatorKinds.h"
43#include "clang/Basic/SourceLocation.h"
44#include "clang/Basic/TypeTraits.h"
45#include "clang/Lex/Lexer.h"
46#include "llvm/ADT/ArrayRef.h"
47#include "llvm/ADT/SmallString.h"
48#include "llvm/ADT/SmallVector.h"
49#include "llvm/ADT/StringRef.h"
50#include "llvm/Support/Casting.h"
51#include "llvm/Support/Compiler.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/Format.h"
54#include "llvm/Support/raw_ostream.h"
55#include <cassert>
56#include <string>
57
58using namespace clang;
59
60//===----------------------------------------------------------------------===//
61// StmtPrinter Visitor
62//===----------------------------------------------------------------------===//
63
64namespace {
65
66  class StmtPrinter : public StmtVisitor<StmtPrinter> {
67    raw_ostream &OS;
68    unsigned IndentLevel;
69    PrinterHelperHelper;
70    PrintingPolicy Policy;
71    std::string NL;
72    const ASTContext *Context;
73
74  public:
75    StmtPrinter(raw_ostream &osPrinterHelper *helper,
76                const PrintingPolicy &Policyunsigned Indentation = 0,
77                StringRef NL = "\n",
78                const ASTContext *Context = nullptr)
79        : OS(os), IndentLevel(Indentation), Helper(helper), Policy(Policy),
80          NL(NL), Context(Context) {}
81
82    void PrintStmt(Stmt *S) {
83      PrintStmt(S, Policy.Indentation);
84    }
85
86    void PrintStmt(Stmt *Sint SubIndent) {
87      IndentLevel += SubIndent;
88      if (S && isa<Expr>(S)) {
89        // If this is an expr used in a stmt context, indent and newline it.
90        Indent();
91        Visit(S);
92        OS << ";" << NL;
93      } else if (S) {
94        Visit(S);
95      } else {
96        Indent() << "<<<NULL STATEMENT>>>" << NL;
97      }
98      IndentLevel -= SubIndent;
99    }
100
101    void PrintInitStmt(Stmt *Sunsigned PrefixWidth) {
102      // FIXME: Cope better with odd prefix widths.
103      IndentLevel += (PrefixWidth + 1) / 2;
104      if (auto *DS = dyn_cast<DeclStmt>(S))
105        PrintRawDeclStmt(DS);
106      else
107        PrintExpr(cast<Expr>(S));
108      OS << "; ";
109      IndentLevel -= (PrefixWidth + 1) / 2;
110    }
111
112    void PrintControlledStmt(Stmt *S) {
113      if (auto *CS = dyn_cast<CompoundStmt>(S)) {
114        OS << " ";
115        PrintRawCompoundStmt(CS);
116        OS << NL;
117      } else {
118        OS << NL;
119        PrintStmt(S);
120      }
121    }
122
123    void PrintRawCompoundStmt(CompoundStmt *S);
124    void PrintRawDecl(Decl *D);
125    void PrintRawDeclStmt(const DeclStmt *S);
126    void PrintRawIfStmt(IfStmt *If);
127    void PrintRawCXXCatchStmt(CXXCatchStmt *Catch);
128    void PrintCallArgs(CallExpr *E);
129    void PrintRawSEHExceptHandler(SEHExceptStmt *S);
130    void PrintRawSEHFinallyStmt(SEHFinallyStmt *S);
131    void PrintOMPExecutableDirective(OMPExecutableDirective *S,
132                                     bool ForceNoStmt = false);
133
134    void PrintExpr(Expr *E) {
135      if (E)
136        Visit(E);
137      else
138        OS << "<null expr>";
139    }
140
141    raw_ostream &Indent(int Delta = 0) {
142      for (int i = 0e = IndentLevel+Deltai < e; ++i)
143        OS << "  ";
144      return OS;
145    }
146
147    void Visit(StmtS) {
148      if (Helper && Helper->handledStmt(S,OS))
149          return;
150      else StmtVisitor<StmtPrinter>::Visit(S);
151    }
152
153    void VisitStmt(Stmt *Node) LLVM_ATTRIBUTE_UNUSED {
154      Indent() << "<<unknown stmt type>>" << NL;
155    }
156
157    void VisitExpr(Expr *Node) LLVM_ATTRIBUTE_UNUSED {
158      OS << "<<unknown expr type>>";
159    }
160
161    void VisitCXXNamedCastExpr(CXXNamedCastExpr *Node);
162
163#define ABSTRACT_STMT(CLASS)
164#define STMT(CLASS, PARENT) \
165    void Visit##CLASS(CLASS *Node);
166#include "clang/AST/StmtNodes.inc"
167  };
168
169// namespace
170
171//===----------------------------------------------------------------------===//
172//  Stmt printing methods.
173//===----------------------------------------------------------------------===//
174
175/// PrintRawCompoundStmt - Print a compound stmt without indenting the {, and
176/// with no newline after the }.
177void StmtPrinter::PrintRawCompoundStmt(CompoundStmt *Node) {
178  OS << "{" << NL;
179  for (auto *I : Node->body())
180    PrintStmt(I);
181
182  Indent() << "}";
183}
184
185void StmtPrinter::PrintRawDecl(Decl *D) {
186  D->print(OS, Policy, IndentLevel);
187}
188
189void StmtPrinter::PrintRawDeclStmt(const DeclStmt *S) {
190  SmallVector<Decl *, 2Decls(S->decls());
191  Decl::printGroup(Decls.data(), Decls.size(), OS, Policy, IndentLevel);
192}
193
194void StmtPrinter::VisitNullStmt(NullStmt *Node) {
195  Indent() << ";" << NL;
196}
197
198void StmtPrinter::VisitDeclStmt(DeclStmt *Node) {
199  Indent();
200  PrintRawDeclStmt(Node);
201  OS << ";" << NL;
202}
203
204void StmtPrinter::VisitCompoundStmt(CompoundStmt *Node) {
205  Indent();
206  PrintRawCompoundStmt(Node);
207  OS << "" << NL;
208}
209
210void StmtPrinter::VisitCaseStmt(CaseStmt *Node) {
211  Indent(-1) << "case ";
212  PrintExpr(Node->getLHS());
213  if (Node->getRHS()) {
214    OS << " ... ";
215    PrintExpr(Node->getRHS());
216  }
217  OS << ":" << NL;
218
219  PrintStmt(Node->getSubStmt(), 0);
220}
221
222void StmtPrinter::VisitDefaultStmt(DefaultStmt *Node) {
223  Indent(-1) << "default:" << NL;
224  PrintStmt(Node->getSubStmt(), 0);
225}
226
227void StmtPrinter::VisitLabelStmt(LabelStmt *Node) {
228  Indent(-1) << Node->getName() << ":" << NL;
229  PrintStmt(Node->getSubStmt(), 0);
230}
231
232void StmtPrinter::VisitAttributedStmt(AttributedStmt *Node) {
233  for (const auto *Attr : Node->getAttrs()) {
234    Attr->printPretty(OS, Policy);
235  }
236
237  PrintStmt(Node->getSubStmt(), 0);
238}
239
240void StmtPrinter::PrintRawIfStmt(IfStmt *If) {
241  OS << "if (";
242  if (If->getInit())
243    PrintInitStmt(If->getInit(), 4);
244  if (const DeclStmt *DS = If->getConditionVariableDeclStmt())
245    PrintRawDeclStmt(DS);
246  else
247    PrintExpr(If->getCond());
248  OS << ')';
249
250  if (auto *CS = dyn_cast<CompoundStmt>(If->getThen())) {
251    OS << ' ';
252    PrintRawCompoundStmt(CS);
253    OS << (If->getElse() ? " " : NL);
254  } else {
255    OS << NL;
256    PrintStmt(If->getThen());
257    if (If->getElse()) Indent();
258  }
259
260  if (Stmt *Else = If->getElse()) {
261    OS << "else";
262
263    if (auto *CS = dyn_cast<CompoundStmt>(Else)) {
264      OS << ' ';
265      PrintRawCompoundStmt(CS);
266      OS << NL;
267    } else if (auto *ElseIf = dyn_cast<IfStmt>(Else)) {
268      OS << ' ';
269      PrintRawIfStmt(ElseIf);
270    } else {
271      OS << NL;
272      PrintStmt(If->getElse());
273    }
274  }
275}
276
277void StmtPrinter::VisitIfStmt(IfStmt *If) {
278  Indent();
279  PrintRawIfStmt(If);
280}
281
282void StmtPrinter::VisitSwitchStmt(SwitchStmt *Node) {
283  Indent() << "switch (";
284  if (Node->getInit())
285    PrintInitStmt(Node->getInit(), 8);
286  if (const DeclStmt *DS = Node->getConditionVariableDeclStmt())
287    PrintRawDeclStmt(DS);
288  else
289    PrintExpr(Node->getCond());
290  OS << ")";
291  PrintControlledStmt(Node->getBody());
292}
293
294void StmtPrinter::VisitWhileStmt(WhileStmt *Node) {
295  Indent() << "while (";
296  if (const DeclStmt *DS = Node->getConditionVariableDeclStmt())
297    PrintRawDeclStmt(DS);
298  else
299    PrintExpr(Node->getCond());
300  OS << ")" << NL;
301  PrintStmt(Node->getBody());
302}
303
304void StmtPrinter::VisitDoStmt(DoStmt *Node) {
305  Indent() << "do ";
306  if (auto *CS = dyn_cast<CompoundStmt>(Node->getBody())) {
307    PrintRawCompoundStmt(CS);
308    OS << " ";
309  } else {
310    OS << NL;
311    PrintStmt(Node->getBody());
312    Indent();
313  }
314
315  OS << "while (";
316  PrintExpr(Node->getCond());
317  OS << ");" << NL;
318}
319
320void StmtPrinter::VisitForStmt(ForStmt *Node) {
321  Indent() << "for (";
322  if (Node->getInit())
323    PrintInitStmt(Node->getInit(), 5);
324  else
325    OS << (Node->getCond() ? "; " : ";");
326  if (Node->getCond())
327    PrintExpr(Node->getCond());
328  OS << ";";
329  if (Node->getInc()) {
330    OS << " ";
331    PrintExpr(Node->getInc());
332  }
333  OS << ")";
334  PrintControlledStmt(Node->getBody());
335}
336
337void StmtPrinter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *Node) {
338  Indent() << "for (";
339  if (auto *DS = dyn_cast<DeclStmt>(Node->getElement()))
340    PrintRawDeclStmt(DS);
341  else
342    PrintExpr(cast<Expr>(Node->getElement()));
343  OS << " in ";
344  PrintExpr(Node->getCollection());
345  OS << ")";
346  PrintControlledStmt(Node->getBody());
347}
348
349void StmtPrinter::VisitCXXForRangeStmt(CXXForRangeStmt *Node) {
350  Indent() << "for (";
351  if (Node->getInit())
352    PrintInitStmt(Node->getInit(), 5);
353  PrintingPolicy SubPolicy(Policy);
354  SubPolicy.SuppressInitializers = true;
355  Node->getLoopVariable()->print(OSSubPolicyIndentLevel);
356  OS << " : ";
357  PrintExpr(Node->getRangeInit());
358  OS << ")";
359  PrintControlledStmt(Node->getBody());
360}
361
362void StmtPrinter::VisitMSDependentExistsStmt(MSDependentExistsStmt *Node) {
363  Indent();
364  if (Node->isIfExists())
365    OS << "__if_exists (";
366  else
367    OS << "__if_not_exists (";
368
369  if (NestedNameSpecifier *Qualifier
370        = Node->getQualifierLoc().getNestedNameSpecifier())
371    Qualifier->print(OS, Policy);
372
373  OS << Node->getNameInfo() << ") ";
374
375  PrintRawCompoundStmt(Node->getSubStmt());
376}
377
378void StmtPrinter::VisitGotoStmt(GotoStmt *Node) {
379  Indent() << "goto " << Node->getLabel()->getName() << ";";
380  if (Policy.IncludeNewlines) OS << NL;
381}
382
383void StmtPrinter::VisitIndirectGotoStmt(IndirectGotoStmt *Node) {
384  Indent() << "goto *";
385  PrintExpr(Node->getTarget());
386  OS << ";";
387  if (Policy.IncludeNewlines) OS << NL;
388}
389
390void StmtPrinter::VisitContinueStmt(ContinueStmt *Node) {
391  Indent() << "continue;";
392  if (Policy.IncludeNewlines) OS << NL;
393}
394
395void StmtPrinter::VisitBreakStmt(BreakStmt *Node) {
396  Indent() << "break;";
397  if (Policy.IncludeNewlines) OS << NL;
398}
399
400void StmtPrinter::VisitReturnStmt(ReturnStmt *Node) {
401  Indent() << "return";
402  if (Node->getRetValue()) {
403    OS << " ";
404    PrintExpr(Node->getRetValue());
405  }
406  OS << ";";
407  if (Policy.IncludeNewlines) OS << NL;
408}
409
410void StmtPrinter::VisitGCCAsmStmt(GCCAsmStmt *Node) {
411  Indent() << "asm ";
412
413  if (Node->isVolatile())
414    OS << "volatile ";
415
416  OS << "(";
417  VisitStringLiteral(Node->getAsmString());
418
419  // Outputs
420  if (Node->getNumOutputs() != 0 || Node->getNumInputs() != 0 ||
421      Node->getNumClobbers() != 0)
422    OS << " : ";
423
424  for (unsigned i = 0e = Node->getNumOutputs(); i != e; ++i) {
425    if (i != 0)
426      OS << ", ";
427
428    if (!Node->getOutputName(i).empty()) {
429      OS << '[';
430      OS << Node->getOutputName(i);
431      OS << "] ";
432    }
433
434    VisitStringLiteral(Node->getOutputConstraintLiteral(i));
435    OS << " (";
436    Visit(Node->getOutputExpr(i));
437    OS << ")";
438  }
439
440  // Inputs
441  if (Node->getNumInputs() != 0 || Node->getNumClobbers() != 0)
442    OS << " : ";
443
444  for (unsigned i = 0e = Node->getNumInputs(); i != e; ++i) {
445    if (i != 0)
446      OS << ", ";
447
448    if (!Node->getInputName(i).empty()) {
449      OS << '[';
450      OS << Node->getInputName(i);
451      OS << "] ";
452    }
453
454    VisitStringLiteral(Node->getInputConstraintLiteral(i));
455    OS << " (";
456    Visit(Node->getInputExpr(i));
457    OS << ")";
458  }
459
460  // Clobbers
461  if (Node->getNumClobbers() != 0)
462    OS << " : ";
463
464  for (unsigned i = 0e = Node->getNumClobbers(); i != e; ++i) {
465    if (i != 0)
466      OS << ", ";
467
468    VisitStringLiteral(Node->getClobberStringLiteral(i));
469  }
470
471  OS << ");";
472  if (Policy.IncludeNewlines) OS << NL;
473}
474
475void StmtPrinter::VisitMSAsmStmt(MSAsmStmt *Node) {
476  // FIXME: Implement MS style inline asm statement printer.
477  Indent() << "__asm ";
478  if (Node->hasBraces())
479    OS << "{" << NL;
480  OS << Node->getAsmString() << NL;
481  if (Node->hasBraces())
482    Indent() << "}" << NL;
483}
484
485void StmtPrinter::VisitCapturedStmt(CapturedStmt *Node) {
486  PrintStmt(Node->getCapturedDecl()->getBody());
487}
488
489void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
490  Indent() << "@try";
491  if (auto *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
492    PrintRawCompoundStmt(TS);
493    OS << NL;
494  }
495
496  for (unsigned I = 0N = Node->getNumCatchStmts(); I != N; ++I) {
497    ObjCAtCatchStmt *catchStmt = Node->getCatchStmt(I);
498    Indent() << "@catch(";
499    if (catchStmt->getCatchParamDecl()) {
500      if (Decl *DS = catchStmt->getCatchParamDecl())
501        PrintRawDecl(DS);
502    }
503    OS << ")";
504    if (auto *CS = dyn_cast<CompoundStmt>(catchStmt->getCatchBody())) {
505      PrintRawCompoundStmt(CS);
506      OS << NL;
507    }
508  }
509
510  if (auto *FS = static_cast<ObjCAtFinallyStmt *>(Node->getFinallyStmt())) {
511    Indent() << "@finally";
512    PrintRawCompoundStmt(dyn_cast<CompoundStmt>(FS->getFinallyBody()));
513    OS << NL;
514  }
515}
516
517void StmtPrinter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *Node) {
518}
519
520void StmtPrinter::VisitObjCAtCatchStmt (ObjCAtCatchStmt *Node) {
521  Indent() << "@catch (...) { /* todo */ } " << NL;
522}
523
524void StmtPrinter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *Node) {
525  Indent() << "@throw";
526  if (Node->getThrowExpr()) {
527    OS << " ";
528    PrintExpr(Node->getThrowExpr());
529  }
530  OS << ";" << NL;
531}
532
533void StmtPrinter::VisitObjCAvailabilityCheckExpr(
534    ObjCAvailabilityCheckExpr *Node) {
535  OS << "@available(...)";
536}
537
538void StmtPrinter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *Node) {
539  Indent() << "@synchronized (";
540  PrintExpr(Node->getSynchExpr());
541  OS << ")";
542  PrintRawCompoundStmt(Node->getSynchBody());
543  OS << NL;
544}
545
546void StmtPrinter::VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *Node) {
547  Indent() << "@autoreleasepool";
548  PrintRawCompoundStmt(dyn_cast<CompoundStmt>(Node->getSubStmt()));
549  OS << NL;
550}
551
552void StmtPrinter::PrintRawCXXCatchStmt(CXXCatchStmt *Node) {
553  OS << "catch (";
554  if (Decl *ExDecl = Node->getExceptionDecl())
555    PrintRawDecl(ExDecl);
556  else
557    OS << "...";
558  OS << ") ";
559  PrintRawCompoundStmt(cast<CompoundStmt>(Node->getHandlerBlock()));
560}
561
562void StmtPrinter::VisitCXXCatchStmt(CXXCatchStmt *Node) {
563  Indent();
564  PrintRawCXXCatchStmt(Node);
565  OS << NL;
566}
567
568void StmtPrinter::VisitCXXTryStmt(CXXTryStmt *Node) {
569  Indent() << "try ";
570  PrintRawCompoundStmt(Node->getTryBlock());
571  for (unsigned i = 0e = Node->getNumHandlers(); i < e; ++i) {
572    OS << " ";
573    PrintRawCXXCatchStmt(Node->getHandler(i));
574  }
575  OS << NL;
576}
577
578void StmtPrinter::VisitSEHTryStmt(SEHTryStmt *Node) {
579  Indent() << (Node->getIsCXXTry() ? "try " : "__try ");
580  PrintRawCompoundStmt(Node->getTryBlock());
581  SEHExceptStmt *E = Node->getExceptHandler();
582  SEHFinallyStmt *F = Node->getFinallyHandler();
583  if(E)
584    PrintRawSEHExceptHandler(E);
585  else {
586     (0) . __assert_fail ("F && \"Must have a finally block...\"", "/home/seafit/code_projects/clang_source/clang/lib/AST/StmtPrinter.cpp", 586, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(F && "Must have a finally block...");
587    PrintRawSEHFinallyStmt(F);
588  }
589  OS << NL;
590}
591
592void StmtPrinter::PrintRawSEHFinallyStmt(SEHFinallyStmt *Node) {
593  OS << "__finally ";
594  PrintRawCompoundStmt(Node->getBlock());
595  OS << NL;
596}
597
598void StmtPrinter::PrintRawSEHExceptHandler(SEHExceptStmt *Node) {
599  OS << "__except (";
600  VisitExpr(Node->getFilterExpr());
601  OS << ")" << NL;
602  PrintRawCompoundStmt(Node->getBlock());
603  OS << NL;
604}
605
606void StmtPrinter::VisitSEHExceptStmt(SEHExceptStmt *Node) {
607  Indent();
608  PrintRawSEHExceptHandler(Node);
609  OS << NL;
610}
611
612void StmtPrinter::VisitSEHFinallyStmt(SEHFinallyStmt *Node) {
613  Indent();
614  PrintRawSEHFinallyStmt(Node);
615  OS << NL;
616}
617
618void StmtPrinter::VisitSEHLeaveStmt(SEHLeaveStmt *Node) {
619  Indent() << "__leave;";
620  if (Policy.IncludeNewlines) OS << NL;
621}
622
623//===----------------------------------------------------------------------===//
624//  OpenMP directives printing methods
625//===----------------------------------------------------------------------===//
626
627void StmtPrinter::PrintOMPExecutableDirective(OMPExecutableDirective *S,
628                                              bool ForceNoStmt) {
629  OMPClausePrinter Printer(OS, Policy);
630  ArrayRef<OMPClause *> Clauses = S->clauses();
631  for (auto *Clause : Clauses)
632    if (Clause && !Clause->isImplicit()) {
633      OS << ' ';
634      Printer.Visit(Clause);
635    }
636  OS << NL;
637  if (!ForceNoStmt && S->hasAssociatedStmt())
638    PrintStmt(S->getInnermostCapturedStmt()->getCapturedStmt());
639}
640
641void StmtPrinter::VisitOMPParallelDirective(OMPParallelDirective *Node) {
642  Indent() << "#pragma omp parallel";
643  PrintOMPExecutableDirective(Node);
644}
645
646void StmtPrinter::VisitOMPSimdDirective(OMPSimdDirective *Node) {
647  Indent() << "#pragma omp simd";
648  PrintOMPExecutableDirective(Node);
649}
650
651void StmtPrinter::VisitOMPForDirective(OMPForDirective *Node) {
652  Indent() << "#pragma omp for";
653  PrintOMPExecutableDirective(Node);
654}
655
656void StmtPrinter::VisitOMPForSimdDirective(OMPForSimdDirective *Node) {
657  Indent() << "#pragma omp for simd";
658  PrintOMPExecutableDirective(Node);
659}
660
661void StmtPrinter::VisitOMPSectionsDirective(OMPSectionsDirective *Node) {
662  Indent() << "#pragma omp sections";
663  PrintOMPExecutableDirective(Node);
664}
665
666void StmtPrinter::VisitOMPSectionDirective(OMPSectionDirective *Node) {
667  Indent() << "#pragma omp section";
668  PrintOMPExecutableDirective(Node);
669}
670
671void StmtPrinter::VisitOMPSingleDirective(OMPSingleDirective *Node) {
672  Indent() << "#pragma omp single";
673  PrintOMPExecutableDirective(Node);
674}
675
676void StmtPrinter::VisitOMPMasterDirective(OMPMasterDirective *Node) {
677  Indent() << "#pragma omp master";
678  PrintOMPExecutableDirective(Node);
679}
680
681void StmtPrinter::VisitOMPCriticalDirective(OMPCriticalDirective *Node) {
682  Indent() << "#pragma omp critical";
683  if (Node->getDirectiveName().getName()) {
684    OS << " (";
685    Node->getDirectiveName().printName(OS);
686    OS << ")";
687  }
688  PrintOMPExecutableDirective(Node);
689}
690
691void StmtPrinter::VisitOMPParallelForDirective(OMPParallelForDirective *Node) {
692  Indent() << "#pragma omp parallel for";
693  PrintOMPExecutableDirective(Node);
694}
695
696void StmtPrinter::VisitOMPParallelForSimdDirective(
697    OMPParallelForSimdDirective *Node) {
698  Indent() << "#pragma omp parallel for simd";
699  PrintOMPExecutableDirective(Node);
700}
701
702void StmtPrinter::VisitOMPParallelSectionsDirective(
703    OMPParallelSectionsDirective *Node) {
704  Indent() << "#pragma omp parallel sections";
705  PrintOMPExecutableDirective(Node);
706}
707
708void StmtPrinter::VisitOMPTaskDirective(OMPTaskDirective *Node) {
709  Indent() << "#pragma omp task";
710  PrintOMPExecutableDirective(Node);
711}
712
713void StmtPrinter::VisitOMPTaskyieldDirective(OMPTaskyieldDirective *Node) {
714  Indent() << "#pragma omp taskyield";
715  PrintOMPExecutableDirective(Node);
716}
717
718void StmtPrinter::VisitOMPBarrierDirective(OMPBarrierDirective *Node) {
719  Indent() << "#pragma omp barrier";
720  PrintOMPExecutableDirective(Node);
721}
722
723void StmtPrinter::VisitOMPTaskwaitDirective(OMPTaskwaitDirective *Node) {
724  Indent() << "#pragma omp taskwait";
725  PrintOMPExecutableDirective(Node);
726}
727
728void StmtPrinter::VisitOMPTaskgroupDirective(OMPTaskgroupDirective *Node) {
729  Indent() << "#pragma omp taskgroup";
730  PrintOMPExecutableDirective(Node);
731}
732
733void StmtPrinter::VisitOMPFlushDirective(OMPFlushDirective *Node) {
734  Indent() << "#pragma omp flush";
735  PrintOMPExecutableDirective(Node);
736}
737
738void StmtPrinter::VisitOMPOrderedDirective(OMPOrderedDirective *Node) {
739  Indent() << "#pragma omp ordered";
740  PrintOMPExecutableDirective(NodeNode->hasClausesOfKind<OMPDependClause>());
741}
742
743void StmtPrinter::VisitOMPAtomicDirective(OMPAtomicDirective *Node) {
744  Indent() << "#pragma omp atomic";
745  PrintOMPExecutableDirective(Node);
746}
747
748void StmtPrinter::VisitOMPTargetDirective(OMPTargetDirective *Node) {
749  Indent() << "#pragma omp target";
750  PrintOMPExecutableDirective(Node);
751}
752
753void StmtPrinter::VisitOMPTargetDataDirective(OMPTargetDataDirective *Node) {
754  Indent() << "#pragma omp target data";
755  PrintOMPExecutableDirective(Node);
756}
757
758void StmtPrinter::VisitOMPTargetEnterDataDirective(
759    OMPTargetEnterDataDirective *Node) {
760  Indent() << "#pragma omp target enter data";
761  PrintOMPExecutableDirective(Node/*ForceNoStmt=*/true);
762}
763
764void StmtPrinter::VisitOMPTargetExitDataDirective(
765    OMPTargetExitDataDirective *Node) {
766  Indent() << "#pragma omp target exit data";
767  PrintOMPExecutableDirective(Node/*ForceNoStmt=*/true);
768}
769
770void StmtPrinter::VisitOMPTargetParallelDirective(
771    OMPTargetParallelDirective *Node) {
772  Indent() << "#pragma omp target parallel";
773  PrintOMPExecutableDirective(Node);
774}
775
776void StmtPrinter::VisitOMPTargetParallelForDirective(
777    OMPTargetParallelForDirective *Node) {
778  Indent() << "#pragma omp target parallel for";
779  PrintOMPExecutableDirective(Node);
780}
781
782void StmtPrinter::VisitOMPTeamsDirective(OMPTeamsDirective *Node) {
783  Indent() << "#pragma omp teams";
784  PrintOMPExecutableDirective(Node);
785}
786
787void StmtPrinter::VisitOMPCancellationPointDirective(
788    OMPCancellationPointDirective *Node) {
789  Indent() << "#pragma omp cancellation point "
790           << getOpenMPDirectiveName(Node->getCancelRegion());
791  PrintOMPExecutableDirective(Node);
792}
793
794void StmtPrinter::VisitOMPCancelDirective(OMPCancelDirective *Node) {
795  Indent() << "#pragma omp cancel "
796           << getOpenMPDirectiveName(Node->getCancelRegion());
797  PrintOMPExecutableDirective(Node);
798}
799
800void StmtPrinter::VisitOMPTaskLoopDirective(OMPTaskLoopDirective *Node) {
801  Indent() << "#pragma omp taskloop";
802  PrintOMPExecutableDirective(Node);
803}
804
805void StmtPrinter::VisitOMPTaskLoopSimdDirective(
806    OMPTaskLoopSimdDirective *Node) {
807  Indent() << "#pragma omp taskloop simd";
808  PrintOMPExecutableDirective(Node);
809}
810
811void StmtPrinter::VisitOMPDistributeDirective(OMPDistributeDirective *Node) {
812  Indent() << "#pragma omp distribute";
813  PrintOMPExecutableDirective(Node);
814}
815
816void StmtPrinter::VisitOMPTargetUpdateDirective(
817    OMPTargetUpdateDirective *Node) {
818  Indent() << "#pragma omp target update";
819  PrintOMPExecutableDirective(Node/*ForceNoStmt=*/true);
820}
821
822void StmtPrinter::VisitOMPDistributeParallelForDirective(
823    OMPDistributeParallelForDirective *Node) {
824  Indent() << "#pragma omp distribute parallel for";
825  PrintOMPExecutableDirective(Node);
826}
827
828void StmtPrinter::VisitOMPDistributeParallelForSimdDirective(
829    OMPDistributeParallelForSimdDirective *Node) {
830  Indent() << "#pragma omp distribute parallel for simd";
831  PrintOMPExecutableDirective(Node);
832}
833
834void StmtPrinter::VisitOMPDistributeSimdDirective(
835    OMPDistributeSimdDirective *Node) {
836  Indent() << "#pragma omp distribute simd";
837  PrintOMPExecutableDirective(Node);
838}
839
840void StmtPrinter::VisitOMPTargetParallelForSimdDirective(
841    OMPTargetParallelForSimdDirective *Node) {
842  Indent() << "#pragma omp target parallel for simd";
843  PrintOMPExecutableDirective(Node);
844}
845
846void StmtPrinter::VisitOMPTargetSimdDirective(OMPTargetSimdDirective *Node) {
847  Indent() << "#pragma omp target simd";
848  PrintOMPExecutableDirective(Node);
849}
850
851void StmtPrinter::VisitOMPTeamsDistributeDirective(
852    OMPTeamsDistributeDirective *Node) {
853  Indent() << "#pragma omp teams distribute";
854  PrintOMPExecutableDirective(Node);
855}
856
857void StmtPrinter::VisitOMPTeamsDistributeSimdDirective(
858    OMPTeamsDistributeSimdDirective *Node) {
859  Indent() << "#pragma omp teams distribute simd";
860  PrintOMPExecutableDirective(Node);
861}
862
863void StmtPrinter::VisitOMPTeamsDistributeParallelForSimdDirective(
864    OMPTeamsDistributeParallelForSimdDirective *Node) {
865  Indent() << "#pragma omp teams distribute parallel for simd";
866  PrintOMPExecutableDirective(Node);
867}
868
869void StmtPrinter::VisitOMPTeamsDistributeParallelForDirective(
870    OMPTeamsDistributeParallelForDirective *Node) {
871  Indent() << "#pragma omp teams distribute parallel for";
872  PrintOMPExecutableDirective(Node);
873}
874
875void StmtPrinter::VisitOMPTargetTeamsDirective(OMPTargetTeamsDirective *Node) {
876  Indent() << "#pragma omp target teams";
877  PrintOMPExecutableDirective(Node);
878}
879
880void StmtPrinter::VisitOMPTargetTeamsDistributeDirective(
881    OMPTargetTeamsDistributeDirective *Node) {
882  Indent() << "#pragma omp target teams distribute";
883  PrintOMPExecutableDirective(Node);
884}
885
886void StmtPrinter::VisitOMPTargetTeamsDistributeParallelForDirective(
887    OMPTargetTeamsDistributeParallelForDirective *Node) {
888  Indent() << "#pragma omp target teams distribute parallel for";
889  PrintOMPExecutableDirective(Node);
890}
891
892void StmtPrinter::VisitOMPTargetTeamsDistributeParallelForSimdDirective(
893    OMPTargetTeamsDistributeParallelForSimdDirective *Node) {
894  Indent() << "#pragma omp target teams distribute parallel for simd";
895  PrintOMPExecutableDirective(Node);
896}
897
898void StmtPrinter::VisitOMPTargetTeamsDistributeSimdDirective(
899    OMPTargetTeamsDistributeSimdDirective *Node) {
900  Indent() << "#pragma omp target teams distribute simd";
901  PrintOMPExecutableDirective(Node);
902}
903
904//===----------------------------------------------------------------------===//
905//  Expr printing methods.
906//===----------------------------------------------------------------------===//
907
908void StmtPrinter::VisitConstantExpr(ConstantExpr *Node) {
909  PrintExpr(Node->getSubExpr());
910}
911
912void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
913  if (const auto *OCED = dyn_cast<OMPCapturedExprDecl>(Node->getDecl())) {
914    OCED->getInit()->IgnoreImpCasts()->printPretty(OS, nullptr, Policy);
915    return;
916  }
917  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
918    Qualifier->print(OS, Policy);
919  if (Node->hasTemplateKeyword())
920    OS << "template ";
921  OS << Node->getNameInfo();
922  if (Node->hasExplicitTemplateArgs())
923    printTemplateArgumentList(OS, Node->template_arguments(), Policy);
924}
925
926void StmtPrinter::VisitDependentScopeDeclRefExpr(
927                                           DependentScopeDeclRefExpr *Node) {
928  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
929    Qualifier->print(OS, Policy);
930  if (Node->hasTemplateKeyword())
931    OS << "template ";
932  OS << Node->getNameInfo();
933  if (Node->hasExplicitTemplateArgs())
934    printTemplateArgumentList(OS, Node->template_arguments(), Policy);
935}
936
937void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
938  if (Node->getQualifier())
939    Node->getQualifier()->print(OS, Policy);
940  if (Node->hasTemplateKeyword())
941    OS << "template ";
942  OS << Node->getNameInfo();
943  if (Node->hasExplicitTemplateArgs())
944    printTemplateArgumentList(OS, Node->template_arguments(), Policy);
945}
946
947static bool isImplicitSelf(const Expr *E) {
948  if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
949    if (const auto *PD = dyn_cast<ImplicitParamDecl>(DRE->getDecl())) {
950      if (PD->getParameterKind() == ImplicitParamDecl::ObjCSelf &&
951          DRE->getBeginLoc().isInvalid())
952        return true;
953    }
954  }
955  return false;
956}
957
958void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
959  if (Node->getBase()) {
960    if (!Policy.SuppressImplicitBase ||
961        !isImplicitSelf(Node->getBase()->IgnoreImpCasts())) {
962      PrintExpr(Node->getBase());
963      OS << (Node->isArrow() ? "->" : ".");
964    }
965  }
966  OS << *Node->getDecl();
967}
968
969void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
970  if (Node->isSuperReceiver())
971    OS << "super.";
972  else if (Node->isObjectReceiver() && Node->getBase()) {
973    PrintExpr(Node->getBase());
974    OS << ".";
975  } else if (Node->isClassReceiver() && Node->getClassReceiver()) {
976    OS << Node->getClassReceiver()->getName() << ".";
977  }
978
979  if (Node->isImplicitProperty()) {
980    if (const auto *Getter = Node->getImplicitPropertyGetter())
981      Getter->getSelector().print(OS);
982    else
983      OS << SelectorTable::getPropertyNameFromSetterSelector(
984          Node->getImplicitPropertySetter()->getSelector());
985  } else
986    OS << Node->getExplicitProperty()->getName();
987}
988
989void StmtPrinter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node) {
990  PrintExpr(Node->getBaseExpr());
991  OS << "[";
992  PrintExpr(Node->getKeyExpr());
993  OS << "]";
994}
995
996void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
997  OS << PredefinedExpr::getIdentKindName(Node->getIdentKind());
998}
999
1000void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
1001  unsigned value = Node->getValue();
1002
1003  switch (Node->getKind()) {
1004  case CharacterLiteral::Asciibreak// no prefix.
1005  case CharacterLiteral::Wide:  OS << 'L'break;
1006  case CharacterLiteral::UTF8:  OS << "u8"break;
1007  case CharacterLiteral::UTF16OS << 'u'break;
1008  case CharacterLiteral::UTF32OS << 'U'break;
1009  }
1010
1011  switch (value) {
1012  case '\\':
1013    OS << "'\\\\'";
1014    break;
1015  case '\'':
1016    OS << "'\\''";
1017    break;
1018  case '\a':
1019    // TODO: K&R: the meaning of '\\a' is different in traditional C
1020    OS << "'\\a'";
1021    break;
1022  case '\b':
1023    OS << "'\\b'";
1024    break;
1025  // Nonstandard escape sequence.
1026  /*case '\e':
1027    OS << "'\\e'";
1028    break;*/
1029  case '\f':
1030    OS << "'\\f'";
1031    break;
1032  case '\n':
1033    OS << "'\\n'";
1034    break;
1035  case '\r':
1036    OS << "'\\r'";
1037    break;
1038  case '\t':
1039    OS << "'\\t'";
1040    break;
1041  case '\v':
1042    OS << "'\\v'";
1043    break;
1044  default:
1045    // A character literal might be sign-extended, which
1046    // would result in an invalid \U escape sequence.
1047    // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1048    // are not correctly handled.
1049    if ((value & ~0xFFu) == ~0xFFu && Node->getKind() == CharacterLiteral::Ascii)
1050      value &= 0xFFu;
1051    if (value < 256 && isPrintable((unsigned char)value))
1052      OS << "'" << (char)value << "'";
1053    else if (value < 256)
1054      OS << "'\\x" << llvm::format("%02x", value) << "'";
1055    else if (value <= 0xFFFF)
1056      OS << "'\\u" << llvm::format("%04x", value) << "'";
1057    else
1058      OS << "'\\U" << llvm::format("%08x", value) << "'";
1059  }
1060}
1061
1062/// Prints the given expression using the original source text. Returns true on
1063/// success, false otherwise.
1064static bool printExprAsWritten(raw_ostream &OSExpr *E,
1065                               const ASTContext *Context) {
1066  if (!Context)
1067    return false;
1068  bool Invalid = false;
1069  StringRef Source = Lexer::getSourceText(
1070      CharSourceRange::getTokenRange(E->getSourceRange()),
1071      Context->getSourceManager(), Context->getLangOpts(), &Invalid);
1072  if (!Invalid) {
1073    OS << Source;
1074    return true;
1075  }
1076  return false;
1077}
1078
1079void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
1080  if (Policy.ConstantsAsWritten && printExprAsWritten(OS, Node, Context))
1081    return;
1082  bool isSigned = Node->getType()->isSignedIntegerType();
1083  OS << Node->getValue().toString(10isSigned);
1084
1085  // Emit suffixes.  Integer literals are always a builtin integer type.
1086  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
1087  default: llvm_unreachable("Unexpected type for integer literal!");
1088  case BuiltinType::Char_S:
1089  case BuiltinType::Char_U:    OS << "i8"break;
1090  case BuiltinType::UChar:     OS << "Ui8"break;
1091  case BuiltinType::Short:     OS << "i16"break;
1092  case BuiltinType::UShort:    OS << "Ui16"break;
1093  case BuiltinType::Int:       break// no suffix.
1094  case BuiltinType::UInt:      OS << 'U'break;
1095  case BuiltinType::Long:      OS << 'L'break;
1096  case BuiltinType::ULong:     OS << "UL"break;
1097  case BuiltinType::LongLong:  OS << "LL"break;
1098  case BuiltinType::ULongLongOS << "ULL"break;
1099  }
1100}
1101
1102void StmtPrinter::VisitFixedPointLiteral(FixedPointLiteral *Node) {
1103  if (Policy.ConstantsAsWritten && printExprAsWritten(OS, Node, Context))
1104    return;
1105  OS << Node->getValueAsString(/*Radix=*/10);
1106
1107  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
1108    default: llvm_unreachable("Unexpected type for fixed point literal!");
1109    case BuiltinType::ShortFract:   OS << "hr"break;
1110    case BuiltinType::ShortAccum:   OS << "hk"break;
1111    case BuiltinType::UShortFract:  OS << "uhr"break;
1112    case BuiltinType::UShortAccum:  OS << "uhk"break;
1113    case BuiltinType::Fract:        OS << "r"break;
1114    case BuiltinType::Accum:        OS << "k"break;
1115    case BuiltinType::UFract:       OS << "ur"break;
1116    case BuiltinType::UAccum:       OS << "uk"break;
1117    case BuiltinType::LongFract:    OS << "lr"break;
1118    case BuiltinType::LongAccum:    OS << "lk"break;
1119    case BuiltinType::ULongFract:   OS << "ulr"break;
1120    case BuiltinType::ULongAccum:   OS << "ulk"break;
1121  }
1122}
1123
1124static void PrintFloatingLiteral(raw_ostream &OSFloatingLiteral *Node,
1125                                 bool PrintSuffix) {
1126  SmallString<16Str;
1127  Node->getValue().toString(Str);
1128  OS << Str;
1129  if (Str.find_first_not_of("-0123456789") == StringRef::npos)
1130    OS << '.'// Trailing dot in order to separate from ints.
1131
1132  if (!PrintSuffix)
1133    return;
1134
1135  // Emit suffixes.  Float literals are always a builtin float type.
1136  switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
1137  default: llvm_unreachable("Unexpected type for float literal!");
1138  case BuiltinType::Half:       break// FIXME: suffix?
1139  case BuiltinType::Double:     break// no suffix.
1140  case BuiltinType::Float16:    OS << "F16"break;
1141  case BuiltinType::Float:      OS << 'F'break;
1142  case BuiltinType::LongDoubleOS << 'L'break;
1143  case BuiltinType::Float128:   OS << 'Q'break;
1144  }
1145}
1146
1147void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
1148  if (Policy.ConstantsAsWritten && printExprAsWritten(OS, Node, Context))
1149    return;
1150  PrintFloatingLiteral(OSNode/*PrintSuffix=*/true);
1151}
1152
1153void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
1154  PrintExpr(Node->getSubExpr());
1155  OS << "i";
1156}
1157
1158void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
1159  Str->outputString(OS);
1160}
1161
1162void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
1163  OS << "(";
1164  PrintExpr(Node->getSubExpr());
1165  OS << ")";
1166}
1167
1168void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
1169  if (!Node->isPostfix()) {
1170    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1171
1172    // Print a space if this is an "identifier operator" like __real, or if
1173    // it might be concatenated incorrectly like '+'.
1174    switch (Node->getOpcode()) {
1175    defaultbreak;
1176    case UO_Real:
1177    case UO_Imag:
1178    case UO_Extension:
1179      OS << ' ';
1180      break;
1181    case UO_Plus:
1182    case UO_Minus:
1183      if (isa<UnaryOperator>(Node->getSubExpr()))
1184        OS << ' ';
1185      break;
1186    }
1187  }
1188  PrintExpr(Node->getSubExpr());
1189
1190  if (Node->isPostfix())
1191    OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1192}
1193
1194void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
1195  OS << "__builtin_offsetof(";
1196  Node->getTypeSourceInfo()->getType().print(OS, Policy);
1197  OS << ", ";
1198  bool PrintedSomething = false;
1199  for (unsigned i = 0n = Node->getNumComponents(); i < n; ++i) {
1200    OffsetOfNode ON = Node->getComponent(i);
1201    if (ON.getKind() == OffsetOfNode::Array) {
1202      // Array node
1203      OS << "[";
1204      PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
1205      OS << "]";
1206      PrintedSomething = true;
1207      continue;
1208    }
1209
1210    // Skip implicit base indirections.
1211    if (ON.getKind() == OffsetOfNode::Base)
1212      continue;
1213
1214    // Field or identifier node.
1215    IdentifierInfo *Id = ON.getFieldName();
1216    if (!Id)
1217      continue;
1218
1219    if (PrintedSomething)
1220      OS << ".";
1221    else
1222      PrintedSomething = true;
1223    OS << Id->getName();
1224  }
1225  OS << ")";
1226}
1227
1228void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
1229  switch(Node->getKind()) {
1230  case UETT_SizeOf:
1231    OS << "sizeof";
1232    break;
1233  case UETT_AlignOf:
1234    if (Policy.Alignof)
1235      OS << "alignof";
1236    else if (Policy.UnderscoreAlignof)
1237      OS << "_Alignof";
1238    else
1239      OS << "__alignof";
1240    break;
1241  case UETT_PreferredAlignOf:
1242    OS << "__alignof";
1243    break;
1244  case UETT_VecStep:
1245    OS << "vec_step";
1246    break;
1247  case UETT_OpenMPRequiredSimdAlign:
1248    OS << "__builtin_omp_required_simd_align";
1249    break;
1250  }
1251  if (Node->isArgumentType()) {
1252    OS << '(';
1253    Node->getArgumentType().print(OS, Policy);
1254    OS << ')';
1255  } else {
1256    OS << " ";
1257    PrintExpr(Node->getArgumentExpr());
1258  }
1259}
1260
1261void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
1262  OS << "_Generic(";
1263  PrintExpr(Node->getControllingExpr());
1264  for (const GenericSelectionExpr::Association &Assoc : Node->associations()) {
1265    OS << ", ";
1266    QualType T = Assoc.getType();
1267    if (T.isNull())
1268      OS << "default";
1269    else
1270      T.print(OS, Policy);
1271    OS << ": ";
1272    PrintExpr(Assoc.getAssociationExpr());
1273  }
1274  OS << ")";
1275}
1276
1277void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
1278  PrintExpr(Node->getLHS());
1279  OS << "[";
1280  PrintExpr(Node->getRHS());
1281  OS << "]";
1282}
1283
1284void StmtPrinter::VisitOMPArraySectionExpr(OMPArraySectionExpr *Node) {
1285  PrintExpr(Node->getBase());
1286  OS << "[";
1287  if (Node->getLowerBound())
1288    PrintExpr(Node->getLowerBound());
1289  if (Node->getColonLoc().isValid()) {
1290    OS << ":";
1291    if (Node->getLength())
1292      PrintExpr(Node->getLength());
1293  }
1294  OS << "]";
1295}
1296
1297void StmtPrinter::PrintCallArgs(CallExpr *Call) {
1298  for (unsigned i = 0e = Call->getNumArgs(); i != e; ++i) {
1299    if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
1300      // Don't print any defaulted arguments
1301      break;
1302    }
1303
1304    if (iOS << ", ";
1305    PrintExpr(Call->getArg(i));
1306  }
1307}
1308
1309void StmtPrinter::VisitCallExpr(CallExpr *Call) {
1310  PrintExpr(Call->getCallee());
1311  OS << "(";
1312  PrintCallArgs(Call);
1313  OS << ")";
1314}
1315
1316static bool isImplicitThis(const Expr *E) {
1317  if (const auto *TE = dyn_cast<CXXThisExpr>(E))
1318    return TE->isImplicit();
1319  return false;
1320}
1321
1322void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
1323  if (!Policy.SuppressImplicitBase || !isImplicitThis(Node->getBase())) {
1324    PrintExpr(Node->getBase());
1325
1326    auto *ParentMember = dyn_cast<MemberExpr>(Node->getBase());
1327    FieldDecl *ParentDecl =
1328        ParentMember ? dyn_cast<FieldDecl>(ParentMember->getMemberDecl())
1329                     : nullptr;
1330
1331    if (!ParentDecl || !ParentDecl->isAnonymousStructOrUnion())
1332      OS << (Node->isArrow() ? "->" : ".");
1333  }
1334
1335  if (auto *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
1336    if (FD->isAnonymousStructOrUnion())
1337      return;
1338
1339  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1340    Qualifier->print(OS, Policy);
1341  if (Node->hasTemplateKeyword())
1342    OS << "template ";
1343  OS << Node->getMemberNameInfo();
1344  if (Node->hasExplicitTemplateArgs())
1345    printTemplateArgumentList(OS, Node->template_arguments(), Policy);
1346}
1347
1348void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
1349  PrintExpr(Node->getBase());
1350  OS << (Node->isArrow() ? "->isa" : ".isa");
1351}
1352
1353void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
1354  PrintExpr(Node->getBase());
1355  OS << ".";
1356  OS << Node->getAccessor().getName();
1357}
1358
1359void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
1360  OS << '(';
1361  Node->getTypeAsWritten().print(OS, Policy);
1362  OS << ')';
1363  PrintExpr(Node->getSubExpr());
1364}
1365
1366void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
1367  OS << '(';
1368  Node->getType().print(OS, Policy);
1369  OS << ')';
1370  PrintExpr(Node->getInitializer());
1371}
1372
1373void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
1374  // No need to print anything, simply forward to the subexpression.
1375  PrintExpr(Node->getSubExpr());
1376}
1377
1378void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
1379  PrintExpr(Node->getLHS());
1380  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1381  PrintExpr(Node->getRHS());
1382}
1383
1384void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
1385  PrintExpr(Node->getLHS());
1386  OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1387  PrintExpr(Node->getRHS());
1388}
1389
1390void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
1391  PrintExpr(Node->getCond());
1392  OS << " ? ";
1393  PrintExpr(Node->getLHS());
1394  OS << " : ";
1395  PrintExpr(Node->getRHS());
1396}
1397
1398// GNU extensions.
1399
1400void
1401StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
1402  PrintExpr(Node->getCommon());
1403  OS << " ?: ";
1404  PrintExpr(Node->getFalseExpr());
1405}
1406
1407void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
1408  OS << "&&" << Node->getLabel()->getName();
1409}
1410
1411void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
1412  OS << "(";
1413  PrintRawCompoundStmt(E->getSubStmt());
1414  OS << ")";
1415}
1416
1417void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
1418  OS << "__builtin_choose_expr(";
1419  PrintExpr(Node->getCond());
1420  OS << ", ";
1421  PrintExpr(Node->getLHS());
1422  OS << ", ";
1423  PrintExpr(Node->getRHS());
1424  OS << ")";
1425}
1426
1427void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
1428  OS << "__null";
1429}
1430
1431void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
1432  OS << "__builtin_shufflevector(";
1433  for (unsigned i = 0e = Node->getNumSubExprs(); i != e; ++i) {
1434    if (iOS << ", ";
1435    PrintExpr(Node->getExpr(i));
1436  }
1437  OS << ")";
1438}
1439
1440void StmtPrinter::VisitConvertVectorExpr(ConvertVectorExpr *Node) {
1441  OS << "__builtin_convertvector(";
1442  PrintExpr(Node->getSrcExpr());
1443  OS << ", ";
1444  Node->getType().print(OS, Policy);
1445  OS << ")";
1446}
1447
1448void StmtPrinter::VisitInitListExpr(InitListExprNode) {
1449  if (Node->getSyntacticForm()) {
1450    Visit(Node->getSyntacticForm());
1451    return;
1452  }
1453
1454  OS << "{";
1455  for (unsigned i = 0e = Node->getNumInits(); i != e; ++i) {
1456    if (iOS << ", ";
1457    if (Node->getInit(i))
1458      PrintExpr(Node->getInit(i));
1459    else
1460      OS << "{}";
1461  }
1462  OS << "}";
1463}
1464
1465void StmtPrinter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *Node) {
1466  // There's no way to express this expression in any of our supported
1467  // languages, so just emit something terse and (hopefully) clear.
1468  OS << "{";
1469  PrintExpr(Node->getSubExpr());
1470  OS << "}";
1471}
1472
1473void StmtPrinter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *Node) {
1474  OS << "*";
1475}
1476
1477void StmtPrinter::VisitParenListExpr(ParenListExprNode) {
1478  OS << "(";
1479  for (unsigned i = 0e = Node->getNumExprs(); i != e; ++i) {
1480    if (iOS << ", ";
1481    PrintExpr(Node->getExpr(i));
1482  }
1483  OS << ")";
1484}
1485
1486void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
1487  bool NeedsEquals = true;
1488  for (const DesignatedInitExpr::Designator &D : Node->designators()) {
1489    if (D.isFieldDesignator()) {
1490      if (D.getDotLoc().isInvalid()) {
1491        if (IdentifierInfo *II = D.getFieldName()) {
1492          OS << II->getName() << ":";
1493          NeedsEquals = false;
1494        }
1495      } else {
1496        OS << "." << D.getFieldName()->getName();
1497      }
1498    } else {
1499      OS << "[";
1500      if (D.isArrayDesignator()) {
1501        PrintExpr(Node->getArrayIndex(D));
1502      } else {
1503        PrintExpr(Node->getArrayRangeStart(D));
1504        OS << " ... ";
1505        PrintExpr(Node->getArrayRangeEnd(D));
1506      }
1507      OS << "]";
1508    }
1509  }
1510
1511  if (NeedsEquals)
1512    OS << " = ";
1513  else
1514    OS << " ";
1515  PrintExpr(Node->getInit());
1516}
1517
1518void StmtPrinter::VisitDesignatedInitUpdateExpr(
1519    DesignatedInitUpdateExpr *Node) {
1520  OS << "{";
1521  OS << "/*base*/";
1522  PrintExpr(Node->getBase());
1523  OS << ", ";
1524
1525  OS << "/*updater*/";
1526  PrintExpr(Node->getUpdater());
1527  OS << "}";
1528}
1529
1530void StmtPrinter::VisitNoInitExpr(NoInitExpr *Node) {
1531  OS << "/*no init*/";
1532}
1533
1534void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
1535  if (Node->getType()->getAsCXXRecordDecl()) {
1536    OS << "/*implicit*/";
1537    Node->getType().print(OS, Policy);
1538    OS << "()";
1539  } else {
1540    OS << "/*implicit*/(";
1541    Node->getType().print(OS, Policy);
1542    OS << ')';
1543    if (Node->getType()->isRecordType())
1544      OS << "{}";
1545    else
1546      OS << 0;
1547  }
1548}
1549
1550void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1551  OS << "__builtin_va_arg(";
1552  PrintExpr(Node->getSubExpr());
1553  OS << ", ";
1554  Node->getType().print(OS, Policy);
1555  OS << ")";
1556}
1557
1558void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
1559  PrintExpr(Node->getSyntacticForm());
1560}
1561
1562void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
1563  const char *Name = nullptr;
1564  switch (Node->getOp()) {
1565#define BUILTIN(ID, TYPE, ATTRS)
1566#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1567  case AtomicExpr::AO ## ID: \
1568    Name = #ID "("; \
1569    break;
1570#include "clang/Basic/Builtins.def"
1571  }
1572  OS << Name;
1573
1574  // AtomicExpr stores its subexpressions in a permuted order.
1575  PrintExpr(Node->getPtr());
1576  if (Node->getOp() != AtomicExpr::AO__c11_atomic_load &&
1577      Node->getOp() != AtomicExpr::AO__atomic_load_n &&
1578      Node->getOp() != AtomicExpr::AO__opencl_atomic_load) {
1579    OS << ", ";
1580    PrintExpr(Node->getVal1());
1581  }
1582  if (Node->getOp() == AtomicExpr::AO__atomic_exchange ||
1583      Node->isCmpXChg()) {
1584    OS << ", ";
1585    PrintExpr(Node->getVal2());
1586  }
1587  if (Node->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1588      Node->getOp() == AtomicExpr::AO__atomic_compare_exchange_n) {
1589    OS << ", ";
1590    PrintExpr(Node->getWeak());
1591  }
1592  if (Node->getOp() != AtomicExpr::AO__c11_atomic_init &&
1593      Node->getOp() != AtomicExpr::AO__opencl_atomic_init) {
1594    OS << ", ";
1595    PrintExpr(Node->getOrder());
1596  }
1597  if (Node->isCmpXChg()) {
1598    OS << ", ";
1599    PrintExpr(Node->getOrderFail());
1600  }
1601  OS << ")";
1602}
1603
1604// C++
1605void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
1606  const char *OpStrings[NUM_OVERLOADED_OPERATORS] = {
1607    "",
1608#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1609    Spelling,
1610#include "clang/Basic/OperatorKinds.def"
1611  };
1612
1613  OverloadedOperatorKind Kind = Node->getOperator();
1614  if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1615    if (Node->getNumArgs() == 1) {
1616      OS << OpStrings[Kind] << ' ';
1617      PrintExpr(Node->getArg(0));
1618    } else {
1619      PrintExpr(Node->getArg(0));
1620      OS << ' ' << OpStrings[Kind];
1621    }
1622  } else if (Kind == OO_Arrow) {
1623    PrintExpr(Node->getArg(0));
1624  } else if (Kind == OO_Call) {
1625    PrintExpr(Node->getArg(0));
1626    OS << '(';
1627    for (unsigned ArgIdx = 1ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1628      if (ArgIdx > 1)
1629        OS << ", ";
1630      if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1631        PrintExpr(Node->getArg(ArgIdx));
1632    }
1633    OS << ')';
1634  } else if (Kind == OO_Subscript) {
1635    PrintExpr(Node->getArg(0));
1636    OS << '[';
1637    PrintExpr(Node->getArg(1));
1638    OS << ']';
1639  } else if (Node->getNumArgs() == 1) {
1640    OS << OpStrings[Kind] << ' ';
1641    PrintExpr(Node->getArg(0));
1642  } else if (Node->getNumArgs() == 2) {
1643    PrintExpr(Node->getArg(0));
1644    OS << ' ' << OpStrings[Kind] << ' ';
1645    PrintExpr(Node->getArg(1));
1646  } else {
1647    llvm_unreachable("unknown overloaded operator");
1648  }
1649}
1650
1651void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1652  // If we have a conversion operator call only print the argument.
1653  CXXMethodDecl *MD = Node->getMethodDecl();
1654  if (MD && isa<CXXConversionDecl>(MD)) {
1655    PrintExpr(Node->getImplicitObjectArgument());
1656    return;
1657  }
1658  VisitCallExpr(cast<CallExpr>(Node));
1659}
1660
1661void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1662  PrintExpr(Node->getCallee());
1663  OS << "<<<";
1664  PrintCallArgs(Node->getConfig());
1665  OS << ">>>(";
1666  PrintCallArgs(Node);
1667  OS << ")";
1668}
1669
1670void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1671  OS << Node->getCastName() << '<';
1672  Node->getTypeAsWritten().print(OS, Policy);
1673  OS << ">(";
1674  PrintExpr(Node->getSubExpr());
1675  OS << ")";
1676}
1677
1678void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1679  VisitCXXNamedCastExpr(Node);
1680}
1681
1682void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1683  VisitCXXNamedCastExpr(Node);
1684}
1685
1686void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1687  VisitCXXNamedCastExpr(Node);
1688}
1689
1690void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1691  VisitCXXNamedCastExpr(Node);
1692}
1693
1694void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1695  OS << "typeid(";
1696  if (Node->isTypeOperand()) {
1697    Node->getTypeOperandSourceInfo()->getType().print(OS, Policy);
1698  } else {
1699    PrintExpr(Node->getExprOperand());
1700  }
1701  OS << ")";
1702}
1703
1704void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1705  OS << "__uuidof(";
1706  if (Node->isTypeOperand()) {
1707    Node->getTypeOperandSourceInfo()->getType().print(OS, Policy);
1708  } else {
1709    PrintExpr(Node->getExprOperand());
1710  }
1711  OS << ")";
1712}
1713
1714void StmtPrinter::VisitMSPropertyRefExpr(MSPropertyRefExpr *Node) {
1715  PrintExpr(Node->getBaseExpr());
1716  if (Node->isArrow())
1717    OS << "->";
1718  else
1719    OS << ".";
1720  if (NestedNameSpecifier *Qualifier =
1721      Node->getQualifierLoc().getNestedNameSpecifier())
1722    Qualifier->print(OS, Policy);
1723  OS << Node->getPropertyDecl()->getDeclName();
1724}
1725
1726void StmtPrinter::VisitMSPropertySubscriptExpr(MSPropertySubscriptExpr *Node) {
1727  PrintExpr(Node->getBase());
1728  OS << "[";
1729  PrintExpr(Node->getIdx());
1730  OS << "]";
1731}
1732
1733void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
1734  switch (Node->getLiteralOperatorKind()) {
1735  case UserDefinedLiteral::LOK_Raw:
1736    OS << cast<StringLiteral>(Node->getArg(0)->IgnoreImpCasts())->getString();
1737    break;
1738  case UserDefinedLiteral::LOK_Template: {
1739    const auto *DRE = cast<DeclRefExpr>(Node->getCallee()->IgnoreImpCasts());
1740    const TemplateArgumentList *Args =
1741      cast<FunctionDecl>(DRE->getDecl())->getTemplateSpecializationArgs();
1742    assert(Args);
1743
1744    if (Args->size() != 1) {
1745      OS << "operator\"\"" << Node->getUDSuffix()->getName();
1746      printTemplateArgumentList(OS, Args->asArray(), Policy);
1747      OS << "()";
1748      return;
1749    }
1750
1751    const TemplateArgument &Pack = Args->get(0);
1752    for (const auto &P : Pack.pack_elements()) {
1753      char C = (char)P.getAsIntegral().getZExtValue();
1754      OS << C;
1755    }
1756    break;
1757  }
1758  case UserDefinedLiteral::LOK_Integer: {
1759    // Print integer literal without suffix.
1760    const auto *Int = cast<IntegerLiteral>(Node->getCookedLiteral());
1761    OS << Int->getValue().toString(10/*isSigned*/false);
1762    break;
1763  }
1764  case UserDefinedLiteral::LOK_Floating: {
1765    // Print floating literal without suffix.
1766    auto *Float = cast<FloatingLiteral>(Node->getCookedLiteral());
1767    PrintFloatingLiteral(OS, Float, /*PrintSuffix=*/false);
1768    break;
1769  }
1770  case UserDefinedLiteral::LOK_String:
1771  case UserDefinedLiteral::LOK_Character:
1772    PrintExpr(Node->getCookedLiteral());
1773    break;
1774  }
1775  OS << Node->getUDSuffix()->getName();
1776}
1777
1778void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1779  OS << (Node->getValue() ? "true" : "false");
1780}
1781
1782void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1783  OS << "nullptr";
1784}
1785
1786void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1787  OS << "this";
1788}
1789
1790void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1791  if (!Node->getSubExpr())
1792    OS << "throw";
1793  else {
1794    OS << "throw ";
1795    PrintExpr(Node->getSubExpr());
1796  }
1797}
1798
1799void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1800  // Nothing to print: we picked up the default argument.
1801}
1802
1803void StmtPrinter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *Node) {
1804  // Nothing to print: we picked up the default initializer.
1805}
1806
1807void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1808  Node->getType().print(OS, Policy);
1809  // If there are no parens, this is list-initialization, and the braces are
1810  // part of the syntax of the inner construct.
1811  if (Node->getLParenLoc().isValid())
1812    OS << "(";
1813  PrintExpr(Node->getSubExpr());
1814  if (Node->getLParenLoc().isValid())
1815    OS << ")";
1816}
1817
1818void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1819  PrintExpr(Node->getSubExpr());
1820}
1821
1822void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1823  Node->getType().print(OS, Policy);
1824  if (Node->isStdInitListInitialization())
1825    /* Nothing to do; braces are part of creating the std::initializer_list. */;
1826  else if (Node->isListInitialization())
1827    OS << "{";
1828  else
1829    OS << "(";
1830  for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1831                                         ArgEnd = Node->arg_end();
1832       Arg != ArgEnd; ++Arg) {
1833    if ((*Arg)->isDefaultArgument())
1834      break;
1835    if (Arg != Node->arg_begin())
1836      OS << ", ";
1837    PrintExpr(*Arg);
1838  }
1839  if (Node->isStdInitListInitialization())
1840    /* See above. */;
1841  else if (Node->isListInitialization())
1842    OS << "}";
1843  else
1844    OS << ")";
1845}
1846
1847void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
1848  OS << '[';
1849  bool NeedComma = false;
1850  switch (Node->getCaptureDefault()) {
1851  case LCD_None:
1852    break;
1853
1854  case LCD_ByCopy:
1855    OS << '=';
1856    NeedComma = true;
1857    break;
1858
1859  case LCD_ByRef:
1860    OS << '&';
1861    NeedComma = true;
1862    break;
1863  }
1864  for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(),
1865                                 CEnd = Node->explicit_capture_end();
1866       C != CEnd;
1867       ++C) {
1868    if (C->capturesVLAType())
1869      continue;
1870
1871    if (NeedComma)
1872      OS << ", ";
1873    NeedComma = true;
1874
1875    switch (C->getCaptureKind()) {
1876    case LCK_This:
1877      OS << "this";
1878      break;
1879
1880    case LCK_StarThis:
1881      OS << "*this";
1882      break;
1883
1884    case LCK_ByRef:
1885      if (Node->getCaptureDefault() != LCD_ByRef || Node->isInitCapture(C))
1886        OS << '&';
1887      OS << C->getCapturedVar()->getName();
1888      break;
1889
1890    case LCK_ByCopy:
1891      OS << C->getCapturedVar()->getName();
1892      break;
1893
1894    case LCK_VLAType:
1895      llvm_unreachable("VLA type in explicit captures.");
1896    }
1897
1898    if (Node->isInitCapture(C))
1899      PrintExpr(C->getCapturedVar()->getInit());
1900  }
1901  OS << ']';
1902
1903  if (Node->hasExplicitParameters()) {
1904    OS << " (";
1905    CXXMethodDecl *Method = Node->getCallOperator();
1906    NeedComma = false;
1907    for (const auto *P : Method->parameters()) {
1908      if (NeedComma) {
1909        OS << ", ";
1910      } else {
1911        NeedComma = true;
1912      }
1913      std::string ParamStr = P->getNameAsString();
1914      P->getOriginalType().print(OS, Policy, ParamStr);
1915    }
1916    if (Method->isVariadic()) {
1917      if (NeedComma)
1918        OS << ", ";
1919      OS << "...";
1920    }
1921    OS << ')';
1922
1923    if (Node->isMutable())
1924      OS << " mutable";
1925
1926    auto *Proto = Method->getType()->getAs<FunctionProtoType>();
1927    Proto->printExceptionSpecification(OS, Policy);
1928
1929    // FIXME: Attributes
1930
1931    // Print the trailing return type if it was specified in the source.
1932    if (Node->hasExplicitResultType()) {
1933      OS << " -> ";
1934      Proto->getReturnType().print(OS, Policy);
1935    }
1936  }
1937
1938  // Print the body.
1939  CompoundStmt *Body = Node->getBody();
1940  OS << ' ';
1941  PrintStmt(Body);
1942}
1943
1944void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1945  if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1946    TSInfo->getType().print(OS, Policy);
1947  else
1948    Node->getType().print(OS, Policy);
1949  OS << "()";
1950}
1951
1952void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1953  if (E->isGlobalNew())
1954    OS << "::";
1955  OS << "new ";
1956  unsigned NumPlace = E->getNumPlacementArgs();
1957  if (NumPlace > 0 && !isa<CXXDefaultArgExpr>(E->getPlacementArg(0))) {
1958    OS << "(";
1959    PrintExpr(E->getPlacementArg(0));
1960    for (unsigned i = 1i < NumPlace; ++i) {
1961      if (isa<CXXDefaultArgExpr>(E->getPlacementArg(i)))
1962        break;
1963      OS << ", ";
1964      PrintExpr(E->getPlacementArg(i));
1965    }
1966    OS << ") ";
1967  }
1968  if (E->isParenTypeId())
1969    OS << "(";
1970  std::string TypeS;
1971  if (Expr *Size = E->getArraySize()) {
1972    llvm::raw_string_ostream s(TypeS);
1973    s << '[';
1974    Size->printPretty(s, Helper, Policy);
1975    s << ']';
1976  }
1977  E->getAllocatedType().print(OS, Policy, TypeS);
1978  if (E->isParenTypeId())
1979    OS << ")";
1980
1981  CXXNewExpr::InitializationStyle InitStyle = E->getInitializationStyle();
1982  if (InitStyle) {
1983    if (InitStyle == CXXNewExpr::CallInit)
1984      OS << "(";
1985    PrintExpr(E->getInitializer());
1986    if (InitStyle == CXXNewExpr::CallInit)
1987      OS << ")";
1988  }
1989}
1990
1991void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1992  if (E->isGlobalDelete())
1993    OS << "::";
1994  OS << "delete ";
1995  if (E->isArrayForm())
1996    OS << "[] ";
1997  PrintExpr(E->getArgument());
1998}
1999
2000void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
2001  PrintExpr(E->getBase());
2002  if (E->isArrow())
2003    OS << "->";
2004  else
2005    OS << '.';
2006  if (E->getQualifier())
2007    E->getQualifier()->print(OS, Policy);
2008  OS << "~";
2009
2010  if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
2011    OS << II->getName();
2012  else
2013    E->getDestroyedType().print(OS, Policy);
2014}
2015
2016void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
2017  if (E->isListInitialization() && !E->isStdInitListInitialization())
2018    OS << "{";
2019
2020  for (unsigned i = 0e = E->getNumArgs(); i != e; ++i) {
2021    if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
2022      // Don't print any defaulted arguments
2023      break;
2024    }
2025
2026    if (iOS << ", ";
2027    PrintExpr(E->getArg(i));
2028  }
2029
2030  if (E->isListInitialization() && !E->isStdInitListInitialization())
2031    OS << "}";
2032}
2033
2034void StmtPrinter::VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E) {
2035  // Parens are printed by the surrounding context.
2036  OS << "<forwarded>";
2037}
2038
2039void StmtPrinter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
2040  PrintExpr(E->getSubExpr());
2041}
2042
2043void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
2044  // Just forward to the subexpression.
2045  PrintExpr(E->getSubExpr());
2046}
2047
2048void
2049StmtPrinter::VisitCXXUnresolvedConstructExpr(
2050                                           CXXUnresolvedConstructExpr *Node) {
2051  Node->getTypeAsWritten().print(OS, Policy);
2052  OS << "(";
2053  for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
2054                                             ArgEnd = Node->arg_end();
2055       Arg != ArgEnd; ++Arg) {
2056    if (Arg != Node->arg_begin())
2057      OS << ", ";
2058    PrintExpr(*Arg);
2059  }
2060  OS << ")";
2061}
2062
2063void StmtPrinter::VisitCXXDependentScopeMemberExpr(
2064                                         CXXDependentScopeMemberExpr *Node) {
2065  if (!Node->isImplicitAccess()) {
2066    PrintExpr(Node->getBase());
2067    OS << (Node->isArrow() ? "->" : ".");
2068  }
2069  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
2070    Qualifier->print(OS, Policy);
2071  if (Node->hasTemplateKeyword())
2072    OS << "template ";
2073  OS << Node->getMemberNameInfo();
2074  if (Node->hasExplicitTemplateArgs())
2075    printTemplateArgumentList(OS, Node->template_arguments(), Policy);
2076}
2077
2078void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
2079  if (!Node->isImplicitAccess()) {
2080    PrintExpr(Node->getBase());
2081    OS << (Node->isArrow() ? "->" : ".");
2082  }
2083  if (NestedNameSpecifier *Qualifier = Node->getQualifier())
2084    Qualifier->print(OS, Policy);
2085  if (Node->hasTemplateKeyword())
2086    OS << "template ";
2087  OS << Node->getMemberNameInfo();
2088  if (Node->hasExplicitTemplateArgs())
2089    printTemplateArgumentList(OS, Node->template_arguments(), Policy);
2090}
2091
2092static const char *getTypeTraitName(TypeTrait TT) {
2093  switch (TT) {
2094#define TYPE_TRAIT_1(Spelling, Name, Key) \
2095case clang::UTT_##Name: return #Spelling;
2096#define TYPE_TRAIT_2(Spelling, Name, Key) \
2097case clang::BTT_##Name: return #Spelling;
2098#define TYPE_TRAIT_N(Spelling, Name, Key) \
2099  case clang::TT_##Name: return #Spelling;
2100#include "clang/Basic/TokenKinds.def"
2101  }
2102  llvm_unreachable("Type trait not covered by switch");
2103}
2104
2105static const char *getTypeTraitName(ArrayTypeTrait ATT) {
2106  switch (ATT) {
2107  case ATT_ArrayRank:        return "__array_rank";
2108  case ATT_ArrayExtent:      return "__array_extent";
2109  }
2110  llvm_unreachable("Array type trait not covered by switch");
2111}
2112
2113static const char *getExpressionTraitName(ExpressionTrait ET) {
2114  switch (ET) {
2115  case ET_IsLValueExpr:      return "__is_lvalue_expr";
2116  case ET_IsRValueExpr:      return "__is_rvalue_expr";
2117  }
2118  llvm_unreachable("Expression type trait not covered by switch");
2119}
2120
2121void StmtPrinter::VisitTypeTraitExpr(TypeTraitExpr *E) {
2122  OS << getTypeTraitName(E->getTrait()) << "(";
2123  for (unsigned I = 0N = E->getNumArgs(); I != N; ++I) {
2124    if (I > 0)
2125      OS << ", ";
2126    E->getArg(I)->getType().print(OS, Policy);
2127  }
2128  OS << ")";
2129}
2130
2131void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2132  OS << getTypeTraitName(E->getTrait()) << '(';
2133  E->getQueriedType().print(OS, Policy);
2134  OS << ')';
2135}
2136
2137void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2138  OS << getExpressionTraitName(E->getTrait()) << '(';
2139  PrintExpr(E->getQueriedExpression());
2140  OS << ')';
2141}
2142
2143void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
2144  OS << "noexcept(";
2145  PrintExpr(E->getOperand());
2146  OS << ")";
2147}
2148
2149void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
2150  PrintExpr(E->getPattern());
2151  OS << "...";
2152}
2153
2154void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2155  OS << "sizeof...(" << *E->getPack() << ")";
2156}
2157
2158void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
2159                                       SubstNonTypeTemplateParmPackExpr *Node) {
2160  OS << *Node->getParameterPack();
2161}
2162
2163void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
2164                                       SubstNonTypeTemplateParmExpr *Node) {
2165  Visit(Node->getReplacement());
2166}
2167
2168void StmtPrinter::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) {
2169  OS << *E->getParameterPack();
2170}
2171
2172void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
2173  PrintExpr(Node->GetTemporaryExpr());
2174}
2175
2176void StmtPrinter::VisitCXXFoldExpr(CXXFoldExpr *E) {
2177  OS << "(";
2178  if (E->getLHS()) {
2179    PrintExpr(E->getLHS());
2180    OS << " " << BinaryOperator::getOpcodeStr(E->getOperator()) << " ";
2181  }
2182  OS << "...";
2183  if (E->getRHS()) {
2184    OS << " " << BinaryOperator::getOpcodeStr(E->getOperator()) << " ";
2185    PrintExpr(E->getRHS());
2186  }
2187  OS << ")";
2188}
2189
2190// C++ Coroutines TS
2191
2192void StmtPrinter::VisitCoroutineBodyStmt(CoroutineBodyStmt *S) {
2193  Visit(S->getBody());
2194}
2195
2196void StmtPrinter::VisitCoreturnStmt(CoreturnStmt *S) {
2197  OS << "co_return";
2198  if (S->getOperand()) {
2199    OS << " ";
2200    Visit(S->getOperand());
2201  }
2202  OS << ";";
2203}
2204
2205void StmtPrinter::VisitCoawaitExpr(CoawaitExpr *S) {
2206  OS << "co_await ";
2207  PrintExpr(S->getOperand());
2208}
2209
2210void StmtPrinter::VisitDependentCoawaitExpr(DependentCoawaitExpr *S) {
2211  OS << "co_await ";
2212  PrintExpr(S->getOperand());
2213}
2214
2215void StmtPrinter::VisitCoyieldExpr(CoyieldExpr *S) {
2216  OS << "co_yield ";
2217  PrintExpr(S->getOperand());
2218}
2219
2220// Obj-C
2221
2222void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
2223  OS << "@";
2224  VisitStringLiteral(Node->getString());
2225}
2226
2227void StmtPrinter::VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
2228  OS << "@";
2229  Visit(E->getSubExpr());
2230}
2231
2232void StmtPrinter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
2233  OS << "@[ ";
2234  ObjCArrayLiteral::child_range Ch = E->children();
2235  for (auto I = Ch.begin(), E = Ch.end(); I != E; ++I) {
2236    if (I != Ch.begin())
2237      OS << ", ";
2238    Visit(*I);
2239  }
2240  OS << " ]";
2241}
2242
2243void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
2244  OS << "@{ ";
2245  for (unsigned I = 0N = E->getNumElements(); I != N; ++I) {
2246    if (I > 0)
2247      OS << ", ";
2248
2249    ObjCDictionaryElement Element = E->getKeyValueElement(I);
2250    Visit(Element.Key);
2251    OS << " : ";
2252    Visit(Element.Value);
2253    if (Element.isPackExpansion())
2254      OS << "...";
2255  }
2256  OS << " }";
2257}
2258
2259void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
2260  OS << "@encode(";
2261  Node->getEncodedType().print(OS, Policy);
2262  OS << ')';
2263}
2264
2265void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
2266  OS << "@selector(";
2267  Node->getSelector().print(OS);
2268  OS << ')';
2269}
2270
2271void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
2272  OS << "@protocol(" << *Node->getProtocol() << ')';
2273}
2274
2275void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
2276  OS << "[";
2277  switch (Mess->getReceiverKind()) {
2278  case ObjCMessageExpr::Instance:
2279    PrintExpr(Mess->getInstanceReceiver());
2280    break;
2281
2282  case ObjCMessageExpr::Class:
2283    Mess->getClassReceiver().print(OS, Policy);
2284    break;
2285
2286  case ObjCMessageExpr::SuperInstance:
2287  case ObjCMessageExpr::SuperClass:
2288    OS << "Super";
2289    break;
2290  }
2291
2292  OS << ' ';
2293  Selector selector = Mess->getSelector();
2294  if (selector.isUnarySelector()) {
2295    OS << selector.getNameForSlot(0);
2296  } else {
2297    for (unsigned i = 0e = Mess->getNumArgs(); i != e; ++i) {
2298      if (i < selector.getNumArgs()) {
2299        if (i > 0OS << ' ';
2300        if (selector.getIdentifierInfoForSlot(i))
2301          OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
2302        else
2303           OS << ":";
2304      }
2305      else OS << ", "// Handle variadic methods.
2306
2307      PrintExpr(Mess->getArg(i));
2308    }
2309  }
2310  OS << "]";
2311}
2312
2313void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
2314  OS << (Node->getValue() ? "__objc_yes" : "__objc_no");
2315}
2316
2317void
2318StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
2319  PrintExpr(E->getSubExpr());
2320}
2321
2322void
2323StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
2324  OS << '(' << E->getBridgeKindName();
2325  E->getType().print(OS, Policy);
2326  OS << ')';
2327  PrintExpr(E->getSubExpr());
2328}
2329
2330void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
2331  BlockDecl *BD = Node->getBlockDecl();
2332  OS << "^";
2333
2334  const FunctionType *AFT = Node->getFunctionType();
2335
2336  if (isa<FunctionNoProtoType>(AFT)) {
2337    OS << "()";
2338  } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
2339    OS << '(';
2340    for (BlockDecl::param_iterator AI = BD->param_begin(),
2341         E = BD->param_end(); AI != E; ++AI) {
2342      if (AI != BD->param_begin()) OS << ", ";
2343      std::string ParamStr = (*AI)->getNameAsString();
2344      (*AI)->getType().print(OS, Policy, ParamStr);
2345    }
2346
2347    const auto *FT = cast<FunctionProtoType>(AFT);
2348    if (FT->isVariadic()) {
2349      if (!BD->param_empty()) OS << ", ";
2350      OS << "...";
2351    }
2352    OS << ')';
2353  }
2354  OS << "{ }";
2355}
2356
2357void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
2358  PrintExpr(Node->getSourceExpr());
2359}
2360
2361void StmtPrinter::VisitTypoExpr(TypoExpr *Node) {
2362  // TODO: Print something reasonable for a TypoExpr, if necessary.
2363  llvm_unreachable("Cannot print TypoExpr nodes");
2364}
2365
2366void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
2367  OS << "__builtin_astype(";
2368  PrintExpr(Node->getSrcExpr());
2369  OS << ", ";
2370  Node->getType().print(OS, Policy);
2371  OS << ")";
2372}
2373
2374//===----------------------------------------------------------------------===//
2375// Stmt method implementations
2376//===----------------------------------------------------------------------===//
2377
2378void Stmt::dumpPretty(const ASTContext &Contextconst {
2379  printPretty(llvm::errs(), nullptr, PrintingPolicy(Context.getLangOpts()));
2380}
2381
2382void Stmt::printPretty(raw_ostream &OSPrinterHelper *Helper,
2383                       const PrintingPolicy &Policyunsigned Indentation,
2384                       StringRef NL,
2385                       const ASTContext *Contextconst {
2386  StmtPrinter P(OS, Helper, Policy, Indentation, NL, Context);
2387  P.Visit(const_cast<Stmt*>(this));
2388}
2389
2390//===----------------------------------------------------------------------===//
2391// PrinterHelper
2392//===----------------------------------------------------------------------===//
2393
2394// Implement virtual destructor.
2395PrinterHelper::~PrinterHelper() = default;
2396
clang::Stmt::dumpPretty
clang::Stmt::printPretty