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