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::VisitOMPNogroupClause(OMPNogroupClause *) {
681   OS << "nogroup";
682 }
683 
684 void OMPClausePrinter::VisitOMPMergeableClause(OMPMergeableClause *) {
685   OS << "mergeable";
686 }
687 
688 void OMPClausePrinter::VisitOMPReadClause(OMPReadClause *) { OS << "read"; }
689 
690 void OMPClausePrinter::VisitOMPWriteClause(OMPWriteClause *) { OS << "write"; }
691 
692 void OMPClausePrinter::VisitOMPUpdateClause(OMPUpdateClause *) {
693   OS << "update";
694 }
695 
696 void OMPClausePrinter::VisitOMPCaptureClause(OMPCaptureClause *) {
697   OS << "capture";
698 }
699 
700 void OMPClausePrinter::VisitOMPSeqCstClause(OMPSeqCstClause *) {
701   OS << "seq_cst";
702 }
703 
704 void OMPClausePrinter::VisitOMPThreadsClause(OMPThreadsClause *) {
705   OS << "threads";
706 }
707 
708 void OMPClausePrinter::VisitOMPSIMDClause(OMPSIMDClause *) { OS << "simd"; }
709 
710 void OMPClausePrinter::VisitOMPDeviceClause(OMPDeviceClause *Node) {
711   OS << "device(";
712   Node->getDevice()->printPretty(OS, nullptr, Policy, 0);
713   OS << ")";
714 }
715 
716 void OMPClausePrinter::VisitOMPNumTeamsClause(OMPNumTeamsClause *Node) {
717   OS << "num_teams(";
718   Node->getNumTeams()->printPretty(OS, nullptr, Policy, 0);
719   OS << ")";
720 }
721 
722 void OMPClausePrinter::VisitOMPThreadLimitClause(OMPThreadLimitClause *Node) {
723   OS << "thread_limit(";
724   Node->getThreadLimit()->printPretty(OS, nullptr, Policy, 0);
725   OS << ")";
726 }
727 
728 void OMPClausePrinter::VisitOMPPriorityClause(OMPPriorityClause *Node) {
729   OS << "priority(";
730   Node->getPriority()->printPretty(OS, nullptr, Policy, 0);
731   OS << ")";
732 }
733 
734 void OMPClausePrinter::VisitOMPGrainsizeClause(OMPGrainsizeClause *Node) {
735   OS << "grainsize(";
736   Node->getGrainsize()->printPretty(OS, nullptr, Policy, 0);
737   OS << ")";
738 }
739 
740 template<typename T>
741 void OMPClausePrinter::VisitOMPClauseList(T *Node, char StartSym) {
742   for (typename T::varlist_iterator I = Node->varlist_begin(),
743                                     E = Node->varlist_end();
744          I != E; ++I) {
745     assert(*I && "Expected non-null Stmt");
746     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*I)) {
747       OS << (I == Node->varlist_begin() ? StartSym : ',');
748       cast<NamedDecl>(DRE->getDecl())->printQualifiedName(OS);
749     } else {
750       OS << (I == Node->varlist_begin() ? StartSym : ',');
751       (*I)->printPretty(OS, nullptr, Policy, 0);
752     }
753   }
754 }
755 
756 void OMPClausePrinter::VisitOMPPrivateClause(OMPPrivateClause *Node) {
757   if (!Node->varlist_empty()) {
758     OS << "private";
759     VisitOMPClauseList(Node, '(');
760     OS << ")";
761   }
762 }
763 
764 void OMPClausePrinter::VisitOMPFirstprivateClause(OMPFirstprivateClause *Node) {
765   if (!Node->varlist_empty()) {
766     OS << "firstprivate";
767     VisitOMPClauseList(Node, '(');
768     OS << ")";
769   }
770 }
771 
772 void OMPClausePrinter::VisitOMPLastprivateClause(OMPLastprivateClause *Node) {
773   if (!Node->varlist_empty()) {
774     OS << "lastprivate";
775     VisitOMPClauseList(Node, '(');
776     OS << ")";
777   }
778 }
779 
780 void OMPClausePrinter::VisitOMPSharedClause(OMPSharedClause *Node) {
781   if (!Node->varlist_empty()) {
782     OS << "shared";
783     VisitOMPClauseList(Node, '(');
784     OS << ")";
785   }
786 }
787 
788 void OMPClausePrinter::VisitOMPReductionClause(OMPReductionClause *Node) {
789   if (!Node->varlist_empty()) {
790     OS << "reduction(";
791     NestedNameSpecifier *QualifierLoc =
792         Node->getQualifierLoc().getNestedNameSpecifier();
793     OverloadedOperatorKind OOK =
794         Node->getNameInfo().getName().getCXXOverloadedOperator();
795     if (QualifierLoc == nullptr && OOK != OO_None) {
796       // Print reduction identifier in C format
797       OS << getOperatorSpelling(OOK);
798     } else {
799       // Use C++ format
800       if (QualifierLoc != nullptr)
801         QualifierLoc->print(OS, Policy);
802       OS << Node->getNameInfo();
803     }
804     OS << ":";
805     VisitOMPClauseList(Node, ' ');
806     OS << ")";
807   }
808 }
809 
810 void OMPClausePrinter::VisitOMPLinearClause(OMPLinearClause *Node) {
811   if (!Node->varlist_empty()) {
812     OS << "linear";
813     if (Node->getModifierLoc().isValid()) {
814       OS << '('
815          << getOpenMPSimpleClauseTypeName(OMPC_linear, Node->getModifier());
816     }
817     VisitOMPClauseList(Node, '(');
818     if (Node->getModifierLoc().isValid())
819       OS << ')';
820     if (Node->getStep() != nullptr) {
821       OS << ": ";
822       Node->getStep()->printPretty(OS, nullptr, Policy, 0);
823     }
824     OS << ")";
825   }
826 }
827 
828 void OMPClausePrinter::VisitOMPAlignedClause(OMPAlignedClause *Node) {
829   if (!Node->varlist_empty()) {
830     OS << "aligned";
831     VisitOMPClauseList(Node, '(');
832     if (Node->getAlignment() != nullptr) {
833       OS << ": ";
834       Node->getAlignment()->printPretty(OS, nullptr, Policy, 0);
835     }
836     OS << ")";
837   }
838 }
839 
840 void OMPClausePrinter::VisitOMPCopyinClause(OMPCopyinClause *Node) {
841   if (!Node->varlist_empty()) {
842     OS << "copyin";
843     VisitOMPClauseList(Node, '(');
844     OS << ")";
845   }
846 }
847 
848 void OMPClausePrinter::VisitOMPCopyprivateClause(OMPCopyprivateClause *Node) {
849   if (!Node->varlist_empty()) {
850     OS << "copyprivate";
851     VisitOMPClauseList(Node, '(');
852     OS << ")";
853   }
854 }
855 
856 void OMPClausePrinter::VisitOMPFlushClause(OMPFlushClause *Node) {
857   if (!Node->varlist_empty()) {
858     VisitOMPClauseList(Node, '(');
859     OS << ")";
860   }
861 }
862 
863 void OMPClausePrinter::VisitOMPDependClause(OMPDependClause *Node) {
864   if (!Node->varlist_empty()) {
865     OS << "depend(";
866     OS << getOpenMPSimpleClauseTypeName(Node->getClauseKind(),
867                                         Node->getDependencyKind())
868        << " :";
869     VisitOMPClauseList(Node, ' ');
870     OS << ")";
871   }
872 }
873 
874 void OMPClausePrinter::VisitOMPMapClause(OMPMapClause *Node) {
875   if (!Node->varlist_empty()) {
876     OS << "map(";
877     if (Node->getMapType() != OMPC_MAP_unknown) {
878       if (Node->getMapTypeModifier() != OMPC_MAP_unknown) {
879         OS << getOpenMPSimpleClauseTypeName(OMPC_map,
880                                             Node->getMapTypeModifier());
881         OS << ',';
882       }
883       OS << getOpenMPSimpleClauseTypeName(OMPC_map, Node->getMapType());
884       OS << ':';
885     }
886     VisitOMPClauseList(Node, ' ');
887     OS << ")";
888   }
889 }
890 }
891 
892 //===----------------------------------------------------------------------===//
893 //  OpenMP directives printing methods
894 //===----------------------------------------------------------------------===//
895 
896 void StmtPrinter::PrintOMPExecutableDirective(OMPExecutableDirective *S) {
897   OMPClausePrinter Printer(OS, Policy);
898   ArrayRef<OMPClause *> Clauses = S->clauses();
899   for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
900        I != E; ++I)
901     if (*I && !(*I)->isImplicit()) {
902       Printer.Visit(*I);
903       OS << ' ';
904     }
905   OS << "\n";
906   if (S->hasAssociatedStmt() && S->getAssociatedStmt()) {
907     assert(isa<CapturedStmt>(S->getAssociatedStmt()) &&
908            "Expected captured statement!");
909     Stmt *CS = cast<CapturedStmt>(S->getAssociatedStmt())->getCapturedStmt();
910     PrintStmt(CS);
911   }
912 }
913 
914 void StmtPrinter::VisitOMPParallelDirective(OMPParallelDirective *Node) {
915   Indent() << "#pragma omp parallel ";
916   PrintOMPExecutableDirective(Node);
917 }
918 
919 void StmtPrinter::VisitOMPSimdDirective(OMPSimdDirective *Node) {
920   Indent() << "#pragma omp simd ";
921   PrintOMPExecutableDirective(Node);
922 }
923 
924 void StmtPrinter::VisitOMPForDirective(OMPForDirective *Node) {
925   Indent() << "#pragma omp for ";
926   PrintOMPExecutableDirective(Node);
927 }
928 
929 void StmtPrinter::VisitOMPForSimdDirective(OMPForSimdDirective *Node) {
930   Indent() << "#pragma omp for simd ";
931   PrintOMPExecutableDirective(Node);
932 }
933 
934 void StmtPrinter::VisitOMPSectionsDirective(OMPSectionsDirective *Node) {
935   Indent() << "#pragma omp sections ";
936   PrintOMPExecutableDirective(Node);
937 }
938 
939 void StmtPrinter::VisitOMPSectionDirective(OMPSectionDirective *Node) {
940   Indent() << "#pragma omp section";
941   PrintOMPExecutableDirective(Node);
942 }
943 
944 void StmtPrinter::VisitOMPSingleDirective(OMPSingleDirective *Node) {
945   Indent() << "#pragma omp single ";
946   PrintOMPExecutableDirective(Node);
947 }
948 
949 void StmtPrinter::VisitOMPMasterDirective(OMPMasterDirective *Node) {
950   Indent() << "#pragma omp master";
951   PrintOMPExecutableDirective(Node);
952 }
953 
954 void StmtPrinter::VisitOMPCriticalDirective(OMPCriticalDirective *Node) {
955   Indent() << "#pragma omp critical";
956   if (Node->getDirectiveName().getName()) {
957     OS << " (";
958     Node->getDirectiveName().printName(OS);
959     OS << ")";
960   }
961   PrintOMPExecutableDirective(Node);
962 }
963 
964 void StmtPrinter::VisitOMPParallelForDirective(OMPParallelForDirective *Node) {
965   Indent() << "#pragma omp parallel for ";
966   PrintOMPExecutableDirective(Node);
967 }
968 
969 void StmtPrinter::VisitOMPParallelForSimdDirective(
970     OMPParallelForSimdDirective *Node) {
971   Indent() << "#pragma omp parallel for simd ";
972   PrintOMPExecutableDirective(Node);
973 }
974 
975 void StmtPrinter::VisitOMPParallelSectionsDirective(
976     OMPParallelSectionsDirective *Node) {
977   Indent() << "#pragma omp parallel sections ";
978   PrintOMPExecutableDirective(Node);
979 }
980 
981 void StmtPrinter::VisitOMPTaskDirective(OMPTaskDirective *Node) {
982   Indent() << "#pragma omp task ";
983   PrintOMPExecutableDirective(Node);
984 }
985 
986 void StmtPrinter::VisitOMPTaskyieldDirective(OMPTaskyieldDirective *Node) {
987   Indent() << "#pragma omp taskyield";
988   PrintOMPExecutableDirective(Node);
989 }
990 
991 void StmtPrinter::VisitOMPBarrierDirective(OMPBarrierDirective *Node) {
992   Indent() << "#pragma omp barrier";
993   PrintOMPExecutableDirective(Node);
994 }
995 
996 void StmtPrinter::VisitOMPTaskwaitDirective(OMPTaskwaitDirective *Node) {
997   Indent() << "#pragma omp taskwait";
998   PrintOMPExecutableDirective(Node);
999 }
1000 
1001 void StmtPrinter::VisitOMPTaskgroupDirective(OMPTaskgroupDirective *Node) {
1002   Indent() << "#pragma omp taskgroup";
1003   PrintOMPExecutableDirective(Node);
1004 }
1005 
1006 void StmtPrinter::VisitOMPFlushDirective(OMPFlushDirective *Node) {
1007   Indent() << "#pragma omp flush ";
1008   PrintOMPExecutableDirective(Node);
1009 }
1010 
1011 void StmtPrinter::VisitOMPOrderedDirective(OMPOrderedDirective *Node) {
1012   Indent() << "#pragma omp ordered ";
1013   PrintOMPExecutableDirective(Node);
1014 }
1015 
1016 void StmtPrinter::VisitOMPAtomicDirective(OMPAtomicDirective *Node) {
1017   Indent() << "#pragma omp atomic ";
1018   PrintOMPExecutableDirective(Node);
1019 }
1020 
1021 void StmtPrinter::VisitOMPTargetDirective(OMPTargetDirective *Node) {
1022   Indent() << "#pragma omp target ";
1023   PrintOMPExecutableDirective(Node);
1024 }
1025 
1026 void StmtPrinter::VisitOMPTargetDataDirective(OMPTargetDataDirective *Node) {
1027   Indent() << "#pragma omp target data ";
1028   PrintOMPExecutableDirective(Node);
1029 }
1030 
1031 void StmtPrinter::VisitOMPTeamsDirective(OMPTeamsDirective *Node) {
1032   Indent() << "#pragma omp teams ";
1033   PrintOMPExecutableDirective(Node);
1034 }
1035 
1036 void StmtPrinter::VisitOMPCancellationPointDirective(
1037     OMPCancellationPointDirective *Node) {
1038   Indent() << "#pragma omp cancellation point "
1039            << getOpenMPDirectiveName(Node->getCancelRegion());
1040   PrintOMPExecutableDirective(Node);
1041 }
1042 
1043 void StmtPrinter::VisitOMPCancelDirective(OMPCancelDirective *Node) {
1044   Indent() << "#pragma omp cancel "
1045            << getOpenMPDirectiveName(Node->getCancelRegion()) << " ";
1046   PrintOMPExecutableDirective(Node);
1047 }
1048 
1049 void StmtPrinter::VisitOMPTaskLoopDirective(OMPTaskLoopDirective *Node) {
1050   Indent() << "#pragma omp taskloop ";
1051   PrintOMPExecutableDirective(Node);
1052 }
1053 
1054 void StmtPrinter::VisitOMPTaskLoopSimdDirective(
1055     OMPTaskLoopSimdDirective *Node) {
1056   Indent() << "#pragma omp taskloop simd ";
1057   PrintOMPExecutableDirective(Node);
1058 }
1059 
1060 //===----------------------------------------------------------------------===//
1061 //  Expr printing methods.
1062 //===----------------------------------------------------------------------===//
1063 
1064 void StmtPrinter::VisitDeclRefExpr(DeclRefExpr *Node) {
1065   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1066     Qualifier->print(OS, Policy);
1067   if (Node->hasTemplateKeyword())
1068     OS << "template ";
1069   OS << Node->getNameInfo();
1070   if (Node->hasExplicitTemplateArgs())
1071     TemplateSpecializationType::PrintTemplateArgumentList(
1072         OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
1073 }
1074 
1075 void StmtPrinter::VisitDependentScopeDeclRefExpr(
1076                                            DependentScopeDeclRefExpr *Node) {
1077   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1078     Qualifier->print(OS, Policy);
1079   if (Node->hasTemplateKeyword())
1080     OS << "template ";
1081   OS << Node->getNameInfo();
1082   if (Node->hasExplicitTemplateArgs())
1083     TemplateSpecializationType::PrintTemplateArgumentList(
1084         OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
1085 }
1086 
1087 void StmtPrinter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *Node) {
1088   if (Node->getQualifier())
1089     Node->getQualifier()->print(OS, Policy);
1090   if (Node->hasTemplateKeyword())
1091     OS << "template ";
1092   OS << Node->getNameInfo();
1093   if (Node->hasExplicitTemplateArgs())
1094     TemplateSpecializationType::PrintTemplateArgumentList(
1095         OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
1096 }
1097 
1098 void StmtPrinter::VisitObjCIvarRefExpr(ObjCIvarRefExpr *Node) {
1099   if (Node->getBase()) {
1100     PrintExpr(Node->getBase());
1101     OS << (Node->isArrow() ? "->" : ".");
1102   }
1103   OS << *Node->getDecl();
1104 }
1105 
1106 void StmtPrinter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *Node) {
1107   if (Node->isSuperReceiver())
1108     OS << "super.";
1109   else if (Node->isObjectReceiver() && Node->getBase()) {
1110     PrintExpr(Node->getBase());
1111     OS << ".";
1112   } else if (Node->isClassReceiver() && Node->getClassReceiver()) {
1113     OS << Node->getClassReceiver()->getName() << ".";
1114   }
1115 
1116   if (Node->isImplicitProperty())
1117     Node->getImplicitPropertyGetter()->getSelector().print(OS);
1118   else
1119     OS << Node->getExplicitProperty()->getName();
1120 }
1121 
1122 void StmtPrinter::VisitObjCSubscriptRefExpr(ObjCSubscriptRefExpr *Node) {
1123 
1124   PrintExpr(Node->getBaseExpr());
1125   OS << "[";
1126   PrintExpr(Node->getKeyExpr());
1127   OS << "]";
1128 }
1129 
1130 void StmtPrinter::VisitPredefinedExpr(PredefinedExpr *Node) {
1131   OS << PredefinedExpr::getIdentTypeName(Node->getIdentType());
1132 }
1133 
1134 void StmtPrinter::VisitCharacterLiteral(CharacterLiteral *Node) {
1135   unsigned value = Node->getValue();
1136 
1137   switch (Node->getKind()) {
1138   case CharacterLiteral::Ascii: break; // no prefix.
1139   case CharacterLiteral::Wide:  OS << 'L'; break;
1140   case CharacterLiteral::UTF16: OS << 'u'; break;
1141   case CharacterLiteral::UTF32: OS << 'U'; break;
1142   }
1143 
1144   switch (value) {
1145   case '\\':
1146     OS << "'\\\\'";
1147     break;
1148   case '\'':
1149     OS << "'\\''";
1150     break;
1151   case '\a':
1152     // TODO: K&R: the meaning of '\\a' is different in traditional C
1153     OS << "'\\a'";
1154     break;
1155   case '\b':
1156     OS << "'\\b'";
1157     break;
1158   // Nonstandard escape sequence.
1159   /*case '\e':
1160     OS << "'\\e'";
1161     break;*/
1162   case '\f':
1163     OS << "'\\f'";
1164     break;
1165   case '\n':
1166     OS << "'\\n'";
1167     break;
1168   case '\r':
1169     OS << "'\\r'";
1170     break;
1171   case '\t':
1172     OS << "'\\t'";
1173     break;
1174   case '\v':
1175     OS << "'\\v'";
1176     break;
1177   default:
1178     if (value < 256 && isPrintable((unsigned char)value))
1179       OS << "'" << (char)value << "'";
1180     else if (value < 256)
1181       OS << "'\\x" << llvm::format("%02x", value) << "'";
1182     else if (value <= 0xFFFF)
1183       OS << "'\\u" << llvm::format("%04x", value) << "'";
1184     else
1185       OS << "'\\U" << llvm::format("%08x", value) << "'";
1186   }
1187 }
1188 
1189 void StmtPrinter::VisitIntegerLiteral(IntegerLiteral *Node) {
1190   bool isSigned = Node->getType()->isSignedIntegerType();
1191   OS << Node->getValue().toString(10, isSigned);
1192 
1193   // Emit suffixes.  Integer literals are always a builtin integer type.
1194   switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
1195   default: llvm_unreachable("Unexpected type for integer literal!");
1196   case BuiltinType::Char_S:
1197   case BuiltinType::Char_U:    OS << "i8"; break;
1198   case BuiltinType::UChar:     OS << "Ui8"; break;
1199   case BuiltinType::Short:     OS << "i16"; break;
1200   case BuiltinType::UShort:    OS << "Ui16"; break;
1201   case BuiltinType::Int:       break; // no suffix.
1202   case BuiltinType::UInt:      OS << 'U'; break;
1203   case BuiltinType::Long:      OS << 'L'; break;
1204   case BuiltinType::ULong:     OS << "UL"; break;
1205   case BuiltinType::LongLong:  OS << "LL"; break;
1206   case BuiltinType::ULongLong: OS << "ULL"; break;
1207   }
1208 }
1209 
1210 static void PrintFloatingLiteral(raw_ostream &OS, FloatingLiteral *Node,
1211                                  bool PrintSuffix) {
1212   SmallString<16> Str;
1213   Node->getValue().toString(Str);
1214   OS << Str;
1215   if (Str.find_first_not_of("-0123456789") == StringRef::npos)
1216     OS << '.'; // Trailing dot in order to separate from ints.
1217 
1218   if (!PrintSuffix)
1219     return;
1220 
1221   // Emit suffixes.  Float literals are always a builtin float type.
1222   switch (Node->getType()->getAs<BuiltinType>()->getKind()) {
1223   default: llvm_unreachable("Unexpected type for float literal!");
1224   case BuiltinType::Half:       break; // FIXME: suffix?
1225   case BuiltinType::Double:     break; // no suffix.
1226   case BuiltinType::Float:      OS << 'F'; break;
1227   case BuiltinType::LongDouble: OS << 'L'; break;
1228   }
1229 }
1230 
1231 void StmtPrinter::VisitFloatingLiteral(FloatingLiteral *Node) {
1232   PrintFloatingLiteral(OS, Node, /*PrintSuffix=*/true);
1233 }
1234 
1235 void StmtPrinter::VisitImaginaryLiteral(ImaginaryLiteral *Node) {
1236   PrintExpr(Node->getSubExpr());
1237   OS << "i";
1238 }
1239 
1240 void StmtPrinter::VisitStringLiteral(StringLiteral *Str) {
1241   Str->outputString(OS);
1242 }
1243 void StmtPrinter::VisitParenExpr(ParenExpr *Node) {
1244   OS << "(";
1245   PrintExpr(Node->getSubExpr());
1246   OS << ")";
1247 }
1248 void StmtPrinter::VisitUnaryOperator(UnaryOperator *Node) {
1249   if (!Node->isPostfix()) {
1250     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1251 
1252     // Print a space if this is an "identifier operator" like __real, or if
1253     // it might be concatenated incorrectly like '+'.
1254     switch (Node->getOpcode()) {
1255     default: break;
1256     case UO_Real:
1257     case UO_Imag:
1258     case UO_Extension:
1259       OS << ' ';
1260       break;
1261     case UO_Plus:
1262     case UO_Minus:
1263       if (isa<UnaryOperator>(Node->getSubExpr()))
1264         OS << ' ';
1265       break;
1266     }
1267   }
1268   PrintExpr(Node->getSubExpr());
1269 
1270   if (Node->isPostfix())
1271     OS << UnaryOperator::getOpcodeStr(Node->getOpcode());
1272 }
1273 
1274 void StmtPrinter::VisitOffsetOfExpr(OffsetOfExpr *Node) {
1275   OS << "__builtin_offsetof(";
1276   Node->getTypeSourceInfo()->getType().print(OS, Policy);
1277   OS << ", ";
1278   bool PrintedSomething = false;
1279   for (unsigned i = 0, n = Node->getNumComponents(); i < n; ++i) {
1280     OffsetOfExpr::OffsetOfNode ON = Node->getComponent(i);
1281     if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Array) {
1282       // Array node
1283       OS << "[";
1284       PrintExpr(Node->getIndexExpr(ON.getArrayExprIndex()));
1285       OS << "]";
1286       PrintedSomething = true;
1287       continue;
1288     }
1289 
1290     // Skip implicit base indirections.
1291     if (ON.getKind() == OffsetOfExpr::OffsetOfNode::Base)
1292       continue;
1293 
1294     // Field or identifier node.
1295     IdentifierInfo *Id = ON.getFieldName();
1296     if (!Id)
1297       continue;
1298 
1299     if (PrintedSomething)
1300       OS << ".";
1301     else
1302       PrintedSomething = true;
1303     OS << Id->getName();
1304   }
1305   OS << ")";
1306 }
1307 
1308 void StmtPrinter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *Node){
1309   switch(Node->getKind()) {
1310   case UETT_SizeOf:
1311     OS << "sizeof";
1312     break;
1313   case UETT_AlignOf:
1314     if (Policy.LangOpts.CPlusPlus)
1315       OS << "alignof";
1316     else if (Policy.LangOpts.C11)
1317       OS << "_Alignof";
1318     else
1319       OS << "__alignof";
1320     break;
1321   case UETT_VecStep:
1322     OS << "vec_step";
1323     break;
1324   case UETT_OpenMPRequiredSimdAlign:
1325     OS << "__builtin_omp_required_simd_align";
1326     break;
1327   }
1328   if (Node->isArgumentType()) {
1329     OS << '(';
1330     Node->getArgumentType().print(OS, Policy);
1331     OS << ')';
1332   } else {
1333     OS << " ";
1334     PrintExpr(Node->getArgumentExpr());
1335   }
1336 }
1337 
1338 void StmtPrinter::VisitGenericSelectionExpr(GenericSelectionExpr *Node) {
1339   OS << "_Generic(";
1340   PrintExpr(Node->getControllingExpr());
1341   for (unsigned i = 0; i != Node->getNumAssocs(); ++i) {
1342     OS << ", ";
1343     QualType T = Node->getAssocType(i);
1344     if (T.isNull())
1345       OS << "default";
1346     else
1347       T.print(OS, Policy);
1348     OS << ": ";
1349     PrintExpr(Node->getAssocExpr(i));
1350   }
1351   OS << ")";
1352 }
1353 
1354 void StmtPrinter::VisitArraySubscriptExpr(ArraySubscriptExpr *Node) {
1355   PrintExpr(Node->getLHS());
1356   OS << "[";
1357   PrintExpr(Node->getRHS());
1358   OS << "]";
1359 }
1360 
1361 void StmtPrinter::VisitOMPArraySectionExpr(OMPArraySectionExpr *Node) {
1362   PrintExpr(Node->getBase());
1363   OS << "[";
1364   if (Node->getLowerBound())
1365     PrintExpr(Node->getLowerBound());
1366   if (Node->getColonLoc().isValid()) {
1367     OS << ":";
1368     if (Node->getLength())
1369       PrintExpr(Node->getLength());
1370   }
1371   OS << "]";
1372 }
1373 
1374 void StmtPrinter::PrintCallArgs(CallExpr *Call) {
1375   for (unsigned i = 0, e = Call->getNumArgs(); i != e; ++i) {
1376     if (isa<CXXDefaultArgExpr>(Call->getArg(i))) {
1377       // Don't print any defaulted arguments
1378       break;
1379     }
1380 
1381     if (i) OS << ", ";
1382     PrintExpr(Call->getArg(i));
1383   }
1384 }
1385 
1386 void StmtPrinter::VisitCallExpr(CallExpr *Call) {
1387   PrintExpr(Call->getCallee());
1388   OS << "(";
1389   PrintCallArgs(Call);
1390   OS << ")";
1391 }
1392 void StmtPrinter::VisitMemberExpr(MemberExpr *Node) {
1393   // FIXME: Suppress printing implicit bases (like "this")
1394   PrintExpr(Node->getBase());
1395 
1396   MemberExpr *ParentMember = dyn_cast<MemberExpr>(Node->getBase());
1397   FieldDecl  *ParentDecl   = ParentMember
1398     ? dyn_cast<FieldDecl>(ParentMember->getMemberDecl()) : nullptr;
1399 
1400   if (!ParentDecl || !ParentDecl->isAnonymousStructOrUnion())
1401     OS << (Node->isArrow() ? "->" : ".");
1402 
1403   if (FieldDecl *FD = dyn_cast<FieldDecl>(Node->getMemberDecl()))
1404     if (FD->isAnonymousStructOrUnion())
1405       return;
1406 
1407   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
1408     Qualifier->print(OS, Policy);
1409   if (Node->hasTemplateKeyword())
1410     OS << "template ";
1411   OS << Node->getMemberNameInfo();
1412   if (Node->hasExplicitTemplateArgs())
1413     TemplateSpecializationType::PrintTemplateArgumentList(
1414         OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
1415 }
1416 void StmtPrinter::VisitObjCIsaExpr(ObjCIsaExpr *Node) {
1417   PrintExpr(Node->getBase());
1418   OS << (Node->isArrow() ? "->isa" : ".isa");
1419 }
1420 
1421 void StmtPrinter::VisitExtVectorElementExpr(ExtVectorElementExpr *Node) {
1422   PrintExpr(Node->getBase());
1423   OS << ".";
1424   OS << Node->getAccessor().getName();
1425 }
1426 void StmtPrinter::VisitCStyleCastExpr(CStyleCastExpr *Node) {
1427   OS << '(';
1428   Node->getTypeAsWritten().print(OS, Policy);
1429   OS << ')';
1430   PrintExpr(Node->getSubExpr());
1431 }
1432 void StmtPrinter::VisitCompoundLiteralExpr(CompoundLiteralExpr *Node) {
1433   OS << '(';
1434   Node->getType().print(OS, Policy);
1435   OS << ')';
1436   PrintExpr(Node->getInitializer());
1437 }
1438 void StmtPrinter::VisitImplicitCastExpr(ImplicitCastExpr *Node) {
1439   // No need to print anything, simply forward to the subexpression.
1440   PrintExpr(Node->getSubExpr());
1441 }
1442 void StmtPrinter::VisitBinaryOperator(BinaryOperator *Node) {
1443   PrintExpr(Node->getLHS());
1444   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1445   PrintExpr(Node->getRHS());
1446 }
1447 void StmtPrinter::VisitCompoundAssignOperator(CompoundAssignOperator *Node) {
1448   PrintExpr(Node->getLHS());
1449   OS << " " << BinaryOperator::getOpcodeStr(Node->getOpcode()) << " ";
1450   PrintExpr(Node->getRHS());
1451 }
1452 void StmtPrinter::VisitConditionalOperator(ConditionalOperator *Node) {
1453   PrintExpr(Node->getCond());
1454   OS << " ? ";
1455   PrintExpr(Node->getLHS());
1456   OS << " : ";
1457   PrintExpr(Node->getRHS());
1458 }
1459 
1460 // GNU extensions.
1461 
1462 void
1463 StmtPrinter::VisitBinaryConditionalOperator(BinaryConditionalOperator *Node) {
1464   PrintExpr(Node->getCommon());
1465   OS << " ?: ";
1466   PrintExpr(Node->getFalseExpr());
1467 }
1468 void StmtPrinter::VisitAddrLabelExpr(AddrLabelExpr *Node) {
1469   OS << "&&" << Node->getLabel()->getName();
1470 }
1471 
1472 void StmtPrinter::VisitStmtExpr(StmtExpr *E) {
1473   OS << "(";
1474   PrintRawCompoundStmt(E->getSubStmt());
1475   OS << ")";
1476 }
1477 
1478 void StmtPrinter::VisitChooseExpr(ChooseExpr *Node) {
1479   OS << "__builtin_choose_expr(";
1480   PrintExpr(Node->getCond());
1481   OS << ", ";
1482   PrintExpr(Node->getLHS());
1483   OS << ", ";
1484   PrintExpr(Node->getRHS());
1485   OS << ")";
1486 }
1487 
1488 void StmtPrinter::VisitGNUNullExpr(GNUNullExpr *) {
1489   OS << "__null";
1490 }
1491 
1492 void StmtPrinter::VisitShuffleVectorExpr(ShuffleVectorExpr *Node) {
1493   OS << "__builtin_shufflevector(";
1494   for (unsigned i = 0, e = Node->getNumSubExprs(); i != e; ++i) {
1495     if (i) OS << ", ";
1496     PrintExpr(Node->getExpr(i));
1497   }
1498   OS << ")";
1499 }
1500 
1501 void StmtPrinter::VisitConvertVectorExpr(ConvertVectorExpr *Node) {
1502   OS << "__builtin_convertvector(";
1503   PrintExpr(Node->getSrcExpr());
1504   OS << ", ";
1505   Node->getType().print(OS, Policy);
1506   OS << ")";
1507 }
1508 
1509 void StmtPrinter::VisitInitListExpr(InitListExpr* Node) {
1510   if (Node->getSyntacticForm()) {
1511     Visit(Node->getSyntacticForm());
1512     return;
1513   }
1514 
1515   OS << "{";
1516   for (unsigned i = 0, e = Node->getNumInits(); i != e; ++i) {
1517     if (i) OS << ", ";
1518     if (Node->getInit(i))
1519       PrintExpr(Node->getInit(i));
1520     else
1521       OS << "{}";
1522   }
1523   OS << "}";
1524 }
1525 
1526 void StmtPrinter::VisitParenListExpr(ParenListExpr* Node) {
1527   OS << "(";
1528   for (unsigned i = 0, e = Node->getNumExprs(); i != e; ++i) {
1529     if (i) OS << ", ";
1530     PrintExpr(Node->getExpr(i));
1531   }
1532   OS << ")";
1533 }
1534 
1535 void StmtPrinter::VisitDesignatedInitExpr(DesignatedInitExpr *Node) {
1536   bool NeedsEquals = true;
1537   for (DesignatedInitExpr::designators_iterator D = Node->designators_begin(),
1538                       DEnd = Node->designators_end();
1539        D != DEnd; ++D) {
1540     if (D->isFieldDesignator()) {
1541       if (D->getDotLoc().isInvalid()) {
1542         if (IdentifierInfo *II = D->getFieldName()) {
1543           OS << II->getName() << ":";
1544           NeedsEquals = false;
1545         }
1546       } else {
1547         OS << "." << D->getFieldName()->getName();
1548       }
1549     } else {
1550       OS << "[";
1551       if (D->isArrayDesignator()) {
1552         PrintExpr(Node->getArrayIndex(*D));
1553       } else {
1554         PrintExpr(Node->getArrayRangeStart(*D));
1555         OS << " ... ";
1556         PrintExpr(Node->getArrayRangeEnd(*D));
1557       }
1558       OS << "]";
1559     }
1560   }
1561 
1562   if (NeedsEquals)
1563     OS << " = ";
1564   else
1565     OS << " ";
1566   PrintExpr(Node->getInit());
1567 }
1568 
1569 void StmtPrinter::VisitDesignatedInitUpdateExpr(
1570     DesignatedInitUpdateExpr *Node) {
1571   OS << "{";
1572   OS << "/*base*/";
1573   PrintExpr(Node->getBase());
1574   OS << ", ";
1575 
1576   OS << "/*updater*/";
1577   PrintExpr(Node->getUpdater());
1578   OS << "}";
1579 }
1580 
1581 void StmtPrinter::VisitNoInitExpr(NoInitExpr *Node) {
1582   OS << "/*no init*/";
1583 }
1584 
1585 void StmtPrinter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *Node) {
1586   if (Policy.LangOpts.CPlusPlus) {
1587     OS << "/*implicit*/";
1588     Node->getType().print(OS, Policy);
1589     OS << "()";
1590   } else {
1591     OS << "/*implicit*/(";
1592     Node->getType().print(OS, Policy);
1593     OS << ')';
1594     if (Node->getType()->isRecordType())
1595       OS << "{}";
1596     else
1597       OS << 0;
1598   }
1599 }
1600 
1601 void StmtPrinter::VisitVAArgExpr(VAArgExpr *Node) {
1602   OS << "__builtin_va_arg(";
1603   PrintExpr(Node->getSubExpr());
1604   OS << ", ";
1605   Node->getType().print(OS, Policy);
1606   OS << ")";
1607 }
1608 
1609 void StmtPrinter::VisitPseudoObjectExpr(PseudoObjectExpr *Node) {
1610   PrintExpr(Node->getSyntacticForm());
1611 }
1612 
1613 void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
1614   const char *Name = nullptr;
1615   switch (Node->getOp()) {
1616 #define BUILTIN(ID, TYPE, ATTRS)
1617 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1618   case AtomicExpr::AO ## ID: \
1619     Name = #ID "("; \
1620     break;
1621 #include "clang/Basic/Builtins.def"
1622   }
1623   OS << Name;
1624 
1625   // AtomicExpr stores its subexpressions in a permuted order.
1626   PrintExpr(Node->getPtr());
1627   if (Node->getOp() != AtomicExpr::AO__c11_atomic_load &&
1628       Node->getOp() != AtomicExpr::AO__atomic_load_n) {
1629     OS << ", ";
1630     PrintExpr(Node->getVal1());
1631   }
1632   if (Node->getOp() == AtomicExpr::AO__atomic_exchange ||
1633       Node->isCmpXChg()) {
1634     OS << ", ";
1635     PrintExpr(Node->getVal2());
1636   }
1637   if (Node->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
1638       Node->getOp() == AtomicExpr::AO__atomic_compare_exchange_n) {
1639     OS << ", ";
1640     PrintExpr(Node->getWeak());
1641   }
1642   if (Node->getOp() != AtomicExpr::AO__c11_atomic_init) {
1643     OS << ", ";
1644     PrintExpr(Node->getOrder());
1645   }
1646   if (Node->isCmpXChg()) {
1647     OS << ", ";
1648     PrintExpr(Node->getOrderFail());
1649   }
1650   OS << ")";
1651 }
1652 
1653 // C++
1654 void StmtPrinter::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *Node) {
1655   const char *OpStrings[NUM_OVERLOADED_OPERATORS] = {
1656     "",
1657 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
1658     Spelling,
1659 #include "clang/Basic/OperatorKinds.def"
1660   };
1661 
1662   OverloadedOperatorKind Kind = Node->getOperator();
1663   if (Kind == OO_PlusPlus || Kind == OO_MinusMinus) {
1664     if (Node->getNumArgs() == 1) {
1665       OS << OpStrings[Kind] << ' ';
1666       PrintExpr(Node->getArg(0));
1667     } else {
1668       PrintExpr(Node->getArg(0));
1669       OS << ' ' << OpStrings[Kind];
1670     }
1671   } else if (Kind == OO_Arrow) {
1672     PrintExpr(Node->getArg(0));
1673   } else if (Kind == OO_Call) {
1674     PrintExpr(Node->getArg(0));
1675     OS << '(';
1676     for (unsigned ArgIdx = 1; ArgIdx < Node->getNumArgs(); ++ArgIdx) {
1677       if (ArgIdx > 1)
1678         OS << ", ";
1679       if (!isa<CXXDefaultArgExpr>(Node->getArg(ArgIdx)))
1680         PrintExpr(Node->getArg(ArgIdx));
1681     }
1682     OS << ')';
1683   } else if (Kind == OO_Subscript) {
1684     PrintExpr(Node->getArg(0));
1685     OS << '[';
1686     PrintExpr(Node->getArg(1));
1687     OS << ']';
1688   } else if (Node->getNumArgs() == 1) {
1689     OS << OpStrings[Kind] << ' ';
1690     PrintExpr(Node->getArg(0));
1691   } else if (Node->getNumArgs() == 2) {
1692     PrintExpr(Node->getArg(0));
1693     OS << ' ' << OpStrings[Kind] << ' ';
1694     PrintExpr(Node->getArg(1));
1695   } else {
1696     llvm_unreachable("unknown overloaded operator");
1697   }
1698 }
1699 
1700 void StmtPrinter::VisitCXXMemberCallExpr(CXXMemberCallExpr *Node) {
1701   // If we have a conversion operator call only print the argument.
1702   CXXMethodDecl *MD = Node->getMethodDecl();
1703   if (MD && isa<CXXConversionDecl>(MD)) {
1704     PrintExpr(Node->getImplicitObjectArgument());
1705     return;
1706   }
1707   VisitCallExpr(cast<CallExpr>(Node));
1708 }
1709 
1710 void StmtPrinter::VisitCUDAKernelCallExpr(CUDAKernelCallExpr *Node) {
1711   PrintExpr(Node->getCallee());
1712   OS << "<<<";
1713   PrintCallArgs(Node->getConfig());
1714   OS << ">>>(";
1715   PrintCallArgs(Node);
1716   OS << ")";
1717 }
1718 
1719 void StmtPrinter::VisitCXXNamedCastExpr(CXXNamedCastExpr *Node) {
1720   OS << Node->getCastName() << '<';
1721   Node->getTypeAsWritten().print(OS, Policy);
1722   OS << ">(";
1723   PrintExpr(Node->getSubExpr());
1724   OS << ")";
1725 }
1726 
1727 void StmtPrinter::VisitCXXStaticCastExpr(CXXStaticCastExpr *Node) {
1728   VisitCXXNamedCastExpr(Node);
1729 }
1730 
1731 void StmtPrinter::VisitCXXDynamicCastExpr(CXXDynamicCastExpr *Node) {
1732   VisitCXXNamedCastExpr(Node);
1733 }
1734 
1735 void StmtPrinter::VisitCXXReinterpretCastExpr(CXXReinterpretCastExpr *Node) {
1736   VisitCXXNamedCastExpr(Node);
1737 }
1738 
1739 void StmtPrinter::VisitCXXConstCastExpr(CXXConstCastExpr *Node) {
1740   VisitCXXNamedCastExpr(Node);
1741 }
1742 
1743 void StmtPrinter::VisitCXXTypeidExpr(CXXTypeidExpr *Node) {
1744   OS << "typeid(";
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::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
1754   OS << "__uuidof(";
1755   if (Node->isTypeOperand()) {
1756     Node->getTypeOperandSourceInfo()->getType().print(OS, Policy);
1757   } else {
1758     PrintExpr(Node->getExprOperand());
1759   }
1760   OS << ")";
1761 }
1762 
1763 void StmtPrinter::VisitMSPropertyRefExpr(MSPropertyRefExpr *Node) {
1764   PrintExpr(Node->getBaseExpr());
1765   if (Node->isArrow())
1766     OS << "->";
1767   else
1768     OS << ".";
1769   if (NestedNameSpecifier *Qualifier =
1770       Node->getQualifierLoc().getNestedNameSpecifier())
1771     Qualifier->print(OS, Policy);
1772   OS << Node->getPropertyDecl()->getDeclName();
1773 }
1774 
1775 void StmtPrinter::VisitMSPropertySubscriptExpr(MSPropertySubscriptExpr *Node) {
1776   PrintExpr(Node->getBase());
1777   OS << "[";
1778   PrintExpr(Node->getIdx());
1779   OS << "]";
1780 }
1781 
1782 void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
1783   switch (Node->getLiteralOperatorKind()) {
1784   case UserDefinedLiteral::LOK_Raw:
1785     OS << cast<StringLiteral>(Node->getArg(0)->IgnoreImpCasts())->getString();
1786     break;
1787   case UserDefinedLiteral::LOK_Template: {
1788     DeclRefExpr *DRE = cast<DeclRefExpr>(Node->getCallee()->IgnoreImpCasts());
1789     const TemplateArgumentList *Args =
1790       cast<FunctionDecl>(DRE->getDecl())->getTemplateSpecializationArgs();
1791     assert(Args);
1792 
1793     if (Args->size() != 1) {
1794       OS << "operator\"\"" << Node->getUDSuffix()->getName();
1795       TemplateSpecializationType::PrintTemplateArgumentList(
1796           OS, Args->data(), Args->size(), Policy);
1797       OS << "()";
1798       return;
1799     }
1800 
1801     const TemplateArgument &Pack = Args->get(0);
1802     for (const auto &P : Pack.pack_elements()) {
1803       char C = (char)P.getAsIntegral().getZExtValue();
1804       OS << C;
1805     }
1806     break;
1807   }
1808   case UserDefinedLiteral::LOK_Integer: {
1809     // Print integer literal without suffix.
1810     IntegerLiteral *Int = cast<IntegerLiteral>(Node->getCookedLiteral());
1811     OS << Int->getValue().toString(10, /*isSigned*/false);
1812     break;
1813   }
1814   case UserDefinedLiteral::LOK_Floating: {
1815     // Print floating literal without suffix.
1816     FloatingLiteral *Float = cast<FloatingLiteral>(Node->getCookedLiteral());
1817     PrintFloatingLiteral(OS, Float, /*PrintSuffix=*/false);
1818     break;
1819   }
1820   case UserDefinedLiteral::LOK_String:
1821   case UserDefinedLiteral::LOK_Character:
1822     PrintExpr(Node->getCookedLiteral());
1823     break;
1824   }
1825   OS << Node->getUDSuffix()->getName();
1826 }
1827 
1828 void StmtPrinter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *Node) {
1829   OS << (Node->getValue() ? "true" : "false");
1830 }
1831 
1832 void StmtPrinter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *Node) {
1833   OS << "nullptr";
1834 }
1835 
1836 void StmtPrinter::VisitCXXThisExpr(CXXThisExpr *Node) {
1837   OS << "this";
1838 }
1839 
1840 void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
1841   if (!Node->getSubExpr())
1842     OS << "throw";
1843   else {
1844     OS << "throw ";
1845     PrintExpr(Node->getSubExpr());
1846   }
1847 }
1848 
1849 void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
1850   // Nothing to print: we picked up the default argument.
1851 }
1852 
1853 void StmtPrinter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *Node) {
1854   // Nothing to print: we picked up the default initializer.
1855 }
1856 
1857 void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
1858   Node->getType().print(OS, Policy);
1859   // If there are no parens, this is list-initialization, and the braces are
1860   // part of the syntax of the inner construct.
1861   if (Node->getLParenLoc().isValid())
1862     OS << "(";
1863   PrintExpr(Node->getSubExpr());
1864   if (Node->getLParenLoc().isValid())
1865     OS << ")";
1866 }
1867 
1868 void StmtPrinter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *Node) {
1869   PrintExpr(Node->getSubExpr());
1870 }
1871 
1872 void StmtPrinter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *Node) {
1873   Node->getType().print(OS, Policy);
1874   if (Node->isStdInitListInitialization())
1875     /* Nothing to do; braces are part of creating the std::initializer_list. */;
1876   else if (Node->isListInitialization())
1877     OS << "{";
1878   else
1879     OS << "(";
1880   for (CXXTemporaryObjectExpr::arg_iterator Arg = Node->arg_begin(),
1881                                          ArgEnd = Node->arg_end();
1882        Arg != ArgEnd; ++Arg) {
1883     if ((*Arg)->isDefaultArgument())
1884       break;
1885     if (Arg != Node->arg_begin())
1886       OS << ", ";
1887     PrintExpr(*Arg);
1888   }
1889   if (Node->isStdInitListInitialization())
1890     /* See above. */;
1891   else if (Node->isListInitialization())
1892     OS << "}";
1893   else
1894     OS << ")";
1895 }
1896 
1897 void StmtPrinter::VisitLambdaExpr(LambdaExpr *Node) {
1898   OS << '[';
1899   bool NeedComma = false;
1900   switch (Node->getCaptureDefault()) {
1901   case LCD_None:
1902     break;
1903 
1904   case LCD_ByCopy:
1905     OS << '=';
1906     NeedComma = true;
1907     break;
1908 
1909   case LCD_ByRef:
1910     OS << '&';
1911     NeedComma = true;
1912     break;
1913   }
1914   for (LambdaExpr::capture_iterator C = Node->explicit_capture_begin(),
1915                                  CEnd = Node->explicit_capture_end();
1916        C != CEnd;
1917        ++C) {
1918     if (NeedComma)
1919       OS << ", ";
1920     NeedComma = true;
1921 
1922     switch (C->getCaptureKind()) {
1923     case LCK_This:
1924       OS << "this";
1925       break;
1926 
1927     case LCK_ByRef:
1928       if (Node->getCaptureDefault() != LCD_ByRef || Node->isInitCapture(C))
1929         OS << '&';
1930       OS << C->getCapturedVar()->getName();
1931       break;
1932 
1933     case LCK_ByCopy:
1934       OS << C->getCapturedVar()->getName();
1935       break;
1936     case LCK_VLAType:
1937       llvm_unreachable("VLA type in explicit captures.");
1938     }
1939 
1940     if (Node->isInitCapture(C))
1941       PrintExpr(C->getCapturedVar()->getInit());
1942   }
1943   OS << ']';
1944 
1945   if (Node->hasExplicitParameters()) {
1946     OS << " (";
1947     CXXMethodDecl *Method = Node->getCallOperator();
1948     NeedComma = false;
1949     for (auto P : Method->params()) {
1950       if (NeedComma) {
1951         OS << ", ";
1952       } else {
1953         NeedComma = true;
1954       }
1955       std::string ParamStr = P->getNameAsString();
1956       P->getOriginalType().print(OS, Policy, ParamStr);
1957     }
1958     if (Method->isVariadic()) {
1959       if (NeedComma)
1960         OS << ", ";
1961       OS << "...";
1962     }
1963     OS << ')';
1964 
1965     if (Node->isMutable())
1966       OS << " mutable";
1967 
1968     const FunctionProtoType *Proto
1969       = Method->getType()->getAs<FunctionProtoType>();
1970     Proto->printExceptionSpecification(OS, Policy);
1971 
1972     // FIXME: Attributes
1973 
1974     // Print the trailing return type if it was specified in the source.
1975     if (Node->hasExplicitResultType()) {
1976       OS << " -> ";
1977       Proto->getReturnType().print(OS, Policy);
1978     }
1979   }
1980 
1981   // Print the body.
1982   CompoundStmt *Body = Node->getBody();
1983   OS << ' ';
1984   PrintStmt(Body);
1985 }
1986 
1987 void StmtPrinter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *Node) {
1988   if (TypeSourceInfo *TSInfo = Node->getTypeSourceInfo())
1989     TSInfo->getType().print(OS, Policy);
1990   else
1991     Node->getType().print(OS, Policy);
1992   OS << "()";
1993 }
1994 
1995 void StmtPrinter::VisitCXXNewExpr(CXXNewExpr *E) {
1996   if (E->isGlobalNew())
1997     OS << "::";
1998   OS << "new ";
1999   unsigned NumPlace = E->getNumPlacementArgs();
2000   if (NumPlace > 0 && !isa<CXXDefaultArgExpr>(E->getPlacementArg(0))) {
2001     OS << "(";
2002     PrintExpr(E->getPlacementArg(0));
2003     for (unsigned i = 1; i < NumPlace; ++i) {
2004       if (isa<CXXDefaultArgExpr>(E->getPlacementArg(i)))
2005         break;
2006       OS << ", ";
2007       PrintExpr(E->getPlacementArg(i));
2008     }
2009     OS << ") ";
2010   }
2011   if (E->isParenTypeId())
2012     OS << "(";
2013   std::string TypeS;
2014   if (Expr *Size = E->getArraySize()) {
2015     llvm::raw_string_ostream s(TypeS);
2016     s << '[';
2017     Size->printPretty(s, Helper, Policy);
2018     s << ']';
2019   }
2020   E->getAllocatedType().print(OS, Policy, TypeS);
2021   if (E->isParenTypeId())
2022     OS << ")";
2023 
2024   CXXNewExpr::InitializationStyle InitStyle = E->getInitializationStyle();
2025   if (InitStyle) {
2026     if (InitStyle == CXXNewExpr::CallInit)
2027       OS << "(";
2028     PrintExpr(E->getInitializer());
2029     if (InitStyle == CXXNewExpr::CallInit)
2030       OS << ")";
2031   }
2032 }
2033 
2034 void StmtPrinter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2035   if (E->isGlobalDelete())
2036     OS << "::";
2037   OS << "delete ";
2038   if (E->isArrayForm())
2039     OS << "[] ";
2040   PrintExpr(E->getArgument());
2041 }
2042 
2043 void StmtPrinter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
2044   PrintExpr(E->getBase());
2045   if (E->isArrow())
2046     OS << "->";
2047   else
2048     OS << '.';
2049   if (E->getQualifier())
2050     E->getQualifier()->print(OS, Policy);
2051   OS << "~";
2052 
2053   if (IdentifierInfo *II = E->getDestroyedTypeIdentifier())
2054     OS << II->getName();
2055   else
2056     E->getDestroyedType().print(OS, Policy);
2057 }
2058 
2059 void StmtPrinter::VisitCXXConstructExpr(CXXConstructExpr *E) {
2060   if (E->isListInitialization() && !E->isStdInitListInitialization())
2061     OS << "{";
2062 
2063   for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
2064     if (isa<CXXDefaultArgExpr>(E->getArg(i))) {
2065       // Don't print any defaulted arguments
2066       break;
2067     }
2068 
2069     if (i) OS << ", ";
2070     PrintExpr(E->getArg(i));
2071   }
2072 
2073   if (E->isListInitialization() && !E->isStdInitListInitialization())
2074     OS << "}";
2075 }
2076 
2077 void StmtPrinter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
2078   PrintExpr(E->getSubExpr());
2079 }
2080 
2081 void StmtPrinter::VisitExprWithCleanups(ExprWithCleanups *E) {
2082   // Just forward to the subexpression.
2083   PrintExpr(E->getSubExpr());
2084 }
2085 
2086 void
2087 StmtPrinter::VisitCXXUnresolvedConstructExpr(
2088                                            CXXUnresolvedConstructExpr *Node) {
2089   Node->getTypeAsWritten().print(OS, Policy);
2090   OS << "(";
2091   for (CXXUnresolvedConstructExpr::arg_iterator Arg = Node->arg_begin(),
2092                                              ArgEnd = Node->arg_end();
2093        Arg != ArgEnd; ++Arg) {
2094     if (Arg != Node->arg_begin())
2095       OS << ", ";
2096     PrintExpr(*Arg);
2097   }
2098   OS << ")";
2099 }
2100 
2101 void StmtPrinter::VisitCXXDependentScopeMemberExpr(
2102                                          CXXDependentScopeMemberExpr *Node) {
2103   if (!Node->isImplicitAccess()) {
2104     PrintExpr(Node->getBase());
2105     OS << (Node->isArrow() ? "->" : ".");
2106   }
2107   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
2108     Qualifier->print(OS, Policy);
2109   if (Node->hasTemplateKeyword())
2110     OS << "template ";
2111   OS << Node->getMemberNameInfo();
2112   if (Node->hasExplicitTemplateArgs())
2113     TemplateSpecializationType::PrintTemplateArgumentList(
2114         OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
2115 }
2116 
2117 void StmtPrinter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *Node) {
2118   if (!Node->isImplicitAccess()) {
2119     PrintExpr(Node->getBase());
2120     OS << (Node->isArrow() ? "->" : ".");
2121   }
2122   if (NestedNameSpecifier *Qualifier = Node->getQualifier())
2123     Qualifier->print(OS, Policy);
2124   if (Node->hasTemplateKeyword())
2125     OS << "template ";
2126   OS << Node->getMemberNameInfo();
2127   if (Node->hasExplicitTemplateArgs())
2128     TemplateSpecializationType::PrintTemplateArgumentList(
2129         OS, Node->getTemplateArgs(), Node->getNumTemplateArgs(), Policy);
2130 }
2131 
2132 static const char *getTypeTraitName(TypeTrait TT) {
2133   switch (TT) {
2134 #define TYPE_TRAIT_1(Spelling, Name, Key) \
2135 case clang::UTT_##Name: return #Spelling;
2136 #define TYPE_TRAIT_2(Spelling, Name, Key) \
2137 case clang::BTT_##Name: return #Spelling;
2138 #define TYPE_TRAIT_N(Spelling, Name, Key) \
2139   case clang::TT_##Name: return #Spelling;
2140 #include "clang/Basic/TokenKinds.def"
2141   }
2142   llvm_unreachable("Type trait not covered by switch");
2143 }
2144 
2145 static const char *getTypeTraitName(ArrayTypeTrait ATT) {
2146   switch (ATT) {
2147   case ATT_ArrayRank:        return "__array_rank";
2148   case ATT_ArrayExtent:      return "__array_extent";
2149   }
2150   llvm_unreachable("Array type trait not covered by switch");
2151 }
2152 
2153 static const char *getExpressionTraitName(ExpressionTrait ET) {
2154   switch (ET) {
2155   case ET_IsLValueExpr:      return "__is_lvalue_expr";
2156   case ET_IsRValueExpr:      return "__is_rvalue_expr";
2157   }
2158   llvm_unreachable("Expression type trait not covered by switch");
2159 }
2160 
2161 void StmtPrinter::VisitTypeTraitExpr(TypeTraitExpr *E) {
2162   OS << getTypeTraitName(E->getTrait()) << "(";
2163   for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
2164     if (I > 0)
2165       OS << ", ";
2166     E->getArg(I)->getType().print(OS, Policy);
2167   }
2168   OS << ")";
2169 }
2170 
2171 void StmtPrinter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
2172   OS << getTypeTraitName(E->getTrait()) << '(';
2173   E->getQueriedType().print(OS, Policy);
2174   OS << ')';
2175 }
2176 
2177 void StmtPrinter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
2178   OS << getExpressionTraitName(E->getTrait()) << '(';
2179   PrintExpr(E->getQueriedExpression());
2180   OS << ')';
2181 }
2182 
2183 void StmtPrinter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
2184   OS << "noexcept(";
2185   PrintExpr(E->getOperand());
2186   OS << ")";
2187 }
2188 
2189 void StmtPrinter::VisitPackExpansionExpr(PackExpansionExpr *E) {
2190   PrintExpr(E->getPattern());
2191   OS << "...";
2192 }
2193 
2194 void StmtPrinter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
2195   OS << "sizeof...(" << *E->getPack() << ")";
2196 }
2197 
2198 void StmtPrinter::VisitSubstNonTypeTemplateParmPackExpr(
2199                                        SubstNonTypeTemplateParmPackExpr *Node) {
2200   OS << *Node->getParameterPack();
2201 }
2202 
2203 void StmtPrinter::VisitSubstNonTypeTemplateParmExpr(
2204                                        SubstNonTypeTemplateParmExpr *Node) {
2205   Visit(Node->getReplacement());
2206 }
2207 
2208 void StmtPrinter::VisitFunctionParmPackExpr(FunctionParmPackExpr *E) {
2209   OS << *E->getParameterPack();
2210 }
2211 
2212 void StmtPrinter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *Node){
2213   PrintExpr(Node->GetTemporaryExpr());
2214 }
2215 
2216 void StmtPrinter::VisitCXXFoldExpr(CXXFoldExpr *E) {
2217   OS << "(";
2218   if (E->getLHS()) {
2219     PrintExpr(E->getLHS());
2220     OS << " " << BinaryOperator::getOpcodeStr(E->getOperator()) << " ";
2221   }
2222   OS << "...";
2223   if (E->getRHS()) {
2224     OS << " " << BinaryOperator::getOpcodeStr(E->getOperator()) << " ";
2225     PrintExpr(E->getRHS());
2226   }
2227   OS << ")";
2228 }
2229 
2230 // C++ Coroutines TS
2231 
2232 void StmtPrinter::VisitCoroutineBodyStmt(CoroutineBodyStmt *S) {
2233   Visit(S->getBody());
2234 }
2235 
2236 void StmtPrinter::VisitCoreturnStmt(CoreturnStmt *S) {
2237   OS << "co_return";
2238   if (S->getOperand()) {
2239     OS << " ";
2240     Visit(S->getOperand());
2241   }
2242   OS << ";";
2243 }
2244 
2245 void StmtPrinter::VisitCoawaitExpr(CoawaitExpr *S) {
2246   OS << "co_await ";
2247   PrintExpr(S->getOperand());
2248 }
2249 
2250 void StmtPrinter::VisitCoyieldExpr(CoyieldExpr *S) {
2251   OS << "co_yield ";
2252   PrintExpr(S->getOperand());
2253 }
2254 
2255 // Obj-C
2256 
2257 void StmtPrinter::VisitObjCStringLiteral(ObjCStringLiteral *Node) {
2258   OS << "@";
2259   VisitStringLiteral(Node->getString());
2260 }
2261 
2262 void StmtPrinter::VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
2263   OS << "@";
2264   Visit(E->getSubExpr());
2265 }
2266 
2267 void StmtPrinter::VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
2268   OS << "@[ ";
2269   ObjCArrayLiteral::child_range Ch = E->children();
2270   for (auto I = Ch.begin(), E = Ch.end(); I != E; ++I) {
2271     if (I != Ch.begin())
2272       OS << ", ";
2273     Visit(*I);
2274   }
2275   OS << " ]";
2276 }
2277 
2278 void StmtPrinter::VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
2279   OS << "@{ ";
2280   for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
2281     if (I > 0)
2282       OS << ", ";
2283 
2284     ObjCDictionaryElement Element = E->getKeyValueElement(I);
2285     Visit(Element.Key);
2286     OS << " : ";
2287     Visit(Element.Value);
2288     if (Element.isPackExpansion())
2289       OS << "...";
2290   }
2291   OS << " }";
2292 }
2293 
2294 void StmtPrinter::VisitObjCEncodeExpr(ObjCEncodeExpr *Node) {
2295   OS << "@encode(";
2296   Node->getEncodedType().print(OS, Policy);
2297   OS << ')';
2298 }
2299 
2300 void StmtPrinter::VisitObjCSelectorExpr(ObjCSelectorExpr *Node) {
2301   OS << "@selector(";
2302   Node->getSelector().print(OS);
2303   OS << ')';
2304 }
2305 
2306 void StmtPrinter::VisitObjCProtocolExpr(ObjCProtocolExpr *Node) {
2307   OS << "@protocol(" << *Node->getProtocol() << ')';
2308 }
2309 
2310 void StmtPrinter::VisitObjCMessageExpr(ObjCMessageExpr *Mess) {
2311   OS << "[";
2312   switch (Mess->getReceiverKind()) {
2313   case ObjCMessageExpr::Instance:
2314     PrintExpr(Mess->getInstanceReceiver());
2315     break;
2316 
2317   case ObjCMessageExpr::Class:
2318     Mess->getClassReceiver().print(OS, Policy);
2319     break;
2320 
2321   case ObjCMessageExpr::SuperInstance:
2322   case ObjCMessageExpr::SuperClass:
2323     OS << "Super";
2324     break;
2325   }
2326 
2327   OS << ' ';
2328   Selector selector = Mess->getSelector();
2329   if (selector.isUnarySelector()) {
2330     OS << selector.getNameForSlot(0);
2331   } else {
2332     for (unsigned i = 0, e = Mess->getNumArgs(); i != e; ++i) {
2333       if (i < selector.getNumArgs()) {
2334         if (i > 0) OS << ' ';
2335         if (selector.getIdentifierInfoForSlot(i))
2336           OS << selector.getIdentifierInfoForSlot(i)->getName() << ':';
2337         else
2338            OS << ":";
2339       }
2340       else OS << ", "; // Handle variadic methods.
2341 
2342       PrintExpr(Mess->getArg(i));
2343     }
2344   }
2345   OS << "]";
2346 }
2347 
2348 void StmtPrinter::VisitObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Node) {
2349   OS << (Node->getValue() ? "__objc_yes" : "__objc_no");
2350 }
2351 
2352 void
2353 StmtPrinter::VisitObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
2354   PrintExpr(E->getSubExpr());
2355 }
2356 
2357 void
2358 StmtPrinter::VisitObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
2359   OS << '(' << E->getBridgeKindName();
2360   E->getType().print(OS, Policy);
2361   OS << ')';
2362   PrintExpr(E->getSubExpr());
2363 }
2364 
2365 void StmtPrinter::VisitBlockExpr(BlockExpr *Node) {
2366   BlockDecl *BD = Node->getBlockDecl();
2367   OS << "^";
2368 
2369   const FunctionType *AFT = Node->getFunctionType();
2370 
2371   if (isa<FunctionNoProtoType>(AFT)) {
2372     OS << "()";
2373   } else if (!BD->param_empty() || cast<FunctionProtoType>(AFT)->isVariadic()) {
2374     OS << '(';
2375     for (BlockDecl::param_iterator AI = BD->param_begin(),
2376          E = BD->param_end(); AI != E; ++AI) {
2377       if (AI != BD->param_begin()) OS << ", ";
2378       std::string ParamStr = (*AI)->getNameAsString();
2379       (*AI)->getType().print(OS, Policy, ParamStr);
2380     }
2381 
2382     const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
2383     if (FT->isVariadic()) {
2384       if (!BD->param_empty()) OS << ", ";
2385       OS << "...";
2386     }
2387     OS << ')';
2388   }
2389   OS << "{ }";
2390 }
2391 
2392 void StmtPrinter::VisitOpaqueValueExpr(OpaqueValueExpr *Node) {
2393   PrintExpr(Node->getSourceExpr());
2394 }
2395 
2396 void StmtPrinter::VisitTypoExpr(TypoExpr *Node) {
2397   // TODO: Print something reasonable for a TypoExpr, if necessary.
2398   assert(false && "Cannot print TypoExpr nodes");
2399 }
2400 
2401 void StmtPrinter::VisitAsTypeExpr(AsTypeExpr *Node) {
2402   OS << "__builtin_astype(";
2403   PrintExpr(Node->getSrcExpr());
2404   OS << ", ";
2405   Node->getType().print(OS, Policy);
2406   OS << ")";
2407 }
2408 
2409 //===----------------------------------------------------------------------===//
2410 // Stmt method implementations
2411 //===----------------------------------------------------------------------===//
2412 
2413 void Stmt::dumpPretty(const ASTContext &Context) const {
2414   printPretty(llvm::errs(), nullptr, PrintingPolicy(Context.getLangOpts()));
2415 }
2416 
2417 void Stmt::printPretty(raw_ostream &OS,
2418                        PrinterHelper *Helper,
2419                        const PrintingPolicy &Policy,
2420                        unsigned Indentation) const {
2421   StmtPrinter P(OS, Helper, Policy, Indentation);
2422   P.Visit(const_cast<Stmt*>(this));
2423 }
2424 
2425 //===----------------------------------------------------------------------===//
2426 // PrinterHelper
2427 //===----------------------------------------------------------------------===//
2428 
2429 // Implement virtual destructor.
2430 PrinterHelper::~PrinterHelper() {}
2431