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