TypePrinter.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  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. #include "clang/AST/Decl.h"
  14. #include "clang/AST/DeclObjC.h"
  15. #include "clang/AST/DeclTemplate.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/Type.h"
  18. #include "clang/AST/PrettyPrinter.h"
  19. #include "clang/Basic/LangOptions.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "llvm/ADT/StringExtras.h"
  22. #include "llvm/Support/raw_ostream.h"
  23. using namespace clang;
  24. namespace {
  25. /// \brief RAII object that enables printing of the ARC __strong lifetime
  26. /// qualifier.
  27. class IncludeStrongLifetimeRAII {
  28. PrintingPolicy &Policy;
  29. bool Old;
  30. public:
  31. explicit IncludeStrongLifetimeRAII(PrintingPolicy &Policy)
  32. : Policy(Policy), Old(Policy.SuppressStrongLifetime) {
  33. Policy.SuppressStrongLifetime = false;
  34. }
  35. ~IncludeStrongLifetimeRAII() {
  36. Policy.SuppressStrongLifetime = Old;
  37. }
  38. };
  39. class TypePrinter {
  40. PrintingPolicy Policy;
  41. public:
  42. explicit TypePrinter(const PrintingPolicy &Policy) : Policy(Policy) { }
  43. void print(const Type *ty, Qualifiers qs, std::string &buffer);
  44. void print(QualType T, std::string &S);
  45. void AppendScope(DeclContext *DC, std::string &S);
  46. void printTag(TagDecl *T, std::string &S);
  47. #define ABSTRACT_TYPE(CLASS, PARENT)
  48. #define TYPE(CLASS, PARENT) \
  49. void print##CLASS(const CLASS##Type *T, std::string &S);
  50. #include "clang/AST/TypeNodes.def"
  51. };
  52. }
  53. static void AppendTypeQualList(std::string &S, unsigned TypeQuals) {
  54. if (TypeQuals & Qualifiers::Const) {
  55. if (!S.empty()) S += ' ';
  56. S += "const";
  57. }
  58. if (TypeQuals & Qualifiers::Volatile) {
  59. if (!S.empty()) S += ' ';
  60. S += "volatile";
  61. }
  62. if (TypeQuals & Qualifiers::Restrict) {
  63. if (!S.empty()) S += ' ';
  64. S += "restrict";
  65. }
  66. }
  67. void TypePrinter::print(QualType t, std::string &buffer) {
  68. SplitQualType split = t.split();
  69. print(split.Ty, split.Quals, buffer);
  70. }
  71. void TypePrinter::print(const Type *T, Qualifiers Quals, std::string &buffer) {
  72. if (!T) {
  73. buffer += "NULL TYPE";
  74. return;
  75. }
  76. if (Policy.SuppressSpecifiers && T->isSpecifierType())
  77. return;
  78. // Print qualifiers as appropriate.
  79. // CanPrefixQualifiers - We prefer to print type qualifiers before the type,
  80. // so that we get "const int" instead of "int const", but we can't do this if
  81. // the type is complex. For example if the type is "int*", we *must* print
  82. // "int * const", printing "const int *" is different. Only do this when the
  83. // type expands to a simple string.
  84. bool CanPrefixQualifiers = false;
  85. bool NeedARCStrongQualifier = false;
  86. Type::TypeClass TC = T->getTypeClass();
  87. if (const AutoType *AT = dyn_cast<AutoType>(T))
  88. TC = AT->desugar()->getTypeClass();
  89. if (const SubstTemplateTypeParmType *Subst
  90. = dyn_cast<SubstTemplateTypeParmType>(T))
  91. TC = Subst->getReplacementType()->getTypeClass();
  92. switch (TC) {
  93. case Type::Builtin:
  94. case Type::Complex:
  95. case Type::UnresolvedUsing:
  96. case Type::Typedef:
  97. case Type::TypeOfExpr:
  98. case Type::TypeOf:
  99. case Type::Decltype:
  100. case Type::UnaryTransform:
  101. case Type::Record:
  102. case Type::Enum:
  103. case Type::Elaborated:
  104. case Type::TemplateTypeParm:
  105. case Type::SubstTemplateTypeParmPack:
  106. case Type::TemplateSpecialization:
  107. case Type::InjectedClassName:
  108. case Type::DependentName:
  109. case Type::DependentTemplateSpecialization:
  110. case Type::ObjCObject:
  111. case Type::ObjCInterface:
  112. case Type::Atomic:
  113. CanPrefixQualifiers = true;
  114. break;
  115. case Type::ObjCObjectPointer:
  116. CanPrefixQualifiers = T->isObjCIdType() || T->isObjCClassType() ||
  117. T->isObjCQualifiedIdType() || T->isObjCQualifiedClassType();
  118. break;
  119. case Type::ConstantArray:
  120. case Type::IncompleteArray:
  121. case Type::VariableArray:
  122. case Type::DependentSizedArray:
  123. NeedARCStrongQualifier = true;
  124. // Fall through
  125. case Type::Pointer:
  126. case Type::BlockPointer:
  127. case Type::LValueReference:
  128. case Type::RValueReference:
  129. case Type::MemberPointer:
  130. case Type::DependentSizedExtVector:
  131. case Type::Vector:
  132. case Type::ExtVector:
  133. case Type::FunctionProto:
  134. case Type::FunctionNoProto:
  135. case Type::Paren:
  136. case Type::Attributed:
  137. case Type::PackExpansion:
  138. case Type::SubstTemplateTypeParm:
  139. case Type::Auto:
  140. CanPrefixQualifiers = false;
  141. break;
  142. }
  143. if (!CanPrefixQualifiers && !Quals.empty()) {
  144. std::string qualsBuffer;
  145. if (NeedARCStrongQualifier) {
  146. IncludeStrongLifetimeRAII Strong(Policy);
  147. Quals.getAsStringInternal(qualsBuffer, Policy);
  148. } else {
  149. Quals.getAsStringInternal(qualsBuffer, Policy);
  150. }
  151. if (!qualsBuffer.empty()) {
  152. if (!buffer.empty()) {
  153. qualsBuffer += ' ';
  154. qualsBuffer += buffer;
  155. }
  156. std::swap(buffer, qualsBuffer);
  157. }
  158. }
  159. switch (T->getTypeClass()) {
  160. #define ABSTRACT_TYPE(CLASS, PARENT)
  161. #define TYPE(CLASS, PARENT) case Type::CLASS: \
  162. print##CLASS(cast<CLASS##Type>(T), buffer); \
  163. break;
  164. #include "clang/AST/TypeNodes.def"
  165. }
  166. // If we're adding the qualifiers as a prefix, do it now.
  167. if (CanPrefixQualifiers && !Quals.empty()) {
  168. std::string qualsBuffer;
  169. if (NeedARCStrongQualifier) {
  170. IncludeStrongLifetimeRAII Strong(Policy);
  171. Quals.getAsStringInternal(qualsBuffer, Policy);
  172. } else {
  173. Quals.getAsStringInternal(qualsBuffer, Policy);
  174. }
  175. if (!qualsBuffer.empty()) {
  176. if (!buffer.empty()) {
  177. qualsBuffer += ' ';
  178. qualsBuffer += buffer;
  179. }
  180. std::swap(buffer, qualsBuffer);
  181. }
  182. }
  183. }
  184. void TypePrinter::printBuiltin(const BuiltinType *T, std::string &S) {
  185. if (S.empty()) {
  186. S = T->getName(Policy);
  187. } else {
  188. // Prefix the basic type, e.g. 'int X'.
  189. S = ' ' + S;
  190. S = T->getName(Policy) + S;
  191. }
  192. }
  193. void TypePrinter::printComplex(const ComplexType *T, std::string &S) {
  194. print(T->getElementType(), S);
  195. S = "_Complex " + S;
  196. }
  197. void TypePrinter::printPointer(const PointerType *T, std::string &S) {
  198. S = '*' + S;
  199. // Handle things like 'int (*A)[4];' correctly.
  200. // FIXME: this should include vectors, but vectors use attributes I guess.
  201. if (isa<ArrayType>(T->getPointeeType()))
  202. S = '(' + S + ')';
  203. IncludeStrongLifetimeRAII Strong(Policy);
  204. print(T->getPointeeType(), S);
  205. }
  206. void TypePrinter::printBlockPointer(const BlockPointerType *T, std::string &S) {
  207. S = '^' + S;
  208. print(T->getPointeeType(), S);
  209. }
  210. void TypePrinter::printLValueReference(const LValueReferenceType *T,
  211. std::string &S) {
  212. S = '&' + S;
  213. // Handle things like 'int (&A)[4];' correctly.
  214. // FIXME: this should include vectors, but vectors use attributes I guess.
  215. if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
  216. S = '(' + S + ')';
  217. IncludeStrongLifetimeRAII Strong(Policy);
  218. print(T->getPointeeTypeAsWritten(), S);
  219. }
  220. void TypePrinter::printRValueReference(const RValueReferenceType *T,
  221. std::string &S) {
  222. S = "&&" + S;
  223. // Handle things like 'int (&&A)[4];' correctly.
  224. // FIXME: this should include vectors, but vectors use attributes I guess.
  225. if (isa<ArrayType>(T->getPointeeTypeAsWritten()))
  226. S = '(' + S + ')';
  227. IncludeStrongLifetimeRAII Strong(Policy);
  228. print(T->getPointeeTypeAsWritten(), S);
  229. }
  230. void TypePrinter::printMemberPointer(const MemberPointerType *T,
  231. std::string &S) {
  232. std::string C;
  233. print(QualType(T->getClass(), 0), C);
  234. C += "::*";
  235. S = C + S;
  236. // Handle things like 'int (Cls::*A)[4];' correctly.
  237. // FIXME: this should include vectors, but vectors use attributes I guess.
  238. if (isa<ArrayType>(T->getPointeeType()))
  239. S = '(' + S + ')';
  240. IncludeStrongLifetimeRAII Strong(Policy);
  241. print(T->getPointeeType(), S);
  242. }
  243. void TypePrinter::printConstantArray(const ConstantArrayType *T,
  244. std::string &S) {
  245. S += '[';
  246. S += llvm::utostr(T->getSize().getZExtValue());
  247. S += ']';
  248. IncludeStrongLifetimeRAII Strong(Policy);
  249. print(T->getElementType(), S);
  250. }
  251. void TypePrinter::printIncompleteArray(const IncompleteArrayType *T,
  252. std::string &S) {
  253. S += "[]";
  254. IncludeStrongLifetimeRAII Strong(Policy);
  255. print(T->getElementType(), S);
  256. }
  257. void TypePrinter::printVariableArray(const VariableArrayType *T,
  258. std::string &S) {
  259. S += '[';
  260. if (T->getIndexTypeQualifiers().hasQualifiers()) {
  261. AppendTypeQualList(S, T->getIndexTypeCVRQualifiers());
  262. S += ' ';
  263. }
  264. if (T->getSizeModifier() == VariableArrayType::Static)
  265. S += "static";
  266. else if (T->getSizeModifier() == VariableArrayType::Star)
  267. S += '*';
  268. if (T->getSizeExpr()) {
  269. std::string SStr;
  270. llvm::raw_string_ostream s(SStr);
  271. T->getSizeExpr()->printPretty(s, 0, Policy);
  272. S += s.str();
  273. }
  274. S += ']';
  275. IncludeStrongLifetimeRAII Strong(Policy);
  276. print(T->getElementType(), S);
  277. }
  278. void TypePrinter::printDependentSizedArray(const DependentSizedArrayType *T,
  279. std::string &S) {
  280. S += '[';
  281. if (T->getSizeExpr()) {
  282. std::string SStr;
  283. llvm::raw_string_ostream s(SStr);
  284. T->getSizeExpr()->printPretty(s, 0, Policy);
  285. S += s.str();
  286. }
  287. S += ']';
  288. IncludeStrongLifetimeRAII Strong(Policy);
  289. print(T->getElementType(), S);
  290. }
  291. void TypePrinter::printDependentSizedExtVector(
  292. const DependentSizedExtVectorType *T,
  293. std::string &S) {
  294. print(T->getElementType(), S);
  295. S += " __attribute__((ext_vector_type(";
  296. if (T->getSizeExpr()) {
  297. std::string SStr;
  298. llvm::raw_string_ostream s(SStr);
  299. T->getSizeExpr()->printPretty(s, 0, Policy);
  300. S += s.str();
  301. }
  302. S += ")))";
  303. }
  304. void TypePrinter::printVector(const VectorType *T, std::string &S) {
  305. switch (T->getVectorKind()) {
  306. case VectorType::AltiVecPixel:
  307. S = "__vector __pixel " + S;
  308. break;
  309. case VectorType::AltiVecBool:
  310. print(T->getElementType(), S);
  311. S = "__vector __bool " + S;
  312. break;
  313. case VectorType::AltiVecVector:
  314. print(T->getElementType(), S);
  315. S = "__vector " + S;
  316. break;
  317. case VectorType::NeonVector:
  318. print(T->getElementType(), S);
  319. S = ("__attribute__((neon_vector_type(" +
  320. llvm::utostr_32(T->getNumElements()) + "))) " + S);
  321. break;
  322. case VectorType::NeonPolyVector:
  323. print(T->getElementType(), S);
  324. S = ("__attribute__((neon_polyvector_type(" +
  325. llvm::utostr_32(T->getNumElements()) + "))) " + S);
  326. break;
  327. case VectorType::GenericVector: {
  328. // FIXME: We prefer to print the size directly here, but have no way
  329. // to get the size of the type.
  330. print(T->getElementType(), S);
  331. std::string V = "__attribute__((__vector_size__(";
  332. V += llvm::utostr_32(T->getNumElements()); // convert back to bytes.
  333. std::string ET;
  334. print(T->getElementType(), ET);
  335. V += " * sizeof(" + ET + ")))) ";
  336. S = V + S;
  337. break;
  338. }
  339. }
  340. }
  341. void TypePrinter::printExtVector(const ExtVectorType *T, std::string &S) {
  342. S += " __attribute__((ext_vector_type(";
  343. S += llvm::utostr_32(T->getNumElements());
  344. S += ")))";
  345. print(T->getElementType(), S);
  346. }
  347. void
  348. FunctionProtoType::printExceptionSpecification(std::string &S,
  349. PrintingPolicy Policy) const {
  350. if (hasDynamicExceptionSpec()) {
  351. S += " throw(";
  352. if (getExceptionSpecType() == EST_MSAny)
  353. S += "...";
  354. else
  355. for (unsigned I = 0, N = getNumExceptions(); I != N; ++I) {
  356. if (I)
  357. S += ", ";
  358. S += getExceptionType(I).getAsString(Policy);
  359. }
  360. S += ")";
  361. } else if (isNoexceptExceptionSpec(getExceptionSpecType())) {
  362. S += " noexcept";
  363. if (getExceptionSpecType() == EST_ComputedNoexcept) {
  364. S += "(";
  365. llvm::raw_string_ostream EOut(S);
  366. getNoexceptExpr()->printPretty(EOut, 0, Policy);
  367. EOut.flush();
  368. S += EOut.str();
  369. S += ")";
  370. }
  371. }
  372. }
  373. void TypePrinter::printFunctionProto(const FunctionProtoType *T,
  374. std::string &S) {
  375. // If needed for precedence reasons, wrap the inner part in grouping parens.
  376. if (!S.empty())
  377. S = "(" + S + ")";
  378. S += "(";
  379. std::string Tmp;
  380. PrintingPolicy ParamPolicy(Policy);
  381. ParamPolicy.SuppressSpecifiers = false;
  382. for (unsigned i = 0, e = T->getNumArgs(); i != e; ++i) {
  383. if (i) S += ", ";
  384. print(T->getArgType(i), Tmp);
  385. S += Tmp;
  386. Tmp.clear();
  387. }
  388. if (T->isVariadic()) {
  389. if (T->getNumArgs())
  390. S += ", ";
  391. S += "...";
  392. } else if (T->getNumArgs() == 0 && !Policy.LangOpts.CPlusPlus) {
  393. // Do not emit int() if we have a proto, emit 'int(void)'.
  394. S += "void";
  395. }
  396. S += ")";
  397. FunctionType::ExtInfo Info = T->getExtInfo();
  398. switch(Info.getCC()) {
  399. case CC_Default: break;
  400. case CC_C:
  401. S += " __attribute__((cdecl))";
  402. break;
  403. case CC_X86StdCall:
  404. S += " __attribute__((stdcall))";
  405. break;
  406. case CC_X86FastCall:
  407. S += " __attribute__((fastcall))";
  408. break;
  409. case CC_X86ThisCall:
  410. S += " __attribute__((thiscall))";
  411. break;
  412. case CC_X86Pascal:
  413. S += " __attribute__((pascal))";
  414. break;
  415. case CC_AAPCS:
  416. S += " __attribute__((pcs(\"aapcs\")))";
  417. break;
  418. case CC_AAPCS_VFP:
  419. S += " __attribute__((pcs(\"aapcs-vfp\")))";
  420. break;
  421. }
  422. if (Info.getNoReturn())
  423. S += " __attribute__((noreturn))";
  424. if (Info.getRegParm())
  425. S += " __attribute__((regparm (" +
  426. llvm::utostr_32(Info.getRegParm()) + ")))";
  427. AppendTypeQualList(S, T->getTypeQuals());
  428. switch (T->getRefQualifier()) {
  429. case RQ_None:
  430. break;
  431. case RQ_LValue:
  432. S += " &";
  433. break;
  434. case RQ_RValue:
  435. S += " &&";
  436. break;
  437. }
  438. T->printExceptionSpecification(S, Policy);
  439. if (T->hasTrailingReturn()) {
  440. std::string ResultS;
  441. print(T->getResultType(), ResultS);
  442. S = "auto " + S + " -> " + ResultS;
  443. } else
  444. print(T->getResultType(), S);
  445. }
  446. void TypePrinter::printFunctionNoProto(const FunctionNoProtoType *T,
  447. std::string &S) {
  448. // If needed for precedence reasons, wrap the inner part in grouping parens.
  449. if (!S.empty())
  450. S = "(" + S + ")";
  451. S += "()";
  452. if (T->getNoReturnAttr())
  453. S += " __attribute__((noreturn))";
  454. print(T->getResultType(), S);
  455. }
  456. static void printTypeSpec(const NamedDecl *D, std::string &S) {
  457. IdentifierInfo *II = D->getIdentifier();
  458. if (S.empty())
  459. S = II->getName().str();
  460. else
  461. S = II->getName().str() + ' ' + S;
  462. }
  463. void TypePrinter::printUnresolvedUsing(const UnresolvedUsingType *T,
  464. std::string &S) {
  465. printTypeSpec(T->getDecl(), S);
  466. }
  467. void TypePrinter::printTypedef(const TypedefType *T, std::string &S) {
  468. printTypeSpec(T->getDecl(), S);
  469. }
  470. void TypePrinter::printTypeOfExpr(const TypeOfExprType *T, std::string &S) {
  471. if (!S.empty()) // Prefix the basic type, e.g. 'typeof(e) X'.
  472. S = ' ' + S;
  473. std::string Str;
  474. llvm::raw_string_ostream s(Str);
  475. T->getUnderlyingExpr()->printPretty(s, 0, Policy);
  476. S = "typeof " + s.str() + S;
  477. }
  478. void TypePrinter::printTypeOf(const TypeOfType *T, std::string &S) {
  479. if (!S.empty()) // Prefix the basic type, e.g. 'typeof(t) X'.
  480. S = ' ' + S;
  481. std::string Tmp;
  482. print(T->getUnderlyingType(), Tmp);
  483. S = "typeof(" + Tmp + ")" + S;
  484. }
  485. void TypePrinter::printDecltype(const DecltypeType *T, std::string &S) {
  486. if (!S.empty()) // Prefix the basic type, e.g. 'decltype(t) X'.
  487. S = ' ' + S;
  488. std::string Str;
  489. llvm::raw_string_ostream s(Str);
  490. T->getUnderlyingExpr()->printPretty(s, 0, Policy);
  491. S = "decltype(" + s.str() + ")" + S;
  492. }
  493. void TypePrinter::printUnaryTransform(const UnaryTransformType *T,
  494. std::string &S) {
  495. if (!S.empty())
  496. S = ' ' + S;
  497. std::string Str;
  498. IncludeStrongLifetimeRAII Strong(Policy);
  499. print(T->getBaseType(), Str);
  500. switch (T->getUTTKind()) {
  501. case UnaryTransformType::EnumUnderlyingType:
  502. S = "__underlying_type(" + Str + ")" + S;
  503. break;
  504. }
  505. }
  506. void TypePrinter::printAuto(const AutoType *T, std::string &S) {
  507. // If the type has been deduced, do not print 'auto'.
  508. if (T->isDeduced()) {
  509. print(T->getDeducedType(), S);
  510. } else {
  511. if (!S.empty()) // Prefix the basic type, e.g. 'auto X'.
  512. S = ' ' + S;
  513. S = "auto" + S;
  514. }
  515. }
  516. void TypePrinter::printAtomic(const AtomicType *T, std::string &S) {
  517. if (!S.empty())
  518. S = ' ' + S;
  519. std::string Str;
  520. IncludeStrongLifetimeRAII Strong(Policy);
  521. print(T->getValueType(), Str);
  522. S = "_Atomic(" + Str + ")" + S;
  523. }
  524. /// Appends the given scope to the end of a string.
  525. void TypePrinter::AppendScope(DeclContext *DC, std::string &Buffer) {
  526. if (DC->isTranslationUnit()) return;
  527. AppendScope(DC->getParent(), Buffer);
  528. unsigned OldSize = Buffer.size();
  529. if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
  530. if (Policy.SuppressUnwrittenScope &&
  531. (NS->isAnonymousNamespace() || NS->isInline()))
  532. return;
  533. if (NS->getIdentifier())
  534. Buffer += NS->getNameAsString();
  535. else
  536. Buffer += "<anonymous>";
  537. } else if (ClassTemplateSpecializationDecl *Spec
  538. = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
  539. IncludeStrongLifetimeRAII Strong(Policy);
  540. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  541. std::string TemplateArgsStr
  542. = TemplateSpecializationType::PrintTemplateArgumentList(
  543. TemplateArgs.data(),
  544. TemplateArgs.size(),
  545. Policy);
  546. Buffer += Spec->getIdentifier()->getName();
  547. Buffer += TemplateArgsStr;
  548. } else if (TagDecl *Tag = dyn_cast<TagDecl>(DC)) {
  549. if (TypedefNameDecl *Typedef = Tag->getTypedefNameForAnonDecl())
  550. Buffer += Typedef->getIdentifier()->getName();
  551. else if (Tag->getIdentifier())
  552. Buffer += Tag->getIdentifier()->getName();
  553. else
  554. return;
  555. }
  556. if (Buffer.size() != OldSize)
  557. Buffer += "::";
  558. }
  559. void TypePrinter::printTag(TagDecl *D, std::string &InnerString) {
  560. if (Policy.SuppressTag)
  561. return;
  562. std::string Buffer;
  563. bool HasKindDecoration = false;
  564. // bool SuppressTagKeyword
  565. // = Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword;
  566. // We don't print tags unless this is an elaborated type.
  567. // In C, we just assume every RecordType is an elaborated type.
  568. if (!(Policy.LangOpts.CPlusPlus || Policy.SuppressTagKeyword ||
  569. D->getTypedefNameForAnonDecl())) {
  570. HasKindDecoration = true;
  571. Buffer += D->getKindName();
  572. Buffer += ' ';
  573. }
  574. // Compute the full nested-name-specifier for this type.
  575. // In C, this will always be empty except when the type
  576. // being printed is anonymous within other Record.
  577. if (!Policy.SuppressScope)
  578. AppendScope(D->getDeclContext(), Buffer);
  579. if (const IdentifierInfo *II = D->getIdentifier())
  580. Buffer += II->getNameStart();
  581. else if (TypedefNameDecl *Typedef = D->getTypedefNameForAnonDecl()) {
  582. assert(Typedef->getIdentifier() && "Typedef without identifier?");
  583. Buffer += Typedef->getIdentifier()->getNameStart();
  584. } else {
  585. // Make an unambiguous representation for anonymous types, e.g.
  586. // <anonymous enum at /usr/include/string.h:120:9>
  587. llvm::raw_string_ostream OS(Buffer);
  588. if (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda()) {
  589. OS << "<lambda";
  590. HasKindDecoration = true;
  591. } else {
  592. OS << "<anonymous";
  593. }
  594. if (Policy.AnonymousTagLocations) {
  595. // Suppress the redundant tag keyword if we just printed one.
  596. // We don't have to worry about ElaboratedTypes here because you can't
  597. // refer to an anonymous type with one.
  598. if (!HasKindDecoration)
  599. OS << " " << D->getKindName();
  600. PresumedLoc PLoc = D->getASTContext().getSourceManager().getPresumedLoc(
  601. D->getLocation());
  602. if (PLoc.isValid()) {
  603. OS << " at " << PLoc.getFilename()
  604. << ':' << PLoc.getLine()
  605. << ':' << PLoc.getColumn();
  606. }
  607. }
  608. OS << '>';
  609. }
  610. // If this is a class template specialization, print the template
  611. // arguments.
  612. if (ClassTemplateSpecializationDecl *Spec
  613. = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
  614. const TemplateArgument *Args;
  615. unsigned NumArgs;
  616. if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
  617. const TemplateSpecializationType *TST =
  618. cast<TemplateSpecializationType>(TAW->getType());
  619. Args = TST->getArgs();
  620. NumArgs = TST->getNumArgs();
  621. } else {
  622. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  623. Args = TemplateArgs.data();
  624. NumArgs = TemplateArgs.size();
  625. }
  626. IncludeStrongLifetimeRAII Strong(Policy);
  627. Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
  628. NumArgs,
  629. Policy);
  630. }
  631. if (!InnerString.empty()) {
  632. Buffer += ' ';
  633. Buffer += InnerString;
  634. }
  635. std::swap(Buffer, InnerString);
  636. }
  637. void TypePrinter::printRecord(const RecordType *T, std::string &S) {
  638. printTag(T->getDecl(), S);
  639. }
  640. void TypePrinter::printEnum(const EnumType *T, std::string &S) {
  641. printTag(T->getDecl(), S);
  642. }
  643. void TypePrinter::printTemplateTypeParm(const TemplateTypeParmType *T,
  644. std::string &S) {
  645. if (!S.empty()) // Prefix the basic type, e.g. 'parmname X'.
  646. S = ' ' + S;
  647. if (IdentifierInfo *Id = T->getIdentifier())
  648. S = Id->getName().str() + S;
  649. else
  650. S = "type-parameter-" + llvm::utostr_32(T->getDepth()) + '-' +
  651. llvm::utostr_32(T->getIndex()) + S;
  652. }
  653. void TypePrinter::printSubstTemplateTypeParm(const SubstTemplateTypeParmType *T,
  654. std::string &S) {
  655. IncludeStrongLifetimeRAII Strong(Policy);
  656. print(T->getReplacementType(), S);
  657. }
  658. void TypePrinter::printSubstTemplateTypeParmPack(
  659. const SubstTemplateTypeParmPackType *T,
  660. std::string &S) {
  661. IncludeStrongLifetimeRAII Strong(Policy);
  662. printTemplateTypeParm(T->getReplacedParameter(), S);
  663. }
  664. void TypePrinter::printTemplateSpecialization(
  665. const TemplateSpecializationType *T,
  666. std::string &S) {
  667. IncludeStrongLifetimeRAII Strong(Policy);
  668. std::string SpecString;
  669. {
  670. llvm::raw_string_ostream OS(SpecString);
  671. T->getTemplateName().print(OS, Policy);
  672. }
  673. SpecString += TemplateSpecializationType::PrintTemplateArgumentList(
  674. T->getArgs(),
  675. T->getNumArgs(),
  676. Policy);
  677. if (S.empty())
  678. S.swap(SpecString);
  679. else
  680. S = SpecString + ' ' + S;
  681. }
  682. void TypePrinter::printInjectedClassName(const InjectedClassNameType *T,
  683. std::string &S) {
  684. printTemplateSpecialization(T->getInjectedTST(), S);
  685. }
  686. void TypePrinter::printElaborated(const ElaboratedType *T, std::string &S) {
  687. std::string MyString;
  688. {
  689. llvm::raw_string_ostream OS(MyString);
  690. OS << TypeWithKeyword::getKeywordName(T->getKeyword());
  691. if (T->getKeyword() != ETK_None)
  692. OS << " ";
  693. NestedNameSpecifier* Qualifier = T->getQualifier();
  694. if (Qualifier)
  695. Qualifier->print(OS, Policy);
  696. }
  697. std::string TypeStr;
  698. PrintingPolicy InnerPolicy(Policy);
  699. InnerPolicy.SuppressTagKeyword = true;
  700. InnerPolicy.SuppressScope = true;
  701. TypePrinter(InnerPolicy).print(T->getNamedType(), TypeStr);
  702. MyString += TypeStr;
  703. if (S.empty())
  704. S.swap(MyString);
  705. else
  706. S = MyString + ' ' + S;
  707. }
  708. void TypePrinter::printParen(const ParenType *T, std::string &S) {
  709. if (!S.empty() && !isa<FunctionType>(T->getInnerType()))
  710. S = '(' + S + ')';
  711. print(T->getInnerType(), S);
  712. }
  713. void TypePrinter::printDependentName(const DependentNameType *T, std::string &S) {
  714. std::string MyString;
  715. {
  716. llvm::raw_string_ostream OS(MyString);
  717. OS << TypeWithKeyword::getKeywordName(T->getKeyword());
  718. if (T->getKeyword() != ETK_None)
  719. OS << " ";
  720. T->getQualifier()->print(OS, Policy);
  721. OS << T->getIdentifier()->getName();
  722. }
  723. if (S.empty())
  724. S.swap(MyString);
  725. else
  726. S = MyString + ' ' + S;
  727. }
  728. void TypePrinter::printDependentTemplateSpecialization(
  729. const DependentTemplateSpecializationType *T, std::string &S) {
  730. IncludeStrongLifetimeRAII Strong(Policy);
  731. std::string MyString;
  732. {
  733. llvm::raw_string_ostream OS(MyString);
  734. OS << TypeWithKeyword::getKeywordName(T->getKeyword());
  735. if (T->getKeyword() != ETK_None)
  736. OS << " ";
  737. if (T->getQualifier())
  738. T->getQualifier()->print(OS, Policy);
  739. OS << T->getIdentifier()->getName();
  740. OS << TemplateSpecializationType::PrintTemplateArgumentList(
  741. T->getArgs(),
  742. T->getNumArgs(),
  743. Policy);
  744. }
  745. if (S.empty())
  746. S.swap(MyString);
  747. else
  748. S = MyString + ' ' + S;
  749. }
  750. void TypePrinter::printPackExpansion(const PackExpansionType *T,
  751. std::string &S) {
  752. print(T->getPattern(), S);
  753. S += "...";
  754. }
  755. void TypePrinter::printAttributed(const AttributedType *T,
  756. std::string &S) {
  757. // Prefer the macro forms of the GC and ownership qualifiers.
  758. if (T->getAttrKind() == AttributedType::attr_objc_gc ||
  759. T->getAttrKind() == AttributedType::attr_objc_ownership)
  760. return print(T->getEquivalentType(), S);
  761. print(T->getModifiedType(), S);
  762. // TODO: not all attributes are GCC-style attributes.
  763. S += " __attribute__((";
  764. switch (T->getAttrKind()) {
  765. case AttributedType::attr_address_space:
  766. S += "address_space(";
  767. S += T->getEquivalentType().getAddressSpace();
  768. S += ")";
  769. break;
  770. case AttributedType::attr_vector_size: {
  771. S += "__vector_size__(";
  772. if (const VectorType *vector =T->getEquivalentType()->getAs<VectorType>()) {
  773. S += vector->getNumElements();
  774. S += " * sizeof(";
  775. std::string tmp;
  776. print(vector->getElementType(), tmp);
  777. S += tmp;
  778. S += ")";
  779. }
  780. S += ")";
  781. break;
  782. }
  783. case AttributedType::attr_neon_vector_type:
  784. case AttributedType::attr_neon_polyvector_type: {
  785. if (T->getAttrKind() == AttributedType::attr_neon_vector_type)
  786. S += "neon_vector_type(";
  787. else
  788. S += "neon_polyvector_type(";
  789. const VectorType *vector = T->getEquivalentType()->getAs<VectorType>();
  790. S += llvm::utostr_32(vector->getNumElements());
  791. S += ")";
  792. break;
  793. }
  794. case AttributedType::attr_regparm: {
  795. S += "regparm(";
  796. QualType t = T->getEquivalentType();
  797. while (!t->isFunctionType())
  798. t = t->getPointeeType();
  799. S += t->getAs<FunctionType>()->getRegParmType();
  800. S += ")";
  801. break;
  802. }
  803. case AttributedType::attr_objc_gc: {
  804. S += "objc_gc(";
  805. QualType tmp = T->getEquivalentType();
  806. while (tmp.getObjCGCAttr() == Qualifiers::GCNone) {
  807. QualType next = tmp->getPointeeType();
  808. if (next == tmp) break;
  809. tmp = next;
  810. }
  811. if (tmp.isObjCGCWeak())
  812. S += "weak";
  813. else
  814. S += "strong";
  815. S += ")";
  816. break;
  817. }
  818. case AttributedType::attr_objc_ownership:
  819. S += "objc_ownership(";
  820. switch (T->getEquivalentType().getObjCLifetime()) {
  821. case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
  822. case Qualifiers::OCL_ExplicitNone: S += "none"; break;
  823. case Qualifiers::OCL_Strong: S += "strong"; break;
  824. case Qualifiers::OCL_Weak: S += "weak"; break;
  825. case Qualifiers::OCL_Autoreleasing: S += "autoreleasing"; break;
  826. }
  827. S += ")";
  828. break;
  829. case AttributedType::attr_noreturn: S += "noreturn"; break;
  830. case AttributedType::attr_cdecl: S += "cdecl"; break;
  831. case AttributedType::attr_fastcall: S += "fastcall"; break;
  832. case AttributedType::attr_stdcall: S += "stdcall"; break;
  833. case AttributedType::attr_thiscall: S += "thiscall"; break;
  834. case AttributedType::attr_pascal: S += "pascal"; break;
  835. case AttributedType::attr_pcs: {
  836. S += "pcs(";
  837. QualType t = T->getEquivalentType();
  838. while (!t->isFunctionType())
  839. t = t->getPointeeType();
  840. S += (t->getAs<FunctionType>()->getCallConv() == CC_AAPCS ?
  841. "\"aapcs\"" : "\"aapcs-vfp\"");
  842. S += ")";
  843. break;
  844. }
  845. }
  846. S += "))";
  847. }
  848. void TypePrinter::printObjCInterface(const ObjCInterfaceType *T,
  849. std::string &S) {
  850. if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
  851. S = ' ' + S;
  852. std::string ObjCQIString = T->getDecl()->getNameAsString();
  853. S = ObjCQIString + S;
  854. }
  855. void TypePrinter::printObjCObject(const ObjCObjectType *T,
  856. std::string &S) {
  857. if (T->qual_empty())
  858. return print(T->getBaseType(), S);
  859. std::string tmp;
  860. print(T->getBaseType(), tmp);
  861. tmp += '<';
  862. bool isFirst = true;
  863. for (ObjCObjectType::qual_iterator
  864. I = T->qual_begin(), E = T->qual_end(); I != E; ++I) {
  865. if (isFirst)
  866. isFirst = false;
  867. else
  868. tmp += ',';
  869. tmp += (*I)->getNameAsString();
  870. }
  871. tmp += '>';
  872. if (!S.empty()) {
  873. tmp += ' ';
  874. tmp += S;
  875. }
  876. std::swap(tmp, S);
  877. }
  878. void TypePrinter::printObjCObjectPointer(const ObjCObjectPointerType *T,
  879. std::string &S) {
  880. std::string ObjCQIString;
  881. T->getPointeeType().getLocalQualifiers().getAsStringInternal(ObjCQIString,
  882. Policy);
  883. if (!ObjCQIString.empty())
  884. ObjCQIString += ' ';
  885. if (T->isObjCIdType() || T->isObjCQualifiedIdType())
  886. ObjCQIString += "id";
  887. else if (T->isObjCClassType() || T->isObjCQualifiedClassType())
  888. ObjCQIString += "Class";
  889. else if (T->isObjCSelType())
  890. ObjCQIString += "SEL";
  891. else
  892. ObjCQIString += T->getInterfaceDecl()->getNameAsString();
  893. if (!T->qual_empty()) {
  894. ObjCQIString += '<';
  895. for (ObjCObjectPointerType::qual_iterator I = T->qual_begin(),
  896. E = T->qual_end();
  897. I != E; ++I) {
  898. ObjCQIString += (*I)->getNameAsString();
  899. if (I+1 != E)
  900. ObjCQIString += ',';
  901. }
  902. ObjCQIString += '>';
  903. }
  904. if (!T->isObjCIdType() && !T->isObjCQualifiedIdType())
  905. ObjCQIString += " *"; // Don't forget the implicit pointer.
  906. else if (!S.empty()) // Prefix the basic type, e.g. 'typedefname X'.
  907. S = ' ' + S;
  908. S = ObjCQIString + S;
  909. }
  910. std::string TemplateSpecializationType::
  911. PrintTemplateArgumentList(const TemplateArgumentListInfo &Args,
  912. const PrintingPolicy &Policy) {
  913. return PrintTemplateArgumentList(Args.getArgumentArray(),
  914. Args.size(),
  915. Policy);
  916. }
  917. std::string
  918. TemplateSpecializationType::PrintTemplateArgumentList(
  919. const TemplateArgument *Args,
  920. unsigned NumArgs,
  921. const PrintingPolicy &Policy,
  922. bool SkipBrackets) {
  923. std::string SpecString;
  924. if (!SkipBrackets)
  925. SpecString += '<';
  926. for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
  927. if (SpecString.size() > unsigned(!SkipBrackets))
  928. SpecString += ", ";
  929. // Print the argument into a string.
  930. std::string ArgString;
  931. if (Args[Arg].getKind() == TemplateArgument::Pack) {
  932. ArgString = PrintTemplateArgumentList(Args[Arg].pack_begin(),
  933. Args[Arg].pack_size(),
  934. Policy, true);
  935. } else {
  936. llvm::raw_string_ostream ArgOut(ArgString);
  937. Args[Arg].print(Policy, ArgOut);
  938. }
  939. // If this is the first argument and its string representation
  940. // begins with the global scope specifier ('::foo'), add a space
  941. // to avoid printing the diagraph '<:'.
  942. if (!Arg && !ArgString.empty() && ArgString[0] == ':')
  943. SpecString += ' ';
  944. SpecString += ArgString;
  945. }
  946. // If the last character of our string is '>', add another space to
  947. // keep the two '>''s separate tokens. We don't *have* to do this in
  948. // C++0x, but it's still good hygiene.
  949. if (!SpecString.empty() && SpecString[SpecString.size() - 1] == '>')
  950. SpecString += ' ';
  951. if (!SkipBrackets)
  952. SpecString += '>';
  953. return SpecString;
  954. }
  955. // Sadly, repeat all that with TemplateArgLoc.
  956. std::string TemplateSpecializationType::
  957. PrintTemplateArgumentList(const TemplateArgumentLoc *Args, unsigned NumArgs,
  958. const PrintingPolicy &Policy) {
  959. std::string SpecString;
  960. SpecString += '<';
  961. for (unsigned Arg = 0; Arg < NumArgs; ++Arg) {
  962. if (SpecString.size() > 1)
  963. SpecString += ", ";
  964. // Print the argument into a string.
  965. std::string ArgString;
  966. if (Args[Arg].getArgument().getKind() == TemplateArgument::Pack) {
  967. ArgString = PrintTemplateArgumentList(
  968. Args[Arg].getArgument().pack_begin(),
  969. Args[Arg].getArgument().pack_size(),
  970. Policy, true);
  971. } else {
  972. llvm::raw_string_ostream ArgOut(ArgString);
  973. Args[Arg].getArgument().print(Policy, ArgOut);
  974. }
  975. // If this is the first argument and its string representation
  976. // begins with the global scope specifier ('::foo'), add a space
  977. // to avoid printing the diagraph '<:'.
  978. if (!Arg && !ArgString.empty() && ArgString[0] == ':')
  979. SpecString += ' ';
  980. SpecString += ArgString;
  981. }
  982. // If the last character of our string is '>', add another space to
  983. // keep the two '>''s separate tokens. We don't *have* to do this in
  984. // C++0x, but it's still good hygiene.
  985. if (SpecString[SpecString.size() - 1] == '>')
  986. SpecString += ' ';
  987. SpecString += '>';
  988. return SpecString;
  989. }
  990. void QualType::dump(const char *msg) const {
  991. std::string R = "identifier";
  992. LangOptions LO;
  993. getAsStringInternal(R, PrintingPolicy(LO));
  994. if (msg)
  995. llvm::errs() << msg << ": ";
  996. llvm::errs() << R << "\n";
  997. }
  998. void QualType::dump() const {
  999. dump("");
  1000. }
  1001. void Type::dump() const {
  1002. QualType(this, 0).dump();
  1003. }
  1004. std::string Qualifiers::getAsString() const {
  1005. LangOptions LO;
  1006. return getAsString(PrintingPolicy(LO));
  1007. }
  1008. // Appends qualifiers to the given string, separated by spaces. Will
  1009. // prefix a space if the string is non-empty. Will not append a final
  1010. // space.
  1011. void Qualifiers::getAsStringInternal(std::string &S,
  1012. const PrintingPolicy& Policy) const {
  1013. AppendTypeQualList(S, getCVRQualifiers());
  1014. if (unsigned addrspace = getAddressSpace()) {
  1015. if (!S.empty()) S += ' ';
  1016. switch (addrspace) {
  1017. case LangAS::opencl_global:
  1018. S += "__global";
  1019. break;
  1020. case LangAS::opencl_local:
  1021. S += "__local";
  1022. break;
  1023. case LangAS::opencl_constant:
  1024. S += "__constant";
  1025. break;
  1026. default:
  1027. S += "__attribute__((address_space(";
  1028. S += llvm::utostr_32(addrspace);
  1029. S += ")))";
  1030. }
  1031. }
  1032. if (Qualifiers::GC gc = getObjCGCAttr()) {
  1033. if (!S.empty()) S += ' ';
  1034. if (gc == Qualifiers::Weak)
  1035. S += "__weak";
  1036. else
  1037. S += "__strong";
  1038. }
  1039. if (Qualifiers::ObjCLifetime lifetime = getObjCLifetime()) {
  1040. if (!S.empty() &&
  1041. !(lifetime == Qualifiers::OCL_Strong && Policy.SuppressStrongLifetime))
  1042. S += ' ';
  1043. switch (lifetime) {
  1044. case Qualifiers::OCL_None: llvm_unreachable("none but true");
  1045. case Qualifiers::OCL_ExplicitNone: S += "__unsafe_unretained"; break;
  1046. case Qualifiers::OCL_Strong:
  1047. if (!Policy.SuppressStrongLifetime)
  1048. S += "__strong";
  1049. break;
  1050. case Qualifiers::OCL_Weak: S += "__weak"; break;
  1051. case Qualifiers::OCL_Autoreleasing: S += "__autoreleasing"; break;
  1052. }
  1053. }
  1054. }
  1055. std::string QualType::getAsString(const Type *ty, Qualifiers qs) {
  1056. std::string buffer;
  1057. LangOptions options;
  1058. getAsStringInternal(ty, qs, buffer, PrintingPolicy(options));
  1059. return buffer;
  1060. }
  1061. void QualType::getAsStringInternal(const Type *ty, Qualifiers qs,
  1062. std::string &buffer,
  1063. const PrintingPolicy &policy) {
  1064. TypePrinter(policy).print(ty, qs, buffer);
  1065. }