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