Separate out BDCE's analysis into a separate DemandedBits analysis.
[oota-llvm.git] / lib / Analysis / TypeBasedAliasAnalysis.cpp
1 //===- TypeBasedAliasAnalysis.cpp - Type-Based Alias Analysis -------------===//
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 file defines the TypeBasedAliasAnalysis pass, which implements
11 // metadata-based TBAA.
12 //
13 // In LLVM IR, memory does not have types, so LLVM's own type system is not
14 // suitable for doing TBAA. Instead, metadata is added to the IR to describe
15 // a type system of a higher level language. This can be used to implement
16 // typical C/C++ TBAA, but it can also be used to implement custom alias
17 // analysis behavior for other languages.
18 //
19 // We now support two types of metadata format: scalar TBAA and struct-path
20 // aware TBAA. After all testing cases are upgraded to use struct-path aware
21 // TBAA and we can auto-upgrade existing bc files, the support for scalar TBAA
22 // can be dropped.
23 //
24 // The scalar TBAA metadata format is very simple. TBAA MDNodes have up to
25 // three fields, e.g.:
26 //   !0 = metadata !{ metadata !"an example type tree" }
27 //   !1 = metadata !{ metadata !"int", metadata !0 }
28 //   !2 = metadata !{ metadata !"float", metadata !0 }
29 //   !3 = metadata !{ metadata !"const float", metadata !2, i64 1 }
30 //
31 // The first field is an identity field. It can be any value, usually
32 // an MDString, which uniquely identifies the type. The most important
33 // name in the tree is the name of the root node. Two trees with
34 // different root node names are entirely disjoint, even if they
35 // have leaves with common names.
36 //
37 // The second field identifies the type's parent node in the tree, or
38 // is null or omitted for a root node. A type is considered to alias
39 // all of its descendants and all of its ancestors in the tree. Also,
40 // a type is considered to alias all types in other trees, so that
41 // bitcode produced from multiple front-ends is handled conservatively.
42 //
43 // If the third field is present, it's an integer which if equal to 1
44 // indicates that the type is "constant" (meaning pointsToConstantMemory
45 // should return true; see
46 // http://llvm.org/docs/AliasAnalysis.html#OtherItfs).
47 //
48 // With struct-path aware TBAA, the MDNodes attached to an instruction using
49 // "!tbaa" are called path tag nodes.
50 //
51 // The path tag node has 4 fields with the last field being optional.
52 //
53 // The first field is the base type node, it can be a struct type node
54 // or a scalar type node. The second field is the access type node, it
55 // must be a scalar type node. The third field is the offset into the base type.
56 // The last field has the same meaning as the last field of our scalar TBAA:
57 // it's an integer which if equal to 1 indicates that the access is "constant".
58 //
59 // The struct type node has a name and a list of pairs, one pair for each member
60 // of the struct. The first element of each pair is a type node (a struct type
61 // node or a sclar type node), specifying the type of the member, the second
62 // element of each pair is the offset of the member.
63 //
64 // Given an example
65 // typedef struct {
66 //   short s;
67 // } A;
68 // typedef struct {
69 //   uint16_t s;
70 //   A a;
71 // } B;
72 //
73 // For an acess to B.a.s, we attach !5 (a path tag node) to the load/store
74 // instruction. The base type is !4 (struct B), the access type is !2 (scalar
75 // type short) and the offset is 4.
76 //
77 // !0 = metadata !{metadata !"Simple C/C++ TBAA"}
78 // !1 = metadata !{metadata !"omnipotent char", metadata !0} // Scalar type node
79 // !2 = metadata !{metadata !"short", metadata !1}           // Scalar type node
80 // !3 = metadata !{metadata !"A", metadata !2, i64 0}        // Struct type node
81 // !4 = metadata !{metadata !"B", metadata !2, i64 0, metadata !3, i64 4}
82 //                                                           // Struct type node
83 // !5 = metadata !{metadata !4, metadata !2, i64 4}          // Path tag node
84 //
85 // The struct type nodes and the scalar type nodes form a type DAG.
86 //         Root (!0)
87 //         char (!1)  -- edge to Root
88 //         short (!2) -- edge to char
89 //         A (!3) -- edge with offset 0 to short
90 //         B (!4) -- edge with offset 0 to short and edge with offset 4 to A
91 //
92 // To check if two tags (tagX and tagY) can alias, we start from the base type
93 // of tagX, follow the edge with the correct offset in the type DAG and adjust
94 // the offset until we reach the base type of tagY or until we reach the Root
95 // node.
96 // If we reach the base type of tagY, compare the adjusted offset with
97 // offset of tagY, return Alias if the offsets are the same, return NoAlias
98 // otherwise.
99 // If we reach the Root node, perform the above starting from base type of tagY
100 // to see if we reach base type of tagX.
101 //
102 // If they have different roots, they're part of different potentially
103 // unrelated type systems, so we return Alias to be conservative.
104 // If neither node is an ancestor of the other and they have the same root,
105 // then we say NoAlias.
106 //
107 // TODO: The current metadata format doesn't support struct
108 // fields. For example:
109 //   struct X {
110 //     double d;
111 //     int i;
112 //   };
113 //   void foo(struct X *x, struct X *y, double *p) {
114 //     *x = *y;
115 //     *p = 0.0;
116 //   }
117 // Struct X has a double member, so the store to *x can alias the store to *p.
118 // Currently it's not possible to precisely describe all the things struct X
119 // aliases, so struct assignments must use conservative TBAA nodes. There's
120 // no scheme for attaching metadata to @llvm.memcpy yet either.
121 //
122 //===----------------------------------------------------------------------===//
123
124 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
125 #include "llvm/ADT/SetVector.h"
126 #include "llvm/IR/Constants.h"
127 #include "llvm/IR/LLVMContext.h"
128 #include "llvm/IR/Module.h"
129 #include "llvm/Support/CommandLine.h"
130 using namespace llvm;
131
132 // A handy option for disabling TBAA functionality. The same effect can also be
133 // achieved by stripping the !tbaa tags from IR, but this option is sometimes
134 // more convenient.
135 static cl::opt<bool> EnableTBAA("enable-tbaa", cl::init(true));
136
137 namespace {
138 /// TBAANode - This is a simple wrapper around an MDNode which provides a
139 /// higher-level interface by hiding the details of how alias analysis
140 /// information is encoded in its operands.
141 class TBAANode {
142   const MDNode *Node;
143
144 public:
145   TBAANode() : Node(nullptr) {}
146   explicit TBAANode(const MDNode *N) : Node(N) {}
147
148   /// getNode - Get the MDNode for this TBAANode.
149   const MDNode *getNode() const { return Node; }
150
151   /// getParent - Get this TBAANode's Alias tree parent.
152   TBAANode getParent() const {
153     if (Node->getNumOperands() < 2)
154       return TBAANode();
155     MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
156     if (!P)
157       return TBAANode();
158     // Ok, this node has a valid parent. Return it.
159     return TBAANode(P);
160   }
161
162   /// TypeIsImmutable - Test if this TBAANode represents a type for objects
163   /// which are not modified (by any means) in the context where this
164   /// AliasAnalysis is relevant.
165   bool TypeIsImmutable() const {
166     if (Node->getNumOperands() < 3)
167       return false;
168     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(2));
169     if (!CI)
170       return false;
171     return CI->getValue()[0];
172   }
173 };
174
175 /// This is a simple wrapper around an MDNode which provides a
176 /// higher-level interface by hiding the details of how alias analysis
177 /// information is encoded in its operands.
178 class TBAAStructTagNode {
179   /// This node should be created with createTBAAStructTagNode.
180   const MDNode *Node;
181
182 public:
183   explicit TBAAStructTagNode(const MDNode *N) : Node(N) {}
184
185   /// Get the MDNode for this TBAAStructTagNode.
186   const MDNode *getNode() const { return Node; }
187
188   const MDNode *getBaseType() const {
189     return dyn_cast_or_null<MDNode>(Node->getOperand(0));
190   }
191   const MDNode *getAccessType() const {
192     return dyn_cast_or_null<MDNode>(Node->getOperand(1));
193   }
194   uint64_t getOffset() const {
195     return mdconst::extract<ConstantInt>(Node->getOperand(2))->getZExtValue();
196   }
197   /// TypeIsImmutable - Test if this TBAAStructTagNode represents a type for
198   /// objects which are not modified (by any means) in the context where this
199   /// AliasAnalysis is relevant.
200   bool TypeIsImmutable() const {
201     if (Node->getNumOperands() < 4)
202       return false;
203     ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(3));
204     if (!CI)
205       return false;
206     return CI->getValue()[0];
207   }
208 };
209
210 /// This is a simple wrapper around an MDNode which provides a
211 /// higher-level interface by hiding the details of how alias analysis
212 /// information is encoded in its operands.
213 class TBAAStructTypeNode {
214   /// This node should be created with createTBAAStructTypeNode.
215   const MDNode *Node;
216
217 public:
218   TBAAStructTypeNode() : Node(nullptr) {}
219   explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
220
221   /// Get the MDNode for this TBAAStructTypeNode.
222   const MDNode *getNode() const { return Node; }
223
224   /// Get this TBAAStructTypeNode's field in the type DAG with
225   /// given offset. Update the offset to be relative to the field type.
226   TBAAStructTypeNode getParent(uint64_t &Offset) const {
227     // Parent can be omitted for the root node.
228     if (Node->getNumOperands() < 2)
229       return TBAAStructTypeNode();
230
231     // Fast path for a scalar type node and a struct type node with a single
232     // field.
233     if (Node->getNumOperands() <= 3) {
234       uint64_t Cur = Node->getNumOperands() == 2
235                          ? 0
236                          : mdconst::extract<ConstantInt>(Node->getOperand(2))
237                                ->getZExtValue();
238       Offset -= Cur;
239       MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
240       if (!P)
241         return TBAAStructTypeNode();
242       return TBAAStructTypeNode(P);
243     }
244
245     // Assume the offsets are in order. We return the previous field if
246     // the current offset is bigger than the given offset.
247     unsigned TheIdx = 0;
248     for (unsigned Idx = 1; Idx < Node->getNumOperands(); Idx += 2) {
249       uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(Idx + 1))
250                          ->getZExtValue();
251       if (Cur > Offset) {
252         assert(Idx >= 3 &&
253                "TBAAStructTypeNode::getParent should have an offset match!");
254         TheIdx = Idx - 2;
255         break;
256       }
257     }
258     // Move along the last field.
259     if (TheIdx == 0)
260       TheIdx = Node->getNumOperands() - 2;
261     uint64_t Cur = mdconst::extract<ConstantInt>(Node->getOperand(TheIdx + 1))
262                        ->getZExtValue();
263     Offset -= Cur;
264     MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(TheIdx));
265     if (!P)
266       return TBAAStructTypeNode();
267     return TBAAStructTypeNode(P);
268   }
269 };
270 }
271
272 // Register this pass...
273 char TypeBasedAliasAnalysis::ID = 0;
274 INITIALIZE_AG_PASS(TypeBasedAliasAnalysis, AliasAnalysis, "tbaa",
275                    "Type-Based Alias Analysis", false, true, false)
276
277 ImmutablePass *llvm::createTypeBasedAliasAnalysisPass() {
278   return new TypeBasedAliasAnalysis();
279 }
280
281 bool TypeBasedAliasAnalysis::doInitialization(Module &M) {
282   InitializeAliasAnalysis(this, &M.getDataLayout());
283   return true;
284 }
285
286 void TypeBasedAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
287   AU.setPreservesAll();
288   AliasAnalysis::getAnalysisUsage(AU);
289 }
290
291 /// Check the first operand of the tbaa tag node, if it is a MDNode, we treat
292 /// it as struct-path aware TBAA format, otherwise, we treat it as scalar TBAA
293 /// format.
294 static bool isStructPathTBAA(const MDNode *MD) {
295   // Anonymous TBAA root starts with a MDNode and dragonegg uses it as
296   // a TBAA tag.
297   return isa<MDNode>(MD->getOperand(0)) && MD->getNumOperands() >= 3;
298 }
299
300 /// Aliases - Test whether the type represented by A may alias the
301 /// type represented by B.
302 bool TypeBasedAliasAnalysis::Aliases(const MDNode *A, const MDNode *B) const {
303   // Make sure that both MDNodes are struct-path aware.
304   if (isStructPathTBAA(A) && isStructPathTBAA(B))
305     return PathAliases(A, B);
306
307   // Keep track of the root node for A and B.
308   TBAANode RootA, RootB;
309
310   // Climb the tree from A to see if we reach B.
311   for (TBAANode T(A);;) {
312     if (T.getNode() == B)
313       // B is an ancestor of A.
314       return true;
315
316     RootA = T;
317     T = T.getParent();
318     if (!T.getNode())
319       break;
320   }
321
322   // Climb the tree from B to see if we reach A.
323   for (TBAANode T(B);;) {
324     if (T.getNode() == A)
325       // A is an ancestor of B.
326       return true;
327
328     RootB = T;
329     T = T.getParent();
330     if (!T.getNode())
331       break;
332   }
333
334   // Neither node is an ancestor of the other.
335
336   // If they have different roots, they're part of different potentially
337   // unrelated type systems, so we must be conservative.
338   if (RootA.getNode() != RootB.getNode())
339     return true;
340
341   // If they have the same root, then we've proved there's no alias.
342   return false;
343 }
344
345 /// Test whether the struct-path tag represented by A may alias the
346 /// struct-path tag represented by B.
347 bool TypeBasedAliasAnalysis::PathAliases(const MDNode *A,
348                                          const MDNode *B) const {
349   // Verify that both input nodes are struct-path aware.
350   assert(isStructPathTBAA(A) && "MDNode A is not struct-path aware.");
351   assert(isStructPathTBAA(B) && "MDNode B is not struct-path aware.");
352
353   // Keep track of the root node for A and B.
354   TBAAStructTypeNode RootA, RootB;
355   TBAAStructTagNode TagA(A), TagB(B);
356
357   // TODO: We need to check if AccessType of TagA encloses AccessType of
358   // TagB to support aggregate AccessType. If yes, return true.
359
360   // Start from the base type of A, follow the edge with the correct offset in
361   // the type DAG and adjust the offset until we reach the base type of B or
362   // until we reach the Root node.
363   // Compare the adjusted offset once we have the same base.
364
365   // Climb the type DAG from base type of A to see if we reach base type of B.
366   const MDNode *BaseA = TagA.getBaseType();
367   const MDNode *BaseB = TagB.getBaseType();
368   uint64_t OffsetA = TagA.getOffset(), OffsetB = TagB.getOffset();
369   for (TBAAStructTypeNode T(BaseA);;) {
370     if (T.getNode() == BaseB)
371       // Base type of A encloses base type of B, check if the offsets match.
372       return OffsetA == OffsetB;
373
374     RootA = T;
375     // Follow the edge with the correct offset, OffsetA will be adjusted to
376     // be relative to the field type.
377     T = T.getParent(OffsetA);
378     if (!T.getNode())
379       break;
380   }
381
382   // Reset OffsetA and climb the type DAG from base type of B to see if we reach
383   // base type of A.
384   OffsetA = TagA.getOffset();
385   for (TBAAStructTypeNode T(BaseB);;) {
386     if (T.getNode() == BaseA)
387       // Base type of B encloses base type of A, check if the offsets match.
388       return OffsetA == OffsetB;
389
390     RootB = T;
391     // Follow the edge with the correct offset, OffsetB will be adjusted to
392     // be relative to the field type.
393     T = T.getParent(OffsetB);
394     if (!T.getNode())
395       break;
396   }
397
398   // Neither node is an ancestor of the other.
399
400   // If they have different roots, they're part of different potentially
401   // unrelated type systems, so we must be conservative.
402   if (RootA.getNode() != RootB.getNode())
403     return true;
404
405   // If they have the same root, then we've proved there's no alias.
406   return false;
407 }
408
409 AliasResult TypeBasedAliasAnalysis::alias(const MemoryLocation &LocA,
410                                           const MemoryLocation &LocB) {
411   if (!EnableTBAA)
412     return AliasAnalysis::alias(LocA, LocB);
413
414   // Get the attached MDNodes. If either value lacks a tbaa MDNode, we must
415   // be conservative.
416   const MDNode *AM = LocA.AATags.TBAA;
417   if (!AM)
418     return AliasAnalysis::alias(LocA, LocB);
419   const MDNode *BM = LocB.AATags.TBAA;
420   if (!BM)
421     return AliasAnalysis::alias(LocA, LocB);
422
423   // If they may alias, chain to the next AliasAnalysis.
424   if (Aliases(AM, BM))
425     return AliasAnalysis::alias(LocA, LocB);
426
427   // Otherwise return a definitive result.
428   return NoAlias;
429 }
430
431 bool TypeBasedAliasAnalysis::pointsToConstantMemory(const MemoryLocation &Loc,
432                                                     bool OrLocal) {
433   if (!EnableTBAA)
434     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
435
436   const MDNode *M = Loc.AATags.TBAA;
437   if (!M)
438     return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
439
440   // If this is an "immutable" type, we can assume the pointer is pointing
441   // to constant memory.
442   if ((!isStructPathTBAA(M) && TBAANode(M).TypeIsImmutable()) ||
443       (isStructPathTBAA(M) && TBAAStructTagNode(M).TypeIsImmutable()))
444     return true;
445
446   return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
447 }
448
449 FunctionModRefBehavior
450 TypeBasedAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
451   if (!EnableTBAA)
452     return AliasAnalysis::getModRefBehavior(CS);
453
454   FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
455
456   // If this is an "immutable" type, we can assume the call doesn't write
457   // to memory.
458   if (const MDNode *M = CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
459     if ((!isStructPathTBAA(M) && TBAANode(M).TypeIsImmutable()) ||
460         (isStructPathTBAA(M) && TBAAStructTagNode(M).TypeIsImmutable()))
461       Min = FMRB_OnlyReadsMemory;
462
463   return FunctionModRefBehavior(AliasAnalysis::getModRefBehavior(CS) & Min);
464 }
465
466 FunctionModRefBehavior
467 TypeBasedAliasAnalysis::getModRefBehavior(const Function *F) {
468   // Functions don't have metadata. Just chain to the next implementation.
469   return AliasAnalysis::getModRefBehavior(F);
470 }
471
472 ModRefInfo TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS,
473                                                  const MemoryLocation &Loc) {
474   if (!EnableTBAA)
475     return AliasAnalysis::getModRefInfo(CS, Loc);
476
477   if (const MDNode *L = Loc.AATags.TBAA)
478     if (const MDNode *M =
479             CS.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
480       if (!Aliases(L, M))
481         return MRI_NoModRef;
482
483   return AliasAnalysis::getModRefInfo(CS, Loc);
484 }
485
486 ModRefInfo TypeBasedAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
487                                                  ImmutableCallSite CS2) {
488   if (!EnableTBAA)
489     return AliasAnalysis::getModRefInfo(CS1, CS2);
490
491   if (const MDNode *M1 =
492           CS1.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
493     if (const MDNode *M2 =
494             CS2.getInstruction()->getMetadata(LLVMContext::MD_tbaa))
495       if (!Aliases(M1, M2))
496         return MRI_NoModRef;
497
498   return AliasAnalysis::getModRefInfo(CS1, CS2);
499 }
500
501 bool MDNode::isTBAAVtableAccess() const {
502   if (!isStructPathTBAA(this)) {
503     if (getNumOperands() < 1)
504       return false;
505     if (MDString *Tag1 = dyn_cast<MDString>(getOperand(0))) {
506       if (Tag1->getString() == "vtable pointer")
507         return true;
508     }
509     return false;
510   }
511
512   // For struct-path aware TBAA, we use the access type of the tag.
513   if (getNumOperands() < 2)
514     return false;
515   MDNode *Tag = cast_or_null<MDNode>(getOperand(1));
516   if (!Tag)
517     return false;
518   if (MDString *Tag1 = dyn_cast<MDString>(Tag->getOperand(0))) {
519     if (Tag1->getString() == "vtable pointer")
520       return true;
521   }
522   return false;
523 }
524
525 MDNode *MDNode::getMostGenericTBAA(MDNode *A, MDNode *B) {
526   if (!A || !B)
527     return nullptr;
528
529   if (A == B)
530     return A;
531
532   // For struct-path aware TBAA, we use the access type of the tag.
533   bool StructPath = isStructPathTBAA(A) && isStructPathTBAA(B);
534   if (StructPath) {
535     A = cast_or_null<MDNode>(A->getOperand(1));
536     if (!A)
537       return nullptr;
538     B = cast_or_null<MDNode>(B->getOperand(1));
539     if (!B)
540       return nullptr;
541   }
542
543   SmallSetVector<MDNode *, 4> PathA;
544   MDNode *T = A;
545   while (T) {
546     if (PathA.count(T))
547       report_fatal_error("Cycle found in TBAA metadata.");
548     PathA.insert(T);
549     T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
550                                  : nullptr;
551   }
552
553   SmallSetVector<MDNode *, 4> PathB;
554   T = B;
555   while (T) {
556     if (PathB.count(T))
557       report_fatal_error("Cycle found in TBAA metadata.");
558     PathB.insert(T);
559     T = T->getNumOperands() >= 2 ? cast_or_null<MDNode>(T->getOperand(1))
560                                  : nullptr;
561   }
562
563   int IA = PathA.size() - 1;
564   int IB = PathB.size() - 1;
565
566   MDNode *Ret = nullptr;
567   while (IA >= 0 && IB >= 0) {
568     if (PathA[IA] == PathB[IB])
569       Ret = PathA[IA];
570     else
571       break;
572     --IA;
573     --IB;
574   }
575   if (!StructPath)
576     return Ret;
577
578   if (!Ret)
579     return nullptr;
580   // We need to convert from a type node to a tag node.
581   Type *Int64 = IntegerType::get(A->getContext(), 64);
582   Metadata *Ops[3] = {Ret, Ret,
583                       ConstantAsMetadata::get(ConstantInt::get(Int64, 0))};
584   return MDNode::get(A->getContext(), Ops);
585 }
586
587 void Instruction::getAAMetadata(AAMDNodes &N, bool Merge) const {
588   if (Merge)
589     N.TBAA =
590         MDNode::getMostGenericTBAA(N.TBAA, getMetadata(LLVMContext::MD_tbaa));
591   else
592     N.TBAA = getMetadata(LLVMContext::MD_tbaa);
593
594   if (Merge)
595     N.Scope = MDNode::getMostGenericAliasScope(
596         N.Scope, getMetadata(LLVMContext::MD_alias_scope));
597   else
598     N.Scope = getMetadata(LLVMContext::MD_alias_scope);
599
600   if (Merge)
601     N.NoAlias =
602         MDNode::intersect(N.NoAlias, getMetadata(LLVMContext::MD_noalias));
603   else
604     N.NoAlias = getMetadata(LLVMContext::MD_noalias);
605 }
606