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