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