LLVM 24.0.0git
TypeBasedAliasAnalysis.cpp
Go to the documentation of this file.
1//===- TypeBasedAliasAnalysis.cpp - Type-Based Alias Analysis -------------===//
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 defines the TypeBasedAliasAnalysis pass, which implements
10// metadata-based TBAA.
11//
12// In LLVM IR, memory does not have types, so LLVM's own type system is not
13// suitable for doing TBAA. Instead, metadata is added to the IR to describe
14// a type system of a higher level language. This can be used to implement
15// typical C/C++ TBAA, but it can also be used to implement custom alias
16// analysis behavior for other languages.
17//
18// Scalar type nodes have up to three fields, e.g.:
19// !0 = !{ !"an example type tree" }
20// !1 = !{ !"int", !0 }
21// !2 = !{ !"float", !0 }
22// !3 = !{ !"const float", !2, i64 1 }
23//
24// The first field is an identity field. It can be any value, usually
25// an MDString, which uniquely identifies the type. The most important
26// name in the tree is the name of the root node. Two trees with
27// different root node names are entirely disjoint, even if they
28// have leaves with common names.
29//
30// The second field identifies the type's parent node in the tree, or
31// is null or omitted for a root node. A type is considered to alias
32// all of its descendants and all of its ancestors in the tree. Also,
33// a type is considered to alias all types in other trees, so that
34// bitcode produced from multiple front-ends is handled conservatively.
35//
36// If the third field is present, it's an integer which if equal to 1
37// indicates that the type is "constant" (meaning pointsToConstantMemory
38// should return true; see
39// http://llvm.org/docs/AliasAnalysis.html#OtherItfs).
40//
41// The MDNodes attached to an instruction using "!tbaa" are not plain type
42// nodes, but path tag nodes.
43//
44// The path tag node has 4 fields with the last field being optional.
45//
46// The first field is the base type node, it can be a struct type node
47// or a scalar type node. The second field is the access type node, it
48// must be a scalar type node. The third field is the offset into the base type.
49// The last field has the same meaning as the last field of our scalar TBAA:
50// it's an integer which if equal to 1 indicates that the access is "constant".
51//
52// The struct type node has a name and a list of pairs, one pair for each member
53// of the struct. The first element of each pair is a type node (a struct type
54// node or a scalar type node), specifying the type of the member, the second
55// element of each pair is the offset of the member.
56//
57// Given an example
58// typedef struct {
59// short s;
60// } A;
61// typedef struct {
62// uint16_t s;
63// A a;
64// } B;
65//
66// For an access to B.a.s, we attach !5 (a path tag node) to the load/store
67// instruction. The base type is !4 (struct B), the access type is !2 (scalar
68// type short) and the offset is 4.
69//
70// !0 = !{!"Simple C/C++ TBAA"}
71// !1 = !{!"omnipotent char", !0} // Scalar type node
72// !2 = !{!"short", !1} // Scalar type node
73// !3 = !{!"A", !2, i64 0} // Struct type node
74// !4 = !{!"B", !2, i64 0, !3, i64 4}
75// // Struct type node
76// !5 = !{!4, !2, i64 4} // Path tag node
77//
78// The struct type nodes and the scalar type nodes form a type DAG.
79// Root (!0)
80// char (!1) -- edge to Root
81// short (!2) -- edge to char
82// A (!3) -- edge with offset 0 to short
83// B (!4) -- edge with offset 0 to short and edge with offset 4 to A
84//
85// To check if two tags (tagX and tagY) can alias, we start from the base type
86// of tagX, follow the edge with the correct offset in the type DAG and adjust
87// the offset until we reach the base type of tagY or until we reach the Root
88// node.
89// If we reach the base type of tagY, compare the adjusted offset with
90// offset of tagY, return Alias if the offsets are the same, return NoAlias
91// otherwise.
92// If we reach the Root node, perform the above starting from base type of tagY
93// to see if we reach base type of tagX.
94//
95// If they have different roots, they're part of different potentially
96// unrelated type systems, so we return Alias to be conservative.
97// If neither node is an ancestor of the other and they have the same root,
98// then we say NoAlias.
99//
100//===----------------------------------------------------------------------===//
101
103#include "llvm/ADT/SetVector.h"
106#include "llvm/IR/Constants.h"
107#include "llvm/IR/DataLayout.h"
108#include "llvm/IR/DerivedTypes.h"
109#include "llvm/IR/InstrTypes.h"
110#include "llvm/IR/LLVMContext.h"
111#include "llvm/IR/Metadata.h"
112#include "llvm/IR/Module.h"
114#include "llvm/Pass.h"
115#include "llvm/Support/Casting.h"
117#include <cassert>
118#include <cstdint>
119
120using namespace llvm;
121
122// A handy option for disabling TBAA functionality. The same effect can also be
123// achieved by stripping the !tbaa tags from IR, but this option is sometimes
124// more convenient.
125static cl::opt<bool> EnableTBAA("enable-tbaa", cl::init(true), cl::Hidden);
126
127namespace {
128
129/// isNewFormatTypeNode - Return true iff the given type node is in the new
130/// size-aware format.
131static bool isNewFormatTypeNode(const MDNode *N) {
132 if (N->getNumOperands() < 3)
133 return false;
134 // In the old format the first operand is a string.
135 if (!isa<MDNode>(N->getOperand(0)))
136 return false;
137 return true;
138}
139
140/// This is a simple wrapper around an MDNode which provides a higher-level
141/// interface by hiding the details of how alias analysis information is encoded
142/// in its operands.
143class TBAANode {
144 const MDNode *Node = nullptr;
145
146public:
147 TBAANode() = default;
148 explicit TBAANode(const MDNode *N) : Node(N) {}
149
150 /// getNode - Get the MDNode for this TBAANode.
151 const MDNode *getNode() const { return Node; }
152
153 /// isNewFormat - Return true iff the wrapped type node is in the new
154 /// size-aware format.
155 bool isNewFormat() const { return isNewFormatTypeNode(Node); }
156
157 /// getParent - Get this TBAANode's Alias tree parent.
158 TBAANode getParent() const {
159 if (isNewFormat())
160 return TBAANode(cast<MDNode>(Node->getOperand(0)));
161
162 if (Node->getNumOperands() < 2)
163 return TBAANode();
164 const MDNode *P = dyn_cast_or_null<MDNode>(Node->getOperand(1));
165 if (!P)
166 return TBAANode();
167 // Ok, this node has a valid parent. Return it.
168 return TBAANode(P);
169 }
170};
171
172/// This is a simple wrapper around an MDNode which provides a
173/// higher-level interface by hiding the details of how alias analysis
174/// information is encoded in its operands.
175class TBAAStructTagNode {
176 /// This node should be created with createTBAAAccessTag().
177 const MDNode *Node;
178
179public:
180 explicit TBAAStructTagNode(const MDNode *N) : Node(N) {}
181
182 /// Get the MDNode for this TBAAStructTagNode.
183 const MDNode *getNode() const { return Node; }
184
185 /// isNewFormat - Return true iff the wrapped access tag is in the new
186 /// size-aware format.
187 bool isNewFormat() const {
188 if (Node->getNumOperands() < 4)
189 return false;
190 if (const MDNode *AccessType = getAccessType())
191 if (!TBAANode(AccessType).isNewFormat())
192 return false;
193 return true;
194 }
195
196 const MDNode *getBaseType() const {
197 return dyn_cast_or_null<MDNode>(Node->getOperand(0));
198 }
199
200 const MDNode *getAccessType() const {
201 return dyn_cast_or_null<MDNode>(Node->getOperand(1));
202 }
203
204 uint64_t getOffset() const {
205 return mdconst::extract<ConstantInt>(Node->getOperand(2))->getZExtValue();
206 }
207
208 uint64_t getSize() const {
209 if (!isNewFormat())
210 return UINT64_MAX;
211 return mdconst::extract<ConstantInt>(Node->getOperand(3))->getZExtValue();
212 }
213
214 /// Test if this TBAAStructTagNode represents a type for objects
215 /// which are not modified (by any means) in the context where this
216 /// AliasAnalysis is relevant.
217 bool isTypeImmutable() const {
218 unsigned OpNo = isNewFormat() ? 4 : 3;
219 if (Node->getNumOperands() < OpNo + 1)
220 return false;
221 ConstantInt *CI = mdconst::dyn_extract<ConstantInt>(Node->getOperand(OpNo));
222 if (!CI)
223 return false;
224 return CI->getValue()[0];
225 }
226};
227
228/// This is a simple wrapper around an MDNode which provides a
229/// higher-level interface by hiding the details of how alias analysis
230/// information is encoded in its operands.
231class TBAAStructTypeNode {
232 /// This node should be created with createTBAATypeNode().
233 const MDNode *Node = nullptr;
234
235public:
236 TBAAStructTypeNode() = default;
237 explicit TBAAStructTypeNode(const MDNode *N) : Node(N) {}
238
239 /// Get the MDNode for this TBAAStructTypeNode.
240 const MDNode *getNode() const { return Node; }
241
242 /// isNewFormat - Return true iff the wrapped type node is in the new
243 /// size-aware format.
244 bool isNewFormat() const { return isNewFormatTypeNode(Node); }
245
246 bool operator==(const TBAAStructTypeNode &Other) const {
247 return getNode() == Other.getNode();
248 }
249
250 /// getId - Return type identifier.
251 Metadata *getId() const {
252 return Node->getOperand(isNewFormat() ? 2 : 0);
253 }
254
255 unsigned getNumFields() const {
256 unsigned FirstFieldOpNo = isNewFormat() ? 3 : 1;
257 unsigned NumOpsPerField = isNewFormat() ? 3 : 2;
258 return (getNode()->getNumOperands() - FirstFieldOpNo) / NumOpsPerField;
259 }
260
261 TBAAStructTypeNode getFieldType(unsigned FieldIndex) const {
262 unsigned FirstFieldOpNo = isNewFormat() ? 3 : 1;
263 unsigned NumOpsPerField = isNewFormat() ? 3 : 2;
264 unsigned OpIndex = FirstFieldOpNo + FieldIndex * NumOpsPerField;
265 auto *TypeNode = cast<MDNode>(getNode()->getOperand(OpIndex));
266 return TBAAStructTypeNode(TypeNode);
267 }
268
269 /// Get this TBAAStructTypeNode's field in the type DAG with
270 /// given offset. Update the offset to be relative to the field type.
271 TBAAStructTypeNode getField(uint64_t &Offset) const {
272 bool NewFormat = isNewFormat();
273 const ArrayRef<MDOperand> Operands = Node->operands();
274 const unsigned NumOperands = Operands.size();
275
276 if (NewFormat) {
277 // New-format root and scalar type nodes have no fields.
278 if (NumOperands < 6)
279 return TBAAStructTypeNode();
280 } else {
281 // Parent can be omitted for the root node.
282 if (NumOperands < 2)
283 return TBAAStructTypeNode();
284
285 // Fast path for a scalar type node and a struct type node with a single
286 // field.
287 if (NumOperands <= 3) {
288 uint64_t Cur =
289 NumOperands == 2
290 ? 0
291 : mdconst::extract<ConstantInt>(Operands[2])->getZExtValue();
292 Offset -= Cur;
293 MDNode *P = dyn_cast_or_null<MDNode>(Operands[1]);
294 if (!P)
295 return TBAAStructTypeNode();
296 return TBAAStructTypeNode(P);
297 }
298 }
299
300 // Assume the offsets are in order. We return the previous field if
301 // the current offset is bigger than the given offset.
302 unsigned FirstFieldOpNo = NewFormat ? 3 : 1;
303 unsigned NumOpsPerField = NewFormat ? 3 : 2;
304 unsigned TheIdx = 0;
305
306 for (unsigned Idx = FirstFieldOpNo; Idx < NumOperands;
307 Idx += NumOpsPerField) {
308 uint64_t Cur =
309 mdconst::extract<ConstantInt>(Operands[Idx + 1])->getZExtValue();
310 if (Cur > Offset) {
311 assert(Idx >= FirstFieldOpNo + NumOpsPerField &&
312 "TBAAStructTypeNode::getField should have an offset match!");
313 TheIdx = Idx - NumOpsPerField;
314 break;
315 }
316 }
317 // Move along the last field.
318 if (TheIdx == 0)
319 TheIdx = NumOperands - NumOpsPerField;
320 uint64_t Cur =
321 mdconst::extract<ConstantInt>(Operands[TheIdx + 1])->getZExtValue();
322 Offset -= Cur;
323 MDNode *P = dyn_cast_or_null<MDNode>(Operands[TheIdx]);
324 if (!P)
325 return TBAAStructTypeNode();
326 return TBAAStructTypeNode(P);
327 }
328};
329
330} // end anonymous namespace
331
333 const MemoryLocation &LocB,
334 AAQueryInfo &AAQI, const Instruction *) {
335 if (!shouldUseTBAA())
337
338 if (Aliases(LocA.AATags.TBAA, LocB.AATags.TBAA))
340
341 // Otherwise return a definitive result.
343}
344
346 const Instruction *CtxI) {
347 if (!shouldUseTBAA())
349
350 const auto *N = Loc.AATags.TBAA;
351 if (!N)
353
354 // There cannot be any alias with errno if TBAA proves the given memory
355 // location does not alias errno.
356 const auto *ErrnoTBAAMD =
357 CtxI->getModule()->getNamedMetadata("llvm.errno.tbaa");
358 if (!ErrnoTBAAMD || any_of(ErrnoTBAAMD->operands(), [&](const auto *Node) {
359 return Aliases(N, Node);
360 }))
363}
364
366 AAQueryInfo &AAQI,
367 bool IgnoreLocals) {
368 if (!shouldUseTBAA())
369 return ModRefInfo::ModRef;
370
371 const MDNode *M = Loc.AATags.TBAA;
372 if (!M)
373 return ModRefInfo::ModRef;
374
375 // If this is an "immutable" type, we can assume the pointer is pointing
376 // to constant memory.
377 if (TBAAStructTagNode(M).isTypeImmutable())
379
380 return ModRefInfo::ModRef;
381}
382
384 AAQueryInfo &AAQI) {
385 if (!shouldUseTBAA())
386 return MemoryEffects::unknown();
387
388 // If this is an "immutable" type, the access is not observable.
389 if (const MDNode *M = Call->getMetadata(LLVMContext::MD_tbaa))
390 if (TBAAStructTagNode(M).isTypeImmutable())
391 return MemoryEffects::none();
392
393 return MemoryEffects::unknown();
394}
395
397 // Functions don't have metadata.
398 return MemoryEffects::unknown();
399}
400
402 const MemoryLocation &Loc,
403 AAQueryInfo &AAQI) {
404 if (!shouldUseTBAA())
405 return ModRefInfo::ModRef;
406
407 if (const MDNode *L = Loc.AATags.TBAA)
408 if (const MDNode *M = Call->getMetadata(LLVMContext::MD_tbaa))
409 if (!Aliases(L, M))
411
412 return ModRefInfo::ModRef;
413}
414
416 const CallBase *Call2,
417 AAQueryInfo &AAQI) {
418 if (!shouldUseTBAA())
419 return ModRefInfo::ModRef;
420
421 if (const MDNode *M1 = Call1->getMetadata(LLVMContext::MD_tbaa))
422 if (const MDNode *M2 = Call2->getMetadata(LLVMContext::MD_tbaa))
423 if (!Aliases(M1, M2))
425
426 return ModRefInfo::ModRef;
427}
428
430 // For struct-path aware TBAA, we use the access type of the tag.
431 TBAAStructTagNode Tag(this);
432 TBAAStructTypeNode AccessType(Tag.getAccessType());
433 if(auto *Id = dyn_cast<MDString>(AccessType.getId()))
434 if (Id->getString() == "vtable pointer")
435 return true;
436 return false;
437}
438
439static bool matchAccessTags(const MDNode *A, const MDNode *B,
440 const MDNode **GenericTag = nullptr);
441
443 const MDNode *GenericTag;
444 matchAccessTags(A, B, &GenericTag);
445 return const_cast<MDNode*>(GenericTag);
446}
447
448static const MDNode *getLeastCommonType(const MDNode *A, const MDNode *B) {
449 if (!A || !B)
450 return nullptr;
451
452 if (A == B)
453 return A;
454
456 TBAANode TA(A);
457 while (TA.getNode()) {
458 [[maybe_unused]] bool Inserted = PathA.insert(TA.getNode());
459 assert(Inserted && "Cycle found in TBAA metadata.");
460 TA = TA.getParent();
461 }
462
464 TBAANode TB(B);
465 while (TB.getNode()) {
466 [[maybe_unused]] bool Inserted = PathB.insert(TB.getNode());
467 assert(Inserted && "Cycle found in TBAA metadata.");
468 TB = TB.getParent();
469 }
470
471 int IA = PathA.size() - 1;
472 int IB = PathB.size() - 1;
473
474 const MDNode *Ret = nullptr;
475 while (IA >= 0 && IB >= 0) {
476 if (PathA[IA] == PathB[IB])
477 Ret = PathA[IA];
478 else
479 break;
480 --IA;
481 --IB;
482 }
483
484 return Ret;
485}
486
488 AAMDNodes Result;
489 Result.TBAA = MDNode::getMostGenericTBAA(TBAA, Other.TBAA);
490 Result.TBAAStruct = nullptr;
491 Result.Scope = MDNode::getMostGenericAliasScope(Scope, Other.Scope);
492 Result.NoAlias = MDNode::intersect(NoAlias, Other.NoAlias);
493 Result.NoAliasAddrSpace = MDNode::getMostGenericNoaliasAddrspace(
494 NoAliasAddrSpace, Other.NoAliasAddrSpace);
495 return Result;
496}
497
499 AAMDNodes Result;
500 Result.TBAA = Result.TBAAStruct = nullptr;
501 Result.Scope = MDNode::getMostGenericAliasScope(Scope, Other.Scope);
502 Result.NoAlias = MDNode::intersect(NoAlias, Other.NoAlias);
503 Result.NoAliasAddrSpace = MDNode::getMostGenericNoaliasAddrspace(
504 NoAliasAddrSpace, Other.NoAliasAddrSpace);
505 return Result;
506}
507
508static const MDNode *createAccessTag(const MDNode *AccessType) {
509 // If there is no access type or the access type is the root node, then
510 // we don't have any useful access tag to return.
511 if (!AccessType || AccessType->getNumOperands() < 2)
512 return nullptr;
513
514 Type *Int64 = IntegerType::get(AccessType->getContext(), 64);
515 auto *OffsetNode = ConstantAsMetadata::get(ConstantInt::get(Int64, 0));
516
517 if (TBAAStructTypeNode(AccessType).isNewFormat()) {
518 // TODO: Take access ranges into account when matching access tags and
519 // fix this code to generate actual access sizes for generic tags.
520 uint64_t AccessSize = UINT64_MAX;
521 auto *SizeNode =
522 ConstantAsMetadata::get(ConstantInt::get(Int64, AccessSize));
523 Metadata *Ops[] = {const_cast<MDNode*>(AccessType),
524 const_cast<MDNode*>(AccessType),
525 OffsetNode, SizeNode};
526 return MDNode::get(AccessType->getContext(), Ops);
527 }
528
529 Metadata *Ops[] = {const_cast<MDNode*>(AccessType),
530 const_cast<MDNode*>(AccessType),
531 OffsetNode};
532 return MDNode::get(AccessType->getContext(), Ops);
533}
534
535static bool hasField(TBAAStructTypeNode BaseType,
536 TBAAStructTypeNode FieldType) {
537 for (unsigned I = 0, E = BaseType.getNumFields(); I != E; ++I) {
538 TBAAStructTypeNode T = BaseType.getFieldType(I);
539 if (T == FieldType || hasField(T, FieldType))
540 return true;
541 }
542 return false;
543}
544
545/// Return true if for two given accesses, one of the accessed objects may be a
546/// subobject of the other. The \p BaseTag and \p SubobjectTag parameters
547/// describe the accesses to the base object and the subobject respectively.
548/// \p CommonType must be the metadata node describing the common type of the
549/// accessed objects. On return, \p MayAlias is set to true iff these accesses
550/// may alias and \p Generic, if not null, points to the most generic access
551/// tag for the given two.
552static bool mayBeAccessToSubobjectOf(TBAAStructTagNode BaseTag,
553 TBAAStructTagNode SubobjectTag,
554 const MDNode *CommonType,
555 const MDNode **GenericTag,
556 bool &MayAlias) {
557 // If the base object is of the least common type, then this may be an access
558 // to its subobject.
559 if (BaseTag.getAccessType() == BaseTag.getBaseType() &&
560 BaseTag.getAccessType() == CommonType) {
561 if (GenericTag)
562 *GenericTag = createAccessTag(CommonType);
563 MayAlias = true;
564 return true;
565 }
566
567 // If the access to the base object is through a field of the subobject's
568 // type, then this may be an access to that field. To check for that we start
569 // from the base type, follow the edge with the correct offset in the type DAG
570 // and adjust the offset until we reach the field type or until we reach the
571 // access type.
572 bool NewFormat = BaseTag.isNewFormat();
573 TBAAStructTypeNode BaseType(BaseTag.getBaseType());
574 uint64_t OffsetInBase = BaseTag.getOffset();
575
576 for (;;) {
577 // In the old format there is no distinction between fields and parent
578 // types, so in this case we consider all nodes up to the root.
579 if (!BaseType.getNode()) {
580 assert(!NewFormat && "Did not see access type in access path!");
581 break;
582 }
583
584 if (BaseType.getNode() == SubobjectTag.getBaseType()) {
585 MayAlias = OffsetInBase == SubobjectTag.getOffset() ||
586 BaseType.getNode() == BaseTag.getAccessType() ||
587 SubobjectTag.getBaseType() == SubobjectTag.getAccessType();
588 if (GenericTag) {
589 if (!MayAlias) {
590 *GenericTag = createAccessTag(CommonType);
591 } else if (SubobjectTag.isTypeImmutable() &&
592 !BaseTag.isTypeImmutable()) {
593 // The generic tag can only be immutable if both accesses are, so
594 // drop the flag and keep the rest of the tag.
595 const MDNode *Tag = SubobjectTag.getNode();
596 unsigned FlagOpNo = SubobjectTag.isNewFormat() ? 4 : 3;
597 SmallVector<Metadata *, 4> Ops(Tag->operands().take_front(FlagOpNo));
598 *GenericTag = MDNode::get(Tag->getContext(), Ops);
599 } else {
600 *GenericTag = SubobjectTag.getNode();
601 }
602 }
603 return true;
604 }
605
606 // With new-format nodes we stop at the access type.
607 if (NewFormat && BaseType.getNode() == BaseTag.getAccessType())
608 break;
609
610 // Follow the edge with the correct offset. Offset will be adjusted to
611 // be relative to the field type.
612 BaseType = BaseType.getField(OffsetInBase);
613 }
614
615 // If the base object has a direct or indirect field of the subobject's type,
616 // then this may be an access to that field. We need this to check now that
617 // we support aggregates as access types.
618 if (NewFormat) {
619 // TBAAStructTypeNode BaseAccessType(BaseTag.getAccessType());
620 TBAAStructTypeNode FieldType(SubobjectTag.getBaseType());
621 if (hasField(BaseType, FieldType)) {
622 if (GenericTag)
623 *GenericTag = createAccessTag(CommonType);
624 MayAlias = true;
625 return true;
626 }
627 }
628
629 return false;
630}
631
632/// matchTags - Return true if the given couple of accesses are allowed to
633/// overlap. If \arg GenericTag is not null, then on return it points to the
634/// most generic access descriptor for the given two.
635static bool matchAccessTags(const MDNode *A, const MDNode *B,
636 const MDNode **GenericTag) {
637 if (A == B) {
638 if (GenericTag)
639 *GenericTag = A;
640 return true;
641 }
642
643 // Accesses with no TBAA information may alias with any other accesses.
644 if (!A || !B) {
645 if (GenericTag)
646 *GenericTag = nullptr;
647 return true;
648 }
649
650 TBAAStructTagNode TagA(A), TagB(B);
651 const MDNode *CommonType = getLeastCommonType(TagA.getAccessType(),
652 TagB.getAccessType());
653
654 // If the final access types have different roots, they're part of different
655 // potentially unrelated type systems, so we must be conservative.
656 if (!CommonType) {
657 if (GenericTag)
658 *GenericTag = nullptr;
659 return true;
660 }
661
662 // If one of the accessed objects may be a subobject of the other, then such
663 // accesses may alias.
664 bool MayAlias;
665 if (mayBeAccessToSubobjectOf(/* BaseTag= */ TagA, /* SubobjectTag= */ TagB,
666 CommonType, GenericTag, MayAlias) ||
667 mayBeAccessToSubobjectOf(/* BaseTag= */ TagB, /* SubobjectTag= */ TagA,
668 CommonType, GenericTag, MayAlias))
669 return MayAlias;
670
671 // Otherwise, we've proved there's no alias.
672 if (GenericTag)
673 *GenericTag = createAccessTag(CommonType);
674 return false;
675}
676
677/// Aliases - Test whether the access represented by tag A may alias the
678/// access represented by tag B.
679bool TypeBasedAAResult::Aliases(const MDNode *A, const MDNode *B) const {
680 return matchAccessTags(A, B);
681}
682
683bool TypeBasedAAResult::shouldUseTBAA() const {
684 return EnableTBAA && !UsingTypeSanitizer;
685}
686
687AnalysisKey TypeBasedAA::Key;
688
690 return TypeBasedAAResult(F.hasFnAttribute(Attribute::SanitizeType));
691}
692
694INITIALIZE_PASS(TypeBasedAAWrapperPass, "tbaa", "Type-Based Alias Analysis",
695 false, true)
696
698 return new TypeBasedAAWrapperPass();
699}
700
702
704 Result.reset(new TypeBasedAAResult(/*UsingTypeSanitizer=*/false));
705 return false;
706}
707
709 Result.reset();
710 return false;
711}
712
716
718 // Fast path if there's no offset
719 if (Offset == 0)
720 return MD;
721
722 // The correct behavior here is to add the offset into the TBAA
723 // struct node offset. The base type, however may not have defined
724 // a type at this additional offset, resulting in errors. Since
725 // this method is only used within a given load/store access
726 // the offset provided is only used to subdivide the previous load
727 // maintaining the validity of the previous TBAA.
728 //
729 // This, however, should be revisited in the future.
730 return MD;
731}
732
733// Read a !tbaa.struct field entry (an offset or a size) as a 64-bit value.
734// Returns std::nullopt if it does not fit in 64 bits.
735static std::optional<uint64_t> getTBAAStructFieldAsInt64(const MDOperand &Op) {
736 return mdconst::extract<ConstantInt>(Op)->getValue().tryZExtValue();
737}
738
739static bool isScalarAccessTag(const MDNode *Tag) {
740 TBAAStructTagNode T(Tag);
741 return T.getAccessType() == T.getBaseType();
742}
743
745 // Fast path if there's no offset
746 if (Offset == 0)
747 return MD;
749 for (size_t i = 0, size = MD->getNumOperands(); i < size; i += 3) {
751 ConstantInt *InnerSize =
753 // Don't include any triples that aren't in bounds
754 if (InnerOffset->getZExtValue() + InnerSize->getZExtValue() <= Offset)
755 continue;
756
757 uint64_t NewSize = InnerSize->getZExtValue();
758 uint64_t NewOffset = InnerOffset->getZExtValue() - Offset;
759 if (InnerOffset->getZExtValue() < Offset) {
760 NewOffset = 0;
761 NewSize -= Offset - InnerOffset->getZExtValue();
762 }
763
764 // Shift the offset of the triple
766 ConstantInt::get(InnerOffset->getType(), NewOffset)));
768 ConstantInt::get(InnerSize->getType(), NewSize)));
769 Sub.push_back(MD->getOperand(i + 2));
770 }
771 return MDNode::get(MD->getContext(), Sub);
772}
773
775 // Fast path if 0-length
776 if (Len == 0)
777 return nullptr;
778
779 TBAAStructTagNode Tag(MD);
780
781 // Only new format TBAA has a size
782 if (!Tag.isNewFormat())
783 return MD;
784
785 // If unknown size, drop the TBAA.
786 if (Len == -1)
787 return nullptr;
788
789 // Otherwise, create TBAA with the new Len
790 ArrayRef<MDOperand> MDOperands = MD->operands();
791 SmallVector<Metadata *, 4> NextNodes(MDOperands);
792 ConstantInt *PreviousSize = mdconst::extract<ConstantInt>(NextNodes[3]);
793
794 // Don't create a new MDNode if it is the same length.
795 if (PreviousSize->equalsInt(Len))
796 return MD;
797
798 NextNodes[3] =
799 ConstantAsMetadata::get(ConstantInt::get(PreviousSize->getType(), Len));
800 return MDNode::get(MD->getContext(), NextNodes);
801}
802
804 AAMDNodes New = *this;
805 MDNode *M = New.TBAAStruct;
806
807 // The access may cover several !tbaa.struct fields (e.g. a {int, int} copy
808 // widened to an i64 load/store). If those fields share a single tag and tile
809 // [0, AccessSize) with no gaps, that tag still describes the whole access.
810 New.TBAAStruct = nullptr;
811 if (New.TBAA || !M)
812 return New;
813 MDNode *CommonTag = nullptr;
814 uint64_t Offset = 0;
815 for (size_t I = 0, E = M->getNumOperands(); I + 2 < E && Offset < AccessSize;
816 I += 3) {
817 std::optional<uint64_t> FieldOffset =
818 getTBAAStructFieldAsInt64(M->getOperand(I));
819 std::optional<uint64_t> FieldSize =
820 getTBAAStructFieldAsInt64(M->getOperand(I + 1));
821 MDNode *FieldTag = dyn_cast_or_null<MDNode>(M->getOperand(I + 2));
822 if (!FieldOffset || !FieldSize || !FieldTag ||
823 !isScalarAccessTag(FieldTag) || *FieldOffset != Offset ||
824 (CommonTag && FieldTag != CommonTag))
825 break;
826 CommonTag = FieldTag;
827 Offset += *FieldSize;
828 }
829 if (Offset == AccessSize)
830 New.TBAA = CommonTag;
831 return New;
832}
833
835 const DataLayout &DL) {
836 AAMDNodes New = shift(Offset);
837 if (!DL.typeSizeEqualsStoreSize(AccessTy))
838 return New;
839 TypeSize Size = DL.getTypeStoreSize(AccessTy);
840 if (Size.isScalable())
841 return New;
842
843 return New.adjustForAccess(Size.getKnownMinValue());
844}
845
846AAMDNodes AAMDNodes::adjustForAccess(size_t Offset, unsigned AccessSize) {
847 AAMDNodes New = shift(Offset);
848 return New.adjustForAccess(AccessSize);
849}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static msgpack::DocNode getNode(msgpack::DocNode DN, msgpack::Type Type, MCValue Val)
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
dxil translate DXIL Translate Metadata
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static MemAccessTy getAccessType(const TargetTransformInfo &TTI, Instruction *Inst, Value *OperandVal)
Return the type of the memory being accessed.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
#define T
#define P(N)
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
SI Fold Operands
static enum BaseType getBaseType(const Value *Val)
Return the baseType for Val which states whether Val is exclusively derived from constant/null,...
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
This file implements a set that has insertion order iteration characteristics.
static bool matchAccessTags(const MDNode *A, const MDNode *B, const MDNode **GenericTag=nullptr)
matchTags - Return true if the given couple of accesses are allowed to overlap.
static cl::opt< bool > EnableTBAA("enable-tbaa", cl::init(true), cl::Hidden)
static bool mayBeAccessToSubobjectOf(TBAAStructTagNode BaseTag, TBAAStructTagNode SubobjectTag, const MDNode *CommonType, const MDNode **GenericTag, bool &MayAlias)
Return true if for two given accesses, one of the accessed objects may be a subobject of the other.
static bool isScalarAccessTag(const MDNode *Tag)
static std::optional< uint64_t > getTBAAStructFieldAsInt64(const MDOperand &Op)
static bool hasField(TBAAStructTypeNode BaseType, TBAAStructTypeNode FieldType)
static const MDNode * createAccessTag(const MDNode *AccessType)
static const MDNode * getLeastCommonType(const MDNode *A, const MDNode *B)
This is the interface for a metadata-based TBAA.
static unsigned getSize(unsigned Kind)
This class stores info we want to provide to or retain within an alias query.
The possible results of an alias query.
@ MayAlias
The two locations may or may not alias.
@ NoAlias
The two locations do not alias at all.
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
static ConstantAsMetadata * get(Constant *C)
Definition Metadata.h:548
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
bool equalsInt(uint64_t V) const
A helper method that can be used to determine if the constant contained within is equal to a constant...
Definition Constants.h:194
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
ImmutablePass class - This class is used to provide information that does not need to be run.
Definition Pass.h:283
ImmutablePass(char &pid)
Definition Pass.h:285
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:338
Metadata node.
Definition Metadata.h:1081
static LLVM_ABI MDNode * getMostGenericAliasScope(MDNode *A, MDNode *B)
LLVM_ABI bool isTBAAVtableAccess() const
Check whether MDNode is a vtable access.
static LLVM_ABI MDNode * getMostGenericTBAA(MDNode *A, MDNode *B)
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
static LLVM_ABI MDNode * getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B)
ArrayRef< MDOperand > operands() const
Definition Metadata.h:1435
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition Metadata.h:1579
unsigned getNumOperands() const
Return number of MDNode operands.
Definition Metadata.h:1443
LLVM_ABI MDNode(LLVMContext &Context, unsigned ID, StorageType Storage, ArrayRef< Metadata * > Ops1, ArrayRef< Metadata * > Ops2={})
Definition Metadata.cpp:651
static LLVM_ABI MDNode * intersect(MDNode *A, MDNode *B)
LLVMContext & getContext() const
Definition Metadata.h:1245
Tracking metadata reference owned by Metadata.
Definition Metadata.h:902
static MemoryEffectsBase none()
Definition ModRef.h:128
static MemoryEffectsBase unknown()
Definition ModRef.h:123
Representation for a specific memory location.
AAMDNodes AATags
The metadata nodes which describes the aliasing of the location (each member is null if that kind of ...
Root of the metadata hierarchy.
Definition Metadata.h:64
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition Module.cpp:301
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A simple AA result that uses TBAA metadata to answer queries.
LLVM_ABI AliasResult aliasErrno(const MemoryLocation &Loc, const Instruction *CtxI)
LLVM_ABI AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB, AAQueryInfo &AAQI, const Instruction *CtxI)
LLVM_ABI ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, AAQueryInfo &AAQI, bool IgnoreLocals)
LLVM_ABI ModRefInfo getModRefInfo(const CallBase *Call, const MemoryLocation &Loc, AAQueryInfo &AAQI)
LLVM_ABI MemoryEffects getMemoryEffects(const CallBase *Call, AAQueryInfo &AAQI)
Legacy wrapper pass to provide the TypeBasedAAResult object.
bool doFinalization(Module &M) override
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
bool doInitialization(Module &M) override
doInitialization - Virtual method overridden by subclasses to do any necessary initialization before ...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
LLVM_ABI TypeBasedAAResult run(Function &F, FunctionAnalysisManager &AM)
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
CallInst * Call
#define UINT64_MAX
Definition DataTypes.h:77
initializer< Ty > init(const Ty &Val)
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:707
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
MemoryEffectsBase< IRMemLocation > MemoryEffects
Summary of how a function affects memory in the program.
Definition ModRef.h:356
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
unsigned M1(unsigned Val)
Definition VE.h:377
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
Definition ModRef.h:28
@ ModRef
The access may reference and may modify the value stored in memory.
Definition ModRef.h:36
@ NoModRef
The access neither references nor modifies the value stored in memory.
Definition ModRef.h:30
@ Other
Any other memory.
Definition ModRef.h:68
@ Sub
Subtraction of integers.
LLVM_ABI ImmutablePass * createTypeBasedAAWrapperPass()
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
#define N
LLVM_ABI AAMDNodes concat(const AAMDNodes &Other) const
Determine the best AAMDNodes after concatenating two different locations together.
static LLVM_ABI MDNode * shiftTBAAStruct(MDNode *M, size_t off)
MDNode * NoAliasAddrSpace
The tag specifying the noalias address spaces.
Definition Metadata.h:803
MDNode * Scope
The tag for alias scope specification (used with noalias).
Definition Metadata.h:797
static LLVM_ABI MDNode * extendToTBAA(MDNode *TBAA, ssize_t len)
MDNode * TBAA
The tag for type-based alias analysis.
Definition Metadata.h:791
AAMDNodes shift(size_t Offset) const
Create a new AAMDNode that describes this AAMDNode after applying a constant offset to the start of t...
Definition Metadata.h:833
LLVM_ABI AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
MDNode * NoAlias
The tag specifying the noalias scope.
Definition Metadata.h:800
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
AAMDNodes()=default
static LLVM_ABI MDNode * shiftTBAA(MDNode *M, size_t off)
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29