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