CodeGenTBAA.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. //===-- CodeGenTBAA.cpp - TBAA information for LLVM CodeGen ---------------===//
  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 is the code that manages TBAA information and defines the TBAA policy
  10. // for the optimizer to use. Relevant standards text includes:
  11. //
  12. // C99 6.5p7
  13. // C++ [basic.lval] (p10 in n3126, p15 in some earlier versions)
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "CodeGenTBAA.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/Mangle.h"
  20. #include "clang/AST/RecordLayout.h"
  21. #include "clang/Basic/CodeGenOptions.h"
  22. #include "llvm/ADT/SmallSet.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/LLVMContext.h"
  25. #include "llvm/IR/Metadata.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IR/Type.h"
  28. using namespace clang;
  29. using namespace CodeGen;
  30. CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::Module &M,
  31. const CodeGenOptions &CGO,
  32. const LangOptions &Features, MangleContext &MContext)
  33. : Context(Ctx), Module(M), CodeGenOpts(CGO),
  34. Features(Features), MContext(MContext), MDHelper(M.getContext()),
  35. Root(nullptr), Char(nullptr)
  36. {}
  37. CodeGenTBAA::~CodeGenTBAA() {
  38. }
  39. llvm::MDNode *CodeGenTBAA::getRoot() {
  40. // Define the root of the tree. This identifies the tree, so that
  41. // if our LLVM IR is linked with LLVM IR from a different front-end
  42. // (or a different version of this front-end), their TBAA trees will
  43. // remain distinct, and the optimizer will treat them conservatively.
  44. if (!Root) {
  45. if (Features.CPlusPlus)
  46. Root = MDHelper.createTBAARoot("Simple C++ TBAA");
  47. else
  48. Root = MDHelper.createTBAARoot("Simple C/C++ TBAA");
  49. }
  50. return Root;
  51. }
  52. llvm::MDNode *CodeGenTBAA::createScalarTypeNode(StringRef Name,
  53. llvm::MDNode *Parent,
  54. uint64_t Size) {
  55. if (CodeGenOpts.NewStructPathTBAA) {
  56. llvm::Metadata *Id = MDHelper.createString(Name);
  57. return MDHelper.createTBAATypeNode(Parent, Size, Id);
  58. }
  59. return MDHelper.createTBAAScalarTypeNode(Name, Parent);
  60. }
  61. llvm::MDNode *CodeGenTBAA::getChar() {
  62. // Define the root of the tree for user-accessible memory. C and C++
  63. // give special powers to char and certain similar types. However,
  64. // these special powers only cover user-accessible memory, and doesn't
  65. // include things like vtables.
  66. if (!Char)
  67. Char = createScalarTypeNode("omnipotent char", getRoot(), /* Size= */ 1);
  68. return Char;
  69. }
  70. static bool TypeHasMayAlias(QualType QTy) {
  71. // Tagged types have declarations, and therefore may have attributes.
  72. if (const TagType *TTy = dyn_cast<TagType>(QTy))
  73. return TTy->getDecl()->hasAttr<MayAliasAttr>();
  74. // Typedef types have declarations, and therefore may have attributes.
  75. if (const TypedefType *TTy = dyn_cast<TypedefType>(QTy)) {
  76. if (TTy->getDecl()->hasAttr<MayAliasAttr>())
  77. return true;
  78. // Also, their underlying types may have relevant attributes.
  79. return TypeHasMayAlias(TTy->desugar());
  80. }
  81. return false;
  82. }
  83. /// Check if the given type is a valid base type to be used in access tags.
  84. static bool isValidBaseType(QualType QTy) {
  85. if (QTy->isReferenceType())
  86. return false;
  87. if (const RecordType *TTy = QTy->getAs<RecordType>()) {
  88. const RecordDecl *RD = TTy->getDecl()->getDefinition();
  89. // Incomplete types are not valid base access types.
  90. if (!RD)
  91. return false;
  92. if (RD->hasFlexibleArrayMember())
  93. return false;
  94. // RD can be struct, union, class, interface or enum.
  95. // For now, we only handle struct and class.
  96. if (RD->isStruct() || RD->isClass())
  97. return true;
  98. }
  99. return false;
  100. }
  101. llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(const Type *Ty) {
  102. uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
  103. // Handle builtin types.
  104. if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
  105. switch (BTy->getKind()) {
  106. // Character types are special and can alias anything.
  107. // In C++, this technically only includes "char" and "unsigned char",
  108. // and not "signed char". In C, it includes all three. For now,
  109. // the risk of exploiting this detail in C++ seems likely to outweigh
  110. // the benefit.
  111. case BuiltinType::Char_U:
  112. case BuiltinType::Char_S:
  113. case BuiltinType::UChar:
  114. case BuiltinType::SChar:
  115. return getChar();
  116. // Unsigned types can alias their corresponding signed types.
  117. case BuiltinType::UShort:
  118. return getTypeInfo(Context.ShortTy);
  119. case BuiltinType::UInt:
  120. return getTypeInfo(Context.IntTy);
  121. case BuiltinType::ULong:
  122. return getTypeInfo(Context.LongTy);
  123. case BuiltinType::ULongLong:
  124. return getTypeInfo(Context.LongLongTy);
  125. case BuiltinType::UInt128:
  126. return getTypeInfo(Context.Int128Ty);
  127. // Treat all other builtin types as distinct types. This includes
  128. // treating wchar_t, char16_t, and char32_t as distinct from their
  129. // "underlying types".
  130. default:
  131. return createScalarTypeNode(BTy->getName(Features), getChar(), Size);
  132. }
  133. }
  134. // C++1z [basic.lval]p10: "If a program attempts to access the stored value of
  135. // an object through a glvalue of other than one of the following types the
  136. // behavior is undefined: [...] a char, unsigned char, or std::byte type."
  137. if (Ty->isStdByteType())
  138. return getChar();
  139. // Handle pointers and references.
  140. // TODO: Implement C++'s type "similarity" and consider dis-"similar"
  141. // pointers distinct.
  142. if (Ty->isPointerType() || Ty->isReferenceType())
  143. return createScalarTypeNode("any pointer", getChar(), Size);
  144. // Accesses to arrays are accesses to objects of their element types.
  145. if (CodeGenOpts.NewStructPathTBAA && Ty->isArrayType())
  146. return getTypeInfo(cast<ArrayType>(Ty)->getElementType());
  147. // Enum types are distinct types. In C++ they have "underlying types",
  148. // however they aren't related for TBAA.
  149. if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
  150. // In C++ mode, types have linkage, so we can rely on the ODR and
  151. // on their mangled names, if they're external.
  152. // TODO: Is there a way to get a program-wide unique name for a
  153. // decl with local linkage or no linkage?
  154. if (!Features.CPlusPlus || !ETy->getDecl()->isExternallyVisible())
  155. return getChar();
  156. SmallString<256> OutName;
  157. llvm::raw_svector_ostream Out(OutName);
  158. MContext.mangleTypeName(QualType(ETy, 0), Out);
  159. return createScalarTypeNode(OutName, getChar(), Size);
  160. }
  161. // For now, handle any other kind of type conservatively.
  162. return getChar();
  163. }
  164. llvm::MDNode *CodeGenTBAA::getTypeInfo(QualType QTy) {
  165. // At -O0 or relaxed aliasing, TBAA is not emitted for regular types.
  166. if (CodeGenOpts.OptimizationLevel == 0 || CodeGenOpts.RelaxedAliasing)
  167. return nullptr;
  168. // If the type has the may_alias attribute (even on a typedef), it is
  169. // effectively in the general char alias class.
  170. if (TypeHasMayAlias(QTy))
  171. return getChar();
  172. // We need this function to not fall back to returning the "omnipotent char"
  173. // type node for aggregate and union types. Otherwise, any dereference of an
  174. // aggregate will result into the may-alias access descriptor, meaning all
  175. // subsequent accesses to direct and indirect members of that aggregate will
  176. // be considered may-alias too.
  177. // TODO: Combine getTypeInfo() and getBaseTypeInfo() into a single function.
  178. if (isValidBaseType(QTy))
  179. return getBaseTypeInfo(QTy);
  180. const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
  181. if (llvm::MDNode *N = MetadataCache[Ty])
  182. return N;
  183. // Note that the following helper call is allowed to add new nodes to the
  184. // cache, which invalidates all its previously obtained iterators. So we
  185. // first generate the node for the type and then add that node to the cache.
  186. llvm::MDNode *TypeNode = getTypeInfoHelper(Ty);
  187. return MetadataCache[Ty] = TypeNode;
  188. }
  189. TBAAAccessInfo CodeGenTBAA::getAccessInfo(QualType AccessType) {
  190. // Pointee values may have incomplete types, but they shall never be
  191. // dereferenced.
  192. if (AccessType->isIncompleteType())
  193. return TBAAAccessInfo::getIncompleteInfo();
  194. if (TypeHasMayAlias(AccessType))
  195. return TBAAAccessInfo::getMayAliasInfo();
  196. uint64_t Size = Context.getTypeSizeInChars(AccessType).getQuantity();
  197. return TBAAAccessInfo(getTypeInfo(AccessType), Size);
  198. }
  199. TBAAAccessInfo CodeGenTBAA::getVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
  200. llvm::DataLayout DL(&Module);
  201. unsigned Size = DL.getPointerTypeSize(VTablePtrType);
  202. return TBAAAccessInfo(createScalarTypeNode("vtable pointer", getRoot(), Size),
  203. Size);
  204. }
  205. bool
  206. CodeGenTBAA::CollectFields(uint64_t BaseOffset,
  207. QualType QTy,
  208. SmallVectorImpl<llvm::MDBuilder::TBAAStructField> &
  209. Fields,
  210. bool MayAlias) {
  211. /* Things not handled yet include: C++ base classes, bitfields, */
  212. if (const RecordType *TTy = QTy->getAs<RecordType>()) {
  213. const RecordDecl *RD = TTy->getDecl()->getDefinition();
  214. if (RD->hasFlexibleArrayMember())
  215. return false;
  216. // TODO: Handle C++ base classes.
  217. if (const CXXRecordDecl *Decl = dyn_cast<CXXRecordDecl>(RD))
  218. if (Decl->bases_begin() != Decl->bases_end())
  219. return false;
  220. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  221. unsigned idx = 0;
  222. for (RecordDecl::field_iterator i = RD->field_begin(),
  223. e = RD->field_end(); i != e; ++i, ++idx) {
  224. if ((*i)->isZeroSize(Context) || (*i)->isUnnamedBitfield())
  225. continue;
  226. uint64_t Offset = BaseOffset +
  227. Layout.getFieldOffset(idx) / Context.getCharWidth();
  228. QualType FieldQTy = i->getType();
  229. if (!CollectFields(Offset, FieldQTy, Fields,
  230. MayAlias || TypeHasMayAlias(FieldQTy)))
  231. return false;
  232. }
  233. return true;
  234. }
  235. /* Otherwise, treat whatever it is as a field. */
  236. uint64_t Offset = BaseOffset;
  237. uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
  238. llvm::MDNode *TBAAType = MayAlias ? getChar() : getTypeInfo(QTy);
  239. llvm::MDNode *TBAATag = getAccessTagInfo(TBAAAccessInfo(TBAAType, Size));
  240. Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
  241. return true;
  242. }
  243. llvm::MDNode *
  244. CodeGenTBAA::getTBAAStructInfo(QualType QTy) {
  245. const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
  246. if (llvm::MDNode *N = StructMetadataCache[Ty])
  247. return N;
  248. SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields;
  249. if (CollectFields(0, QTy, Fields, TypeHasMayAlias(QTy)))
  250. return MDHelper.createTBAAStructNode(Fields);
  251. // For now, handle any other kind of type conservatively.
  252. return StructMetadataCache[Ty] = nullptr;
  253. }
  254. llvm::MDNode *CodeGenTBAA::getBaseTypeInfoHelper(const Type *Ty) {
  255. if (auto *TTy = dyn_cast<RecordType>(Ty)) {
  256. const RecordDecl *RD = TTy->getDecl()->getDefinition();
  257. const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
  258. SmallVector<llvm::MDBuilder::TBAAStructField, 4> Fields;
  259. for (FieldDecl *Field : RD->fields()) {
  260. if (Field->isZeroSize(Context) || Field->isUnnamedBitfield())
  261. continue;
  262. QualType FieldQTy = Field->getType();
  263. llvm::MDNode *TypeNode = isValidBaseType(FieldQTy) ?
  264. getBaseTypeInfo(FieldQTy) : getTypeInfo(FieldQTy);
  265. if (!TypeNode)
  266. return BaseTypeMetadataCache[Ty] = nullptr;
  267. uint64_t BitOffset = Layout.getFieldOffset(Field->getFieldIndex());
  268. uint64_t Offset = Context.toCharUnitsFromBits(BitOffset).getQuantity();
  269. uint64_t Size = Context.getTypeSizeInChars(FieldQTy).getQuantity();
  270. Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size,
  271. TypeNode));
  272. }
  273. SmallString<256> OutName;
  274. if (Features.CPlusPlus) {
  275. // Don't use the mangler for C code.
  276. llvm::raw_svector_ostream Out(OutName);
  277. MContext.mangleTypeName(QualType(Ty, 0), Out);
  278. } else {
  279. OutName = RD->getName();
  280. }
  281. if (CodeGenOpts.NewStructPathTBAA) {
  282. llvm::MDNode *Parent = getChar();
  283. uint64_t Size = Context.getTypeSizeInChars(Ty).getQuantity();
  284. llvm::Metadata *Id = MDHelper.createString(OutName);
  285. return MDHelper.createTBAATypeNode(Parent, Size, Id, Fields);
  286. }
  287. // Create the struct type node with a vector of pairs (offset, type).
  288. SmallVector<std::pair<llvm::MDNode*, uint64_t>, 4> OffsetsAndTypes;
  289. for (const auto &Field : Fields)
  290. OffsetsAndTypes.push_back(std::make_pair(Field.Type, Field.Offset));
  291. return MDHelper.createTBAAStructTypeNode(OutName, OffsetsAndTypes);
  292. }
  293. return nullptr;
  294. }
  295. llvm::MDNode *CodeGenTBAA::getBaseTypeInfo(QualType QTy) {
  296. if (!isValidBaseType(QTy))
  297. return nullptr;
  298. const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
  299. if (llvm::MDNode *N = BaseTypeMetadataCache[Ty])
  300. return N;
  301. // Note that the following helper call is allowed to add new nodes to the
  302. // cache, which invalidates all its previously obtained iterators. So we
  303. // first generate the node for the type and then add that node to the cache.
  304. llvm::MDNode *TypeNode = getBaseTypeInfoHelper(Ty);
  305. return BaseTypeMetadataCache[Ty] = TypeNode;
  306. }
  307. llvm::MDNode *CodeGenTBAA::getAccessTagInfo(TBAAAccessInfo Info) {
  308. assert(!Info.isIncomplete() && "Access to an object of an incomplete type!");
  309. if (Info.isMayAlias())
  310. Info = TBAAAccessInfo(getChar(), Info.Size);
  311. if (!Info.AccessType)
  312. return nullptr;
  313. if (!CodeGenOpts.StructPathTBAA)
  314. Info = TBAAAccessInfo(Info.AccessType, Info.Size);
  315. llvm::MDNode *&N = AccessTagMetadataCache[Info];
  316. if (N)
  317. return N;
  318. if (!Info.BaseType) {
  319. Info.BaseType = Info.AccessType;
  320. assert(!Info.Offset && "Nonzero offset for an access with no base type!");
  321. }
  322. if (CodeGenOpts.NewStructPathTBAA) {
  323. return N = MDHelper.createTBAAAccessTag(Info.BaseType, Info.AccessType,
  324. Info.Offset, Info.Size);
  325. }
  326. return N = MDHelper.createTBAAStructTagNode(Info.BaseType, Info.AccessType,
  327. Info.Offset);
  328. }
  329. TBAAAccessInfo CodeGenTBAA::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
  330. TBAAAccessInfo TargetInfo) {
  331. if (SourceInfo.isMayAlias() || TargetInfo.isMayAlias())
  332. return TBAAAccessInfo::getMayAliasInfo();
  333. return TargetInfo;
  334. }
  335. TBAAAccessInfo
  336. CodeGenTBAA::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
  337. TBAAAccessInfo InfoB) {
  338. if (InfoA == InfoB)
  339. return InfoA;
  340. if (!InfoA || !InfoB)
  341. return TBAAAccessInfo();
  342. if (InfoA.isMayAlias() || InfoB.isMayAlias())
  343. return TBAAAccessInfo::getMayAliasInfo();
  344. // TODO: Implement the rest of the logic here. For example, two accesses
  345. // with same final access types result in an access to an object of that final
  346. // access type regardless of their base types.
  347. return TBAAAccessInfo::getMayAliasInfo();
  348. }
  349. TBAAAccessInfo
  350. CodeGenTBAA::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
  351. TBAAAccessInfo SrcInfo) {
  352. if (DestInfo == SrcInfo)
  353. return DestInfo;
  354. if (!DestInfo || !SrcInfo)
  355. return TBAAAccessInfo();
  356. if (DestInfo.isMayAlias() || SrcInfo.isMayAlias())
  357. return TBAAAccessInfo::getMayAliasInfo();
  358. // TODO: Implement the rest of the logic here. For example, two accesses
  359. // with same final access types result in an access to an object of that final
  360. // access type regardless of their base types.
  361. return TBAAAccessInfo::getMayAliasInfo();
  362. }