CodeGenTBAA.cpp revision f7ccbad5d9949e7ddd1cbef43d482553b811e026
1//===--- CodeGenTypes.cpp - TBAA information for LLVM CodeGen -------------===//
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 is the code that manages TBAA information and defines the TBAA policy
11// for the optimizer to use. Relevant standards text includes:
12//
13//   C99 6.5p7
14//   C++ [basic.lval] (p10 in n3126, p15 in some earlier versions)
15//
16//===----------------------------------------------------------------------===//
17
18#include "CodeGenTBAA.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/Mangle.h"
21#include "llvm/LLVMContext.h"
22#include "llvm/Metadata.h"
23#include "llvm/Constants.h"
24#include "llvm/Type.h"
25#include "llvm/ADT/STLExtras.h"
26using namespace clang;
27using namespace CodeGen;
28
29CodeGenTBAA::CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext& VMContext,
30                         const LangOptions &Features, MangleContext &MContext)
31  : Context(Ctx), VMContext(VMContext), Features(Features), MContext(MContext),
32    Root(0), Char(0) {
33}
34
35CodeGenTBAA::~CodeGenTBAA() {
36}
37
38llvm::MDNode *CodeGenTBAA::getRoot() {
39  // Define the root of the tree. This identifies the tree, so that
40  // if our LLVM IR is linked with LLVM IR from a different front-end
41  // (or a different version of this front-end), their TBAA trees will
42  // remain distinct, and the optimizer will treat them conservatively.
43  if (!Root)
44    Root = getTBAAInfoForNamedType("Simple C/C++ TBAA", 0);
45
46  return Root;
47}
48
49llvm::MDNode *CodeGenTBAA::getChar() {
50  // Define the root of the tree for user-accessible memory. C and C++
51  // give special powers to char and certain similar types. However,
52  // these special powers only cover user-accessible memory, and doesn't
53  // include things like vtables.
54  if (!Char)
55    Char = getTBAAInfoForNamedType("omnipotent char", getRoot());
56
57  return Char;
58}
59
60/// getTBAAInfoForNamedType - Create a TBAA tree node with the given string
61/// as its identifier, and the given Parent node as its tree parent.
62llvm::MDNode *CodeGenTBAA::getTBAAInfoForNamedType(StringRef NameStr,
63                                                   llvm::MDNode *Parent,
64                                                   bool Readonly) {
65  // Currently there is only one flag defined - the readonly flag.
66  llvm::Value *Flags = 0;
67  if (Readonly)
68    Flags = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), true);
69
70  // Set up the mdnode operand list.
71  llvm::Value *Ops[] = {
72    llvm::MDString::get(VMContext, NameStr),
73    Parent,
74    Flags
75  };
76
77  // Create the mdnode.
78  unsigned Len = llvm::array_lengthof(Ops) - !Flags;
79  return llvm::MDNode::get(VMContext, llvm::makeArrayRef(Ops, Len));
80}
81
82static bool TypeHasMayAlias(QualType QTy) {
83  // Tagged types have declarations, and therefore may have attributes.
84  if (const TagType *TTy = dyn_cast<TagType>(QTy))
85    return TTy->getDecl()->hasAttr<MayAliasAttr>();
86
87  // Typedef types have declarations, and therefore may have attributes.
88  if (const TypedefType *TTy = dyn_cast<TypedefType>(QTy)) {
89    if (TTy->getDecl()->hasAttr<MayAliasAttr>())
90      return true;
91    // Also, their underlying types may have relevant attributes.
92    return TypeHasMayAlias(TTy->desugar());
93  }
94
95  return false;
96}
97
98llvm::MDNode *
99CodeGenTBAA::getTBAAInfo(QualType QTy) {
100  // If the type has the may_alias attribute (even on a typedef), it is
101  // effectively in the general char alias class.
102  if (TypeHasMayAlias(QTy))
103    return getChar();
104
105  const Type *Ty = Context.getCanonicalType(QTy).getTypePtr();
106
107  if (llvm::MDNode *N = MetadataCache[Ty])
108    return N;
109
110  // Handle builtin types.
111  if (const BuiltinType *BTy = dyn_cast<BuiltinType>(Ty)) {
112    switch (BTy->getKind()) {
113    // Character types are special and can alias anything.
114    // In C++, this technically only includes "char" and "unsigned char",
115    // and not "signed char". In C, it includes all three. For now,
116    // the risk of exploiting this detail in C++ seems likely to outweigh
117    // the benefit.
118    case BuiltinType::Char_U:
119    case BuiltinType::Char_S:
120    case BuiltinType::UChar:
121    case BuiltinType::SChar:
122      return getChar();
123
124    // Unsigned types can alias their corresponding signed types.
125    case BuiltinType::UShort:
126      return getTBAAInfo(Context.ShortTy);
127    case BuiltinType::UInt:
128      return getTBAAInfo(Context.IntTy);
129    case BuiltinType::ULong:
130      return getTBAAInfo(Context.LongTy);
131    case BuiltinType::ULongLong:
132      return getTBAAInfo(Context.LongLongTy);
133    case BuiltinType::UInt128:
134      return getTBAAInfo(Context.Int128Ty);
135
136    // Treat all other builtin types as distinct types. This includes
137    // treating wchar_t, char16_t, and char32_t as distinct from their
138    // "underlying types".
139    default:
140      return MetadataCache[Ty] =
141               getTBAAInfoForNamedType(BTy->getName(Features), getChar());
142    }
143  }
144
145  // Handle pointers.
146  // TODO: Implement C++'s type "similarity" and consider dis-"similar"
147  // pointers distinct.
148  if (Ty->isPointerType())
149    return MetadataCache[Ty] = getTBAAInfoForNamedType("any pointer",
150                                                       getChar());
151
152  // Enum types are distinct types. In C++ they have "underlying types",
153  // however they aren't related for TBAA.
154  if (const EnumType *ETy = dyn_cast<EnumType>(Ty)) {
155    // In C mode, two anonymous enums are compatible iff their members
156    // are the same -- see C99 6.2.7p1. For now, be conservative. We could
157    // theoretically implement this by combining information about all the
158    // members into a single identifying MDNode.
159    if (!Features.CPlusPlus &&
160        ETy->getDecl()->getTypedefNameForAnonDecl())
161      return MetadataCache[Ty] = getChar();
162
163    // In C++ mode, types have linkage, so we can rely on the ODR and
164    // on their mangled names, if they're external.
165    // TODO: Is there a way to get a program-wide unique name for a
166    // decl with local linkage or no linkage?
167    if (Features.CPlusPlus &&
168        ETy->getDecl()->getLinkage() != ExternalLinkage)
169      return MetadataCache[Ty] = getChar();
170
171    // TODO: This is using the RTTI name. Is there a better way to get
172    // a unique string for a type?
173    SmallString<256> OutName;
174    llvm::raw_svector_ostream Out(OutName);
175    MContext.mangleCXXRTTIName(QualType(ETy, 0), Out);
176    Out.flush();
177    return MetadataCache[Ty] = getTBAAInfoForNamedType(OutName, getChar());
178  }
179
180  // For now, handle any other kind of type conservatively.
181  return MetadataCache[Ty] = getChar();
182}
183