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