1 //===--- DeclPrinter.cpp - Printing implementation for Decl 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 Decl::print method, which pretty prints the
10 // AST back out to C/Objective-C/C++/Objective-C++ code.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/PrettyPrinter.h"
23 #include "clang/Basic/Module.h"
24 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
26 
27 namespace {
28   class DeclPrinter : public DeclVisitor<DeclPrinter> {
29     raw_ostream &Out;
30     PrintingPolicy Policy;
31     const ASTContext &Context;
32     unsigned Indentation;
33     bool PrintInstantiation;
34 
35     raw_ostream& Indent() { return Indent(Indentation); }
36     raw_ostream& Indent(unsigned Indentation);
37     void ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls);
38 
39     void Print(AccessSpecifier AS);
40     void PrintConstructorInitializers(CXXConstructorDecl *CDecl,
41                                       std::string &Proto);
42 
43     /// Print an Objective-C method type in parentheses.
44     ///
45     /// \param Quals The Objective-C declaration qualifiers.
46     /// \param T The type to print.
47     void PrintObjCMethodType(ASTContext &Ctx, Decl::ObjCDeclQualifier Quals,
48                              QualType T);
49 
50     void PrintObjCTypeParams(ObjCTypeParamList *Params);
51 
52   public:
53     DeclPrinter(raw_ostream &Out, const PrintingPolicy &Policy,
54                 const ASTContext &Context, unsigned Indentation = 0,
55                 bool PrintInstantiation = false)
56         : Out(Out), Policy(Policy), Context(Context), Indentation(Indentation),
57           PrintInstantiation(PrintInstantiation) {}
58 
59     void VisitDeclContext(DeclContext *DC, bool Indent = true);
60 
61     void VisitTranslationUnitDecl(TranslationUnitDecl *D);
62     void VisitTypedefDecl(TypedefDecl *D);
63     void VisitTypeAliasDecl(TypeAliasDecl *D);
64     void VisitEnumDecl(EnumDecl *D);
65     void VisitRecordDecl(RecordDecl *D);
66     void VisitEnumConstantDecl(EnumConstantDecl *D);
67     void VisitEmptyDecl(EmptyDecl *D);
68     void VisitFunctionDecl(FunctionDecl *D);
69     void VisitFriendDecl(FriendDecl *D);
70     void VisitFieldDecl(FieldDecl *D);
71     void VisitVarDecl(VarDecl *D);
72     void VisitLabelDecl(LabelDecl *D);
73     void VisitParmVarDecl(ParmVarDecl *D);
74     void VisitFileScopeAsmDecl(FileScopeAsmDecl *D);
75     void VisitImportDecl(ImportDecl *D);
76     void VisitStaticAssertDecl(StaticAssertDecl *D);
77     void VisitNamespaceDecl(NamespaceDecl *D);
78     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
79     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
80     void VisitCXXRecordDecl(CXXRecordDecl *D);
81     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
82     void VisitTemplateDecl(const TemplateDecl *D);
83     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
84     void VisitClassTemplateDecl(ClassTemplateDecl *D);
85     void VisitClassTemplateSpecializationDecl(
86                                             ClassTemplateSpecializationDecl *D);
87     void VisitClassTemplatePartialSpecializationDecl(
88                                      ClassTemplatePartialSpecializationDecl *D);
89     void VisitObjCMethodDecl(ObjCMethodDecl *D);
90     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
91     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
92     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
93     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
94     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
95     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
96     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
97     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
98     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
99     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
100     void VisitUsingDecl(UsingDecl *D);
101     void VisitUsingEnumDecl(UsingEnumDecl *D);
102     void VisitUsingShadowDecl(UsingShadowDecl *D);
103     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
104     void VisitOMPAllocateDecl(OMPAllocateDecl *D);
105     void VisitOMPRequiresDecl(OMPRequiresDecl *D);
106     void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
107     void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
108     void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
109     void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP);
110     void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *NTTP);
111 
112     void printTemplateParameters(const TemplateParameterList *Params,
113                                  bool OmitTemplateKW = false);
114     void printTemplateArguments(llvm::ArrayRef<TemplateArgument> Args,
115                                 const TemplateParameterList *Params);
116     void printTemplateArguments(llvm::ArrayRef<TemplateArgumentLoc> Args,
117                                 const TemplateParameterList *Params);
118     void prettyPrintAttributes(Decl *D);
119     void prettyPrintPragmas(Decl *D);
120     void printDeclType(QualType T, StringRef DeclName, bool Pack = false);
121   };
122 }
123 
124 void Decl::print(raw_ostream &Out, unsigned Indentation,
125                  bool PrintInstantiation) const {
126   print(Out, getASTContext().getPrintingPolicy(), Indentation, PrintInstantiation);
127 }
128 
129 void Decl::print(raw_ostream &Out, const PrintingPolicy &Policy,
130                  unsigned Indentation, bool PrintInstantiation) const {
131   DeclPrinter Printer(Out, Policy, getASTContext(), Indentation,
132                       PrintInstantiation);
133   Printer.Visit(const_cast<Decl*>(this));
134 }
135 
136 void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context,
137                                   bool OmitTemplateKW) const {
138   print(Out, Context, Context.getPrintingPolicy(), OmitTemplateKW);
139 }
140 
141 void TemplateParameterList::print(raw_ostream &Out, const ASTContext &Context,
142                                   const PrintingPolicy &Policy,
143                                   bool OmitTemplateKW) const {
144   DeclPrinter Printer(Out, Policy, Context);
145   Printer.printTemplateParameters(this, OmitTemplateKW);
146 }
147 
148 static QualType GetBaseType(QualType T) {
149   // FIXME: This should be on the Type class!
150   QualType BaseType = T;
151   while (!BaseType->isSpecifierType()) {
152     if (const PointerType *PTy = BaseType->getAs<PointerType>())
153       BaseType = PTy->getPointeeType();
154     else if (const ObjCObjectPointerType *OPT =
155                  BaseType->getAs<ObjCObjectPointerType>())
156       BaseType = OPT->getPointeeType();
157     else if (const BlockPointerType *BPy = BaseType->getAs<BlockPointerType>())
158       BaseType = BPy->getPointeeType();
159     else if (const ArrayType *ATy = dyn_cast<ArrayType>(BaseType))
160       BaseType = ATy->getElementType();
161     else if (const FunctionType *FTy = BaseType->getAs<FunctionType>())
162       BaseType = FTy->getReturnType();
163     else if (const VectorType *VTy = BaseType->getAs<VectorType>())
164       BaseType = VTy->getElementType();
165     else if (const ReferenceType *RTy = BaseType->getAs<ReferenceType>())
166       BaseType = RTy->getPointeeType();
167     else if (const AutoType *ATy = BaseType->getAs<AutoType>())
168       BaseType = ATy->getDeducedType();
169     else if (const ParenType *PTy = BaseType->getAs<ParenType>())
170       BaseType = PTy->desugar();
171     else
172       // This must be a syntax error.
173       break;
174   }
175   return BaseType;
176 }
177 
178 static QualType getDeclType(Decl* D) {
179   if (TypedefNameDecl* TDD = dyn_cast<TypedefNameDecl>(D))
180     return TDD->getUnderlyingType();
181   if (ValueDecl* VD = dyn_cast<ValueDecl>(D))
182     return VD->getType();
183   return QualType();
184 }
185 
186 void Decl::printGroup(Decl** Begin, unsigned NumDecls,
187                       raw_ostream &Out, const PrintingPolicy &Policy,
188                       unsigned Indentation) {
189   if (NumDecls == 1) {
190     (*Begin)->print(Out, Policy, Indentation);
191     return;
192   }
193 
194   Decl** End = Begin + NumDecls;
195   TagDecl* TD = dyn_cast<TagDecl>(*Begin);
196   if (TD)
197     ++Begin;
198 
199   PrintingPolicy SubPolicy(Policy);
200 
201   bool isFirst = true;
202   for ( ; Begin != End; ++Begin) {
203     if (isFirst) {
204       if(TD)
205         SubPolicy.IncludeTagDefinition = true;
206       SubPolicy.SuppressSpecifiers = false;
207       isFirst = false;
208     } else {
209       if (!isFirst) Out << ", ";
210       SubPolicy.IncludeTagDefinition = false;
211       SubPolicy.SuppressSpecifiers = true;
212     }
213 
214     (*Begin)->print(Out, SubPolicy, Indentation);
215   }
216 }
217 
218 LLVM_DUMP_METHOD void DeclContext::dumpDeclContext() const {
219   // Get the translation unit
220   const DeclContext *DC = this;
221   while (!DC->isTranslationUnit())
222     DC = DC->getParent();
223 
224   ASTContext &Ctx = cast<TranslationUnitDecl>(DC)->getASTContext();
225   DeclPrinter Printer(llvm::errs(), Ctx.getPrintingPolicy(), Ctx, 0);
226   Printer.VisitDeclContext(const_cast<DeclContext *>(this), /*Indent=*/false);
227 }
228 
229 raw_ostream& DeclPrinter::Indent(unsigned Indentation) {
230   for (unsigned i = 0; i != Indentation; ++i)
231     Out << "  ";
232   return Out;
233 }
234 
235 void DeclPrinter::prettyPrintAttributes(Decl *D) {
236   if (Policy.PolishForDeclaration)
237     return;
238 
239   if (D->hasAttrs()) {
240     AttrVec &Attrs = D->getAttrs();
241     for (auto *A : Attrs) {
242       if (A->isInherited() || A->isImplicit())
243         continue;
244       switch (A->getKind()) {
245 #define ATTR(X)
246 #define PRAGMA_SPELLING_ATTR(X) case attr::X:
247 #include "clang/Basic/AttrList.inc"
248         break;
249       default:
250         A->printPretty(Out, Policy);
251         break;
252       }
253     }
254   }
255 }
256 
257 void DeclPrinter::prettyPrintPragmas(Decl *D) {
258   if (Policy.PolishForDeclaration)
259     return;
260 
261   if (D->hasAttrs()) {
262     AttrVec &Attrs = D->getAttrs();
263     for (auto *A : Attrs) {
264       switch (A->getKind()) {
265 #define ATTR(X)
266 #define PRAGMA_SPELLING_ATTR(X) case attr::X:
267 #include "clang/Basic/AttrList.inc"
268         A->printPretty(Out, Policy);
269         Indent();
270         break;
271       default:
272         break;
273       }
274     }
275   }
276 }
277 
278 void DeclPrinter::printDeclType(QualType T, StringRef DeclName, bool Pack) {
279   // Normally, a PackExpansionType is written as T[3]... (for instance, as a
280   // template argument), but if it is the type of a declaration, the ellipsis
281   // is placed before the name being declared.
282   if (auto *PET = T->getAs<PackExpansionType>()) {
283     Pack = true;
284     T = PET->getPattern();
285   }
286   T.print(Out, Policy, (Pack ? "..." : "") + DeclName, Indentation);
287 }
288 
289 void DeclPrinter::ProcessDeclGroup(SmallVectorImpl<Decl*>& Decls) {
290   this->Indent();
291   Decl::printGroup(Decls.data(), Decls.size(), Out, Policy, Indentation);
292   Out << ";\n";
293   Decls.clear();
294 
295 }
296 
297 void DeclPrinter::Print(AccessSpecifier AS) {
298   const auto AccessSpelling = getAccessSpelling(AS);
299   if (AccessSpelling.empty())
300     llvm_unreachable("No access specifier!");
301   Out << AccessSpelling;
302 }
303 
304 void DeclPrinter::PrintConstructorInitializers(CXXConstructorDecl *CDecl,
305                                                std::string &Proto) {
306   bool HasInitializerList = false;
307   for (const auto *BMInitializer : CDecl->inits()) {
308     if (BMInitializer->isInClassMemberInitializer())
309       continue;
310 
311     if (!HasInitializerList) {
312       Proto += " : ";
313       Out << Proto;
314       Proto.clear();
315       HasInitializerList = true;
316     } else
317       Out << ", ";
318 
319     if (BMInitializer->isAnyMemberInitializer()) {
320       FieldDecl *FD = BMInitializer->getAnyMember();
321       Out << *FD;
322     } else {
323       Out << QualType(BMInitializer->getBaseClass(), 0).getAsString(Policy);
324     }
325 
326     Out << "(";
327     if (!BMInitializer->getInit()) {
328       // Nothing to print
329     } else {
330       Expr *Init = BMInitializer->getInit();
331       if (ExprWithCleanups *Tmp = dyn_cast<ExprWithCleanups>(Init))
332         Init = Tmp->getSubExpr();
333 
334       Init = Init->IgnoreParens();
335 
336       Expr *SimpleInit = nullptr;
337       Expr **Args = nullptr;
338       unsigned NumArgs = 0;
339       if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
340         Args = ParenList->getExprs();
341         NumArgs = ParenList->getNumExprs();
342       } else if (CXXConstructExpr *Construct =
343                      dyn_cast<CXXConstructExpr>(Init)) {
344         Args = Construct->getArgs();
345         NumArgs = Construct->getNumArgs();
346       } else
347         SimpleInit = Init;
348 
349       if (SimpleInit)
350         SimpleInit->printPretty(Out, nullptr, Policy, Indentation, "\n",
351                                 &Context);
352       else {
353         for (unsigned I = 0; I != NumArgs; ++I) {
354           assert(Args[I] != nullptr && "Expected non-null Expr");
355           if (isa<CXXDefaultArgExpr>(Args[I]))
356             break;
357 
358           if (I)
359             Out << ", ";
360           Args[I]->printPretty(Out, nullptr, Policy, Indentation, "\n",
361                                &Context);
362         }
363       }
364     }
365     Out << ")";
366     if (BMInitializer->isPackExpansion())
367       Out << "...";
368   }
369 }
370 
371 //----------------------------------------------------------------------------
372 // Common C declarations
373 //----------------------------------------------------------------------------
374 
375 void DeclPrinter::VisitDeclContext(DeclContext *DC, bool Indent) {
376   if (Policy.TerseOutput)
377     return;
378 
379   if (Indent)
380     Indentation += Policy.Indentation;
381 
382   SmallVector<Decl*, 2> Decls;
383   for (DeclContext::decl_iterator D = DC->decls_begin(), DEnd = DC->decls_end();
384        D != DEnd; ++D) {
385 
386     // Don't print ObjCIvarDecls, as they are printed when visiting the
387     // containing ObjCInterfaceDecl.
388     if (isa<ObjCIvarDecl>(*D))
389       continue;
390 
391     // Skip over implicit declarations in pretty-printing mode.
392     if (D->isImplicit())
393       continue;
394 
395     // Don't print implicit specializations, as they are printed when visiting
396     // corresponding templates.
397     if (auto FD = dyn_cast<FunctionDecl>(*D))
398       if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
399           !isa<ClassTemplateSpecializationDecl>(DC))
400         continue;
401 
402     // The next bits of code handle stuff like "struct {int x;} a,b"; we're
403     // forced to merge the declarations because there's no other way to
404     // refer to the struct in question.  When that struct is named instead, we
405     // also need to merge to avoid splitting off a stand-alone struct
406     // declaration that produces the warning ext_no_declarators in some
407     // contexts.
408     //
409     // This limited merging is safe without a bunch of other checks because it
410     // only merges declarations directly referring to the tag, not typedefs.
411     //
412     // Check whether the current declaration should be grouped with a previous
413     // non-free-standing tag declaration.
414     QualType CurDeclType = getDeclType(*D);
415     if (!Decls.empty() && !CurDeclType.isNull()) {
416       QualType BaseType = GetBaseType(CurDeclType);
417       if (!BaseType.isNull() && isa<ElaboratedType>(BaseType) &&
418           cast<ElaboratedType>(BaseType)->getOwnedTagDecl() == Decls[0]) {
419         Decls.push_back(*D);
420         continue;
421       }
422     }
423 
424     // If we have a merged group waiting to be handled, handle it now.
425     if (!Decls.empty())
426       ProcessDeclGroup(Decls);
427 
428     // If the current declaration is not a free standing declaration, save it
429     // so we can merge it with the subsequent declaration(s) using it.
430     if (isa<TagDecl>(*D) && !cast<TagDecl>(*D)->isFreeStanding()) {
431       Decls.push_back(*D);
432       continue;
433     }
434 
435     if (isa<AccessSpecDecl>(*D)) {
436       Indentation -= Policy.Indentation;
437       this->Indent();
438       Print(D->getAccess());
439       Out << ":\n";
440       Indentation += Policy.Indentation;
441       continue;
442     }
443 
444     this->Indent();
445     Visit(*D);
446 
447     // FIXME: Need to be able to tell the DeclPrinter when
448     const char *Terminator = nullptr;
449     if (isa<OMPThreadPrivateDecl>(*D) || isa<OMPDeclareReductionDecl>(*D) ||
450         isa<OMPDeclareMapperDecl>(*D) || isa<OMPRequiresDecl>(*D) ||
451         isa<OMPAllocateDecl>(*D))
452       Terminator = nullptr;
453     else if (isa<ObjCMethodDecl>(*D) && cast<ObjCMethodDecl>(*D)->hasBody())
454       Terminator = nullptr;
455     else if (auto FD = dyn_cast<FunctionDecl>(*D)) {
456       if (FD->isThisDeclarationADefinition())
457         Terminator = nullptr;
458       else
459         Terminator = ";";
460     } else if (auto TD = dyn_cast<FunctionTemplateDecl>(*D)) {
461       if (TD->getTemplatedDecl()->isThisDeclarationADefinition())
462         Terminator = nullptr;
463       else
464         Terminator = ";";
465     } else if (isa<NamespaceDecl>(*D) || isa<LinkageSpecDecl>(*D) ||
466              isa<ObjCImplementationDecl>(*D) ||
467              isa<ObjCInterfaceDecl>(*D) ||
468              isa<ObjCProtocolDecl>(*D) ||
469              isa<ObjCCategoryImplDecl>(*D) ||
470              isa<ObjCCategoryDecl>(*D))
471       Terminator = nullptr;
472     else if (isa<EnumConstantDecl>(*D)) {
473       DeclContext::decl_iterator Next = D;
474       ++Next;
475       if (Next != DEnd)
476         Terminator = ",";
477     } else
478       Terminator = ";";
479 
480     if (Terminator)
481       Out << Terminator;
482     if (!Policy.TerseOutput &&
483         ((isa<FunctionDecl>(*D) &&
484           cast<FunctionDecl>(*D)->doesThisDeclarationHaveABody()) ||
485          (isa<FunctionTemplateDecl>(*D) &&
486           cast<FunctionTemplateDecl>(*D)->getTemplatedDecl()->doesThisDeclarationHaveABody())))
487       ; // StmtPrinter already added '\n' after CompoundStmt.
488     else
489       Out << "\n";
490 
491     // Declare target attribute is special one, natural spelling for the pragma
492     // assumes "ending" construct so print it here.
493     if (D->hasAttr<OMPDeclareTargetDeclAttr>())
494       Out << "#pragma omp end declare target\n";
495   }
496 
497   if (!Decls.empty())
498     ProcessDeclGroup(Decls);
499 
500   if (Indent)
501     Indentation -= Policy.Indentation;
502 }
503 
504 void DeclPrinter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
505   VisitDeclContext(D, false);
506 }
507 
508 void DeclPrinter::VisitTypedefDecl(TypedefDecl *D) {
509   if (!Policy.SuppressSpecifiers) {
510     Out << "typedef ";
511 
512     if (D->isModulePrivate())
513       Out << "__module_private__ ";
514   }
515   QualType Ty = D->getTypeSourceInfo()->getType();
516   Ty.print(Out, Policy, D->getName(), Indentation);
517   prettyPrintAttributes(D);
518 }
519 
520 void DeclPrinter::VisitTypeAliasDecl(TypeAliasDecl *D) {
521   Out << "using " << *D;
522   prettyPrintAttributes(D);
523   Out << " = " << D->getTypeSourceInfo()->getType().getAsString(Policy);
524 }
525 
526 void DeclPrinter::VisitEnumDecl(EnumDecl *D) {
527   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
528     Out << "__module_private__ ";
529   Out << "enum";
530   if (D->isScoped()) {
531     if (D->isScopedUsingClassTag())
532       Out << " class";
533     else
534       Out << " struct";
535   }
536 
537   prettyPrintAttributes(D);
538 
539   if (D->getDeclName())
540     Out << ' ' << D->getDeclName();
541 
542   if (D->isFixed())
543     Out << " : " << D->getIntegerType().stream(Policy);
544 
545   if (D->isCompleteDefinition()) {
546     Out << " {\n";
547     VisitDeclContext(D);
548     Indent() << "}";
549   }
550 }
551 
552 void DeclPrinter::VisitRecordDecl(RecordDecl *D) {
553   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
554     Out << "__module_private__ ";
555   Out << D->getKindName();
556 
557   prettyPrintAttributes(D);
558 
559   if (D->getIdentifier())
560     Out << ' ' << *D;
561 
562   if (D->isCompleteDefinition()) {
563     Out << " {\n";
564     VisitDeclContext(D);
565     Indent() << "}";
566   }
567 }
568 
569 void DeclPrinter::VisitEnumConstantDecl(EnumConstantDecl *D) {
570   Out << *D;
571   prettyPrintAttributes(D);
572   if (Expr *Init = D->getInitExpr()) {
573     Out << " = ";
574     Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
575   }
576 }
577 
578 static void printExplicitSpecifier(ExplicitSpecifier ES, llvm::raw_ostream &Out,
579                                    PrintingPolicy &Policy, unsigned Indentation,
580                                    const ASTContext &Context) {
581   std::string Proto = "explicit";
582   llvm::raw_string_ostream EOut(Proto);
583   if (ES.getExpr()) {
584     EOut << "(";
585     ES.getExpr()->printPretty(EOut, nullptr, Policy, Indentation, "\n",
586                               &Context);
587     EOut << ")";
588   }
589   EOut << " ";
590   EOut.flush();
591   Out << Proto;
592 }
593 
594 void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
595   if (!D->getDescribedFunctionTemplate() &&
596       !D->isFunctionTemplateSpecialization())
597     prettyPrintPragmas(D);
598 
599   if (D->isFunctionTemplateSpecialization())
600     Out << "template<> ";
601   else if (!D->getDescribedFunctionTemplate()) {
602     for (unsigned I = 0, NumTemplateParams = D->getNumTemplateParameterLists();
603          I < NumTemplateParams; ++I)
604       printTemplateParameters(D->getTemplateParameterList(I));
605   }
606 
607   CXXConstructorDecl *CDecl = dyn_cast<CXXConstructorDecl>(D);
608   CXXConversionDecl *ConversionDecl = dyn_cast<CXXConversionDecl>(D);
609   CXXDeductionGuideDecl *GuideDecl = dyn_cast<CXXDeductionGuideDecl>(D);
610   if (!Policy.SuppressSpecifiers) {
611     switch (D->getStorageClass()) {
612     case SC_None: break;
613     case SC_Extern: Out << "extern "; break;
614     case SC_Static: Out << "static "; break;
615     case SC_PrivateExtern: Out << "__private_extern__ "; break;
616     case SC_Auto: case SC_Register:
617       llvm_unreachable("invalid for functions");
618     }
619 
620     if (D->isInlineSpecified())  Out << "inline ";
621     if (D->isVirtualAsWritten()) Out << "virtual ";
622     if (D->isModulePrivate())    Out << "__module_private__ ";
623     if (D->isConstexprSpecified() && !D->isExplicitlyDefaulted())
624       Out << "constexpr ";
625     if (D->isConsteval())        Out << "consteval ";
626     ExplicitSpecifier ExplicitSpec = ExplicitSpecifier::getFromDecl(D);
627     if (ExplicitSpec.isSpecified())
628       printExplicitSpecifier(ExplicitSpec, Out, Policy, Indentation, Context);
629   }
630 
631   PrintingPolicy SubPolicy(Policy);
632   SubPolicy.SuppressSpecifiers = false;
633   std::string Proto;
634 
635   if (Policy.FullyQualifiedName) {
636     Proto += D->getQualifiedNameAsString();
637   } else {
638     llvm::raw_string_ostream OS(Proto);
639     if (!Policy.SuppressScope) {
640       if (const NestedNameSpecifier *NS = D->getQualifier()) {
641         NS->print(OS, Policy);
642       }
643     }
644     D->getNameInfo().printName(OS, Policy);
645   }
646 
647   if (GuideDecl)
648     Proto = GuideDecl->getDeducedTemplate()->getDeclName().getAsString();
649   if (D->isFunctionTemplateSpecialization()) {
650     llvm::raw_string_ostream POut(Proto);
651     DeclPrinter TArgPrinter(POut, SubPolicy, Context, Indentation);
652     const auto *TArgAsWritten = D->getTemplateSpecializationArgsAsWritten();
653     if (TArgAsWritten && !Policy.PrintCanonicalTypes)
654       TArgPrinter.printTemplateArguments(TArgAsWritten->arguments(), nullptr);
655     else if (const TemplateArgumentList *TArgs =
656                  D->getTemplateSpecializationArgs())
657       TArgPrinter.printTemplateArguments(TArgs->asArray(), nullptr);
658   }
659 
660   QualType Ty = D->getType();
661   while (const ParenType *PT = dyn_cast<ParenType>(Ty)) {
662     Proto = '(' + Proto + ')';
663     Ty = PT->getInnerType();
664   }
665 
666   if (const FunctionType *AFT = Ty->getAs<FunctionType>()) {
667     const FunctionProtoType *FT = nullptr;
668     if (D->hasWrittenPrototype())
669       FT = dyn_cast<FunctionProtoType>(AFT);
670 
671     Proto += "(";
672     if (FT) {
673       llvm::raw_string_ostream POut(Proto);
674       DeclPrinter ParamPrinter(POut, SubPolicy, Context, Indentation);
675       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
676         if (i) POut << ", ";
677         ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
678       }
679 
680       if (FT->isVariadic()) {
681         if (D->getNumParams()) POut << ", ";
682         POut << "...";
683       } else if (!D->getNumParams() && !Context.getLangOpts().CPlusPlus) {
684         // The function has a prototype, so it needs to retain the prototype
685         // in C.
686         POut << "void";
687       }
688     } else if (D->doesThisDeclarationHaveABody() && !D->hasPrototype()) {
689       for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
690         if (i)
691           Proto += ", ";
692         Proto += D->getParamDecl(i)->getNameAsString();
693       }
694     }
695 
696     Proto += ")";
697 
698     if (FT) {
699       if (FT->isConst())
700         Proto += " const";
701       if (FT->isVolatile())
702         Proto += " volatile";
703       if (FT->isRestrict())
704         Proto += " restrict";
705 
706       switch (FT->getRefQualifier()) {
707       case RQ_None:
708         break;
709       case RQ_LValue:
710         Proto += " &";
711         break;
712       case RQ_RValue:
713         Proto += " &&";
714         break;
715       }
716     }
717 
718     if (FT && FT->hasDynamicExceptionSpec()) {
719       Proto += " throw(";
720       if (FT->getExceptionSpecType() == EST_MSAny)
721         Proto += "...";
722       else
723         for (unsigned I = 0, N = FT->getNumExceptions(); I != N; ++I) {
724           if (I)
725             Proto += ", ";
726 
727           Proto += FT->getExceptionType(I).getAsString(SubPolicy);
728         }
729       Proto += ")";
730     } else if (FT && isNoexceptExceptionSpec(FT->getExceptionSpecType())) {
731       Proto += " noexcept";
732       if (isComputedNoexcept(FT->getExceptionSpecType())) {
733         Proto += "(";
734         llvm::raw_string_ostream EOut(Proto);
735         FT->getNoexceptExpr()->printPretty(EOut, nullptr, SubPolicy,
736                                            Indentation, "\n", &Context);
737         EOut.flush();
738         Proto += ")";
739       }
740     }
741 
742     if (CDecl) {
743       if (!Policy.TerseOutput)
744         PrintConstructorInitializers(CDecl, Proto);
745     } else if (!ConversionDecl && !isa<CXXDestructorDecl>(D)) {
746       if (FT && FT->hasTrailingReturn()) {
747         if (!GuideDecl)
748           Out << "auto ";
749         Out << Proto << " -> ";
750         Proto.clear();
751       }
752       AFT->getReturnType().print(Out, Policy, Proto);
753       Proto.clear();
754     }
755     Out << Proto;
756 
757     if (Expr *TrailingRequiresClause = D->getTrailingRequiresClause()) {
758       Out << " requires ";
759       TrailingRequiresClause->printPretty(Out, nullptr, SubPolicy, Indentation,
760                                           "\n", &Context);
761     }
762   } else {
763     Ty.print(Out, Policy, Proto);
764   }
765 
766   prettyPrintAttributes(D);
767 
768   if (D->isPure())
769     Out << " = 0";
770   else if (D->isDeletedAsWritten())
771     Out << " = delete";
772   else if (D->isExplicitlyDefaulted())
773     Out << " = default";
774   else if (D->doesThisDeclarationHaveABody()) {
775     if (!Policy.TerseOutput) {
776       if (!D->hasPrototype() && D->getNumParams()) {
777         // This is a K&R function definition, so we need to print the
778         // parameters.
779         Out << '\n';
780         DeclPrinter ParamPrinter(Out, SubPolicy, Context, Indentation);
781         Indentation += Policy.Indentation;
782         for (unsigned i = 0, e = D->getNumParams(); i != e; ++i) {
783           Indent();
784           ParamPrinter.VisitParmVarDecl(D->getParamDecl(i));
785           Out << ";\n";
786         }
787         Indentation -= Policy.Indentation;
788       }
789 
790       if (D->getBody())
791         D->getBody()->printPrettyControlled(Out, nullptr, SubPolicy, Indentation, "\n",
792                                   &Context);
793     } else {
794       if (!Policy.TerseOutput && isa<CXXConstructorDecl>(*D))
795         Out << " {}";
796     }
797   }
798 }
799 
800 void DeclPrinter::VisitFriendDecl(FriendDecl *D) {
801   if (TypeSourceInfo *TSI = D->getFriendType()) {
802     unsigned NumTPLists = D->getFriendTypeNumTemplateParameterLists();
803     for (unsigned i = 0; i < NumTPLists; ++i)
804       printTemplateParameters(D->getFriendTypeTemplateParameterList(i));
805     Out << "friend ";
806     Out << " " << TSI->getType().getAsString(Policy);
807   }
808   else if (FunctionDecl *FD =
809       dyn_cast<FunctionDecl>(D->getFriendDecl())) {
810     Out << "friend ";
811     VisitFunctionDecl(FD);
812   }
813   else if (FunctionTemplateDecl *FTD =
814            dyn_cast<FunctionTemplateDecl>(D->getFriendDecl())) {
815     Out << "friend ";
816     VisitFunctionTemplateDecl(FTD);
817   }
818   else if (ClassTemplateDecl *CTD =
819            dyn_cast<ClassTemplateDecl>(D->getFriendDecl())) {
820     Out << "friend ";
821     VisitRedeclarableTemplateDecl(CTD);
822   }
823 }
824 
825 void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
826   // FIXME: add printing of pragma attributes if required.
827   if (!Policy.SuppressSpecifiers && D->isMutable())
828     Out << "mutable ";
829   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
830     Out << "__module_private__ ";
831 
832   Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
833          stream(Policy, D->getName(), Indentation);
834 
835   if (D->isBitField()) {
836     Out << " : ";
837     D->getBitWidth()->printPretty(Out, nullptr, Policy, Indentation, "\n",
838                                   &Context);
839   }
840 
841   Expr *Init = D->getInClassInitializer();
842   if (!Policy.SuppressInitializers && Init) {
843     if (D->getInClassInitStyle() == ICIS_ListInit)
844       Out << " ";
845     else
846       Out << " = ";
847     Init->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
848   }
849   prettyPrintAttributes(D);
850 }
851 
852 void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
853   Out << *D << ":";
854 }
855 
856 void DeclPrinter::VisitVarDecl(VarDecl *D) {
857   prettyPrintPragmas(D);
858 
859   QualType T = D->getTypeSourceInfo()
860     ? D->getTypeSourceInfo()->getType()
861     : D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
862 
863   if (!Policy.SuppressSpecifiers) {
864     StorageClass SC = D->getStorageClass();
865     if (SC != SC_None)
866       Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
867 
868     switch (D->getTSCSpec()) {
869     case TSCS_unspecified:
870       break;
871     case TSCS___thread:
872       Out << "__thread ";
873       break;
874     case TSCS__Thread_local:
875       Out << "_Thread_local ";
876       break;
877     case TSCS_thread_local:
878       Out << "thread_local ";
879       break;
880     }
881 
882     if (D->isModulePrivate())
883       Out << "__module_private__ ";
884 
885     if (D->isConstexpr()) {
886       Out << "constexpr ";
887       T.removeLocalConst();
888     }
889   }
890 
891   printDeclType(T, (isa<ParmVarDecl>(D) && Policy.CleanUglifiedParameters &&
892                     D->getIdentifier())
893                        ? D->getIdentifier()->deuglifiedName()
894                        : D->getName());
895   Expr *Init = D->getInit();
896   if (!Policy.SuppressInitializers && Init) {
897     bool ImplicitInit = false;
898     if (D->isCXXForRangeDecl()) {
899       // FIXME: We should print the range expression instead.
900       ImplicitInit = true;
901     } else if (CXXConstructExpr *Construct =
902                    dyn_cast<CXXConstructExpr>(Init->IgnoreImplicit())) {
903       if (D->getInitStyle() == VarDecl::CallInit &&
904           !Construct->isListInitialization()) {
905         ImplicitInit = Construct->getNumArgs() == 0 ||
906                        Construct->getArg(0)->isDefaultArgument();
907       }
908     }
909     if (!ImplicitInit) {
910       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
911         Out << "(";
912       else if (D->getInitStyle() == VarDecl::CInit) {
913         Out << " = ";
914       }
915       PrintingPolicy SubPolicy(Policy);
916       SubPolicy.SuppressSpecifiers = false;
917       SubPolicy.IncludeTagDefinition = false;
918       Init->printPretty(Out, nullptr, SubPolicy, Indentation, "\n", &Context);
919       if ((D->getInitStyle() == VarDecl::CallInit) && !isa<ParenListExpr>(Init))
920         Out << ")";
921     }
922   }
923   prettyPrintAttributes(D);
924 }
925 
926 void DeclPrinter::VisitParmVarDecl(ParmVarDecl *D) {
927   VisitVarDecl(D);
928 }
929 
930 void DeclPrinter::VisitFileScopeAsmDecl(FileScopeAsmDecl *D) {
931   Out << "__asm (";
932   D->getAsmString()->printPretty(Out, nullptr, Policy, Indentation, "\n",
933                                  &Context);
934   Out << ")";
935 }
936 
937 void DeclPrinter::VisitImportDecl(ImportDecl *D) {
938   Out << "@import " << D->getImportedModule()->getFullModuleName()
939       << ";\n";
940 }
941 
942 void DeclPrinter::VisitStaticAssertDecl(StaticAssertDecl *D) {
943   Out << "static_assert(";
944   D->getAssertExpr()->printPretty(Out, nullptr, Policy, Indentation, "\n",
945                                   &Context);
946   if (StringLiteral *SL = D->getMessage()) {
947     Out << ", ";
948     SL->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
949   }
950   Out << ")";
951 }
952 
953 //----------------------------------------------------------------------------
954 // C++ declarations
955 //----------------------------------------------------------------------------
956 void DeclPrinter::VisitNamespaceDecl(NamespaceDecl *D) {
957   if (D->isInline())
958     Out << "inline ";
959 
960   Out << "namespace ";
961   if (D->getDeclName())
962     Out << D->getDeclName() << ' ';
963   Out << "{\n";
964 
965   VisitDeclContext(D);
966   Indent() << "}";
967 }
968 
969 void DeclPrinter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
970   Out << "using namespace ";
971   if (D->getQualifier())
972     D->getQualifier()->print(Out, Policy);
973   Out << *D->getNominatedNamespaceAsWritten();
974 }
975 
976 void DeclPrinter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
977   Out << "namespace " << *D << " = ";
978   if (D->getQualifier())
979     D->getQualifier()->print(Out, Policy);
980   Out << *D->getAliasedNamespace();
981 }
982 
983 void DeclPrinter::VisitEmptyDecl(EmptyDecl *D) {
984   prettyPrintAttributes(D);
985 }
986 
987 void DeclPrinter::VisitCXXRecordDecl(CXXRecordDecl *D) {
988   // FIXME: add printing of pragma attributes if required.
989   if (!Policy.SuppressSpecifiers && D->isModulePrivate())
990     Out << "__module_private__ ";
991   Out << D->getKindName();
992 
993   prettyPrintAttributes(D);
994 
995   if (D->getIdentifier()) {
996     Out << ' ' << *D;
997 
998     if (auto S = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
999       ArrayRef<TemplateArgument> Args = S->getTemplateArgs().asArray();
1000       if (!Policy.PrintCanonicalTypes)
1001         if (const auto* TSI = S->getTypeAsWritten())
1002           if (const auto *TST =
1003                   dyn_cast<TemplateSpecializationType>(TSI->getType()))
1004             Args = TST->template_arguments();
1005       printTemplateArguments(
1006           Args, S->getSpecializedTemplate()->getTemplateParameters());
1007     }
1008   }
1009 
1010   if (auto *Def = D->getDefinition()) {
1011       if (D->hasAttr<FinalAttr>()) {
1012           Out << " final";
1013       }
1014   }
1015 
1016   if (D->isCompleteDefinition()) {
1017     // Print the base classes
1018     if (D->getNumBases()) {
1019       Out << " : ";
1020       for (CXXRecordDecl::base_class_iterator Base = D->bases_begin(),
1021              BaseEnd = D->bases_end(); Base != BaseEnd; ++Base) {
1022         if (Base != D->bases_begin())
1023           Out << ", ";
1024 
1025         if (Base->isVirtual())
1026           Out << "virtual ";
1027 
1028         AccessSpecifier AS = Base->getAccessSpecifierAsWritten();
1029         if (AS != AS_none) {
1030           Print(AS);
1031           Out << " ";
1032         }
1033         Out << Base->getType().getAsString(Policy);
1034 
1035         if (Base->isPackExpansion())
1036           Out << "...";
1037       }
1038     }
1039 
1040     // Print the class definition
1041     // FIXME: Doesn't print access specifiers, e.g., "public:"
1042     if (Policy.TerseOutput) {
1043       Out << " {}";
1044     } else {
1045       Out << " {\n";
1046       VisitDeclContext(D);
1047       Indent() << "}";
1048     }
1049   }
1050 }
1051 
1052 void DeclPrinter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1053   const char *l;
1054   if (D->getLanguage() == LinkageSpecDecl::lang_c)
1055     l = "C";
1056   else {
1057     assert(D->getLanguage() == LinkageSpecDecl::lang_cxx &&
1058            "unknown language in linkage specification");
1059     l = "C++";
1060   }
1061 
1062   Out << "extern \"" << l << "\" ";
1063   if (D->hasBraces()) {
1064     Out << "{\n";
1065     VisitDeclContext(D);
1066     Indent() << "}";
1067   } else
1068     Visit(*D->decls_begin());
1069 }
1070 
1071 void DeclPrinter::printTemplateParameters(const TemplateParameterList *Params,
1072                                           bool OmitTemplateKW) {
1073   assert(Params);
1074 
1075   if (!OmitTemplateKW)
1076     Out << "template ";
1077   Out << '<';
1078 
1079   bool NeedComma = false;
1080   for (const Decl *Param : *Params) {
1081     if (Param->isImplicit())
1082       continue;
1083 
1084     if (NeedComma)
1085       Out << ", ";
1086     else
1087       NeedComma = true;
1088 
1089     if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
1090       VisitTemplateTypeParmDecl(TTP);
1091     } else if (auto NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1092       VisitNonTypeTemplateParmDecl(NTTP);
1093     } else if (auto TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
1094       VisitTemplateDecl(TTPD);
1095       // FIXME: print the default argument, if present.
1096     }
1097   }
1098 
1099   Out << '>';
1100   if (!OmitTemplateKW)
1101     Out << ' ';
1102 }
1103 
1104 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgument> Args,
1105                                          const TemplateParameterList *Params) {
1106   Out << "<";
1107   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1108     if (I)
1109       Out << ", ";
1110     if (!Params)
1111       Args[I].print(Policy, Out, /*IncludeType*/ true);
1112     else
1113       Args[I].print(Policy, Out,
1114                     TemplateParameterList::shouldIncludeTypeForArgument(
1115                         Policy, Params, I));
1116   }
1117   Out << ">";
1118 }
1119 
1120 void DeclPrinter::printTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
1121                                          const TemplateParameterList *Params) {
1122   Out << "<";
1123   for (size_t I = 0, E = Args.size(); I < E; ++I) {
1124     if (I)
1125       Out << ", ";
1126     if (!Params)
1127       Args[I].getArgument().print(Policy, Out, /*IncludeType*/ true);
1128     else
1129       Args[I].getArgument().print(
1130           Policy, Out,
1131           TemplateParameterList::shouldIncludeTypeForArgument(Policy, Params,
1132                                                               I));
1133   }
1134   Out << ">";
1135 }
1136 
1137 void DeclPrinter::VisitTemplateDecl(const TemplateDecl *D) {
1138   printTemplateParameters(D->getTemplateParameters());
1139 
1140   if (const TemplateTemplateParmDecl *TTP =
1141         dyn_cast<TemplateTemplateParmDecl>(D)) {
1142     Out << "class";
1143 
1144     if (TTP->isParameterPack())
1145       Out << " ...";
1146     else if (TTP->getDeclName())
1147       Out << ' ';
1148 
1149     if (TTP->getDeclName()) {
1150       if (Policy.CleanUglifiedParameters && TTP->getIdentifier())
1151         Out << TTP->getIdentifier()->deuglifiedName();
1152       else
1153         Out << TTP->getDeclName();
1154     }
1155   } else if (auto *TD = D->getTemplatedDecl())
1156     Visit(TD);
1157   else if (const auto *Concept = dyn_cast<ConceptDecl>(D)) {
1158     Out << "concept " << Concept->getName() << " = " ;
1159     Concept->getConstraintExpr()->printPretty(Out, nullptr, Policy, Indentation,
1160                                               "\n", &Context);
1161   }
1162 }
1163 
1164 void DeclPrinter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1165   prettyPrintPragmas(D->getTemplatedDecl());
1166   // Print any leading template parameter lists.
1167   if (const FunctionDecl *FD = D->getTemplatedDecl()) {
1168     for (unsigned I = 0, NumTemplateParams = FD->getNumTemplateParameterLists();
1169          I < NumTemplateParams; ++I)
1170       printTemplateParameters(FD->getTemplateParameterList(I));
1171   }
1172   VisitRedeclarableTemplateDecl(D);
1173   // Declare target attribute is special one, natural spelling for the pragma
1174   // assumes "ending" construct so print it here.
1175   if (D->getTemplatedDecl()->hasAttr<OMPDeclareTargetDeclAttr>())
1176     Out << "#pragma omp end declare target\n";
1177 
1178   // Never print "instantiations" for deduction guides (they don't really
1179   // have them).
1180   if (PrintInstantiation &&
1181       !isa<CXXDeductionGuideDecl>(D->getTemplatedDecl())) {
1182     FunctionDecl *PrevDecl = D->getTemplatedDecl();
1183     const FunctionDecl *Def;
1184     if (PrevDecl->isDefined(Def) && Def != PrevDecl)
1185       return;
1186     for (auto *I : D->specializations())
1187       if (I->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) {
1188         if (!PrevDecl->isThisDeclarationADefinition())
1189           Out << ";\n";
1190         Indent();
1191         prettyPrintPragmas(I);
1192         Visit(I);
1193       }
1194   }
1195 }
1196 
1197 void DeclPrinter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1198   VisitRedeclarableTemplateDecl(D);
1199 
1200   if (PrintInstantiation) {
1201     for (auto *I : D->specializations())
1202       if (I->getSpecializationKind() == TSK_ImplicitInstantiation) {
1203         if (D->isThisDeclarationADefinition())
1204           Out << ";";
1205         Out << "\n";
1206         Indent();
1207         Visit(I);
1208       }
1209   }
1210 }
1211 
1212 void DeclPrinter::VisitClassTemplateSpecializationDecl(
1213                                            ClassTemplateSpecializationDecl *D) {
1214   Out << "template<> ";
1215   VisitCXXRecordDecl(D);
1216 }
1217 
1218 void DeclPrinter::VisitClassTemplatePartialSpecializationDecl(
1219                                     ClassTemplatePartialSpecializationDecl *D) {
1220   printTemplateParameters(D->getTemplateParameters());
1221   VisitCXXRecordDecl(D);
1222 }
1223 
1224 //----------------------------------------------------------------------------
1225 // Objective-C declarations
1226 //----------------------------------------------------------------------------
1227 
1228 void DeclPrinter::PrintObjCMethodType(ASTContext &Ctx,
1229                                       Decl::ObjCDeclQualifier Quals,
1230                                       QualType T) {
1231   Out << '(';
1232   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_In)
1233     Out << "in ";
1234   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Inout)
1235     Out << "inout ";
1236   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Out)
1237     Out << "out ";
1238   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Bycopy)
1239     Out << "bycopy ";
1240   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Byref)
1241     Out << "byref ";
1242   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_Oneway)
1243     Out << "oneway ";
1244   if (Quals & Decl::ObjCDeclQualifier::OBJC_TQ_CSNullability) {
1245     if (auto nullability = AttributedType::stripOuterNullability(T))
1246       Out << getNullabilitySpelling(*nullability, true) << ' ';
1247   }
1248 
1249   Out << Ctx.getUnqualifiedObjCPointerType(T).getAsString(Policy);
1250   Out << ')';
1251 }
1252 
1253 void DeclPrinter::PrintObjCTypeParams(ObjCTypeParamList *Params) {
1254   Out << "<";
1255   unsigned First = true;
1256   for (auto *Param : *Params) {
1257     if (First) {
1258       First = false;
1259     } else {
1260       Out << ", ";
1261     }
1262 
1263     switch (Param->getVariance()) {
1264     case ObjCTypeParamVariance::Invariant:
1265       break;
1266 
1267     case ObjCTypeParamVariance::Covariant:
1268       Out << "__covariant ";
1269       break;
1270 
1271     case ObjCTypeParamVariance::Contravariant:
1272       Out << "__contravariant ";
1273       break;
1274     }
1275 
1276     Out << Param->getDeclName();
1277 
1278     if (Param->hasExplicitBound()) {
1279       Out << " : " << Param->getUnderlyingType().getAsString(Policy);
1280     }
1281   }
1282   Out << ">";
1283 }
1284 
1285 void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
1286   if (OMD->isInstanceMethod())
1287     Out << "- ";
1288   else
1289     Out << "+ ";
1290   if (!OMD->getReturnType().isNull()) {
1291     PrintObjCMethodType(OMD->getASTContext(), OMD->getObjCDeclQualifier(),
1292                         OMD->getReturnType());
1293   }
1294 
1295   std::string name = OMD->getSelector().getAsString();
1296   std::string::size_type pos, lastPos = 0;
1297   for (const auto *PI : OMD->parameters()) {
1298     // FIXME: selector is missing here!
1299     pos = name.find_first_of(':', lastPos);
1300     if (lastPos != 0)
1301       Out << " ";
1302     Out << name.substr(lastPos, pos - lastPos) << ':';
1303     PrintObjCMethodType(OMD->getASTContext(),
1304                         PI->getObjCDeclQualifier(),
1305                         PI->getType());
1306     Out << *PI;
1307     lastPos = pos + 1;
1308   }
1309 
1310   if (OMD->param_begin() == OMD->param_end())
1311     Out << name;
1312 
1313   if (OMD->isVariadic())
1314       Out << ", ...";
1315 
1316   prettyPrintAttributes(OMD);
1317 
1318   if (OMD->getBody() && !Policy.TerseOutput) {
1319     Out << ' ';
1320     OMD->getBody()->printPretty(Out, nullptr, Policy, Indentation, "\n",
1321                                 &Context);
1322   }
1323   else if (Policy.PolishForDeclaration)
1324     Out << ';';
1325 }
1326 
1327 void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
1328   std::string I = OID->getNameAsString();
1329   ObjCInterfaceDecl *SID = OID->getSuperClass();
1330 
1331   bool eolnOut = false;
1332   if (SID)
1333     Out << "@implementation " << I << " : " << *SID;
1334   else
1335     Out << "@implementation " << I;
1336 
1337   if (OID->ivar_size() > 0) {
1338     Out << "{\n";
1339     eolnOut = true;
1340     Indentation += Policy.Indentation;
1341     for (const auto *I : OID->ivars()) {
1342       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1343                     getAsString(Policy) << ' ' << *I << ";\n";
1344     }
1345     Indentation -= Policy.Indentation;
1346     Out << "}\n";
1347   }
1348   else if (SID || (OID->decls_begin() != OID->decls_end())) {
1349     Out << "\n";
1350     eolnOut = true;
1351   }
1352   VisitDeclContext(OID, false);
1353   if (!eolnOut)
1354     Out << "\n";
1355   Out << "@end";
1356 }
1357 
1358 void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
1359   std::string I = OID->getNameAsString();
1360   ObjCInterfaceDecl *SID = OID->getSuperClass();
1361 
1362   if (!OID->isThisDeclarationADefinition()) {
1363     Out << "@class " << I;
1364 
1365     if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1366       PrintObjCTypeParams(TypeParams);
1367     }
1368 
1369     Out << ";";
1370     return;
1371   }
1372   bool eolnOut = false;
1373   Out << "@interface " << I;
1374 
1375   if (auto TypeParams = OID->getTypeParamListAsWritten()) {
1376     PrintObjCTypeParams(TypeParams);
1377   }
1378 
1379   if (SID)
1380     Out << " : " << QualType(OID->getSuperClassType(), 0).getAsString(Policy);
1381 
1382   // Protocols?
1383   const ObjCList<ObjCProtocolDecl> &Protocols = OID->getReferencedProtocols();
1384   if (!Protocols.empty()) {
1385     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1386          E = Protocols.end(); I != E; ++I)
1387       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1388     Out << "> ";
1389   }
1390 
1391   if (OID->ivar_size() > 0) {
1392     Out << "{\n";
1393     eolnOut = true;
1394     Indentation += Policy.Indentation;
1395     for (const auto *I : OID->ivars()) {
1396       Indent() << I->getASTContext()
1397                       .getUnqualifiedObjCPointerType(I->getType())
1398                       .getAsString(Policy) << ' ' << *I << ";\n";
1399     }
1400     Indentation -= Policy.Indentation;
1401     Out << "}\n";
1402   }
1403   else if (SID || (OID->decls_begin() != OID->decls_end())) {
1404     Out << "\n";
1405     eolnOut = true;
1406   }
1407 
1408   VisitDeclContext(OID, false);
1409   if (!eolnOut)
1410     Out << "\n";
1411   Out << "@end";
1412   // FIXME: implement the rest...
1413 }
1414 
1415 void DeclPrinter::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
1416   if (!PID->isThisDeclarationADefinition()) {
1417     Out << "@protocol " << *PID << ";\n";
1418     return;
1419   }
1420   // Protocols?
1421   const ObjCList<ObjCProtocolDecl> &Protocols = PID->getReferencedProtocols();
1422   if (!Protocols.empty()) {
1423     Out << "@protocol " << *PID;
1424     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
1425          E = Protocols.end(); I != E; ++I)
1426       Out << (I == Protocols.begin() ? '<' : ',') << **I;
1427     Out << ">\n";
1428   } else
1429     Out << "@protocol " << *PID << '\n';
1430   VisitDeclContext(PID, false);
1431   Out << "@end";
1432 }
1433 
1434 void DeclPrinter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *PID) {
1435   Out << "@implementation ";
1436   if (const auto *CID = PID->getClassInterface())
1437     Out << *CID;
1438   else
1439     Out << "<<error-type>>";
1440   Out << '(' << *PID << ")\n";
1441 
1442   VisitDeclContext(PID, false);
1443   Out << "@end";
1444   // FIXME: implement the rest...
1445 }
1446 
1447 void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
1448   Out << "@interface ";
1449   if (const auto *CID = PID->getClassInterface())
1450     Out << *CID;
1451   else
1452     Out << "<<error-type>>";
1453   if (auto TypeParams = PID->getTypeParamList()) {
1454     PrintObjCTypeParams(TypeParams);
1455   }
1456   Out << "(" << *PID << ")\n";
1457   if (PID->ivar_size() > 0) {
1458     Out << "{\n";
1459     Indentation += Policy.Indentation;
1460     for (const auto *I : PID->ivars())
1461       Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
1462                     getAsString(Policy) << ' ' << *I << ";\n";
1463     Indentation -= Policy.Indentation;
1464     Out << "}\n";
1465   }
1466 
1467   VisitDeclContext(PID, false);
1468   Out << "@end";
1469 
1470   // FIXME: implement the rest...
1471 }
1472 
1473 void DeclPrinter::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *AID) {
1474   Out << "@compatibility_alias " << *AID
1475       << ' ' << *AID->getClassInterface() << ";\n";
1476 }
1477 
1478 /// PrintObjCPropertyDecl - print a property declaration.
1479 ///
1480 /// Print attributes in the following order:
1481 /// - class
1482 /// - nonatomic | atomic
1483 /// - assign | retain | strong | copy | weak | unsafe_unretained
1484 /// - readwrite | readonly
1485 /// - getter & setter
1486 /// - nullability
1487 void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
1488   if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Required)
1489     Out << "@required\n";
1490   else if (PDecl->getPropertyImplementation() == ObjCPropertyDecl::Optional)
1491     Out << "@optional\n";
1492 
1493   QualType T = PDecl->getType();
1494 
1495   Out << "@property";
1496   if (PDecl->getPropertyAttributes() != ObjCPropertyAttribute::kind_noattr) {
1497     bool first = true;
1498     Out << "(";
1499     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_class) {
1500       Out << (first ? "" : ", ") << "class";
1501       first = false;
1502     }
1503 
1504     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_direct) {
1505       Out << (first ? "" : ", ") << "direct";
1506       first = false;
1507     }
1508 
1509     if (PDecl->getPropertyAttributes() &
1510         ObjCPropertyAttribute::kind_nonatomic) {
1511       Out << (first ? "" : ", ") << "nonatomic";
1512       first = false;
1513     }
1514     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_atomic) {
1515       Out << (first ? "" : ", ") << "atomic";
1516       first = false;
1517     }
1518 
1519     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_assign) {
1520       Out << (first ? "" : ", ") << "assign";
1521       first = false;
1522     }
1523     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_retain) {
1524       Out << (first ? "" : ", ") << "retain";
1525       first = false;
1526     }
1527 
1528     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_strong) {
1529       Out << (first ? "" : ", ") << "strong";
1530       first = false;
1531     }
1532     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_copy) {
1533       Out << (first ? "" : ", ") << "copy";
1534       first = false;
1535     }
1536     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak) {
1537       Out << (first ? "" : ", ") << "weak";
1538       first = false;
1539     }
1540     if (PDecl->getPropertyAttributes() &
1541         ObjCPropertyAttribute::kind_unsafe_unretained) {
1542       Out << (first ? "" : ", ") << "unsafe_unretained";
1543       first = false;
1544     }
1545 
1546     if (PDecl->getPropertyAttributes() &
1547         ObjCPropertyAttribute::kind_readwrite) {
1548       Out << (first ? "" : ", ") << "readwrite";
1549       first = false;
1550     }
1551     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_readonly) {
1552       Out << (first ? "" : ", ") << "readonly";
1553       first = false;
1554     }
1555 
1556     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_getter) {
1557       Out << (first ? "" : ", ") << "getter = ";
1558       PDecl->getGetterName().print(Out);
1559       first = false;
1560     }
1561     if (PDecl->getPropertyAttributes() & ObjCPropertyAttribute::kind_setter) {
1562       Out << (first ? "" : ", ") << "setter = ";
1563       PDecl->getSetterName().print(Out);
1564       first = false;
1565     }
1566 
1567     if (PDecl->getPropertyAttributes() &
1568         ObjCPropertyAttribute::kind_nullability) {
1569       if (auto nullability = AttributedType::stripOuterNullability(T)) {
1570         if (*nullability == NullabilityKind::Unspecified &&
1571             (PDecl->getPropertyAttributes() &
1572              ObjCPropertyAttribute::kind_null_resettable)) {
1573           Out << (first ? "" : ", ") << "null_resettable";
1574         } else {
1575           Out << (first ? "" : ", ")
1576               << getNullabilitySpelling(*nullability, true);
1577         }
1578         first = false;
1579       }
1580     }
1581 
1582     (void) first; // Silence dead store warning due to idiomatic code.
1583     Out << ")";
1584   }
1585   std::string TypeStr = PDecl->getASTContext().getUnqualifiedObjCPointerType(T).
1586       getAsString(Policy);
1587   Out << ' ' << TypeStr;
1588   if (!StringRef(TypeStr).endswith("*"))
1589     Out << ' ';
1590   Out << *PDecl;
1591   if (Policy.PolishForDeclaration)
1592     Out << ';';
1593 }
1594 
1595 void DeclPrinter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *PID) {
1596   if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize)
1597     Out << "@synthesize ";
1598   else
1599     Out << "@dynamic ";
1600   Out << *PID->getPropertyDecl();
1601   if (PID->getPropertyIvarDecl())
1602     Out << '=' << *PID->getPropertyIvarDecl();
1603 }
1604 
1605 void DeclPrinter::VisitUsingDecl(UsingDecl *D) {
1606   if (!D->isAccessDeclaration())
1607     Out << "using ";
1608   if (D->hasTypename())
1609     Out << "typename ";
1610   D->getQualifier()->print(Out, Policy);
1611 
1612   // Use the correct record name when the using declaration is used for
1613   // inheriting constructors.
1614   for (const auto *Shadow : D->shadows()) {
1615     if (const auto *ConstructorShadow =
1616             dyn_cast<ConstructorUsingShadowDecl>(Shadow)) {
1617       assert(Shadow->getDeclContext() == ConstructorShadow->getDeclContext());
1618       Out << *ConstructorShadow->getNominatedBaseClass();
1619       return;
1620     }
1621   }
1622   Out << *D;
1623 }
1624 
1625 void DeclPrinter::VisitUsingEnumDecl(UsingEnumDecl *D) {
1626   Out << "using enum " << D->getEnumDecl();
1627 }
1628 
1629 void
1630 DeclPrinter::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
1631   Out << "using typename ";
1632   D->getQualifier()->print(Out, Policy);
1633   Out << D->getDeclName();
1634 }
1635 
1636 void DeclPrinter::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1637   if (!D->isAccessDeclaration())
1638     Out << "using ";
1639   D->getQualifier()->print(Out, Policy);
1640   Out << D->getDeclName();
1641 }
1642 
1643 void DeclPrinter::VisitUsingShadowDecl(UsingShadowDecl *D) {
1644   // ignore
1645 }
1646 
1647 void DeclPrinter::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1648   Out << "#pragma omp threadprivate";
1649   if (!D->varlist_empty()) {
1650     for (OMPThreadPrivateDecl::varlist_iterator I = D->varlist_begin(),
1651                                                 E = D->varlist_end();
1652                                                 I != E; ++I) {
1653       Out << (I == D->varlist_begin() ? '(' : ',');
1654       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1655       ND->printQualifiedName(Out);
1656     }
1657     Out << ")";
1658   }
1659 }
1660 
1661 void DeclPrinter::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
1662   Out << "#pragma omp allocate";
1663   if (!D->varlist_empty()) {
1664     for (OMPAllocateDecl::varlist_iterator I = D->varlist_begin(),
1665                                            E = D->varlist_end();
1666          I != E; ++I) {
1667       Out << (I == D->varlist_begin() ? '(' : ',');
1668       NamedDecl *ND = cast<DeclRefExpr>(*I)->getDecl();
1669       ND->printQualifiedName(Out);
1670     }
1671     Out << ")";
1672   }
1673   if (!D->clauselist_empty()) {
1674     OMPClausePrinter Printer(Out, Policy);
1675     for (OMPClause *C : D->clauselists()) {
1676       Out << " ";
1677       Printer.Visit(C);
1678     }
1679   }
1680 }
1681 
1682 void DeclPrinter::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
1683   Out << "#pragma omp requires ";
1684   if (!D->clauselist_empty()) {
1685     OMPClausePrinter Printer(Out, Policy);
1686     for (auto I = D->clauselist_begin(), E = D->clauselist_end(); I != E; ++I)
1687       Printer.Visit(*I);
1688   }
1689 }
1690 
1691 void DeclPrinter::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
1692   if (!D->isInvalidDecl()) {
1693     Out << "#pragma omp declare reduction (";
1694     if (D->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) {
1695       const char *OpName =
1696           getOperatorSpelling(D->getDeclName().getCXXOverloadedOperator());
1697       assert(OpName && "not an overloaded operator");
1698       Out << OpName;
1699     } else {
1700       assert(D->getDeclName().isIdentifier());
1701       D->printName(Out);
1702     }
1703     Out << " : ";
1704     D->getType().print(Out, Policy);
1705     Out << " : ";
1706     D->getCombiner()->printPretty(Out, nullptr, Policy, 0, "\n", &Context);
1707     Out << ")";
1708     if (auto *Init = D->getInitializer()) {
1709       Out << " initializer(";
1710       switch (D->getInitializerKind()) {
1711       case OMPDeclareReductionDecl::DirectInit:
1712         Out << "omp_priv(";
1713         break;
1714       case OMPDeclareReductionDecl::CopyInit:
1715         Out << "omp_priv = ";
1716         break;
1717       case OMPDeclareReductionDecl::CallInit:
1718         break;
1719       }
1720       Init->printPretty(Out, nullptr, Policy, 0, "\n", &Context);
1721       if (D->getInitializerKind() == OMPDeclareReductionDecl::DirectInit)
1722         Out << ")";
1723       Out << ")";
1724     }
1725   }
1726 }
1727 
1728 void DeclPrinter::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
1729   if (!D->isInvalidDecl()) {
1730     Out << "#pragma omp declare mapper (";
1731     D->printName(Out);
1732     Out << " : ";
1733     D->getType().print(Out, Policy);
1734     Out << " ";
1735     Out << D->getVarName();
1736     Out << ")";
1737     if (!D->clauselist_empty()) {
1738       OMPClausePrinter Printer(Out, Policy);
1739       for (auto *C : D->clauselists()) {
1740         Out << " ";
1741         Printer.Visit(C);
1742       }
1743     }
1744   }
1745 }
1746 
1747 void DeclPrinter::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
1748   D->getInit()->printPretty(Out, nullptr, Policy, Indentation, "\n", &Context);
1749 }
1750 
1751 void DeclPrinter::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *TTP) {
1752   if (const TypeConstraint *TC = TTP->getTypeConstraint())
1753     TC->print(Out, Policy);
1754   else if (TTP->wasDeclaredWithTypename())
1755     Out << "typename";
1756   else
1757     Out << "class";
1758 
1759   if (TTP->isParameterPack())
1760     Out << " ...";
1761   else if (TTP->getDeclName())
1762     Out << ' ';
1763 
1764   if (TTP->getDeclName()) {
1765     if (Policy.CleanUglifiedParameters && TTP->getIdentifier())
1766       Out << TTP->getIdentifier()->deuglifiedName();
1767     else
1768       Out << TTP->getDeclName();
1769   }
1770 
1771   if (TTP->hasDefaultArgument()) {
1772     Out << " = ";
1773     Out << TTP->getDefaultArgument().getAsString(Policy);
1774   }
1775 }
1776 
1777 void DeclPrinter::VisitNonTypeTemplateParmDecl(
1778     const NonTypeTemplateParmDecl *NTTP) {
1779   StringRef Name;
1780   if (IdentifierInfo *II = NTTP->getIdentifier())
1781     Name =
1782         Policy.CleanUglifiedParameters ? II->deuglifiedName() : II->getName();
1783   printDeclType(NTTP->getType(), Name, NTTP->isParameterPack());
1784 
1785   if (NTTP->hasDefaultArgument()) {
1786     Out << " = ";
1787     NTTP->getDefaultArgument()->printPretty(Out, nullptr, Policy, Indentation,
1788                                             "\n", &Context);
1789   }
1790 }
1791