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