APValue.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. //===--- APValue.cpp - Union class for APFloat/APSInt/Complex -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the APValue class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/APValue.h"
  13. #include "Linkage.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/CharUnits.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/Type.h"
  20. #include "llvm/Support/ErrorHandling.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. using namespace clang;
  23. /// The identity of a type_info object depends on the canonical unqualified
  24. /// type only.
  25. TypeInfoLValue::TypeInfoLValue(const Type *T)
  26. : T(T->getCanonicalTypeUnqualified().getTypePtr()) {}
  27. void TypeInfoLValue::print(llvm::raw_ostream &Out,
  28. const PrintingPolicy &Policy) const {
  29. Out << "typeid(";
  30. QualType(getType(), 0).print(Out, Policy);
  31. Out << ")";
  32. }
  33. static_assert(
  34. 1 << llvm::PointerLikeTypeTraits<TypeInfoLValue>::NumLowBitsAvailable <=
  35. alignof(Type),
  36. "Type is insufficiently aligned");
  37. APValue::LValueBase::LValueBase(const ValueDecl *P, unsigned I, unsigned V)
  38. : Ptr(P ? cast<ValueDecl>(P->getCanonicalDecl()) : nullptr), Local{I, V} {}
  39. APValue::LValueBase::LValueBase(const Expr *P, unsigned I, unsigned V)
  40. : Ptr(P), Local{I, V} {}
  41. APValue::LValueBase APValue::LValueBase::getDynamicAlloc(DynamicAllocLValue LV,
  42. QualType Type) {
  43. LValueBase Base;
  44. Base.Ptr = LV;
  45. Base.DynamicAllocType = Type.getAsOpaquePtr();
  46. return Base;
  47. }
  48. APValue::LValueBase APValue::LValueBase::getTypeInfo(TypeInfoLValue LV,
  49. QualType TypeInfo) {
  50. LValueBase Base;
  51. Base.Ptr = LV;
  52. Base.TypeInfoType = TypeInfo.getAsOpaquePtr();
  53. return Base;
  54. }
  55. QualType APValue::LValueBase::getType() const {
  56. if (!*this) return QualType();
  57. if (const ValueDecl *D = dyn_cast<const ValueDecl*>()) {
  58. // FIXME: It's unclear where we're supposed to take the type from, and
  59. // this actually matters for arrays of unknown bound. Eg:
  60. //
  61. // extern int arr[]; void f() { extern int arr[3]; };
  62. // constexpr int *p = &arr[1]; // valid?
  63. //
  64. // For now, we take the most complete type we can find.
  65. for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
  66. Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
  67. QualType T = Redecl->getType();
  68. if (!T->isIncompleteArrayType())
  69. return T;
  70. }
  71. return D->getType();
  72. }
  73. if (is<TypeInfoLValue>())
  74. return getTypeInfoType();
  75. if (is<DynamicAllocLValue>())
  76. return getDynamicAllocType();
  77. const Expr *Base = get<const Expr*>();
  78. // For a materialized temporary, the type of the temporary we materialized
  79. // may not be the type of the expression.
  80. if (const MaterializeTemporaryExpr *MTE =
  81. clang::dyn_cast<MaterializeTemporaryExpr>(Base)) {
  82. SmallVector<const Expr *, 2> CommaLHSs;
  83. SmallVector<SubobjectAdjustment, 2> Adjustments;
  84. const Expr *Temp = MTE->getSubExpr();
  85. const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
  86. Adjustments);
  87. // Keep any cv-qualifiers from the reference if we generated a temporary
  88. // for it directly. Otherwise use the type after adjustment.
  89. if (!Adjustments.empty())
  90. return Inner->getType();
  91. }
  92. return Base->getType();
  93. }
  94. unsigned APValue::LValueBase::getCallIndex() const {
  95. return (is<TypeInfoLValue>() || is<DynamicAllocLValue>()) ? 0
  96. : Local.CallIndex;
  97. }
  98. unsigned APValue::LValueBase::getVersion() const {
  99. return (is<TypeInfoLValue>() || is<DynamicAllocLValue>()) ? 0 : Local.Version;
  100. }
  101. QualType APValue::LValueBase::getTypeInfoType() const {
  102. assert(is<TypeInfoLValue>() && "not a type_info lvalue");
  103. return QualType::getFromOpaquePtr(TypeInfoType);
  104. }
  105. QualType APValue::LValueBase::getDynamicAllocType() const {
  106. assert(is<DynamicAllocLValue>() && "not a dynamic allocation lvalue");
  107. return QualType::getFromOpaquePtr(DynamicAllocType);
  108. }
  109. void APValue::LValueBase::Profile(llvm::FoldingSetNodeID &ID) const {
  110. ID.AddPointer(Ptr.getOpaqueValue());
  111. if (is<TypeInfoLValue>() || is<DynamicAllocLValue>())
  112. return;
  113. ID.AddInteger(Local.CallIndex);
  114. ID.AddInteger(Local.Version);
  115. }
  116. namespace clang {
  117. bool operator==(const APValue::LValueBase &LHS,
  118. const APValue::LValueBase &RHS) {
  119. if (LHS.Ptr != RHS.Ptr)
  120. return false;
  121. if (LHS.is<TypeInfoLValue>() || LHS.is<DynamicAllocLValue>())
  122. return true;
  123. return LHS.Local.CallIndex == RHS.Local.CallIndex &&
  124. LHS.Local.Version == RHS.Local.Version;
  125. }
  126. }
  127. APValue::LValuePathEntry::LValuePathEntry(BaseOrMemberType BaseOrMember) {
  128. if (const Decl *D = BaseOrMember.getPointer())
  129. BaseOrMember.setPointer(D->getCanonicalDecl());
  130. Value = reinterpret_cast<uintptr_t>(BaseOrMember.getOpaqueValue());
  131. }
  132. void APValue::LValuePathEntry::Profile(llvm::FoldingSetNodeID &ID) const {
  133. ID.AddInteger(Value);
  134. }
  135. APValue::LValuePathSerializationHelper::LValuePathSerializationHelper(
  136. ArrayRef<LValuePathEntry> Path, QualType ElemTy)
  137. : ElemTy((const void *)ElemTy.getTypePtrOrNull()), Path(Path) {}
  138. QualType APValue::LValuePathSerializationHelper::getType() {
  139. return QualType::getFromOpaquePtr(ElemTy);
  140. }
  141. namespace {
  142. struct LVBase {
  143. APValue::LValueBase Base;
  144. CharUnits Offset;
  145. unsigned PathLength;
  146. bool IsNullPtr : 1;
  147. bool IsOnePastTheEnd : 1;
  148. };
  149. }
  150. void *APValue::LValueBase::getOpaqueValue() const {
  151. return Ptr.getOpaqueValue();
  152. }
  153. bool APValue::LValueBase::isNull() const {
  154. return Ptr.isNull();
  155. }
  156. APValue::LValueBase::operator bool () const {
  157. return static_cast<bool>(Ptr);
  158. }
  159. clang::APValue::LValueBase
  160. llvm::DenseMapInfo<clang::APValue::LValueBase>::getEmptyKey() {
  161. clang::APValue::LValueBase B;
  162. B.Ptr = DenseMapInfo<const ValueDecl*>::getEmptyKey();
  163. return B;
  164. }
  165. clang::APValue::LValueBase
  166. llvm::DenseMapInfo<clang::APValue::LValueBase>::getTombstoneKey() {
  167. clang::APValue::LValueBase B;
  168. B.Ptr = DenseMapInfo<const ValueDecl*>::getTombstoneKey();
  169. return B;
  170. }
  171. namespace clang {
  172. llvm::hash_code hash_value(const APValue::LValueBase &Base) {
  173. if (Base.is<TypeInfoLValue>() || Base.is<DynamicAllocLValue>())
  174. return llvm::hash_value(Base.getOpaqueValue());
  175. return llvm::hash_combine(Base.getOpaqueValue(), Base.getCallIndex(),
  176. Base.getVersion());
  177. }
  178. }
  179. unsigned llvm::DenseMapInfo<clang::APValue::LValueBase>::getHashValue(
  180. const clang::APValue::LValueBase &Base) {
  181. return hash_value(Base);
  182. }
  183. bool llvm::DenseMapInfo<clang::APValue::LValueBase>::isEqual(
  184. const clang::APValue::LValueBase &LHS,
  185. const clang::APValue::LValueBase &RHS) {
  186. return LHS == RHS;
  187. }
  188. struct APValue::LV : LVBase {
  189. static const unsigned InlinePathSpace =
  190. (DataSize - sizeof(LVBase)) / sizeof(LValuePathEntry);
  191. /// Path - The sequence of base classes, fields and array indices to follow to
  192. /// walk from Base to the subobject. When performing GCC-style folding, there
  193. /// may not be such a path.
  194. union {
  195. LValuePathEntry Path[InlinePathSpace];
  196. LValuePathEntry *PathPtr;
  197. };
  198. LV() { PathLength = (unsigned)-1; }
  199. ~LV() { resizePath(0); }
  200. void resizePath(unsigned Length) {
  201. if (Length == PathLength)
  202. return;
  203. if (hasPathPtr())
  204. delete [] PathPtr;
  205. PathLength = Length;
  206. if (hasPathPtr())
  207. PathPtr = new LValuePathEntry[Length];
  208. }
  209. bool hasPath() const { return PathLength != (unsigned)-1; }
  210. bool hasPathPtr() const { return hasPath() && PathLength > InlinePathSpace; }
  211. LValuePathEntry *getPath() { return hasPathPtr() ? PathPtr : Path; }
  212. const LValuePathEntry *getPath() const {
  213. return hasPathPtr() ? PathPtr : Path;
  214. }
  215. };
  216. namespace {
  217. struct MemberPointerBase {
  218. llvm::PointerIntPair<const ValueDecl*, 1, bool> MemberAndIsDerivedMember;
  219. unsigned PathLength;
  220. };
  221. }
  222. struct APValue::MemberPointerData : MemberPointerBase {
  223. static const unsigned InlinePathSpace =
  224. (DataSize - sizeof(MemberPointerBase)) / sizeof(const CXXRecordDecl*);
  225. typedef const CXXRecordDecl *PathElem;
  226. union {
  227. PathElem Path[InlinePathSpace];
  228. PathElem *PathPtr;
  229. };
  230. MemberPointerData() { PathLength = 0; }
  231. ~MemberPointerData() { resizePath(0); }
  232. void resizePath(unsigned Length) {
  233. if (Length == PathLength)
  234. return;
  235. if (hasPathPtr())
  236. delete [] PathPtr;
  237. PathLength = Length;
  238. if (hasPathPtr())
  239. PathPtr = new PathElem[Length];
  240. }
  241. bool hasPathPtr() const { return PathLength > InlinePathSpace; }
  242. PathElem *getPath() { return hasPathPtr() ? PathPtr : Path; }
  243. const PathElem *getPath() const {
  244. return hasPathPtr() ? PathPtr : Path;
  245. }
  246. };
  247. // FIXME: Reduce the malloc traffic here.
  248. APValue::Arr::Arr(unsigned NumElts, unsigned Size) :
  249. Elts(new APValue[NumElts + (NumElts != Size ? 1 : 0)]),
  250. NumElts(NumElts), ArrSize(Size) {}
  251. APValue::Arr::~Arr() { delete [] Elts; }
  252. APValue::StructData::StructData(unsigned NumBases, unsigned NumFields) :
  253. Elts(new APValue[NumBases+NumFields]),
  254. NumBases(NumBases), NumFields(NumFields) {}
  255. APValue::StructData::~StructData() {
  256. delete [] Elts;
  257. }
  258. APValue::UnionData::UnionData() : Field(nullptr), Value(new APValue) {}
  259. APValue::UnionData::~UnionData () {
  260. delete Value;
  261. }
  262. APValue::APValue(const APValue &RHS) : Kind(None) {
  263. switch (RHS.getKind()) {
  264. case None:
  265. case Indeterminate:
  266. Kind = RHS.getKind();
  267. break;
  268. case Int:
  269. MakeInt();
  270. setInt(RHS.getInt());
  271. break;
  272. case Float:
  273. MakeFloat();
  274. setFloat(RHS.getFloat());
  275. break;
  276. case FixedPoint: {
  277. APFixedPoint FXCopy = RHS.getFixedPoint();
  278. MakeFixedPoint(std::move(FXCopy));
  279. break;
  280. }
  281. case Vector:
  282. MakeVector();
  283. setVector(((const Vec *)(const char *)&RHS.Data)->Elts,
  284. RHS.getVectorLength());
  285. break;
  286. case ComplexInt:
  287. MakeComplexInt();
  288. setComplexInt(RHS.getComplexIntReal(), RHS.getComplexIntImag());
  289. break;
  290. case ComplexFloat:
  291. MakeComplexFloat();
  292. setComplexFloat(RHS.getComplexFloatReal(), RHS.getComplexFloatImag());
  293. break;
  294. case LValue:
  295. MakeLValue();
  296. if (RHS.hasLValuePath())
  297. setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), RHS.getLValuePath(),
  298. RHS.isLValueOnePastTheEnd(), RHS.isNullPointer());
  299. else
  300. setLValue(RHS.getLValueBase(), RHS.getLValueOffset(), NoLValuePath(),
  301. RHS.isNullPointer());
  302. break;
  303. case Array:
  304. MakeArray(RHS.getArrayInitializedElts(), RHS.getArraySize());
  305. for (unsigned I = 0, N = RHS.getArrayInitializedElts(); I != N; ++I)
  306. getArrayInitializedElt(I) = RHS.getArrayInitializedElt(I);
  307. if (RHS.hasArrayFiller())
  308. getArrayFiller() = RHS.getArrayFiller();
  309. break;
  310. case Struct:
  311. MakeStruct(RHS.getStructNumBases(), RHS.getStructNumFields());
  312. for (unsigned I = 0, N = RHS.getStructNumBases(); I != N; ++I)
  313. getStructBase(I) = RHS.getStructBase(I);
  314. for (unsigned I = 0, N = RHS.getStructNumFields(); I != N; ++I)
  315. getStructField(I) = RHS.getStructField(I);
  316. break;
  317. case Union:
  318. MakeUnion();
  319. setUnion(RHS.getUnionField(), RHS.getUnionValue());
  320. break;
  321. case MemberPointer:
  322. MakeMemberPointer(RHS.getMemberPointerDecl(),
  323. RHS.isMemberPointerToDerivedMember(),
  324. RHS.getMemberPointerPath());
  325. break;
  326. case AddrLabelDiff:
  327. MakeAddrLabelDiff();
  328. setAddrLabelDiff(RHS.getAddrLabelDiffLHS(), RHS.getAddrLabelDiffRHS());
  329. break;
  330. }
  331. }
  332. APValue::APValue(APValue &&RHS) : Kind(RHS.Kind), Data(RHS.Data) {
  333. RHS.Kind = None;
  334. }
  335. APValue &APValue::operator=(const APValue &RHS) {
  336. if (this != &RHS)
  337. *this = APValue(RHS);
  338. return *this;
  339. }
  340. APValue &APValue::operator=(APValue &&RHS) {
  341. if (Kind != None && Kind != Indeterminate)
  342. DestroyDataAndMakeUninit();
  343. Kind = RHS.Kind;
  344. Data = RHS.Data;
  345. RHS.Kind = None;
  346. return *this;
  347. }
  348. void APValue::DestroyDataAndMakeUninit() {
  349. if (Kind == Int)
  350. ((APSInt *)(char *)&Data)->~APSInt();
  351. else if (Kind == Float)
  352. ((APFloat *)(char *)&Data)->~APFloat();
  353. else if (Kind == FixedPoint)
  354. ((APFixedPoint *)(char *)&Data)->~APFixedPoint();
  355. else if (Kind == Vector)
  356. ((Vec *)(char *)&Data)->~Vec();
  357. else if (Kind == ComplexInt)
  358. ((ComplexAPSInt *)(char *)&Data)->~ComplexAPSInt();
  359. else if (Kind == ComplexFloat)
  360. ((ComplexAPFloat *)(char *)&Data)->~ComplexAPFloat();
  361. else if (Kind == LValue)
  362. ((LV *)(char *)&Data)->~LV();
  363. else if (Kind == Array)
  364. ((Arr *)(char *)&Data)->~Arr();
  365. else if (Kind == Struct)
  366. ((StructData *)(char *)&Data)->~StructData();
  367. else if (Kind == Union)
  368. ((UnionData *)(char *)&Data)->~UnionData();
  369. else if (Kind == MemberPointer)
  370. ((MemberPointerData *)(char *)&Data)->~MemberPointerData();
  371. else if (Kind == AddrLabelDiff)
  372. ((AddrLabelDiffData *)(char *)&Data)->~AddrLabelDiffData();
  373. Kind = None;
  374. }
  375. bool APValue::needsCleanup() const {
  376. switch (getKind()) {
  377. case None:
  378. case Indeterminate:
  379. case AddrLabelDiff:
  380. return false;
  381. case Struct:
  382. case Union:
  383. case Array:
  384. case Vector:
  385. return true;
  386. case Int:
  387. return getInt().needsCleanup();
  388. case Float:
  389. return getFloat().needsCleanup();
  390. case FixedPoint:
  391. return getFixedPoint().getValue().needsCleanup();
  392. case ComplexFloat:
  393. assert(getComplexFloatImag().needsCleanup() ==
  394. getComplexFloatReal().needsCleanup() &&
  395. "In _Complex float types, real and imaginary values always have the "
  396. "same size.");
  397. return getComplexFloatReal().needsCleanup();
  398. case ComplexInt:
  399. assert(getComplexIntImag().needsCleanup() ==
  400. getComplexIntReal().needsCleanup() &&
  401. "In _Complex int types, real and imaginary values must have the "
  402. "same size.");
  403. return getComplexIntReal().needsCleanup();
  404. case LValue:
  405. return reinterpret_cast<const LV *>(&Data)->hasPathPtr();
  406. case MemberPointer:
  407. return reinterpret_cast<const MemberPointerData *>(&Data)->hasPathPtr();
  408. }
  409. llvm_unreachable("Unknown APValue kind!");
  410. }
  411. void APValue::swap(APValue &RHS) {
  412. std::swap(Kind, RHS.Kind);
  413. std::swap(Data, RHS.Data);
  414. }
  415. /// Profile the value of an APInt, excluding its bit-width.
  416. static void profileIntValue(llvm::FoldingSetNodeID &ID, const llvm::APInt &V) {
  417. for (unsigned I = 0, N = V.getBitWidth(); I < N; I += 32)
  418. ID.AddInteger((uint32_t)V.extractBitsAsZExtValue(std::min(32u, N - I), I));
  419. }
  420. void APValue::Profile(llvm::FoldingSetNodeID &ID) const {
  421. // Note that our profiling assumes that only APValues of the same type are
  422. // ever compared. As a result, we don't consider collisions that could only
  423. // happen if the types are different. (For example, structs with different
  424. // numbers of members could profile the same.)
  425. ID.AddInteger(Kind);
  426. switch (Kind) {
  427. case None:
  428. case Indeterminate:
  429. return;
  430. case AddrLabelDiff:
  431. ID.AddPointer(getAddrLabelDiffLHS()->getLabel()->getCanonicalDecl());
  432. ID.AddPointer(getAddrLabelDiffRHS()->getLabel()->getCanonicalDecl());
  433. return;
  434. case Struct:
  435. for (unsigned I = 0, N = getStructNumBases(); I != N; ++I)
  436. getStructBase(I).Profile(ID);
  437. for (unsigned I = 0, N = getStructNumFields(); I != N; ++I)
  438. getStructField(I).Profile(ID);
  439. return;
  440. case Union:
  441. if (!getUnionField()) {
  442. ID.AddInteger(0);
  443. return;
  444. }
  445. ID.AddInteger(getUnionField()->getFieldIndex() + 1);
  446. getUnionValue().Profile(ID);
  447. return;
  448. case Array: {
  449. if (getArraySize() == 0)
  450. return;
  451. // The profile should not depend on whether the array is expanded or
  452. // not, but we don't want to profile the array filler many times for
  453. // a large array. So treat all equal trailing elements as the filler.
  454. // Elements are profiled in reverse order to support this, and the
  455. // first profiled element is followed by a count. For example:
  456. //
  457. // ['a', 'c', 'x', 'x', 'x'] is profiled as
  458. // [5, 'x', 3, 'c', 'a']
  459. llvm::FoldingSetNodeID FillerID;
  460. (hasArrayFiller() ? getArrayFiller()
  461. : getArrayInitializedElt(getArrayInitializedElts() - 1))
  462. .Profile(FillerID);
  463. ID.AddNodeID(FillerID);
  464. unsigned NumFillers = getArraySize() - getArrayInitializedElts();
  465. unsigned N = getArrayInitializedElts();
  466. // Count the number of elements equal to the last one. This loop ends
  467. // by adding an integer indicating the number of such elements, with
  468. // N set to the number of elements left to profile.
  469. while (true) {
  470. if (N == 0) {
  471. // All elements are fillers.
  472. assert(NumFillers == getArraySize());
  473. ID.AddInteger(NumFillers);
  474. break;
  475. }
  476. // No need to check if the last element is equal to the last
  477. // element.
  478. if (N != getArraySize()) {
  479. llvm::FoldingSetNodeID ElemID;
  480. getArrayInitializedElt(N - 1).Profile(ElemID);
  481. if (ElemID != FillerID) {
  482. ID.AddInteger(NumFillers);
  483. ID.AddNodeID(ElemID);
  484. --N;
  485. break;
  486. }
  487. }
  488. // This is a filler.
  489. ++NumFillers;
  490. --N;
  491. }
  492. // Emit the remaining elements.
  493. for (; N != 0; --N)
  494. getArrayInitializedElt(N - 1).Profile(ID);
  495. return;
  496. }
  497. case Vector:
  498. for (unsigned I = 0, N = getVectorLength(); I != N; ++I)
  499. getVectorElt(I).Profile(ID);
  500. return;
  501. case Int:
  502. profileIntValue(ID, getInt());
  503. return;
  504. case Float:
  505. profileIntValue(ID, getFloat().bitcastToAPInt());
  506. return;
  507. case FixedPoint:
  508. profileIntValue(ID, getFixedPoint().getValue());
  509. return;
  510. case ComplexFloat:
  511. profileIntValue(ID, getComplexFloatReal().bitcastToAPInt());
  512. profileIntValue(ID, getComplexFloatImag().bitcastToAPInt());
  513. return;
  514. case ComplexInt:
  515. profileIntValue(ID, getComplexIntReal());
  516. profileIntValue(ID, getComplexIntImag());
  517. return;
  518. case LValue:
  519. getLValueBase().Profile(ID);
  520. ID.AddInteger(getLValueOffset().getQuantity());
  521. ID.AddInteger((isNullPointer() ? 1 : 0) |
  522. (isLValueOnePastTheEnd() ? 2 : 0) |
  523. (hasLValuePath() ? 4 : 0));
  524. if (hasLValuePath()) {
  525. ID.AddInteger(getLValuePath().size());
  526. // For uniqueness, we only need to profile the entries corresponding
  527. // to union members, but we don't have the type here so we don't know
  528. // how to interpret the entries.
  529. for (LValuePathEntry E : getLValuePath())
  530. E.Profile(ID);
  531. }
  532. return;
  533. case MemberPointer:
  534. ID.AddPointer(getMemberPointerDecl());
  535. ID.AddInteger(isMemberPointerToDerivedMember());
  536. for (const CXXRecordDecl *D : getMemberPointerPath())
  537. ID.AddPointer(D);
  538. return;
  539. }
  540. llvm_unreachable("Unknown APValue kind!");
  541. }
  542. static double GetApproxValue(const llvm::APFloat &F) {
  543. llvm::APFloat V = F;
  544. bool ignored;
  545. V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
  546. &ignored);
  547. return V.convertToDouble();
  548. }
  549. void APValue::printPretty(raw_ostream &Out, const ASTContext &Ctx,
  550. QualType Ty) const {
  551. printPretty(Out, Ctx.getPrintingPolicy(), Ty, &Ctx);
  552. }
  553. void APValue::printPretty(raw_ostream &Out, const PrintingPolicy &Policy,
  554. QualType Ty, const ASTContext *Ctx) const {
  555. // There are no objects of type 'void', but values of this type can be
  556. // returned from functions.
  557. if (Ty->isVoidType()) {
  558. Out << "void()";
  559. return;
  560. }
  561. switch (getKind()) {
  562. case APValue::None:
  563. Out << "<out of lifetime>";
  564. return;
  565. case APValue::Indeterminate:
  566. Out << "<uninitialized>";
  567. return;
  568. case APValue::Int:
  569. if (Ty->isBooleanType())
  570. Out << (getInt().getBoolValue() ? "true" : "false");
  571. else
  572. Out << getInt();
  573. return;
  574. case APValue::Float:
  575. Out << GetApproxValue(getFloat());
  576. return;
  577. case APValue::FixedPoint:
  578. Out << getFixedPoint();
  579. return;
  580. case APValue::Vector: {
  581. Out << '{';
  582. QualType ElemTy = Ty->castAs<VectorType>()->getElementType();
  583. getVectorElt(0).printPretty(Out, Policy, ElemTy, Ctx);
  584. for (unsigned i = 1; i != getVectorLength(); ++i) {
  585. Out << ", ";
  586. getVectorElt(i).printPretty(Out, Policy, ElemTy, Ctx);
  587. }
  588. Out << '}';
  589. return;
  590. }
  591. case APValue::ComplexInt:
  592. Out << getComplexIntReal() << "+" << getComplexIntImag() << "i";
  593. return;
  594. case APValue::ComplexFloat:
  595. Out << GetApproxValue(getComplexFloatReal()) << "+"
  596. << GetApproxValue(getComplexFloatImag()) << "i";
  597. return;
  598. case APValue::LValue: {
  599. bool IsReference = Ty->isReferenceType();
  600. QualType InnerTy
  601. = IsReference ? Ty.getNonReferenceType() : Ty->getPointeeType();
  602. if (InnerTy.isNull())
  603. InnerTy = Ty;
  604. LValueBase Base = getLValueBase();
  605. if (!Base) {
  606. if (isNullPointer()) {
  607. Out << (Policy.Nullptr ? "nullptr" : "0");
  608. } else if (IsReference) {
  609. Out << "*(" << InnerTy.stream(Policy) << "*)"
  610. << getLValueOffset().getQuantity();
  611. } else {
  612. Out << "(" << Ty.stream(Policy) << ")"
  613. << getLValueOffset().getQuantity();
  614. }
  615. return;
  616. }
  617. if (!hasLValuePath()) {
  618. // No lvalue path: just print the offset.
  619. CharUnits O = getLValueOffset();
  620. CharUnits S = Ctx ? Ctx->getTypeSizeInCharsIfKnown(InnerTy).getValueOr(
  621. CharUnits::Zero())
  622. : CharUnits::Zero();
  623. if (!O.isZero()) {
  624. if (IsReference)
  625. Out << "*(";
  626. if (S.isZero() || O % S) {
  627. Out << "(char*)";
  628. S = CharUnits::One();
  629. }
  630. Out << '&';
  631. } else if (!IsReference) {
  632. Out << '&';
  633. }
  634. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
  635. Out << *VD;
  636. else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
  637. TI.print(Out, Policy);
  638. } else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
  639. Out << "{*new "
  640. << Base.getDynamicAllocType().stream(Policy) << "#"
  641. << DA.getIndex() << "}";
  642. } else {
  643. assert(Base.get<const Expr *>() != nullptr &&
  644. "Expecting non-null Expr");
  645. Base.get<const Expr*>()->printPretty(Out, nullptr, Policy);
  646. }
  647. if (!O.isZero()) {
  648. Out << " + " << (O / S);
  649. if (IsReference)
  650. Out << ')';
  651. }
  652. return;
  653. }
  654. // We have an lvalue path. Print it out nicely.
  655. if (!IsReference)
  656. Out << '&';
  657. else if (isLValueOnePastTheEnd())
  658. Out << "*(&";
  659. QualType ElemTy = Base.getType();
  660. if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
  661. Out << *VD;
  662. } else if (TypeInfoLValue TI = Base.dyn_cast<TypeInfoLValue>()) {
  663. TI.print(Out, Policy);
  664. } else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
  665. Out << "{*new " << Base.getDynamicAllocType().stream(Policy) << "#"
  666. << DA.getIndex() << "}";
  667. } else {
  668. const Expr *E = Base.get<const Expr*>();
  669. assert(E != nullptr && "Expecting non-null Expr");
  670. E->printPretty(Out, nullptr, Policy);
  671. }
  672. ArrayRef<LValuePathEntry> Path = getLValuePath();
  673. const CXXRecordDecl *CastToBase = nullptr;
  674. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  675. if (ElemTy->isRecordType()) {
  676. // The lvalue refers to a class type, so the next path entry is a base
  677. // or member.
  678. const Decl *BaseOrMember = Path[I].getAsBaseOrMember().getPointer();
  679. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(BaseOrMember)) {
  680. CastToBase = RD;
  681. // Leave ElemTy referring to the most-derived class. The actual type
  682. // doesn't matter except for array types.
  683. } else {
  684. const ValueDecl *VD = cast<ValueDecl>(BaseOrMember);
  685. Out << ".";
  686. if (CastToBase)
  687. Out << *CastToBase << "::";
  688. Out << *VD;
  689. ElemTy = VD->getType();
  690. }
  691. } else {
  692. // The lvalue must refer to an array.
  693. Out << '[' << Path[I].getAsArrayIndex() << ']';
  694. ElemTy = ElemTy->castAsArrayTypeUnsafe()->getElementType();
  695. }
  696. }
  697. // Handle formatting of one-past-the-end lvalues.
  698. if (isLValueOnePastTheEnd()) {
  699. // FIXME: If CastToBase is non-0, we should prefix the output with
  700. // "(CastToBase*)".
  701. Out << " + 1";
  702. if (IsReference)
  703. Out << ')';
  704. }
  705. return;
  706. }
  707. case APValue::Array: {
  708. const ArrayType *AT = Ty->castAsArrayTypeUnsafe();
  709. QualType ElemTy = AT->getElementType();
  710. Out << '{';
  711. if (unsigned N = getArrayInitializedElts()) {
  712. getArrayInitializedElt(0).printPretty(Out, Policy, ElemTy, Ctx);
  713. for (unsigned I = 1; I != N; ++I) {
  714. Out << ", ";
  715. if (I == 10) {
  716. // Avoid printing out the entire contents of large arrays.
  717. Out << "...";
  718. break;
  719. }
  720. getArrayInitializedElt(I).printPretty(Out, Policy, ElemTy, Ctx);
  721. }
  722. }
  723. Out << '}';
  724. return;
  725. }
  726. case APValue::Struct: {
  727. Out << '{';
  728. const RecordDecl *RD = Ty->castAs<RecordType>()->getDecl();
  729. bool First = true;
  730. if (unsigned N = getStructNumBases()) {
  731. const CXXRecordDecl *CD = cast<CXXRecordDecl>(RD);
  732. CXXRecordDecl::base_class_const_iterator BI = CD->bases_begin();
  733. for (unsigned I = 0; I != N; ++I, ++BI) {
  734. assert(BI != CD->bases_end());
  735. if (!First)
  736. Out << ", ";
  737. getStructBase(I).printPretty(Out, Policy, BI->getType(), Ctx);
  738. First = false;
  739. }
  740. }
  741. for (const auto *FI : RD->fields()) {
  742. if (!First)
  743. Out << ", ";
  744. if (FI->isUnnamedBitfield()) continue;
  745. getStructField(FI->getFieldIndex()).
  746. printPretty(Out, Policy, FI->getType(), Ctx);
  747. First = false;
  748. }
  749. Out << '}';
  750. return;
  751. }
  752. case APValue::Union:
  753. Out << '{';
  754. if (const FieldDecl *FD = getUnionField()) {
  755. Out << "." << *FD << " = ";
  756. getUnionValue().printPretty(Out, Policy, FD->getType(), Ctx);
  757. }
  758. Out << '}';
  759. return;
  760. case APValue::MemberPointer:
  761. // FIXME: This is not enough to unambiguously identify the member in a
  762. // multiple-inheritance scenario.
  763. if (const ValueDecl *VD = getMemberPointerDecl()) {
  764. Out << '&' << *cast<CXXRecordDecl>(VD->getDeclContext()) << "::" << *VD;
  765. return;
  766. }
  767. Out << "0";
  768. return;
  769. case APValue::AddrLabelDiff:
  770. Out << "&&" << getAddrLabelDiffLHS()->getLabel()->getName();
  771. Out << " - ";
  772. Out << "&&" << getAddrLabelDiffRHS()->getLabel()->getName();
  773. return;
  774. }
  775. llvm_unreachable("Unknown APValue kind!");
  776. }
  777. std::string APValue::getAsString(const ASTContext &Ctx, QualType Ty) const {
  778. std::string Result;
  779. llvm::raw_string_ostream Out(Result);
  780. printPretty(Out, Ctx, Ty);
  781. Out.flush();
  782. return Result;
  783. }
  784. bool APValue::toIntegralConstant(APSInt &Result, QualType SrcTy,
  785. const ASTContext &Ctx) const {
  786. if (isInt()) {
  787. Result = getInt();
  788. return true;
  789. }
  790. if (isLValue() && isNullPointer()) {
  791. Result = Ctx.MakeIntValue(Ctx.getTargetNullPointerValue(SrcTy), SrcTy);
  792. return true;
  793. }
  794. if (isLValue() && !getLValueBase()) {
  795. Result = Ctx.MakeIntValue(getLValueOffset().getQuantity(), SrcTy);
  796. return true;
  797. }
  798. return false;
  799. }
  800. const APValue::LValueBase APValue::getLValueBase() const {
  801. assert(isLValue() && "Invalid accessor");
  802. return ((const LV *)(const void *)&Data)->Base;
  803. }
  804. bool APValue::isLValueOnePastTheEnd() const {
  805. assert(isLValue() && "Invalid accessor");
  806. return ((const LV *)(const void *)&Data)->IsOnePastTheEnd;
  807. }
  808. CharUnits &APValue::getLValueOffset() {
  809. assert(isLValue() && "Invalid accessor");
  810. return ((LV *)(void *)&Data)->Offset;
  811. }
  812. bool APValue::hasLValuePath() const {
  813. assert(isLValue() && "Invalid accessor");
  814. return ((const LV *)(const char *)&Data)->hasPath();
  815. }
  816. ArrayRef<APValue::LValuePathEntry> APValue::getLValuePath() const {
  817. assert(isLValue() && hasLValuePath() && "Invalid accessor");
  818. const LV &LVal = *((const LV *)(const char *)&Data);
  819. return llvm::makeArrayRef(LVal.getPath(), LVal.PathLength);
  820. }
  821. unsigned APValue::getLValueCallIndex() const {
  822. assert(isLValue() && "Invalid accessor");
  823. return ((const LV *)(const char *)&Data)->Base.getCallIndex();
  824. }
  825. unsigned APValue::getLValueVersion() const {
  826. assert(isLValue() && "Invalid accessor");
  827. return ((const LV *)(const char *)&Data)->Base.getVersion();
  828. }
  829. bool APValue::isNullPointer() const {
  830. assert(isLValue() && "Invalid usage");
  831. return ((const LV *)(const char *)&Data)->IsNullPtr;
  832. }
  833. void APValue::setLValue(LValueBase B, const CharUnits &O, NoLValuePath,
  834. bool IsNullPtr) {
  835. assert(isLValue() && "Invalid accessor");
  836. LV &LVal = *((LV *)(char *)&Data);
  837. LVal.Base = B;
  838. LVal.IsOnePastTheEnd = false;
  839. LVal.Offset = O;
  840. LVal.resizePath((unsigned)-1);
  841. LVal.IsNullPtr = IsNullPtr;
  842. }
  843. MutableArrayRef<APValue::LValuePathEntry>
  844. APValue::setLValueUninit(LValueBase B, const CharUnits &O, unsigned Size,
  845. bool IsOnePastTheEnd, bool IsNullPtr) {
  846. assert(isLValue() && "Invalid accessor");
  847. LV &LVal = *((LV *)(char *)&Data);
  848. LVal.Base = B;
  849. LVal.IsOnePastTheEnd = IsOnePastTheEnd;
  850. LVal.Offset = O;
  851. LVal.IsNullPtr = IsNullPtr;
  852. LVal.resizePath(Size);
  853. return {LVal.getPath(), Size};
  854. }
  855. void APValue::setLValue(LValueBase B, const CharUnits &O,
  856. ArrayRef<LValuePathEntry> Path, bool IsOnePastTheEnd,
  857. bool IsNullPtr) {
  858. MutableArrayRef<APValue::LValuePathEntry> InternalPath =
  859. setLValueUninit(B, O, Path.size(), IsOnePastTheEnd, IsNullPtr);
  860. if (Path.size()) {
  861. memcpy(InternalPath.data(), Path.data(),
  862. Path.size() * sizeof(LValuePathEntry));
  863. }
  864. }
  865. void APValue::setUnion(const FieldDecl *Field, const APValue &Value) {
  866. assert(isUnion() && "Invalid accessor");
  867. ((UnionData *)(char *)&Data)->Field =
  868. Field ? Field->getCanonicalDecl() : nullptr;
  869. *((UnionData *)(char *)&Data)->Value = Value;
  870. }
  871. const ValueDecl *APValue::getMemberPointerDecl() const {
  872. assert(isMemberPointer() && "Invalid accessor");
  873. const MemberPointerData &MPD =
  874. *((const MemberPointerData *)(const char *)&Data);
  875. return MPD.MemberAndIsDerivedMember.getPointer();
  876. }
  877. bool APValue::isMemberPointerToDerivedMember() const {
  878. assert(isMemberPointer() && "Invalid accessor");
  879. const MemberPointerData &MPD =
  880. *((const MemberPointerData *)(const char *)&Data);
  881. return MPD.MemberAndIsDerivedMember.getInt();
  882. }
  883. ArrayRef<const CXXRecordDecl*> APValue::getMemberPointerPath() const {
  884. assert(isMemberPointer() && "Invalid accessor");
  885. const MemberPointerData &MPD =
  886. *((const MemberPointerData *)(const char *)&Data);
  887. return llvm::makeArrayRef(MPD.getPath(), MPD.PathLength);
  888. }
  889. void APValue::MakeLValue() {
  890. assert(isAbsent() && "Bad state change");
  891. static_assert(sizeof(LV) <= DataSize, "LV too big");
  892. new ((void *)(char *)&Data) LV();
  893. Kind = LValue;
  894. }
  895. void APValue::MakeArray(unsigned InitElts, unsigned Size) {
  896. assert(isAbsent() && "Bad state change");
  897. new ((void *)(char *)&Data) Arr(InitElts, Size);
  898. Kind = Array;
  899. }
  900. MutableArrayRef<APValue::LValuePathEntry>
  901. setLValueUninit(APValue::LValueBase B, const CharUnits &O, unsigned Size,
  902. bool OnePastTheEnd, bool IsNullPtr);
  903. MutableArrayRef<const CXXRecordDecl *>
  904. APValue::setMemberPointerUninit(const ValueDecl *Member, bool IsDerivedMember,
  905. unsigned Size) {
  906. assert(isAbsent() && "Bad state change");
  907. MemberPointerData *MPD = new ((void *)(char *)&Data) MemberPointerData;
  908. Kind = MemberPointer;
  909. MPD->MemberAndIsDerivedMember.setPointer(
  910. Member ? cast<ValueDecl>(Member->getCanonicalDecl()) : nullptr);
  911. MPD->MemberAndIsDerivedMember.setInt(IsDerivedMember);
  912. MPD->resizePath(Size);
  913. return {MPD->getPath(), MPD->PathLength};
  914. }
  915. void APValue::MakeMemberPointer(const ValueDecl *Member, bool IsDerivedMember,
  916. ArrayRef<const CXXRecordDecl *> Path) {
  917. MutableArrayRef<const CXXRecordDecl *> InternalPath =
  918. setMemberPointerUninit(Member, IsDerivedMember, Path.size());
  919. for (unsigned I = 0; I != Path.size(); ++I)
  920. InternalPath[I] = Path[I]->getCanonicalDecl();
  921. }
  922. LinkageInfo LinkageComputer::getLVForValue(const APValue &V,
  923. LVComputationKind computation) {
  924. LinkageInfo LV = LinkageInfo::external();
  925. auto MergeLV = [&](LinkageInfo MergeLV) {
  926. LV.merge(MergeLV);
  927. return LV.getLinkage() == InternalLinkage;
  928. };
  929. auto Merge = [&](const APValue &V) {
  930. return MergeLV(getLVForValue(V, computation));
  931. };
  932. switch (V.getKind()) {
  933. case APValue::None:
  934. case APValue::Indeterminate:
  935. case APValue::Int:
  936. case APValue::Float:
  937. case APValue::FixedPoint:
  938. case APValue::ComplexInt:
  939. case APValue::ComplexFloat:
  940. case APValue::Vector:
  941. break;
  942. case APValue::AddrLabelDiff:
  943. // Even for an inline function, it's not reasonable to treat a difference
  944. // between the addresses of labels as an external value.
  945. return LinkageInfo::internal();
  946. case APValue::Struct: {
  947. for (unsigned I = 0, N = V.getStructNumBases(); I != N; ++I)
  948. if (Merge(V.getStructBase(I)))
  949. break;
  950. for (unsigned I = 0, N = V.getStructNumFields(); I != N; ++I)
  951. if (Merge(V.getStructField(I)))
  952. break;
  953. break;
  954. }
  955. case APValue::Union:
  956. if (V.getUnionField())
  957. Merge(V.getUnionValue());
  958. break;
  959. case APValue::Array: {
  960. for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
  961. if (Merge(V.getArrayInitializedElt(I)))
  962. break;
  963. if (V.hasArrayFiller())
  964. Merge(V.getArrayFiller());
  965. break;
  966. }
  967. case APValue::LValue: {
  968. if (!V.getLValueBase()) {
  969. // Null or absolute address: this is external.
  970. } else if (const auto *VD =
  971. V.getLValueBase().dyn_cast<const ValueDecl *>()) {
  972. if (VD && MergeLV(getLVForDecl(VD, computation)))
  973. break;
  974. } else if (const auto TI = V.getLValueBase().dyn_cast<TypeInfoLValue>()) {
  975. if (MergeLV(getLVForType(*TI.getType(), computation)))
  976. break;
  977. } else if (const Expr *E = V.getLValueBase().dyn_cast<const Expr *>()) {
  978. // Almost all expression bases are internal. The exception is
  979. // lifetime-extended temporaries.
  980. // FIXME: These should be modeled as having the
  981. // LifetimeExtendedTemporaryDecl itself as the base.
  982. // FIXME: If we permit Objective-C object literals in template arguments,
  983. // they should not imply internal linkage.
  984. auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
  985. if (!MTE || MTE->getStorageDuration() == SD_FullExpression)
  986. return LinkageInfo::internal();
  987. if (MergeLV(getLVForDecl(MTE->getExtendingDecl(), computation)))
  988. break;
  989. } else {
  990. assert(V.getLValueBase().is<DynamicAllocLValue>() &&
  991. "unexpected LValueBase kind");
  992. return LinkageInfo::internal();
  993. }
  994. // The lvalue path doesn't matter: pointers to all subobjects always have
  995. // the same visibility as pointers to the complete object.
  996. break;
  997. }
  998. case APValue::MemberPointer:
  999. if (const NamedDecl *D = V.getMemberPointerDecl())
  1000. MergeLV(getLVForDecl(D, computation));
  1001. // Note that we could have a base-to-derived conversion here to a member of
  1002. // a derived class with less linkage/visibility. That's covered by the
  1003. // linkage and visibility of the value's type.
  1004. break;
  1005. }
  1006. return LV;
  1007. }