xref: /openbsd/gnu/llvm/clang/lib/AST/TypePrinter.cpp (revision 12c85518)
1 //===- TypePrinter.cpp - Pretty-Print Clang Types -------------------------===//
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 contains code to print types from Clang's type system.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Attr.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclBase.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/NestedNameSpecifier.h"
22 #include "clang/AST/PrettyPrinter.h"
23 #include "clang/AST/TemplateBase.h"
24 #include "clang/AST/TemplateName.h"
25 #include "clang/AST/TextNodeDumper.h"
26 #include "clang/AST/Type.h"
27 #include "clang/Basic/AddressSpaces.h"
28 #include "clang/Basic/ExceptionSpecificationType.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/LLVM.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/SourceLocation.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/Specifiers.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ADT/Twine.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/SaveAndRestore.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include <cassert>
46 #include <string>
47 
48 using namespace clang;
49 
50 namespace {
51 
52 /// RAII object that enables printing of the ARC __strong lifetime
53 /// qualifier.
54 class IncludeStrongLifetimeRAII {
55   PrintingPolicy &Policy;
56   bool Old;
57 
58 public:
IncludeStrongLifetimeRAII(PrintingPolicy & Policy)59   explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
60       : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
61     if (!Policy.SuppressLifetimeQualifiers)
62       Policy.SuppressStrongLifetime = false;
63   }
64 
~IncludeStrongLifetimeRAII()65   ~IncludeStrongLifetimeRAII() { Policy.SuppressStrongLifetime = Old; }
66 };
67 
68 class ParamPolicyRAII {
69   PrintingPolicy &Policy;
70   bool Old;
71 
72 public:
ParamPolicyRAII(PrintingPolicy & Policy)73   explicit ParamPolicyRAII(PrintingPolicy &Policy)
74       : Policy(Policy), Old(Policy.SuppressSpecifiers) {
75     Policy.SuppressSpecifiers = false;
76   }
77 
~ParamPolicyRAII()78   ~ParamPolicyRAII() { Policy.SuppressSpecifiers = Old; }
79 };
80 
81 class DefaultTemplateArgsPolicyRAII {
82   PrintingPolicy &Policy;
83   bool Old;
84 
85 public:
DefaultTemplateArgsPolicyRAII(PrintingPolicy & Policy)86   explicit DefaultTemplateArgsPolicyRAII(PrintingPolicy &Policy)
87       : Policy(Policy), Old(Policy.SuppressDefaultTemplateArgs) {
88     Policy.SuppressDefaultTemplateArgs = false;
89   }
90 
~DefaultTemplateArgsPolicyRAII()91   ~DefaultTemplateArgsPolicyRAII() { Policy.SuppressDefaultTemplateArgs = Old; }
92 };
93 
94 class ElaboratedTypePolicyRAII {
95   PrintingPolicy &Policy;
96   bool SuppressTagKeyword;
97   bool SuppressScope;
98 
99 public:
ElaboratedTypePolicyRAII(PrintingPolicy & Policy)100   explicit ElaboratedTypePolicyRAII(PrintingPolicy &Policy) : Policy(Policy) {
101     SuppressTagKeyword = Policy.SuppressTagKeyword;
102     SuppressScope = Policy.SuppressScope;
103     Policy.SuppressTagKeyword = true;
104     Policy.SuppressScope = true;
105   }
106 
~ElaboratedTypePolicyRAII()107   ~ElaboratedTypePolicyRAII() {
108     Policy.SuppressTagKeyword = SuppressTagKeyword;
109     Policy.SuppressScope = SuppressScope;
110   }
111 };
112 
113 class TypePrinter {
114   PrintingPolicy Policy;
115   unsigned Indentation;
116   bool HasEmptyPlaceHolder = false;
117   bool InsideCCAttribute = false;
118 
119 public:
TypePrinter(const PrintingPolicy & Policy,unsigned Indentation=0)120   explicit TypePrinter(const PrintingPolicy &Policy, unsigned Indentation = 0)
121       : Policy(Policy), Indentation(Indentation) {}
122 
123   void print(const Type *ty, Qualifiers qs, raw_ostream &OS,
124              StringRef PlaceHolder);
125   void print(QualType T, raw_ostream &OS, StringRef PlaceHolder);
126 
127   static bool canPrefixQualifiers(const Type *T, bool &NeedARCStrongQualifier);
128   void spaceBeforePlaceHolder(raw_ostream &OS);
129   void printTypeSpec(NamedDecl *D, raw_ostream &OS);
130   void printTemplateId(const TemplateSpecializationType *T, raw_ostream &OS,
131                        bool FullyQualify);
132 
133   void printBefore(QualType T, raw_ostream &OS);
134   void printAfter(QualType T, raw_ostream &OS);
135   void AppendScope(DeclContext *DC, raw_ostream &OS,
136                    DeclarationName NameInScope);
137   void printTag(TagDecl *T, raw_ostream &OS);
138   void printFunctionAfter(const FunctionType::ExtInfo &Info, raw_ostream &OS);
139 #define ABSTRACT_TYPE(CLASS, PARENT)
140 #define TYPE(CLASS, PARENT)                                                    \
141   void print##CLASS##Before(const CLASS##Type *T, raw_ostream &OS);            \
142   void print##CLASS##After(const CLASS##Type *T, raw_ostream &OS);
143 #include "clang/AST/TypeNodes.inc"
144 
145 private:
146   void printBefore(const Type *ty, Qualifiers qs, raw_ostream &OS);
147   void printAfter(const Type *ty, Qualifiers qs, raw_ostream &OS);
148 };
149 
150 } // namespace
151 
AppendTypeQualList(raw_ostream & OS,unsigned TypeQuals,bool HasRestrictKeyword)152 static void AppendTypeQualList(raw_ostream &OS, unsigned TypeQuals,
153                                bool HasRestrictKeyword) {
154   bool appendSpace = false;
155   if (TypeQuals & Qualifiers::Const) {
156     OS << "const";
157     appendSpace = true;
158   }
159   if (TypeQuals & Qualifiers::Volatile) {
160     if (appendSpace) OS << ' ';
161     OS << "volatile";
162     appendSpace = true;
163   }
164   if (TypeQuals & Qualifiers::Restrict) {
165     if (appendSpace) OS << ' ';
166     if (HasRestrictKeyword) {
167       OS << "restrict";
168     } else {
169       OS << "__restrict";
170     }
171   }
172 }
173 
spaceBeforePlaceHolder(raw_ostream & OS)174 void TypePrinter::spaceBeforePlaceHolder(raw_ostream &OS) {
175   if (!HasEmptyPlaceHolder)
176     OS << ' ';
177 }
178 
splitAccordingToPolicy(QualType QT,const PrintingPolicy & Policy)179 static SplitQualType splitAccordingToPolicy(QualType QT,
180                                             const PrintingPolicy &Policy) {
181   if (Policy.PrintCanonicalTypes)
182     QT = QT.getCanonicalType();
183   return QT.split();
184 }
185 
print(QualType t,raw_ostream & OS,StringRef PlaceHolder)186 void TypePrinter::print(QualType t, raw_ostream &OS, StringRef PlaceHolder) {
187   SplitQualType split = splitAccordingToPolicy(t, Policy);
188   print(split.Ty, split.Quals, OS, PlaceHolder);
189 }
190 
print(const Type * T,Qualifiers Quals,raw_ostream & OS,StringRef PlaceHolder)191 void TypePrinter::print(const Type *T, Qualifiers Quals, raw_ostream &OS,
192                         StringRef PlaceHolder) {
193   if (!T) {
194     OS << "NULL TYPE";
195     return;
196   }
197 
198   SaveAndRestore PHVal(HasEmptyPlaceHolder, PlaceHolder.empty());
199 
200   printBefore(T, Quals, OS);
201   OS << PlaceHolder;
202   printAfter(T, Quals, OS);
203 }
204 
canPrefixQualifiers(const Type * T,bool & NeedARCStrongQualifier)205 bool TypePrinter::canPrefixQualifiers(const Type *T,
206                                       bool &NeedARCStrongQualifier) {
207   // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
208   // so that we get "const int" instead of "int const", but we can't do this if
209   // the type is complex.  For example if the type is "int*", we *must* print
210   // "int * const", printing "const int *" is different.  Only do this when the
211   // type expands to a simple string.
212   bool CanPrefixQualifiers = false;
213   NeedARCStrongQualifier = false;
214   const Type *UnderlyingType = T;
215   if (const auto *AT = dyn_cast<AutoType>(T))
216     UnderlyingType = AT->desugar().getTypePtr();
217   if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(T))
218     UnderlyingType = Subst->getReplacementType().getTypePtr();
219   Type::TypeClass TC = UnderlyingType->getTypeClass();
220 
221   switch (TC) {
222     case Type::Auto:
223     case Type::Builtin:
224     case Type::Complex:
225     case Type::UnresolvedUsing:
226     case Type::Using:
227     case Type::Typedef:
228     case Type::TypeOfExpr:
229     case Type::TypeOf:
230     case Type::Decltype:
231     case Type::UnaryTransform:
232     case Type::Record:
233     case Type::Enum:
234     case Type::Elaborated:
235     case Type::TemplateTypeParm:
236     case Type::SubstTemplateTypeParmPack:
237     case Type::DeducedTemplateSpecialization:
238     case Type::TemplateSpecialization:
239     case Type::InjectedClassName:
240     case Type::DependentName:
241     case Type::DependentTemplateSpecialization:
242     case Type::ObjCObject:
243     case Type::ObjCTypeParam:
244     case Type::ObjCInterface:
245     case Type::Atomic:
246     case Type::Pipe:
247     case Type::BitInt:
248     case Type::DependentBitInt:
249     case Type::BTFTagAttributed:
250       CanPrefixQualifiers = true;
251       break;
252 
253     case Type::ObjCObjectPointer:
254       CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
255         T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
256       break;
257 
258     case Type::VariableArray:
259     case Type::DependentSizedArray:
260       NeedARCStrongQualifier = true;
261       [[fallthrough]];
262 
263     case Type::ConstantArray:
264     case Type::IncompleteArray:
265       return canPrefixQualifiers(
266           cast<ArrayType>(UnderlyingType)->getElementType().getTypePtr(),
267           NeedARCStrongQualifier);
268 
269     case Type::Adjusted:
270     case Type::Decayed:
271     case Type::Pointer:
272     case Type::BlockPointer:
273     case Type::LValueReference:
274     case Type::RValueReference:
275     case Type::MemberPointer:
276     case Type::DependentAddressSpace:
277     case Type::DependentVector:
278     case Type::DependentSizedExtVector:
279     case Type::Vector:
280     case Type::ExtVector:
281     case Type::ConstantMatrix:
282     case Type::DependentSizedMatrix:
283     case Type::FunctionProto:
284     case Type::FunctionNoProto:
285     case Type::Paren:
286     case Type::PackExpansion:
287     case Type::SubstTemplateTypeParm:
288     case Type::MacroQualified:
289       CanPrefixQualifiers = false;
290       break;
291 
292     case Type::Attributed: {
293       // We still want to print the address_space before the type if it is an
294       // address_space attribute.
295       const auto *AttrTy = cast<AttributedType>(UnderlyingType);
296       CanPrefixQualifiers = AttrTy->getAttrKind() == attr::AddressSpace;
297       break;
298     }
299   }
300 
301   return CanPrefixQualifiers;
302 }
303 
printBefore(QualType T,raw_ostream & OS)304 void TypePrinter::printBefore(QualType T, raw_ostream &OS) {
305   SplitQualType Split = splitAccordingToPolicy(T, Policy);
306 
307   // If we have cv1 T, where T is substituted for cv2 U, only print cv1 - cv2
308   // at this level.
309   Qualifiers Quals = Split.Quals;
310   if (const auto *Subst = dyn_cast<SubstTemplateTypeParmType>(Split.Ty))
311     Quals -= QualType(Subst, 0).getQualifiers();
312 
313   printBefore(Split.Ty, Quals, OS);
314 }
315 
316 /// Prints the part of the type string before an identifier, e.g. for
317 /// "int foo[10]" it prints "int ".
printBefore(const Type * T,Qualifiers Quals,raw_ostream & OS)318 void TypePrinter::printBefore(const Type *T,Qualifiers Quals, raw_ostream &OS) {
319   if (Policy.SuppressSpecifiers && T->isSpecifierType())
320     return;
321 
322   SaveAndRestore PrevPHIsEmpty(HasEmptyPlaceHolder);
323 
324   // Print qualifiers as appropriate.
325 
326   bool CanPrefixQualifiers = false;
327   bool NeedARCStrongQualifier = false;
328   CanPrefixQualifiers = canPrefixQualifiers(T, NeedARCStrongQualifier);
329 
330   if (CanPrefixQualifiers && !Quals.empty()) {
331     if (NeedARCStrongQualifier) {
332       IncludeStrongLifetimeRAII Strong(Policy);
333       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
334     } else {
335       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/true);
336     }
337   }
338 
339   bool hasAfterQuals = false;
340   if (!CanPrefixQualifiers && !Quals.empty()) {
341     hasAfterQuals = !Quals.isEmptyWhenPrinted(Policy);
342     if (hasAfterQuals)
343       HasEmptyPlaceHolder = false;
344   }
345 
346   switch (T->getTypeClass()) {
347 #define ABSTRACT_TYPE(CLASS, PARENT)
348 #define TYPE(CLASS, PARENT) case Type::CLASS: \
349     print##CLASS##Before(cast<CLASS##Type>(T), OS); \
350     break;
351 #include "clang/AST/TypeNodes.inc"
352   }
353 
354   if (hasAfterQuals) {
355     if (NeedARCStrongQualifier) {
356       IncludeStrongLifetimeRAII Strong(Policy);
357       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
358     } else {
359       Quals.print(OS, Policy, /*appendSpaceIfNonEmpty=*/!PrevPHIsEmpty.get());
360     }
361   }
362 }
363 
printAfter(QualType t,raw_ostream & OS)364 void TypePrinter::printAfter(QualType t, raw_ostream &OS) {
365   SplitQualType split = splitAccordingToPolicy(t, Policy);
366   printAfter(split.Ty, split.Quals, OS);
367 }
368 
369 /// Prints the part of the type string after an identifier, e.g. for
370 /// "int foo[10]" it prints "[10]".
printAfter(const Type * T,Qualifiers Quals,raw_ostream & OS)371 void TypePrinter::printAfter(const Type *T, Qualifiers Quals, raw_ostream &OS) {
372   switch (T->getTypeClass()) {
373 #define ABSTRACT_TYPE(CLASS, PARENT)
374 #define TYPE(CLASS, PARENT) case Type::CLASS: \
375     print##CLASS##After(cast<CLASS##Type>(T), OS); \
376     break;
377 #include "clang/AST/TypeNodes.inc"
378   }
379 }
380 
printBuiltinBefore(const BuiltinType * T,raw_ostream & OS)381 void TypePrinter::printBuiltinBefore(const BuiltinType *T, raw_ostream &OS) {
382   OS << T->getName(Policy);
383   spaceBeforePlaceHolder(OS);
384 }
385 
printBuiltinAfter(const BuiltinType * T,raw_ostream & OS)386 void TypePrinter::printBuiltinAfter(const BuiltinType *T, raw_ostream &OS) {}
387 
printComplexBefore(const ComplexType * T,raw_ostream & OS)388 void TypePrinter::printComplexBefore(const ComplexType *T, raw_ostream &OS) {
389   OS << "_Complex ";
390   printBefore(T->getElementType(), OS);
391 }
392 
printComplexAfter(const ComplexType * T,raw_ostream & OS)393 void TypePrinter::printComplexAfter(const ComplexType *T, raw_ostream &OS) {
394   printAfter(T->getElementType(), OS);
395 }
396 
printPointerBefore(const PointerType * T,raw_ostream & OS)397 void TypePrinter::printPointerBefore(const PointerType *T, raw_ostream &OS) {
398   IncludeStrongLifetimeRAII Strong(Policy);
399   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
400   printBefore(T->getPointeeType(), OS);
401   // Handle things like 'int (*A)[4];' correctly.
402   // FIXME: this should include vectors, but vectors use attributes I guess.
403   if (isa<ArrayType>(T->getPointeeType()))
404     OS << '(';
405   OS << '*';
406 }
407 
printPointerAfter(const PointerType * T,raw_ostream & OS)408 void TypePrinter::printPointerAfter(const PointerType *T, raw_ostream &OS) {
409   IncludeStrongLifetimeRAII Strong(Policy);
410   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
411   // Handle things like 'int (*A)[4];' correctly.
412   // FIXME: this should include vectors, but vectors use attributes I guess.
413   if (isa<ArrayType>(T->getPointeeType()))
414     OS << ')';
415   printAfter(T->getPointeeType(), OS);
416 }
417 
printBlockPointerBefore(const BlockPointerType * T,raw_ostream & OS)418 void TypePrinter::printBlockPointerBefore(const BlockPointerType *T,
419                                           raw_ostream &OS) {
420   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
421   printBefore(T->getPointeeType(), OS);
422   OS << '^';
423 }
424 
printBlockPointerAfter(const BlockPointerType * T,raw_ostream & OS)425 void TypePrinter::printBlockPointerAfter(const BlockPointerType *T,
426                                           raw_ostream &OS) {
427   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
428   printAfter(T->getPointeeType(), OS);
429 }
430 
431 // When printing a reference, the referenced type might also be a reference.
432 // If so, we want to skip that before printing the inner type.
skipTopLevelReferences(QualType T)433 static QualType skipTopLevelReferences(QualType T) {
434   if (auto *Ref = T->getAs<ReferenceType>())
435     return skipTopLevelReferences(Ref->getPointeeTypeAsWritten());
436   return T;
437 }
438 
printLValueReferenceBefore(const LValueReferenceType * T,raw_ostream & OS)439 void TypePrinter::printLValueReferenceBefore(const LValueReferenceType *T,
440                                              raw_ostream &OS) {
441   IncludeStrongLifetimeRAII Strong(Policy);
442   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
443   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
444   printBefore(Inner, OS);
445   // Handle things like 'int (&A)[4];' correctly.
446   // FIXME: this should include vectors, but vectors use attributes I guess.
447   if (isa<ArrayType>(Inner))
448     OS << '(';
449   OS << '&';
450 }
451 
printLValueReferenceAfter(const LValueReferenceType * T,raw_ostream & OS)452 void TypePrinter::printLValueReferenceAfter(const LValueReferenceType *T,
453                                             raw_ostream &OS) {
454   IncludeStrongLifetimeRAII Strong(Policy);
455   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
456   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
457   // Handle things like 'int (&A)[4];' correctly.
458   // FIXME: this should include vectors, but vectors use attributes I guess.
459   if (isa<ArrayType>(Inner))
460     OS << ')';
461   printAfter(Inner, OS);
462 }
463 
printRValueReferenceBefore(const RValueReferenceType * T,raw_ostream & OS)464 void TypePrinter::printRValueReferenceBefore(const RValueReferenceType *T,
465                                              raw_ostream &OS) {
466   IncludeStrongLifetimeRAII Strong(Policy);
467   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
468   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
469   printBefore(Inner, OS);
470   // Handle things like 'int (&&A)[4];' correctly.
471   // FIXME: this should include vectors, but vectors use attributes I guess.
472   if (isa<ArrayType>(Inner))
473     OS << '(';
474   OS << "&&";
475 }
476 
printRValueReferenceAfter(const RValueReferenceType * T,raw_ostream & OS)477 void TypePrinter::printRValueReferenceAfter(const RValueReferenceType *T,
478                                             raw_ostream &OS) {
479   IncludeStrongLifetimeRAII Strong(Policy);
480   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
481   QualType Inner = skipTopLevelReferences(T->getPointeeTypeAsWritten());
482   // Handle things like 'int (&&A)[4];' correctly.
483   // FIXME: this should include vectors, but vectors use attributes I guess.
484   if (isa<ArrayType>(Inner))
485     OS << ')';
486   printAfter(Inner, OS);
487 }
488 
printMemberPointerBefore(const MemberPointerType * T,raw_ostream & OS)489 void TypePrinter::printMemberPointerBefore(const MemberPointerType *T,
490                                            raw_ostream &OS) {
491   IncludeStrongLifetimeRAII Strong(Policy);
492   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
493   printBefore(T->getPointeeType(), OS);
494   // Handle things like 'int (Cls::*A)[4];' correctly.
495   // FIXME: this should include vectors, but vectors use attributes I guess.
496   if (isa<ArrayType>(T->getPointeeType()))
497     OS << '(';
498 
499   PrintingPolicy InnerPolicy(Policy);
500   InnerPolicy.IncludeTagDefinition = false;
501   TypePrinter(InnerPolicy).print(QualType(T->getClass(), 0), OS, StringRef());
502 
503   OS << "::*";
504 }
505 
printMemberPointerAfter(const MemberPointerType * T,raw_ostream & OS)506 void TypePrinter::printMemberPointerAfter(const MemberPointerType *T,
507                                           raw_ostream &OS) {
508   IncludeStrongLifetimeRAII Strong(Policy);
509   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
510   // Handle things like 'int (Cls::*A)[4];' correctly.
511   // FIXME: this should include vectors, but vectors use attributes I guess.
512   if (isa<ArrayType>(T->getPointeeType()))
513     OS << ')';
514   printAfter(T->getPointeeType(), OS);
515 }
516 
printConstantArrayBefore(const ConstantArrayType * T,raw_ostream & OS)517 void TypePrinter::printConstantArrayBefore(const ConstantArrayType *T,
518                                            raw_ostream &OS) {
519   IncludeStrongLifetimeRAII Strong(Policy);
520   printBefore(T->getElementType(), OS);
521 }
522 
printConstantArrayAfter(const ConstantArrayType * T,raw_ostream & OS)523 void TypePrinter::printConstantArrayAfter(const ConstantArrayType *T,
524                                           raw_ostream &OS) {
525   OS << '[';
526   if (T->getIndexTypeQualifiers().hasQualifiers()) {
527     AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(),
528                        Policy.Restrict);
529     OS << ' ';
530   }
531 
532   if (T->getSizeModifier() == ArrayType::Static)
533     OS << "static ";
534 
535   OS << T->getSize().getZExtValue() << ']';
536   printAfter(T->getElementType(), OS);
537 }
538 
printIncompleteArrayBefore(const IncompleteArrayType * T,raw_ostream & OS)539 void TypePrinter::printIncompleteArrayBefore(const IncompleteArrayType *T,
540                                              raw_ostream &OS) {
541   IncludeStrongLifetimeRAII Strong(Policy);
542   printBefore(T->getElementType(), OS);
543 }
544 
printIncompleteArrayAfter(const IncompleteArrayType * T,raw_ostream & OS)545 void TypePrinter::printIncompleteArrayAfter(const IncompleteArrayType *T,
546                                             raw_ostream &OS) {
547   OS << "[]";
548   printAfter(T->getElementType(), OS);
549 }
550 
printVariableArrayBefore(const VariableArrayType * T,raw_ostream & OS)551 void TypePrinter::printVariableArrayBefore(const VariableArrayType *T,
552                                            raw_ostream &OS) {
553   IncludeStrongLifetimeRAII Strong(Policy);
554   printBefore(T->getElementType(), OS);
555 }
556 
printVariableArrayAfter(const VariableArrayType * T,raw_ostream & OS)557 void TypePrinter::printVariableArrayAfter(const VariableArrayType *T,
558                                           raw_ostream &OS) {
559   OS << '[';
560   if (T->getIndexTypeQualifiers().hasQualifiers()) {
561     AppendTypeQualList(OS, T->getIndexTypeCVRQualifiers(), Policy.Restrict);
562     OS << ' ';
563   }
564 
565   if (T->getSizeModifier() == VariableArrayType::Static)
566     OS << "static ";
567   else if (T->getSizeModifier() == VariableArrayType::Star)
568     OS << '*';
569 
570   if (T->getSizeExpr())
571     T->getSizeExpr()->printPretty(OS, nullptr, Policy);
572   OS << ']';
573 
574   printAfter(T->getElementType(), OS);
575 }
576 
printAdjustedBefore(const AdjustedType * T,raw_ostream & OS)577 void TypePrinter::printAdjustedBefore(const AdjustedType *T, raw_ostream &OS) {
578   // Print the adjusted representation, otherwise the adjustment will be
579   // invisible.
580   printBefore(T->getAdjustedType(), OS);
581 }
582 
printAdjustedAfter(const AdjustedType * T,raw_ostream & OS)583 void TypePrinter::printAdjustedAfter(const AdjustedType *T, raw_ostream &OS) {
584   printAfter(T->getAdjustedType(), OS);
585 }
586 
printDecayedBefore(const DecayedType * T,raw_ostream & OS)587 void TypePrinter::printDecayedBefore(const DecayedType *T, raw_ostream &OS) {
588   // Print as though it's a pointer.
589   printAdjustedBefore(T, OS);
590 }
591 
printDecayedAfter(const DecayedType * T,raw_ostream & OS)592 void TypePrinter::printDecayedAfter(const DecayedType *T, raw_ostream &OS) {
593   printAdjustedAfter(T, OS);
594 }
595 
printDependentSizedArrayBefore(const DependentSizedArrayType * T,raw_ostream & OS)596 void TypePrinter::printDependentSizedArrayBefore(
597                                                const DependentSizedArrayType *T,
598                                                raw_ostream &OS) {
599   IncludeStrongLifetimeRAII Strong(Policy);
600   printBefore(T->getElementType(), OS);
601 }
602 
printDependentSizedArrayAfter(const DependentSizedArrayType * T,raw_ostream & OS)603 void TypePrinter::printDependentSizedArrayAfter(
604                                                const DependentSizedArrayType *T,
605                                                raw_ostream &OS) {
606   OS << '[';
607   if (T->getSizeExpr())
608     T->getSizeExpr()->printPretty(OS, nullptr, Policy);
609   OS << ']';
610   printAfter(T->getElementType(), OS);
611 }
612 
printDependentAddressSpaceBefore(const DependentAddressSpaceType * T,raw_ostream & OS)613 void TypePrinter::printDependentAddressSpaceBefore(
614     const DependentAddressSpaceType *T, raw_ostream &OS) {
615   printBefore(T->getPointeeType(), OS);
616 }
617 
printDependentAddressSpaceAfter(const DependentAddressSpaceType * T,raw_ostream & OS)618 void TypePrinter::printDependentAddressSpaceAfter(
619     const DependentAddressSpaceType *T, raw_ostream &OS) {
620   OS << " __attribute__((address_space(";
621   if (T->getAddrSpaceExpr())
622     T->getAddrSpaceExpr()->printPretty(OS, nullptr, Policy);
623   OS << ")))";
624   printAfter(T->getPointeeType(), OS);
625 }
626 
printDependentSizedExtVectorBefore(const DependentSizedExtVectorType * T,raw_ostream & OS)627 void TypePrinter::printDependentSizedExtVectorBefore(
628                                           const DependentSizedExtVectorType *T,
629                                           raw_ostream &OS) {
630   printBefore(T->getElementType(), OS);
631 }
632 
printDependentSizedExtVectorAfter(const DependentSizedExtVectorType * T,raw_ostream & OS)633 void TypePrinter::printDependentSizedExtVectorAfter(
634                                           const DependentSizedExtVectorType *T,
635                                           raw_ostream &OS) {
636   OS << " __attribute__((ext_vector_type(";
637   if (T->getSizeExpr())
638     T->getSizeExpr()->printPretty(OS, nullptr, Policy);
639   OS << ")))";
640   printAfter(T->getElementType(), OS);
641 }
642 
printVectorBefore(const VectorType * T,raw_ostream & OS)643 void TypePrinter::printVectorBefore(const VectorType *T, raw_ostream &OS) {
644   switch (T->getVectorKind()) {
645   case VectorType::AltiVecPixel:
646     OS << "__vector __pixel ";
647     break;
648   case VectorType::AltiVecBool:
649     OS << "__vector __bool ";
650     printBefore(T->getElementType(), OS);
651     break;
652   case VectorType::AltiVecVector:
653     OS << "__vector ";
654     printBefore(T->getElementType(), OS);
655     break;
656   case VectorType::NeonVector:
657     OS << "__attribute__((neon_vector_type("
658        << T->getNumElements() << "))) ";
659     printBefore(T->getElementType(), OS);
660     break;
661   case VectorType::NeonPolyVector:
662     OS << "__attribute__((neon_polyvector_type(" <<
663           T->getNumElements() << "))) ";
664     printBefore(T->getElementType(), OS);
665     break;
666   case VectorType::GenericVector: {
667     // FIXME: We prefer to print the size directly here, but have no way
668     // to get the size of the type.
669     OS << "__attribute__((__vector_size__("
670        << T->getNumElements()
671        << " * sizeof(";
672     print(T->getElementType(), OS, StringRef());
673     OS << ")))) ";
674     printBefore(T->getElementType(), OS);
675     break;
676   }
677   case VectorType::SveFixedLengthDataVector:
678   case VectorType::SveFixedLengthPredicateVector:
679     // FIXME: We prefer to print the size directly here, but have no way
680     // to get the size of the type.
681     OS << "__attribute__((__arm_sve_vector_bits__(";
682 
683     if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
684       // Predicates take a bit per byte of the vector size, multiply by 8 to
685       // get the number of bits passed to the attribute.
686       OS << T->getNumElements() * 8;
687     else
688       OS << T->getNumElements();
689 
690     OS << " * sizeof(";
691     print(T->getElementType(), OS, StringRef());
692     // Multiply by 8 for the number of bits.
693     OS << ") * 8))) ";
694     printBefore(T->getElementType(), OS);
695   }
696 }
697 
printVectorAfter(const VectorType * T,raw_ostream & OS)698 void TypePrinter::printVectorAfter(const VectorType *T, raw_ostream &OS) {
699   printAfter(T->getElementType(), OS);
700 }
701 
printDependentVectorBefore(const DependentVectorType * T,raw_ostream & OS)702 void TypePrinter::printDependentVectorBefore(
703     const DependentVectorType *T, raw_ostream &OS) {
704   switch (T->getVectorKind()) {
705   case VectorType::AltiVecPixel:
706     OS << "__vector __pixel ";
707     break;
708   case VectorType::AltiVecBool:
709     OS << "__vector __bool ";
710     printBefore(T->getElementType(), OS);
711     break;
712   case VectorType::AltiVecVector:
713     OS << "__vector ";
714     printBefore(T->getElementType(), OS);
715     break;
716   case VectorType::NeonVector:
717     OS << "__attribute__((neon_vector_type(";
718     if (T->getSizeExpr())
719       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
720     OS << "))) ";
721     printBefore(T->getElementType(), OS);
722     break;
723   case VectorType::NeonPolyVector:
724     OS << "__attribute__((neon_polyvector_type(";
725     if (T->getSizeExpr())
726       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
727     OS << "))) ";
728     printBefore(T->getElementType(), OS);
729     break;
730   case VectorType::GenericVector: {
731     // FIXME: We prefer to print the size directly here, but have no way
732     // to get the size of the type.
733     OS << "__attribute__((__vector_size__(";
734     if (T->getSizeExpr())
735       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
736     OS << " * sizeof(";
737     print(T->getElementType(), OS, StringRef());
738     OS << ")))) ";
739     printBefore(T->getElementType(), OS);
740     break;
741   }
742   case VectorType::SveFixedLengthDataVector:
743   case VectorType::SveFixedLengthPredicateVector:
744     // FIXME: We prefer to print the size directly here, but have no way
745     // to get the size of the type.
746     OS << "__attribute__((__arm_sve_vector_bits__(";
747     if (T->getSizeExpr()) {
748       T->getSizeExpr()->printPretty(OS, nullptr, Policy);
749       if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
750         // Predicates take a bit per byte of the vector size, multiply by 8 to
751         // get the number of bits passed to the attribute.
752         OS << " * 8";
753       OS << " * sizeof(";
754       print(T->getElementType(), OS, StringRef());
755       // Multiply by 8 for the number of bits.
756       OS << ") * 8";
757     }
758     OS << "))) ";
759     printBefore(T->getElementType(), OS);
760   }
761 }
762 
printDependentVectorAfter(const DependentVectorType * T,raw_ostream & OS)763 void TypePrinter::printDependentVectorAfter(
764     const DependentVectorType *T, raw_ostream &OS) {
765   printAfter(T->getElementType(), OS);
766 }
767 
printExtVectorBefore(const ExtVectorType * T,raw_ostream & OS)768 void TypePrinter::printExtVectorBefore(const ExtVectorType *T,
769                                        raw_ostream &OS) {
770   printBefore(T->getElementType(), OS);
771 }
772 
printExtVectorAfter(const ExtVectorType * T,raw_ostream & OS)773 void TypePrinter::printExtVectorAfter(const ExtVectorType *T, raw_ostream &OS) {
774   printAfter(T->getElementType(), OS);
775   OS << " __attribute__((ext_vector_type(";
776   OS << T->getNumElements();
777   OS << ")))";
778 }
779 
printConstantMatrixBefore(const ConstantMatrixType * T,raw_ostream & OS)780 void TypePrinter::printConstantMatrixBefore(const ConstantMatrixType *T,
781                                             raw_ostream &OS) {
782   printBefore(T->getElementType(), OS);
783   OS << " __attribute__((matrix_type(";
784   OS << T->getNumRows() << ", " << T->getNumColumns();
785   OS << ")))";
786 }
787 
printConstantMatrixAfter(const ConstantMatrixType * T,raw_ostream & OS)788 void TypePrinter::printConstantMatrixAfter(const ConstantMatrixType *T,
789                                            raw_ostream &OS) {
790   printAfter(T->getElementType(), OS);
791 }
792 
printDependentSizedMatrixBefore(const DependentSizedMatrixType * T,raw_ostream & OS)793 void TypePrinter::printDependentSizedMatrixBefore(
794     const DependentSizedMatrixType *T, raw_ostream &OS) {
795   printBefore(T->getElementType(), OS);
796   OS << " __attribute__((matrix_type(";
797   if (T->getRowExpr()) {
798     T->getRowExpr()->printPretty(OS, nullptr, Policy);
799   }
800   OS << ", ";
801   if (T->getColumnExpr()) {
802     T->getColumnExpr()->printPretty(OS, nullptr, Policy);
803   }
804   OS << ")))";
805 }
806 
printDependentSizedMatrixAfter(const DependentSizedMatrixType * T,raw_ostream & OS)807 void TypePrinter::printDependentSizedMatrixAfter(
808     const DependentSizedMatrixType *T, raw_ostream &OS) {
809   printAfter(T->getElementType(), OS);
810 }
811 
812 void
printExceptionSpecification(raw_ostream & OS,const PrintingPolicy & Policy) const813 FunctionProtoType::printExceptionSpecification(raw_ostream &OS,
814                                                const PrintingPolicy &Policy)
815                                                                          const {
816   if (hasDynamicExceptionSpec()) {
817     OS << " throw(";
818     if (getExceptionSpecType() == EST_MSAny)
819       OS << "...";
820     else
821       for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
822         if (I)
823           OS << ", ";
824 
825         OS << getExceptionType(I).stream(Policy);
826       }
827     OS << ')';
828   } else if (EST_NoThrow == getExceptionSpecType()) {
829     OS << " __attribute__((nothrow))";
830   } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
831     OS << " noexcept";
832     // FIXME:Is it useful to print out the expression for a non-dependent
833     // noexcept specification?
834     if (isComputedNoexcept(getExceptionSpecType())) {
835       OS << '(';
836       if (getNoexceptExpr())
837         getNoexceptExpr()->printPretty(OS, nullptr, Policy);
838       OS << ')';
839     }
840   }
841 }
842 
printFunctionProtoBefore(const FunctionProtoType * T,raw_ostream & OS)843 void TypePrinter::printFunctionProtoBefore(const FunctionProtoType *T,
844                                            raw_ostream &OS) {
845   if (T->hasTrailingReturn()) {
846     OS << "auto ";
847     if (!HasEmptyPlaceHolder)
848       OS << '(';
849   } else {
850     // If needed for precedence reasons, wrap the inner part in grouping parens.
851     SaveAndRestore PrevPHIsEmpty(HasEmptyPlaceHolder, false);
852     printBefore(T->getReturnType(), OS);
853     if (!PrevPHIsEmpty.get())
854       OS << '(';
855   }
856 }
857 
getParameterABISpelling(ParameterABI ABI)858 StringRef clang::getParameterABISpelling(ParameterABI ABI) {
859   switch (ABI) {
860   case ParameterABI::Ordinary:
861     llvm_unreachable("asking for spelling of ordinary parameter ABI");
862   case ParameterABI::SwiftContext:
863     return "swift_context";
864   case ParameterABI::SwiftAsyncContext:
865     return "swift_async_context";
866   case ParameterABI::SwiftErrorResult:
867     return "swift_error_result";
868   case ParameterABI::SwiftIndirectResult:
869     return "swift_indirect_result";
870   }
871   llvm_unreachable("bad parameter ABI kind");
872 }
873 
printFunctionProtoAfter(const FunctionProtoType * T,raw_ostream & OS)874 void TypePrinter::printFunctionProtoAfter(const FunctionProtoType *T,
875                                           raw_ostream &OS) {
876   // If needed for precedence reasons, wrap the inner part in grouping parens.
877   if (!HasEmptyPlaceHolder)
878     OS << ')';
879   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
880 
881   OS << '(';
882   {
883     ParamPolicyRAII ParamPolicy(Policy);
884     for (unsigned i = 0, e = T->getNumParams(); i != e; ++i) {
885       if (i) OS << ", ";
886 
887       auto EPI = T->getExtParameterInfo(i);
888       if (EPI.isConsumed()) OS << "__attribute__((ns_consumed)) ";
889       if (EPI.isNoEscape())
890         OS << "__attribute__((noescape)) ";
891       auto ABI = EPI.getABI();
892       if (ABI != ParameterABI::Ordinary)
893         OS << "__attribute__((" << getParameterABISpelling(ABI) << ")) ";
894 
895       print(T->getParamType(i), OS, StringRef());
896     }
897   }
898 
899   if (T->isVariadic()) {
900     if (T->getNumParams())
901       OS << ", ";
902     OS << "...";
903   } else if (T->getNumParams() == 0 && Policy.UseVoidForZeroParams) {
904     // Do not emit int() if we have a proto, emit 'int(void)'.
905     OS << "void";
906   }
907 
908   OS << ')';
909 
910   FunctionType::ExtInfo Info = T->getExtInfo();
911 
912   printFunctionAfter(Info, OS);
913 
914   if (!T->getMethodQuals().empty())
915     OS << " " << T->getMethodQuals().getAsString();
916 
917   switch (T->getRefQualifier()) {
918   case RQ_None:
919     break;
920 
921   case RQ_LValue:
922     OS << " &";
923     break;
924 
925   case RQ_RValue:
926     OS << " &&";
927     break;
928   }
929   T->printExceptionSpecification(OS, Policy);
930 
931   if (T->hasTrailingReturn()) {
932     OS << " -> ";
933     print(T->getReturnType(), OS, StringRef());
934   } else
935     printAfter(T->getReturnType(), OS);
936 }
937 
printFunctionAfter(const FunctionType::ExtInfo & Info,raw_ostream & OS)938 void TypePrinter::printFunctionAfter(const FunctionType::ExtInfo &Info,
939                                      raw_ostream &OS) {
940   if (!InsideCCAttribute) {
941     switch (Info.getCC()) {
942     case CC_C:
943       // The C calling convention is the default on the vast majority of platforms
944       // we support.  If the user wrote it explicitly, it will usually be printed
945       // while traversing the AttributedType.  If the type has been desugared, let
946       // the canonical spelling be the implicit calling convention.
947       // FIXME: It would be better to be explicit in certain contexts, such as a
948       // cdecl function typedef used to declare a member function with the
949       // Microsoft C++ ABI.
950       break;
951     case CC_X86StdCall:
952       OS << " __attribute__((stdcall))";
953       break;
954     case CC_X86FastCall:
955       OS << " __attribute__((fastcall))";
956       break;
957     case CC_X86ThisCall:
958       OS << " __attribute__((thiscall))";
959       break;
960     case CC_X86VectorCall:
961       OS << " __attribute__((vectorcall))";
962       break;
963     case CC_X86Pascal:
964       OS << " __attribute__((pascal))";
965       break;
966     case CC_AAPCS:
967       OS << " __attribute__((pcs(\"aapcs\")))";
968       break;
969     case CC_AAPCS_VFP:
970       OS << " __attribute__((pcs(\"aapcs-vfp\")))";
971       break;
972     case CC_AArch64VectorCall:
973       OS << "__attribute__((aarch64_vector_pcs))";
974       break;
975     case CC_AArch64SVEPCS:
976       OS << "__attribute__((aarch64_sve_pcs))";
977       break;
978     case CC_AMDGPUKernelCall:
979       OS << "__attribute__((amdgpu_kernel))";
980       break;
981     case CC_IntelOclBicc:
982       OS << " __attribute__((intel_ocl_bicc))";
983       break;
984     case CC_Win64:
985       OS << " __attribute__((ms_abi))";
986       break;
987     case CC_X86_64SysV:
988       OS << " __attribute__((sysv_abi))";
989       break;
990     case CC_X86RegCall:
991       OS << " __attribute__((regcall))";
992       break;
993     case CC_SpirFunction:
994     case CC_OpenCLKernel:
995       // Do nothing. These CCs are not available as attributes.
996       break;
997     case CC_Swift:
998       OS << " __attribute__((swiftcall))";
999       break;
1000     case CC_SwiftAsync:
1001       OS << "__attribute__((swiftasynccall))";
1002       break;
1003     case CC_PreserveMost:
1004       OS << " __attribute__((preserve_most))";
1005       break;
1006     case CC_PreserveAll:
1007       OS << " __attribute__((preserve_all))";
1008       break;
1009     }
1010   }
1011 
1012   if (Info.getNoReturn())
1013     OS << " __attribute__((noreturn))";
1014   if (Info.getCmseNSCall())
1015     OS << " __attribute__((cmse_nonsecure_call))";
1016   if (Info.getProducesResult())
1017     OS << " __attribute__((ns_returns_retained))";
1018   if (Info.getRegParm())
1019     OS << " __attribute__((regparm ("
1020        << Info.getRegParm() << ")))";
1021   if (Info.getNoCallerSavedRegs())
1022     OS << " __attribute__((no_caller_saved_registers))";
1023   if (Info.getNoCfCheck())
1024     OS << " __attribute__((nocf_check))";
1025 }
1026 
printFunctionNoProtoBefore(const FunctionNoProtoType * T,raw_ostream & OS)1027 void TypePrinter::printFunctionNoProtoBefore(const FunctionNoProtoType *T,
1028                                              raw_ostream &OS) {
1029   // If needed for precedence reasons, wrap the inner part in grouping parens.
1030   SaveAndRestore PrevPHIsEmpty(HasEmptyPlaceHolder, false);
1031   printBefore(T->getReturnType(), OS);
1032   if (!PrevPHIsEmpty.get())
1033     OS << '(';
1034 }
1035 
printFunctionNoProtoAfter(const FunctionNoProtoType * T,raw_ostream & OS)1036 void TypePrinter::printFunctionNoProtoAfter(const FunctionNoProtoType *T,
1037                                             raw_ostream &OS) {
1038   // If needed for precedence reasons, wrap the inner part in grouping parens.
1039   if (!HasEmptyPlaceHolder)
1040     OS << ')';
1041   SaveAndRestore NonEmptyPH(HasEmptyPlaceHolder, false);
1042 
1043   OS << "()";
1044   printFunctionAfter(T->getExtInfo(), OS);
1045   printAfter(T->getReturnType(), OS);
1046 }
1047 
printTypeSpec(NamedDecl * D,raw_ostream & OS)1048 void TypePrinter::printTypeSpec(NamedDecl *D, raw_ostream &OS) {
1049 
1050   // Compute the full nested-name-specifier for this type.
1051   // In C, this will always be empty except when the type
1052   // being printed is anonymous within other Record.
1053   if (!Policy.SuppressScope)
1054     AppendScope(D->getDeclContext(), OS, D->getDeclName());
1055 
1056   IdentifierInfo *II = D->getIdentifier();
1057   OS << II->getName();
1058   spaceBeforePlaceHolder(OS);
1059 }
1060 
printUnresolvedUsingBefore(const UnresolvedUsingType * T,raw_ostream & OS)1061 void TypePrinter::printUnresolvedUsingBefore(const UnresolvedUsingType *T,
1062                                              raw_ostream &OS) {
1063   printTypeSpec(T->getDecl(), OS);
1064 }
1065 
printUnresolvedUsingAfter(const UnresolvedUsingType * T,raw_ostream & OS)1066 void TypePrinter::printUnresolvedUsingAfter(const UnresolvedUsingType *T,
1067                                             raw_ostream &OS) {}
1068 
printUsingBefore(const UsingType * T,raw_ostream & OS)1069 void TypePrinter::printUsingBefore(const UsingType *T, raw_ostream &OS) {
1070   // After `namespace b { using a::X }`, is the type X within B a::X or b::X?
1071   //
1072   // - b::X is more formally correct given the UsingType model
1073   // - b::X makes sense if "re-exporting" a symbol in a new namespace
1074   // - a::X makes sense if "importing" a symbol for convenience
1075   //
1076   // The "importing" use seems much more common, so we print a::X.
1077   // This could be a policy option, but the right choice seems to rest more
1078   // with the intent of the code than the caller.
1079   printTypeSpec(T->getFoundDecl()->getUnderlyingDecl(), OS);
1080 }
1081 
printUsingAfter(const UsingType * T,raw_ostream & OS)1082 void TypePrinter::printUsingAfter(const UsingType *T, raw_ostream &OS) {}
1083 
printTypedefBefore(const TypedefType * T,raw_ostream & OS)1084 void TypePrinter::printTypedefBefore(const TypedefType *T, raw_ostream &OS) {
1085   printTypeSpec(T->getDecl(), OS);
1086 }
1087 
printMacroQualifiedBefore(const MacroQualifiedType * T,raw_ostream & OS)1088 void TypePrinter::printMacroQualifiedBefore(const MacroQualifiedType *T,
1089                                             raw_ostream &OS) {
1090   StringRef MacroName = T->getMacroIdentifier()->getName();
1091   OS << MacroName << " ";
1092 
1093   // Since this type is meant to print the macro instead of the whole attribute,
1094   // we trim any attributes and go directly to the original modified type.
1095   printBefore(T->getModifiedType(), OS);
1096 }
1097 
printMacroQualifiedAfter(const MacroQualifiedType * T,raw_ostream & OS)1098 void TypePrinter::printMacroQualifiedAfter(const MacroQualifiedType *T,
1099                                            raw_ostream &OS) {
1100   printAfter(T->getModifiedType(), OS);
1101 }
1102 
printTypedefAfter(const TypedefType * T,raw_ostream & OS)1103 void TypePrinter::printTypedefAfter(const TypedefType *T, raw_ostream &OS) {}
1104 
printTypeOfExprBefore(const TypeOfExprType * T,raw_ostream & OS)1105 void TypePrinter::printTypeOfExprBefore(const TypeOfExprType *T,
1106                                         raw_ostream &OS) {
1107   OS << (T->getKind() == TypeOfKind::Unqualified ? "typeof_unqual "
1108                                                  : "typeof ");
1109   if (T->getUnderlyingExpr())
1110     T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
1111   spaceBeforePlaceHolder(OS);
1112 }
1113 
printTypeOfExprAfter(const TypeOfExprType * T,raw_ostream & OS)1114 void TypePrinter::printTypeOfExprAfter(const TypeOfExprType *T,
1115                                        raw_ostream &OS) {}
1116 
printTypeOfBefore(const TypeOfType * T,raw_ostream & OS)1117 void TypePrinter::printTypeOfBefore(const TypeOfType *T, raw_ostream &OS) {
1118   OS << (T->getKind() == TypeOfKind::Unqualified ? "typeof_unqual("
1119                                                  : "typeof(");
1120   print(T->getUnmodifiedType(), OS, StringRef());
1121   OS << ')';
1122   spaceBeforePlaceHolder(OS);
1123 }
1124 
printTypeOfAfter(const TypeOfType * T,raw_ostream & OS)1125 void TypePrinter::printTypeOfAfter(const TypeOfType *T, raw_ostream &OS) {}
1126 
printDecltypeBefore(const DecltypeType * T,raw_ostream & OS)1127 void TypePrinter::printDecltypeBefore(const DecltypeType *T, raw_ostream &OS) {
1128   OS << "decltype(";
1129   if (T->getUnderlyingExpr())
1130     T->getUnderlyingExpr()->printPretty(OS, nullptr, Policy);
1131   OS << ')';
1132   spaceBeforePlaceHolder(OS);
1133 }
1134 
printDecltypeAfter(const DecltypeType * T,raw_ostream & OS)1135 void TypePrinter::printDecltypeAfter(const DecltypeType *T, raw_ostream &OS) {}
1136 
printUnaryTransformBefore(const UnaryTransformType * T,raw_ostream & OS)1137 void TypePrinter::printUnaryTransformBefore(const UnaryTransformType *T,
1138                                             raw_ostream &OS) {
1139   IncludeStrongLifetimeRAII Strong(Policy);
1140 
1141   static llvm::DenseMap<int, const char *> Transformation = {{
1142 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait)                                  \
1143   {UnaryTransformType::Enum, "__" #Trait},
1144 #include "clang/Basic/TransformTypeTraits.def"
1145   }};
1146   OS << Transformation[T->getUTTKind()] << '(';
1147   print(T->getBaseType(), OS, StringRef());
1148   OS << ')';
1149   spaceBeforePlaceHolder(OS);
1150 }
1151 
printUnaryTransformAfter(const UnaryTransformType * T,raw_ostream & OS)1152 void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
1153                                            raw_ostream &OS) {}
1154 
printAutoBefore(const AutoType * T,raw_ostream & OS)1155 void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
1156   // If the type has been deduced, do not print 'auto'.
1157   if (!T->getDeducedType().isNull()) {
1158     printBefore(T->getDeducedType(), OS);
1159   } else {
1160     if (T->isConstrained()) {
1161       // FIXME: Track a TypeConstraint as type sugar, so that we can print the
1162       // type as it was written.
1163       T->getTypeConstraintConcept()->getDeclName().print(OS, Policy);
1164       auto Args = T->getTypeConstraintArguments();
1165       if (!Args.empty())
1166         printTemplateArgumentList(
1167             OS, Args, Policy,
1168             T->getTypeConstraintConcept()->getTemplateParameters());
1169       OS << ' ';
1170     }
1171     switch (T->getKeyword()) {
1172     case AutoTypeKeyword::Auto: OS << "auto"; break;
1173     case AutoTypeKeyword::DecltypeAuto: OS << "decltype(auto)"; break;
1174     case AutoTypeKeyword::GNUAutoType: OS << "__auto_type"; break;
1175     }
1176     spaceBeforePlaceHolder(OS);
1177   }
1178 }
1179 
printAutoAfter(const AutoType * T,raw_ostream & OS)1180 void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
1181   // If the type has been deduced, do not print 'auto'.
1182   if (!T->getDeducedType().isNull())
1183     printAfter(T->getDeducedType(), OS);
1184 }
1185 
printDeducedTemplateSpecializationBefore(const DeducedTemplateSpecializationType * T,raw_ostream & OS)1186 void TypePrinter::printDeducedTemplateSpecializationBefore(
1187     const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1188   // If the type has been deduced, print the deduced type.
1189   if (!T->getDeducedType().isNull()) {
1190     printBefore(T->getDeducedType(), OS);
1191   } else {
1192     IncludeStrongLifetimeRAII Strong(Policy);
1193     T->getTemplateName().print(OS, Policy);
1194     spaceBeforePlaceHolder(OS);
1195   }
1196 }
1197 
printDeducedTemplateSpecializationAfter(const DeducedTemplateSpecializationType * T,raw_ostream & OS)1198 void TypePrinter::printDeducedTemplateSpecializationAfter(
1199     const DeducedTemplateSpecializationType *T, raw_ostream &OS) {
1200   // If the type has been deduced, print the deduced type.
1201   if (!T->getDeducedType().isNull())
1202     printAfter(T->getDeducedType(), OS);
1203 }
1204 
printAtomicBefore(const AtomicType * T,raw_ostream & OS)1205 void TypePrinter::printAtomicBefore(const AtomicType *T, raw_ostream &OS) {
1206   IncludeStrongLifetimeRAII Strong(Policy);
1207 
1208   OS << "_Atomic(";
1209   print(T->getValueType(), OS, StringRef());
1210   OS << ')';
1211   spaceBeforePlaceHolder(OS);
1212 }
1213 
printAtomicAfter(const AtomicType * T,raw_ostream & OS)1214 void TypePrinter::printAtomicAfter(const AtomicType *T, raw_ostream &OS) {}
1215 
printPipeBefore(const PipeType * T,raw_ostream & OS)1216 void TypePrinter::printPipeBefore(const PipeType *T, raw_ostream &OS) {
1217   IncludeStrongLifetimeRAII Strong(Policy);
1218 
1219   if (T->isReadOnly())
1220     OS << "read_only ";
1221   else
1222     OS << "write_only ";
1223   OS << "pipe ";
1224   print(T->getElementType(), OS, StringRef());
1225   spaceBeforePlaceHolder(OS);
1226 }
1227 
printPipeAfter(const PipeType * T,raw_ostream & OS)1228 void TypePrinter::printPipeAfter(const PipeType *T, raw_ostream &OS) {}
1229 
printBitIntBefore(const BitIntType * T,raw_ostream & OS)1230 void TypePrinter::printBitIntBefore(const BitIntType *T, raw_ostream &OS) {
1231   if (T->isUnsigned())
1232     OS << "unsigned ";
1233   OS << "_BitInt(" << T->getNumBits() << ")";
1234   spaceBeforePlaceHolder(OS);
1235 }
1236 
printBitIntAfter(const BitIntType * T,raw_ostream & OS)1237 void TypePrinter::printBitIntAfter(const BitIntType *T, raw_ostream &OS) {}
1238 
printDependentBitIntBefore(const DependentBitIntType * T,raw_ostream & OS)1239 void TypePrinter::printDependentBitIntBefore(const DependentBitIntType *T,
1240                                              raw_ostream &OS) {
1241   if (T->isUnsigned())
1242     OS << "unsigned ";
1243   OS << "_BitInt(";
1244   T->getNumBitsExpr()->printPretty(OS, nullptr, Policy);
1245   OS << ")";
1246   spaceBeforePlaceHolder(OS);
1247 }
1248 
printDependentBitIntAfter(const DependentBitIntType * T,raw_ostream & OS)1249 void TypePrinter::printDependentBitIntAfter(const DependentBitIntType *T,
1250                                             raw_ostream &OS) {}
1251 
1252 /// Appends the given scope to the end of a string.
AppendScope(DeclContext * DC,raw_ostream & OS,DeclarationName NameInScope)1253 void TypePrinter::AppendScope(DeclContext *DC, raw_ostream &OS,
1254                               DeclarationName NameInScope) {
1255   if (DC->isTranslationUnit())
1256     return;
1257 
1258   // FIXME: Consider replacing this with NamedDecl::printNestedNameSpecifier,
1259   // which can also print names for function and method scopes.
1260   if (DC->isFunctionOrMethod())
1261     return;
1262 
1263   if (Policy.Callbacks && Policy.Callbacks->isScopeVisible(DC))
1264     return;
1265 
1266   if (const auto *NS = dyn_cast<NamespaceDecl>(DC)) {
1267     if (Policy.SuppressUnwrittenScope && NS->isAnonymousNamespace())
1268       return AppendScope(DC->getParent(), OS, NameInScope);
1269 
1270     // Only suppress an inline namespace if the name has the same lookup
1271     // results in the enclosing namespace.
1272     if (Policy.SuppressInlineNamespace && NS->isInline() && NameInScope &&
1273         NS->isRedundantInlineQualifierFor(NameInScope))
1274       return AppendScope(DC->getParent(), OS, NameInScope);
1275 
1276     AppendScope(DC->getParent(), OS, NS->getDeclName());
1277     if (NS->getIdentifier())
1278       OS << NS->getName() << "::";
1279     else
1280       OS << "(anonymous namespace)::";
1281   } else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1282     AppendScope(DC->getParent(), OS, Spec->getDeclName());
1283     IncludeStrongLifetimeRAII Strong(Policy);
1284     OS << Spec->getIdentifier()->getName();
1285     const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1286     printTemplateArgumentList(
1287         OS, TemplateArgs.asArray(), Policy,
1288         Spec->getSpecializedTemplate()->getTemplateParameters());
1289     OS << "::";
1290   } else if (const auto *Tag = dyn_cast<TagDecl>(DC)) {
1291     AppendScope(DC->getParent(), OS, Tag->getDeclName());
1292     if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
1293       OS << Typedef->getIdentifier()->getName() << "::";
1294     else if (Tag->getIdentifier())
1295       OS << Tag->getIdentifier()->getName() << "::";
1296     else
1297       return;
1298   } else {
1299     AppendScope(DC->getParent(), OS, NameInScope);
1300   }
1301 }
1302 
printTag(TagDecl * D,raw_ostream & OS)1303 void TypePrinter::printTag(TagDecl *D, raw_ostream &OS) {
1304   if (Policy.IncludeTagDefinition) {
1305     PrintingPolicy SubPolicy = Policy;
1306     SubPolicy.IncludeTagDefinition = false;
1307     D->print(OS, SubPolicy, Indentation);
1308     spaceBeforePlaceHolder(OS);
1309     return;
1310   }
1311 
1312   bool HasKindDecoration = false;
1313 
1314   // We don't print tags unless this is an elaborated type.
1315   // In C, we just assume every RecordType is an elaborated type.
1316   if (!Policy.SuppressTagKeyword && !D->getTypedefNameForAnonDecl()) {
1317     HasKindDecoration = true;
1318     OS << D->getKindName();
1319     OS << ' ';
1320   }
1321 
1322   // Compute the full nested-name-specifier for this type.
1323   // In C, this will always be empty except when the type
1324   // being printed is anonymous within other Record.
1325   if (!Policy.SuppressScope)
1326     AppendScope(D->getDeclContext(), OS, D->getDeclName());
1327 
1328   if (const IdentifierInfo *II = D->getIdentifier())
1329     OS << II->getName();
1330   else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
1331     assert(Typedef->getIdentifier() && "Typedef without identifier?");
1332     OS << Typedef->getIdentifier()->getName();
1333   } else {
1334     // Make an unambiguous representation for anonymous types, e.g.
1335     //   (anonymous enum at /usr/include/string.h:120:9)
1336     OS << (Policy.MSVCFormatting ? '`' : '(');
1337 
1338     if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
1339       OS << "lambda";
1340       HasKindDecoration = true;
1341     } else if ((isa<RecordDecl>(D) && cast<RecordDecl>(D)->isAnonymousStructOrUnion())) {
1342       OS << "anonymous";
1343     } else {
1344       OS << "unnamed";
1345     }
1346 
1347     if (Policy.AnonymousTagLocations) {
1348       // Suppress the redundant tag keyword if we just printed one.
1349       // We don't have to worry about ElaboratedTypes here because you can't
1350       // refer to an anonymous type with one.
1351       if (!HasKindDecoration)
1352         OS << " " << D->getKindName();
1353 
1354       PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
1355           D->getLocation());
1356       if (PLoc.isValid()) {
1357         OS << " at ";
1358         StringRef File = PLoc.getFilename();
1359         if (auto *Callbacks = Policy.Callbacks)
1360           OS << Callbacks->remapPath(File);
1361         else
1362           OS << File;
1363         OS << ':' << PLoc.getLine() << ':' << PLoc.getColumn();
1364       }
1365     }
1366 
1367     OS << (Policy.MSVCFormatting ? '\'' : ')');
1368   }
1369 
1370   // If this is a class template specialization, print the template
1371   // arguments.
1372   if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
1373     ArrayRef<TemplateArgument> Args;
1374     TypeSourceInfo *TAW = Spec->getTypeAsWritten();
1375     if (!Policy.PrintCanonicalTypes && TAW) {
1376       const TemplateSpecializationType *TST =
1377         cast<TemplateSpecializationType>(TAW->getType());
1378       Args = TST->template_arguments();
1379     } else {
1380       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1381       Args = TemplateArgs.asArray();
1382     }
1383     IncludeStrongLifetimeRAII Strong(Policy);
1384     printTemplateArgumentList(
1385         OS, Args, Policy,
1386         Spec->getSpecializedTemplate()->getTemplateParameters());
1387   }
1388 
1389   spaceBeforePlaceHolder(OS);
1390 }
1391 
printRecordBefore(const RecordType * T,raw_ostream & OS)1392 void TypePrinter::printRecordBefore(const RecordType *T, raw_ostream &OS) {
1393   // Print the preferred name if we have one for this type.
1394   if (Policy.UsePreferredNames) {
1395     for (const auto *PNA : T->getDecl()->specific_attrs<PreferredNameAttr>()) {
1396       if (!declaresSameEntity(PNA->getTypedefType()->getAsCXXRecordDecl(),
1397                               T->getDecl()))
1398         continue;
1399       // Find the outermost typedef or alias template.
1400       QualType T = PNA->getTypedefType();
1401       while (true) {
1402         if (auto *TT = dyn_cast<TypedefType>(T))
1403           return printTypeSpec(TT->getDecl(), OS);
1404         if (auto *TST = dyn_cast<TemplateSpecializationType>(T))
1405           return printTemplateId(TST, OS, /*FullyQualify=*/true);
1406         T = T->getLocallyUnqualifiedSingleStepDesugaredType();
1407       }
1408     }
1409   }
1410 
1411   printTag(T->getDecl(), OS);
1412 }
1413 
printRecordAfter(const RecordType * T,raw_ostream & OS)1414 void TypePrinter::printRecordAfter(const RecordType *T, raw_ostream &OS) {}
1415 
printEnumBefore(const EnumType * T,raw_ostream & OS)1416 void TypePrinter::printEnumBefore(const EnumType *T, raw_ostream &OS) {
1417   printTag(T->getDecl(), OS);
1418 }
1419 
printEnumAfter(const EnumType * T,raw_ostream & OS)1420 void TypePrinter::printEnumAfter(const EnumType *T, raw_ostream &OS) {}
1421 
printTemplateTypeParmBefore(const TemplateTypeParmType * T,raw_ostream & OS)1422 void TypePrinter::printTemplateTypeParmBefore(const TemplateTypeParmType *T,
1423                                               raw_ostream &OS) {
1424   TemplateTypeParmDecl *D = T->getDecl();
1425   if (D && D->isImplicit()) {
1426     if (auto *TC = D->getTypeConstraint()) {
1427       TC->print(OS, Policy);
1428       OS << ' ';
1429     }
1430     OS << "auto";
1431   } else if (IdentifierInfo *Id = T->getIdentifier())
1432     OS << (Policy.CleanUglifiedParameters ? Id->deuglifiedName()
1433                                           : Id->getName());
1434   else
1435     OS << "type-parameter-" << T->getDepth() << '-' << T->getIndex();
1436 
1437   spaceBeforePlaceHolder(OS);
1438 }
1439 
printTemplateTypeParmAfter(const TemplateTypeParmType * T,raw_ostream & OS)1440 void TypePrinter::printTemplateTypeParmAfter(const TemplateTypeParmType *T,
1441                                              raw_ostream &OS) {}
1442 
printSubstTemplateTypeParmBefore(const SubstTemplateTypeParmType * T,raw_ostream & OS)1443 void TypePrinter::printSubstTemplateTypeParmBefore(
1444                                              const SubstTemplateTypeParmType *T,
1445                                              raw_ostream &OS) {
1446   IncludeStrongLifetimeRAII Strong(Policy);
1447   printBefore(T->getReplacementType(), OS);
1448 }
1449 
printSubstTemplateTypeParmAfter(const SubstTemplateTypeParmType * T,raw_ostream & OS)1450 void TypePrinter::printSubstTemplateTypeParmAfter(
1451                                              const SubstTemplateTypeParmType *T,
1452                                              raw_ostream &OS) {
1453   IncludeStrongLifetimeRAII Strong(Policy);
1454   printAfter(T->getReplacementType(), OS);
1455 }
1456 
printSubstTemplateTypeParmPackBefore(const SubstTemplateTypeParmPackType * T,raw_ostream & OS)1457 void TypePrinter::printSubstTemplateTypeParmPackBefore(
1458                                         const SubstTemplateTypeParmPackType *T,
1459                                         raw_ostream &OS) {
1460   IncludeStrongLifetimeRAII Strong(Policy);
1461   if (const TemplateTypeParmDecl *D = T->getReplacedParameter()) {
1462     if (D && D->isImplicit()) {
1463       if (auto *TC = D->getTypeConstraint()) {
1464         TC->print(OS, Policy);
1465         OS << ' ';
1466       }
1467       OS << "auto";
1468     } else if (IdentifierInfo *Id = D->getIdentifier())
1469       OS << (Policy.CleanUglifiedParameters ? Id->deuglifiedName()
1470                                             : Id->getName());
1471     else
1472       OS << "type-parameter-" << D->getDepth() << '-' << D->getIndex();
1473 
1474     spaceBeforePlaceHolder(OS);
1475   }
1476 }
1477 
printSubstTemplateTypeParmPackAfter(const SubstTemplateTypeParmPackType * T,raw_ostream & OS)1478 void TypePrinter::printSubstTemplateTypeParmPackAfter(
1479                                         const SubstTemplateTypeParmPackType *T,
1480                                         raw_ostream &OS) {
1481   IncludeStrongLifetimeRAII Strong(Policy);
1482 }
1483 
printTemplateId(const TemplateSpecializationType * T,raw_ostream & OS,bool FullyQualify)1484 void TypePrinter::printTemplateId(const TemplateSpecializationType *T,
1485                                   raw_ostream &OS, bool FullyQualify) {
1486   IncludeStrongLifetimeRAII Strong(Policy);
1487 
1488   TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
1489   // FIXME: Null TD never excercised in test suite.
1490   if (FullyQualify && TD) {
1491     if (!Policy.SuppressScope)
1492       AppendScope(TD->getDeclContext(), OS, TD->getDeclName());
1493 
1494     OS << TD->getName();
1495   } else {
1496     T->getTemplateName().print(OS, Policy);
1497   }
1498 
1499   DefaultTemplateArgsPolicyRAII TemplateArgs(Policy);
1500   const TemplateParameterList *TPL = TD ? TD->getTemplateParameters() : nullptr;
1501   printTemplateArgumentList(OS, T->template_arguments(), Policy, TPL);
1502   spaceBeforePlaceHolder(OS);
1503 }
1504 
printTemplateSpecializationBefore(const TemplateSpecializationType * T,raw_ostream & OS)1505 void TypePrinter::printTemplateSpecializationBefore(
1506                                             const TemplateSpecializationType *T,
1507                                             raw_ostream &OS) {
1508   printTemplateId(T, OS, Policy.FullyQualifiedName);
1509 }
1510 
printTemplateSpecializationAfter(const TemplateSpecializationType * T,raw_ostream & OS)1511 void TypePrinter::printTemplateSpecializationAfter(
1512                                             const TemplateSpecializationType *T,
1513                                             raw_ostream &OS) {}
1514 
printInjectedClassNameBefore(const InjectedClassNameType * T,raw_ostream & OS)1515 void TypePrinter::printInjectedClassNameBefore(const InjectedClassNameType *T,
1516                                                raw_ostream &OS) {
1517   if (Policy.PrintInjectedClassNameWithArguments)
1518     return printTemplateSpecializationBefore(T->getInjectedTST(), OS);
1519 
1520   IncludeStrongLifetimeRAII Strong(Policy);
1521   T->getTemplateName().print(OS, Policy);
1522   spaceBeforePlaceHolder(OS);
1523 }
1524 
printInjectedClassNameAfter(const InjectedClassNameType * T,raw_ostream & OS)1525 void TypePrinter::printInjectedClassNameAfter(const InjectedClassNameType *T,
1526                                                raw_ostream &OS) {}
1527 
printElaboratedBefore(const ElaboratedType * T,raw_ostream & OS)1528 void TypePrinter::printElaboratedBefore(const ElaboratedType *T,
1529                                         raw_ostream &OS) {
1530   if (Policy.IncludeTagDefinition && T->getOwnedTagDecl()) {
1531     TagDecl *OwnedTagDecl = T->getOwnedTagDecl();
1532     assert(OwnedTagDecl->getTypeForDecl() == T->getNamedType().getTypePtr() &&
1533            "OwnedTagDecl expected to be a declaration for the type");
1534     PrintingPolicy SubPolicy = Policy;
1535     SubPolicy.IncludeTagDefinition = false;
1536     OwnedTagDecl->print(OS, SubPolicy, Indentation);
1537     spaceBeforePlaceHolder(OS);
1538     return;
1539   }
1540 
1541   // The tag definition will take care of these.
1542   if (!Policy.IncludeTagDefinition)
1543   {
1544     OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1545     if (T->getKeyword() != ETK_None)
1546       OS << " ";
1547     NestedNameSpecifier *Qualifier = T->getQualifier();
1548     if (Qualifier)
1549       Qualifier->print(OS, Policy);
1550   }
1551 
1552   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1553   printBefore(T->getNamedType(), OS);
1554 }
1555 
printElaboratedAfter(const ElaboratedType * T,raw_ostream & OS)1556 void TypePrinter::printElaboratedAfter(const ElaboratedType *T,
1557                                         raw_ostream &OS) {
1558   if (Policy.IncludeTagDefinition && T->getOwnedTagDecl())
1559     return;
1560   ElaboratedTypePolicyRAII PolicyRAII(Policy);
1561   printAfter(T->getNamedType(), OS);
1562 }
1563 
printParenBefore(const ParenType * T,raw_ostream & OS)1564 void TypePrinter::printParenBefore(const ParenType *T, raw_ostream &OS) {
1565   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1566     printBefore(T->getInnerType(), OS);
1567     OS << '(';
1568   } else
1569     printBefore(T->getInnerType(), OS);
1570 }
1571 
printParenAfter(const ParenType * T,raw_ostream & OS)1572 void TypePrinter::printParenAfter(const ParenType *T, raw_ostream &OS) {
1573   if (!HasEmptyPlaceHolder && !isa<FunctionType>(T->getInnerType())) {
1574     OS << ')';
1575     printAfter(T->getInnerType(), OS);
1576   } else
1577     printAfter(T->getInnerType(), OS);
1578 }
1579 
printDependentNameBefore(const DependentNameType * T,raw_ostream & OS)1580 void TypePrinter::printDependentNameBefore(const DependentNameType *T,
1581                                            raw_ostream &OS) {
1582   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1583   if (T->getKeyword() != ETK_None)
1584     OS << " ";
1585 
1586   T->getQualifier()->print(OS, Policy);
1587 
1588   OS << T->getIdentifier()->getName();
1589   spaceBeforePlaceHolder(OS);
1590 }
1591 
printDependentNameAfter(const DependentNameType * T,raw_ostream & OS)1592 void TypePrinter::printDependentNameAfter(const DependentNameType *T,
1593                                           raw_ostream &OS) {}
1594 
printDependentTemplateSpecializationBefore(const DependentTemplateSpecializationType * T,raw_ostream & OS)1595 void TypePrinter::printDependentTemplateSpecializationBefore(
1596         const DependentTemplateSpecializationType *T, raw_ostream &OS) {
1597   IncludeStrongLifetimeRAII Strong(Policy);
1598 
1599   OS << TypeWithKeyword::getKeywordName(T->getKeyword());
1600   if (T->getKeyword() != ETK_None)
1601     OS << " ";
1602 
1603   if (T->getQualifier())
1604     T->getQualifier()->print(OS, Policy);
1605   OS << "template " << T->getIdentifier()->getName();
1606   printTemplateArgumentList(OS, T->template_arguments(), Policy);
1607   spaceBeforePlaceHolder(OS);
1608 }
1609 
printDependentTemplateSpecializationAfter(const DependentTemplateSpecializationType * T,raw_ostream & OS)1610 void TypePrinter::printDependentTemplateSpecializationAfter(
1611         const DependentTemplateSpecializationType *T, raw_ostream &OS) {}
1612 
printPackExpansionBefore(const PackExpansionType * T,raw_ostream & OS)1613 void TypePrinter::printPackExpansionBefore(const PackExpansionType *T,
1614                                            raw_ostream &OS) {
1615   printBefore(T->getPattern(), OS);
1616 }
1617 
printPackExpansionAfter(const PackExpansionType * T,raw_ostream & OS)1618 void TypePrinter::printPackExpansionAfter(const PackExpansionType *T,
1619                                           raw_ostream &OS) {
1620   printAfter(T->getPattern(), OS);
1621   OS << "...";
1622 }
1623 
printAttributedBefore(const AttributedType * T,raw_ostream & OS)1624 void TypePrinter::printAttributedBefore(const AttributedType *T,
1625                                         raw_ostream &OS) {
1626   // FIXME: Generate this with TableGen.
1627 
1628   // Prefer the macro forms of the GC and ownership qualifiers.
1629   if (T->getAttrKind() == attr::ObjCGC ||
1630       T->getAttrKind() == attr::ObjCOwnership)
1631     return printBefore(T->getEquivalentType(), OS);
1632 
1633   if (T->getAttrKind() == attr::ObjCKindOf)
1634     OS << "__kindof ";
1635 
1636   if (T->getAttrKind() == attr::AddressSpace)
1637     printBefore(T->getEquivalentType(), OS);
1638   else
1639     printBefore(T->getModifiedType(), OS);
1640 
1641   if (T->isMSTypeSpec()) {
1642     switch (T->getAttrKind()) {
1643     default: return;
1644     case attr::Ptr32: OS << " __ptr32"; break;
1645     case attr::Ptr64: OS << " __ptr64"; break;
1646     case attr::SPtr: OS << " __sptr"; break;
1647     case attr::UPtr: OS << " __uptr"; break;
1648     }
1649     spaceBeforePlaceHolder(OS);
1650   }
1651 
1652   // Print nullability type specifiers.
1653   if (T->getImmediateNullability()) {
1654     if (T->getAttrKind() == attr::TypeNonNull)
1655       OS << " _Nonnull";
1656     else if (T->getAttrKind() == attr::TypeNullable)
1657       OS << " _Nullable";
1658     else if (T->getAttrKind() == attr::TypeNullUnspecified)
1659       OS << " _Null_unspecified";
1660     else if (T->getAttrKind() == attr::TypeNullableResult)
1661       OS << " _Nullable_result";
1662     else
1663       llvm_unreachable("unhandled nullability");
1664     spaceBeforePlaceHolder(OS);
1665   }
1666 }
1667 
printAttributedAfter(const AttributedType * T,raw_ostream & OS)1668 void TypePrinter::printAttributedAfter(const AttributedType *T,
1669                                        raw_ostream &OS) {
1670   // FIXME: Generate this with TableGen.
1671 
1672   // Prefer the macro forms of the GC and ownership qualifiers.
1673   if (T->getAttrKind() == attr::ObjCGC ||
1674       T->getAttrKind() == attr::ObjCOwnership)
1675     return printAfter(T->getEquivalentType(), OS);
1676 
1677   // If this is a calling convention attribute, don't print the implicit CC from
1678   // the modified type.
1679   SaveAndRestore MaybeSuppressCC(InsideCCAttribute, T->isCallingConv());
1680 
1681   printAfter(T->getModifiedType(), OS);
1682 
1683   // Some attributes are printed as qualifiers before the type, so we have
1684   // nothing left to do.
1685   if (T->getAttrKind() == attr::ObjCKindOf ||
1686       T->isMSTypeSpec() || T->getImmediateNullability())
1687     return;
1688 
1689   // Don't print the inert __unsafe_unretained attribute at all.
1690   if (T->getAttrKind() == attr::ObjCInertUnsafeUnretained)
1691     return;
1692 
1693   // Don't print ns_returns_retained unless it had an effect.
1694   if (T->getAttrKind() == attr::NSReturnsRetained &&
1695       !T->getEquivalentType()->castAs<FunctionType>()
1696                              ->getExtInfo().getProducesResult())
1697     return;
1698 
1699   if (T->getAttrKind() == attr::LifetimeBound) {
1700     OS << " [[clang::lifetimebound]]";
1701     return;
1702   }
1703 
1704   // The printing of the address_space attribute is handled by the qualifier
1705   // since it is still stored in the qualifier. Return early to prevent printing
1706   // this twice.
1707   if (T->getAttrKind() == attr::AddressSpace)
1708     return;
1709 
1710   if (T->getAttrKind() == attr::AnnotateType) {
1711     // FIXME: Print the attribute arguments once we have a way to retrieve these
1712     // here. For the meantime, we just print `[[clang::annotate_type(...)]]`
1713     // without the arguments so that we know at least that we had _some_
1714     // annotation on the type.
1715     OS << " [[clang::annotate_type(...)]]";
1716     return;
1717   }
1718 
1719   OS << " __attribute__((";
1720   switch (T->getAttrKind()) {
1721 #define TYPE_ATTR(NAME)
1722 #define DECL_OR_TYPE_ATTR(NAME)
1723 #define ATTR(NAME) case attr::NAME:
1724 #include "clang/Basic/AttrList.inc"
1725     llvm_unreachable("non-type attribute attached to type");
1726 
1727   case attr::BTFTypeTag:
1728     llvm_unreachable("BTFTypeTag attribute handled separately");
1729 
1730   case attr::OpenCLPrivateAddressSpace:
1731   case attr::OpenCLGlobalAddressSpace:
1732   case attr::OpenCLGlobalDeviceAddressSpace:
1733   case attr::OpenCLGlobalHostAddressSpace:
1734   case attr::OpenCLLocalAddressSpace:
1735   case attr::OpenCLConstantAddressSpace:
1736   case attr::OpenCLGenericAddressSpace:
1737   case attr::HLSLGroupSharedAddressSpace:
1738     // FIXME: Update printAttributedBefore to print these once we generate
1739     // AttributedType nodes for them.
1740     break;
1741 
1742   case attr::LifetimeBound:
1743   case attr::TypeNonNull:
1744   case attr::TypeNullable:
1745   case attr::TypeNullableResult:
1746   case attr::TypeNullUnspecified:
1747   case attr::ObjCGC:
1748   case attr::ObjCInertUnsafeUnretained:
1749   case attr::ObjCKindOf:
1750   case attr::ObjCOwnership:
1751   case attr::Ptr32:
1752   case attr::Ptr64:
1753   case attr::SPtr:
1754   case attr::UPtr:
1755   case attr::AddressSpace:
1756   case attr::CmseNSCall:
1757   case attr::AnnotateType:
1758     llvm_unreachable("This attribute should have been handled already");
1759 
1760   case attr::NSReturnsRetained:
1761     OS << "ns_returns_retained";
1762     break;
1763 
1764   // FIXME: When Sema learns to form this AttributedType, avoid printing the
1765   // attribute again in printFunctionProtoAfter.
1766   case attr::AnyX86NoCfCheck: OS << "nocf_check"; break;
1767   case attr::CDecl: OS << "cdecl"; break;
1768   case attr::FastCall: OS << "fastcall"; break;
1769   case attr::StdCall: OS << "stdcall"; break;
1770   case attr::ThisCall: OS << "thiscall"; break;
1771   case attr::SwiftCall: OS << "swiftcall"; break;
1772   case attr::SwiftAsyncCall: OS << "swiftasynccall"; break;
1773   case attr::VectorCall: OS << "vectorcall"; break;
1774   case attr::Pascal: OS << "pascal"; break;
1775   case attr::MSABI: OS << "ms_abi"; break;
1776   case attr::SysVABI: OS << "sysv_abi"; break;
1777   case attr::RegCall: OS << "regcall"; break;
1778   case attr::Pcs: {
1779     OS << "pcs(";
1780    QualType t = T->getEquivalentType();
1781    while (!t->isFunctionType())
1782      t = t->getPointeeType();
1783    OS << (t->castAs<FunctionType>()->getCallConv() == CC_AAPCS ?
1784          "\"aapcs\"" : "\"aapcs-vfp\"");
1785    OS << ')';
1786    break;
1787   }
1788   case attr::AArch64VectorPcs: OS << "aarch64_vector_pcs"; break;
1789   case attr::AArch64SVEPcs: OS << "aarch64_sve_pcs"; break;
1790   case attr::AMDGPUKernelCall: OS << "amdgpu_kernel"; break;
1791   case attr::IntelOclBicc: OS << "inteloclbicc"; break;
1792   case attr::PreserveMost:
1793     OS << "preserve_most";
1794     break;
1795 
1796   case attr::PreserveAll:
1797     OS << "preserve_all";
1798     break;
1799   case attr::NoDeref:
1800     OS << "noderef";
1801     break;
1802   case attr::AcquireHandle:
1803     OS << "acquire_handle";
1804     break;
1805   case attr::ArmMveStrictPolymorphism:
1806     OS << "__clang_arm_mve_strict_polymorphism";
1807     break;
1808   }
1809   OS << "))";
1810 }
1811 
printBTFTagAttributedBefore(const BTFTagAttributedType * T,raw_ostream & OS)1812 void TypePrinter::printBTFTagAttributedBefore(const BTFTagAttributedType *T,
1813                                               raw_ostream &OS) {
1814   printBefore(T->getWrappedType(), OS);
1815   OS << " __attribute__((btf_type_tag(\"" << T->getAttr()->getBTFTypeTag() << "\")))";
1816 }
1817 
printBTFTagAttributedAfter(const BTFTagAttributedType * T,raw_ostream & OS)1818 void TypePrinter::printBTFTagAttributedAfter(const BTFTagAttributedType *T,
1819                                              raw_ostream &OS) {
1820   printAfter(T->getWrappedType(), OS);
1821 }
1822 
printObjCInterfaceBefore(const ObjCInterfaceType * T,raw_ostream & OS)1823 void TypePrinter::printObjCInterfaceBefore(const ObjCInterfaceType *T,
1824                                            raw_ostream &OS) {
1825   OS << T->getDecl()->getName();
1826   spaceBeforePlaceHolder(OS);
1827 }
1828 
printObjCInterfaceAfter(const ObjCInterfaceType * T,raw_ostream & OS)1829 void TypePrinter::printObjCInterfaceAfter(const ObjCInterfaceType *T,
1830                                           raw_ostream &OS) {}
1831 
printObjCTypeParamBefore(const ObjCTypeParamType * T,raw_ostream & OS)1832 void TypePrinter::printObjCTypeParamBefore(const ObjCTypeParamType *T,
1833                                           raw_ostream &OS) {
1834   OS << T->getDecl()->getName();
1835   if (!T->qual_empty()) {
1836     bool isFirst = true;
1837     OS << '<';
1838     for (const auto *I : T->quals()) {
1839       if (isFirst)
1840         isFirst = false;
1841       else
1842         OS << ',';
1843       OS << I->getName();
1844     }
1845     OS << '>';
1846   }
1847 
1848   spaceBeforePlaceHolder(OS);
1849 }
1850 
printObjCTypeParamAfter(const ObjCTypeParamType * T,raw_ostream & OS)1851 void TypePrinter::printObjCTypeParamAfter(const ObjCTypeParamType *T,
1852                                           raw_ostream &OS) {}
1853 
printObjCObjectBefore(const ObjCObjectType * T,raw_ostream & OS)1854 void TypePrinter::printObjCObjectBefore(const ObjCObjectType *T,
1855                                         raw_ostream &OS) {
1856   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1857       !T->isKindOfTypeAsWritten())
1858     return printBefore(T->getBaseType(), OS);
1859 
1860   if (T->isKindOfTypeAsWritten())
1861     OS << "__kindof ";
1862 
1863   print(T->getBaseType(), OS, StringRef());
1864 
1865   if (T->isSpecializedAsWritten()) {
1866     bool isFirst = true;
1867     OS << '<';
1868     for (auto typeArg : T->getTypeArgsAsWritten()) {
1869       if (isFirst)
1870         isFirst = false;
1871       else
1872         OS << ",";
1873 
1874       print(typeArg, OS, StringRef());
1875     }
1876     OS << '>';
1877   }
1878 
1879   if (!T->qual_empty()) {
1880     bool isFirst = true;
1881     OS << '<';
1882     for (const auto *I : T->quals()) {
1883       if (isFirst)
1884         isFirst = false;
1885       else
1886         OS << ',';
1887       OS << I->getName();
1888     }
1889     OS << '>';
1890   }
1891 
1892   spaceBeforePlaceHolder(OS);
1893 }
1894 
printObjCObjectAfter(const ObjCObjectType * T,raw_ostream & OS)1895 void TypePrinter::printObjCObjectAfter(const ObjCObjectType *T,
1896                                         raw_ostream &OS) {
1897   if (T->qual_empty() && T->isUnspecializedAsWritten() &&
1898       !T->isKindOfTypeAsWritten())
1899     return printAfter(T->getBaseType(), OS);
1900 }
1901 
printObjCObjectPointerBefore(const ObjCObjectPointerType * T,raw_ostream & OS)1902 void TypePrinter::printObjCObjectPointerBefore(const ObjCObjectPointerType *T,
1903                                                raw_ostream &OS) {
1904   printBefore(T->getPointeeType(), OS);
1905 
1906   // If we need to print the pointer, print it now.
1907   if (!T->isObjCIdType() && !T->isObjCQualifiedIdType() &&
1908       !T->isObjCClassType() && !T->isObjCQualifiedClassType()) {
1909     if (HasEmptyPlaceHolder)
1910       OS << ' ';
1911     OS << '*';
1912   }
1913 }
1914 
printObjCObjectPointerAfter(const ObjCObjectPointerType * T,raw_ostream & OS)1915 void TypePrinter::printObjCObjectPointerAfter(const ObjCObjectPointerType *T,
1916                                               raw_ostream &OS) {}
1917 
1918 static
getArgument(const TemplateArgument & A)1919 const TemplateArgument &getArgument(const TemplateArgument &A) { return A; }
1920 
getArgument(const TemplateArgumentLoc & A)1921 static const TemplateArgument &getArgument(const TemplateArgumentLoc &A) {
1922   return A.getArgument();
1923 }
1924 
printArgument(const TemplateArgument & A,const PrintingPolicy & PP,llvm::raw_ostream & OS,bool IncludeType)1925 static void printArgument(const TemplateArgument &A, const PrintingPolicy &PP,
1926                           llvm::raw_ostream &OS, bool IncludeType) {
1927   A.print(PP, OS, IncludeType);
1928 }
1929 
printArgument(const TemplateArgumentLoc & A,const PrintingPolicy & PP,llvm::raw_ostream & OS,bool IncludeType)1930 static void printArgument(const TemplateArgumentLoc &A,
1931                           const PrintingPolicy &PP, llvm::raw_ostream &OS,
1932                           bool IncludeType) {
1933   const TemplateArgument::ArgKind &Kind = A.getArgument().getKind();
1934   if (Kind == TemplateArgument::ArgKind::Type)
1935     return A.getTypeSourceInfo()->getType().print(OS, PP);
1936   return A.getArgument().print(PP, OS, IncludeType);
1937 }
1938 
1939 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg,
1940                                           TemplateArgument Pattern,
1941                                           ArrayRef<TemplateArgument> Args,
1942                                           unsigned Depth);
1943 
isSubstitutedType(ASTContext & Ctx,QualType T,QualType Pattern,ArrayRef<TemplateArgument> Args,unsigned Depth)1944 static bool isSubstitutedType(ASTContext &Ctx, QualType T, QualType Pattern,
1945                               ArrayRef<TemplateArgument> Args, unsigned Depth) {
1946   if (Ctx.hasSameType(T, Pattern))
1947     return true;
1948 
1949   // A type parameter matches its argument.
1950   if (auto *TTPT = Pattern->getAs<TemplateTypeParmType>()) {
1951     if (TTPT->getDepth() == Depth && TTPT->getIndex() < Args.size() &&
1952         Args[TTPT->getIndex()].getKind() == TemplateArgument::Type) {
1953       QualType SubstArg = Ctx.getQualifiedType(
1954           Args[TTPT->getIndex()].getAsType(), Pattern.getQualifiers());
1955       return Ctx.hasSameType(SubstArg, T);
1956     }
1957     return false;
1958   }
1959 
1960   // FIXME: Recurse into array types.
1961 
1962   // All other cases will need the types to be identically qualified.
1963   Qualifiers TQual, PatQual;
1964   T = Ctx.getUnqualifiedArrayType(T, TQual);
1965   Pattern = Ctx.getUnqualifiedArrayType(Pattern, PatQual);
1966   if (TQual != PatQual)
1967     return false;
1968 
1969   // Recurse into pointer-like types.
1970   {
1971     QualType TPointee = T->getPointeeType();
1972     QualType PPointee = Pattern->getPointeeType();
1973     if (!TPointee.isNull() && !PPointee.isNull())
1974       return T->getTypeClass() == Pattern->getTypeClass() &&
1975              isSubstitutedType(Ctx, TPointee, PPointee, Args, Depth);
1976   }
1977 
1978   // Recurse into template specialization types.
1979   if (auto *PTST =
1980           Pattern.getCanonicalType()->getAs<TemplateSpecializationType>()) {
1981     TemplateName Template;
1982     ArrayRef<TemplateArgument> TemplateArgs;
1983     if (auto *TTST = T->getAs<TemplateSpecializationType>()) {
1984       Template = TTST->getTemplateName();
1985       TemplateArgs = TTST->template_arguments();
1986     } else if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1987                    T->getAsCXXRecordDecl())) {
1988       Template = TemplateName(CTSD->getSpecializedTemplate());
1989       TemplateArgs = CTSD->getTemplateArgs().asArray();
1990     } else {
1991       return false;
1992     }
1993 
1994     if (!isSubstitutedTemplateArgument(Ctx, Template, PTST->getTemplateName(),
1995                                        Args, Depth))
1996       return false;
1997     if (TemplateArgs.size() != PTST->template_arguments().size())
1998       return false;
1999     for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2000       if (!isSubstitutedTemplateArgument(
2001               Ctx, TemplateArgs[I], PTST->template_arguments()[I], Args, Depth))
2002         return false;
2003     return true;
2004   }
2005 
2006   // FIXME: Handle more cases.
2007   return false;
2008 }
2009 
isSubstitutedTemplateArgument(ASTContext & Ctx,TemplateArgument Arg,TemplateArgument Pattern,ArrayRef<TemplateArgument> Args,unsigned Depth)2010 static bool isSubstitutedTemplateArgument(ASTContext &Ctx, TemplateArgument Arg,
2011                                           TemplateArgument Pattern,
2012                                           ArrayRef<TemplateArgument> Args,
2013                                           unsigned Depth) {
2014   Arg = Ctx.getCanonicalTemplateArgument(Arg);
2015   Pattern = Ctx.getCanonicalTemplateArgument(Pattern);
2016   if (Arg.structurallyEquals(Pattern))
2017     return true;
2018 
2019   if (Pattern.getKind() == TemplateArgument::Expression) {
2020     if (auto *DRE =
2021             dyn_cast<DeclRefExpr>(Pattern.getAsExpr()->IgnoreParenImpCasts())) {
2022       if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()))
2023         return NTTP->getDepth() == Depth && Args.size() > NTTP->getIndex() &&
2024                Args[NTTP->getIndex()].structurallyEquals(Arg);
2025     }
2026   }
2027 
2028   if (Arg.getKind() == TemplateArgument::Integral &&
2029       Pattern.getKind() == TemplateArgument::Expression) {
2030     Expr const *expr = Pattern.getAsExpr();
2031 
2032     if (!expr->isValueDependent() && expr->isIntegerConstantExpr(Ctx)) {
2033       return llvm::APSInt::isSameValue(expr->EvaluateKnownConstInt(Ctx),
2034                                        Arg.getAsIntegral());
2035     }
2036   }
2037 
2038   if (Arg.getKind() != Pattern.getKind())
2039     return false;
2040 
2041   if (Arg.getKind() == TemplateArgument::Type)
2042     return isSubstitutedType(Ctx, Arg.getAsType(), Pattern.getAsType(), Args,
2043                              Depth);
2044 
2045   if (Arg.getKind() == TemplateArgument::Template) {
2046     TemplateDecl *PatTD = Pattern.getAsTemplate().getAsTemplateDecl();
2047     if (auto *TTPD = dyn_cast_or_null<TemplateTemplateParmDecl>(PatTD))
2048       return TTPD->getDepth() == Depth && Args.size() > TTPD->getIndex() &&
2049              Ctx.getCanonicalTemplateArgument(Args[TTPD->getIndex()])
2050                  .structurallyEquals(Arg);
2051   }
2052 
2053   // FIXME: Handle more cases.
2054   return false;
2055 }
2056 
isSubstitutedDefaultArgument(ASTContext & Ctx,TemplateArgument Arg,const NamedDecl * Param,ArrayRef<TemplateArgument> Args,unsigned Depth)2057 bool clang::isSubstitutedDefaultArgument(ASTContext &Ctx, TemplateArgument Arg,
2058                                          const NamedDecl *Param,
2059                                          ArrayRef<TemplateArgument> Args,
2060                                          unsigned Depth) {
2061   // An empty pack is equivalent to not providing a pack argument.
2062   if (Arg.getKind() == TemplateArgument::Pack && Arg.pack_size() == 0)
2063     return true;
2064 
2065   if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Param)) {
2066     return TTPD->hasDefaultArgument() &&
2067            isSubstitutedTemplateArgument(Ctx, Arg, TTPD->getDefaultArgument(),
2068                                          Args, Depth);
2069   } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Param)) {
2070     return TTPD->hasDefaultArgument() &&
2071            isSubstitutedTemplateArgument(
2072                Ctx, Arg, TTPD->getDefaultArgument().getArgument(), Args, Depth);
2073   } else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2074     return NTTPD->hasDefaultArgument() &&
2075            isSubstitutedTemplateArgument(Ctx, Arg, NTTPD->getDefaultArgument(),
2076                                          Args, Depth);
2077   }
2078   return false;
2079 }
2080 
2081 template <typename TA>
2082 static void
printTo(raw_ostream & OS,ArrayRef<TA> Args,const PrintingPolicy & Policy,const TemplateParameterList * TPL,bool IsPack,unsigned ParmIndex)2083 printTo(raw_ostream &OS, ArrayRef<TA> Args, const PrintingPolicy &Policy,
2084         const TemplateParameterList *TPL, bool IsPack, unsigned ParmIndex) {
2085   // Drop trailing template arguments that match default arguments.
2086   if (TPL && Policy.SuppressDefaultTemplateArgs &&
2087       !Policy.PrintCanonicalTypes && !Args.empty() && !IsPack &&
2088       Args.size() <= TPL->size()) {
2089     ASTContext &Ctx = TPL->getParam(0)->getASTContext();
2090     llvm::SmallVector<TemplateArgument, 8> OrigArgs;
2091     for (const TA &A : Args)
2092       OrigArgs.push_back(getArgument(A));
2093     while (!Args.empty() &&
2094            isSubstitutedDefaultArgument(Ctx, getArgument(Args.back()),
2095                                         TPL->getParam(Args.size() - 1),
2096                                         OrigArgs, TPL->getDepth()))
2097       Args = Args.drop_back();
2098   }
2099 
2100   const char *Comma = Policy.MSVCFormatting ? "," : ", ";
2101   if (!IsPack)
2102     OS << '<';
2103 
2104   bool NeedSpace = false;
2105   bool FirstArg = true;
2106   for (const auto &Arg : Args) {
2107     // Print the argument into a string.
2108     SmallString<128> Buf;
2109     llvm::raw_svector_ostream ArgOS(Buf);
2110     const TemplateArgument &Argument = getArgument(Arg);
2111     if (Argument.getKind() == TemplateArgument::Pack) {
2112       if (Argument.pack_size() && !FirstArg)
2113         OS << Comma;
2114       printTo(ArgOS, Argument.getPackAsArray(), Policy, TPL,
2115               /*IsPack*/ true, ParmIndex);
2116     } else {
2117       if (!FirstArg)
2118         OS << Comma;
2119       // Tries to print the argument with location info if exists.
2120       printArgument(Arg, Policy, ArgOS,
2121                     TemplateParameterList::shouldIncludeTypeForArgument(
2122                         Policy, TPL, ParmIndex));
2123     }
2124     StringRef ArgString = ArgOS.str();
2125 
2126     // If this is the first argument and its string representation
2127     // begins with the global scope specifier ('::foo'), add a space
2128     // to avoid printing the diagraph '<:'.
2129     if (FirstArg && !ArgString.empty() && ArgString[0] == ':')
2130       OS << ' ';
2131 
2132     OS << ArgString;
2133 
2134     // If the last character of our string is '>', add another space to
2135     // keep the two '>''s separate tokens.
2136     if (!ArgString.empty()) {
2137       NeedSpace = Policy.SplitTemplateClosers && ArgString.back() == '>';
2138       FirstArg = false;
2139     }
2140 
2141     // Use same template parameter for all elements of Pack
2142     if (!IsPack)
2143       ParmIndex++;
2144   }
2145 
2146   if (!IsPack) {
2147     if (NeedSpace)
2148       OS << ' ';
2149     OS << '>';
2150   }
2151 }
2152 
printTemplateArgumentList(raw_ostream & OS,const TemplateArgumentListInfo & Args,const PrintingPolicy & Policy,const TemplateParameterList * TPL)2153 void clang::printTemplateArgumentList(raw_ostream &OS,
2154                                       const TemplateArgumentListInfo &Args,
2155                                       const PrintingPolicy &Policy,
2156                                       const TemplateParameterList *TPL) {
2157   printTemplateArgumentList(OS, Args.arguments(), Policy, TPL);
2158 }
2159 
printTemplateArgumentList(raw_ostream & OS,ArrayRef<TemplateArgument> Args,const PrintingPolicy & Policy,const TemplateParameterList * TPL)2160 void clang::printTemplateArgumentList(raw_ostream &OS,
2161                                       ArrayRef<TemplateArgument> Args,
2162                                       const PrintingPolicy &Policy,
2163                                       const TemplateParameterList *TPL) {
2164   printTo(OS, Args, Policy, TPL, /*isPack*/ false, /*parmIndex*/ 0);
2165 }
2166 
printTemplateArgumentList(raw_ostream & OS,ArrayRef<TemplateArgumentLoc> Args,const PrintingPolicy & Policy,const TemplateParameterList * TPL)2167 void clang::printTemplateArgumentList(raw_ostream &OS,
2168                                       ArrayRef<TemplateArgumentLoc> Args,
2169                                       const PrintingPolicy &Policy,
2170                                       const TemplateParameterList *TPL) {
2171   printTo(OS, Args, Policy, TPL, /*isPack*/ false, /*parmIndex*/ 0);
2172 }
2173 
getAsString() const2174 std::string Qualifiers::getAsString() const {
2175   LangOptions LO;
2176   return getAsString(PrintingPolicy(LO));
2177 }
2178 
2179 // Appends qualifiers to the given string, separated by spaces.  Will
2180 // prefix a space if the string is non-empty.  Will not append a final
2181 // space.
getAsString(const PrintingPolicy & Policy) const2182 std::string Qualifiers::getAsString(const PrintingPolicy &Policy) const {
2183   SmallString<64> Buf;
2184   llvm::raw_svector_ostream StrOS(Buf);
2185   print(StrOS, Policy);
2186   return std::string(StrOS.str());
2187 }
2188 
isEmptyWhenPrinted(const PrintingPolicy & Policy) const2189 bool Qualifiers::isEmptyWhenPrinted(const PrintingPolicy &Policy) const {
2190   if (getCVRQualifiers())
2191     return false;
2192 
2193   if (getAddressSpace() != LangAS::Default)
2194     return false;
2195 
2196   if (getObjCGCAttr())
2197     return false;
2198 
2199   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime())
2200     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
2201       return false;
2202 
2203   return true;
2204 }
2205 
getAddrSpaceAsString(LangAS AS)2206 std::string Qualifiers::getAddrSpaceAsString(LangAS AS) {
2207   switch (AS) {
2208   case LangAS::Default:
2209     return "";
2210   case LangAS::opencl_global:
2211   case LangAS::sycl_global:
2212     return "__global";
2213   case LangAS::opencl_local:
2214   case LangAS::sycl_local:
2215     return "__local";
2216   case LangAS::opencl_private:
2217   case LangAS::sycl_private:
2218     return "__private";
2219   case LangAS::opencl_constant:
2220     return "__constant";
2221   case LangAS::opencl_generic:
2222     return "__generic";
2223   case LangAS::opencl_global_device:
2224   case LangAS::sycl_global_device:
2225     return "__global_device";
2226   case LangAS::opencl_global_host:
2227   case LangAS::sycl_global_host:
2228     return "__global_host";
2229   case LangAS::cuda_device:
2230     return "__device__";
2231   case LangAS::cuda_constant:
2232     return "__constant__";
2233   case LangAS::cuda_shared:
2234     return "__shared__";
2235   case LangAS::ptr32_sptr:
2236     return "__sptr __ptr32";
2237   case LangAS::ptr32_uptr:
2238     return "__uptr __ptr32";
2239   case LangAS::ptr64:
2240     return "__ptr64";
2241   case LangAS::hlsl_groupshared:
2242     return "groupshared";
2243   default:
2244     return std::to_string(toTargetAddressSpace(AS));
2245   }
2246 }
2247 
2248 // Appends qualifiers to the given string, separated by spaces.  Will
2249 // prefix a space if the string is non-empty.  Will not append a final
2250 // space.
print(raw_ostream & OS,const PrintingPolicy & Policy,bool appendSpaceIfNonEmpty) const2251 void Qualifiers::print(raw_ostream &OS, const PrintingPolicy& Policy,
2252                        bool appendSpaceIfNonEmpty) const {
2253   bool addSpace = false;
2254 
2255   unsigned quals = getCVRQualifiers();
2256   if (quals) {
2257     AppendTypeQualList(OS, quals, Policy.Restrict);
2258     addSpace = true;
2259   }
2260   if (hasUnaligned()) {
2261     if (addSpace)
2262       OS << ' ';
2263     OS << "__unaligned";
2264     addSpace = true;
2265   }
2266   auto ASStr = getAddrSpaceAsString(getAddressSpace());
2267   if (!ASStr.empty()) {
2268     if (addSpace)
2269       OS << ' ';
2270     addSpace = true;
2271     // Wrap target address space into an attribute syntax
2272     if (isTargetAddressSpace(getAddressSpace()))
2273       OS << "__attribute__((address_space(" << ASStr << ")))";
2274     else
2275       OS << ASStr;
2276   }
2277 
2278   if (Qualifiers::GC gc = getObjCGCAttr()) {
2279     if (addSpace)
2280       OS << ' ';
2281     addSpace = true;
2282     if (gc == Qualifiers::Weak)
2283       OS << "__weak";
2284     else
2285       OS << "__strong";
2286   }
2287   if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
2288     if (!(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime)){
2289       if (addSpace)
2290         OS << ' ';
2291       addSpace = true;
2292     }
2293 
2294     switch (lifetime) {
2295     case Qualifiers::OCL_None: llvm_unreachable("none but true");
2296     case Qualifiers::OCL_ExplicitNone: OS << "__unsafe_unretained"; break;
2297     case Qualifiers::OCL_Strong:
2298       if (!Policy.SuppressStrongLifetime)
2299         OS << "__strong";
2300       break;
2301 
2302     case Qualifiers::OCL_Weak: OS << "__weak"; break;
2303     case Qualifiers::OCL_Autoreleasing: OS << "__autoreleasing"; break;
2304     }
2305   }
2306 
2307   if (appendSpaceIfNonEmpty && addSpace)
2308     OS << ' ';
2309 }
2310 
getAsString() const2311 std::string QualType::getAsString() const {
2312   return getAsString(split(), LangOptions());
2313 }
2314 
getAsString(const PrintingPolicy & Policy) const2315 std::string QualType::getAsString(const PrintingPolicy &Policy) const {
2316   std::string S;
2317   getAsStringInternal(S, Policy);
2318   return S;
2319 }
2320 
getAsString(const Type * ty,Qualifiers qs,const PrintingPolicy & Policy)2321 std::string QualType::getAsString(const Type *ty, Qualifiers qs,
2322                                   const PrintingPolicy &Policy) {
2323   std::string buffer;
2324   getAsStringInternal(ty, qs, buffer, Policy);
2325   return buffer;
2326 }
2327 
print(raw_ostream & OS,const PrintingPolicy & Policy,const Twine & PlaceHolder,unsigned Indentation) const2328 void QualType::print(raw_ostream &OS, const PrintingPolicy &Policy,
2329                      const Twine &PlaceHolder, unsigned Indentation) const {
2330   print(splitAccordingToPolicy(*this, Policy), OS, Policy, PlaceHolder,
2331         Indentation);
2332 }
2333 
print(const Type * ty,Qualifiers qs,raw_ostream & OS,const PrintingPolicy & policy,const Twine & PlaceHolder,unsigned Indentation)2334 void QualType::print(const Type *ty, Qualifiers qs,
2335                      raw_ostream &OS, const PrintingPolicy &policy,
2336                      const Twine &PlaceHolder, unsigned Indentation) {
2337   SmallString<128> PHBuf;
2338   StringRef PH = PlaceHolder.toStringRef(PHBuf);
2339 
2340   TypePrinter(policy, Indentation).print(ty, qs, OS, PH);
2341 }
2342 
getAsStringInternal(std::string & Str,const PrintingPolicy & Policy) const2343 void QualType::getAsStringInternal(std::string &Str,
2344                                    const PrintingPolicy &Policy) const {
2345   return getAsStringInternal(splitAccordingToPolicy(*this, Policy), Str,
2346                              Policy);
2347 }
2348 
getAsStringInternal(const Type * ty,Qualifiers qs,std::string & buffer,const PrintingPolicy & policy)2349 void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
2350                                    std::string &buffer,
2351                                    const PrintingPolicy &policy) {
2352   SmallString<256> Buf;
2353   llvm::raw_svector_ostream StrOS(Buf);
2354   TypePrinter(policy).print(ty, qs, StrOS, buffer);
2355   std::string str = std::string(StrOS.str());
2356   buffer.swap(str);
2357 }
2358 
operator <<(raw_ostream & OS,QualType QT)2359 raw_ostream &clang::operator<<(raw_ostream &OS, QualType QT) {
2360   SplitQualType S = QT.split();
2361   TypePrinter(LangOptions()).print(S.Ty, S.Quals, OS, /*PlaceHolder=*/"");
2362   return OS;
2363 }
2364