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