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