Bug Summary

File:include/llvm/ADT/APInt.h
Warning:line 910, column 15
Assigned value is garbage or undefined

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name BasicAliasAnalysis.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn337204/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/lib/Analysis -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-17-043059-5239-1 -x c++ /build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp

/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp

1//===- BasicAliasAnalysis.cpp - Stateless Alias Analysis Impl -------------===//
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 primary stateless implementation of the
11// Alias Analysis interface that implements identities (two different
12// globals cannot alias, etc), but does no stateful analysis.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Analysis/BasicAliasAnalysis.h"
17#include "llvm/ADT/APInt.h"
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/CFG.h"
24#include "llvm/Analysis/CaptureTracking.h"
25#include "llvm/Analysis/InstructionSimplify.h"
26#include "llvm/Analysis/LoopInfo.h"
27#include "llvm/Analysis/MemoryBuiltins.h"
28#include "llvm/Analysis/MemoryLocation.h"
29#include "llvm/Analysis/TargetLibraryInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/IR/Argument.h"
32#include "llvm/IR/Attributes.h"
33#include "llvm/IR/CallSite.h"
34#include "llvm/IR/Constant.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/DerivedTypes.h"
38#include "llvm/IR/Dominators.h"
39#include "llvm/IR/Function.h"
40#include "llvm/IR/GetElementPtrTypeIterator.h"
41#include "llvm/IR/GlobalAlias.h"
42#include "llvm/IR/GlobalVariable.h"
43#include "llvm/IR/InstrTypes.h"
44#include "llvm/IR/Instruction.h"
45#include "llvm/IR/Instructions.h"
46#include "llvm/IR/IntrinsicInst.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/Metadata.h"
49#include "llvm/IR/Operator.h"
50#include "llvm/IR/Type.h"
51#include "llvm/IR/User.h"
52#include "llvm/IR/Value.h"
53#include "llvm/Pass.h"
54#include "llvm/Support/Casting.h"
55#include "llvm/Support/CommandLine.h"
56#include "llvm/Support/Compiler.h"
57#include "llvm/Support/KnownBits.h"
58#include <cassert>
59#include <cstdint>
60#include <cstdlib>
61#include <utility>
62
63#define DEBUG_TYPE"basicaa" "basicaa"
64
65using namespace llvm;
66
67/// Enable analysis of recursive PHI nodes.
68static cl::opt<bool> EnableRecPhiAnalysis("basicaa-recphi", cl::Hidden,
69 cl::init(false));
70/// SearchLimitReached / SearchTimes shows how often the limit of
71/// to decompose GEPs is reached. It will affect the precision
72/// of basic alias analysis.
73STATISTIC(SearchLimitReached, "Number of times the limit to "static llvm::Statistic SearchLimitReached = {"basicaa", "SearchLimitReached"
, "Number of times the limit to " "decompose GEPs is reached"
, {0}, {false}}
74 "decompose GEPs is reached")static llvm::Statistic SearchLimitReached = {"basicaa", "SearchLimitReached"
, "Number of times the limit to " "decompose GEPs is reached"
, {0}, {false}}
;
75STATISTIC(SearchTimes, "Number of times a GEP is decomposed")static llvm::Statistic SearchTimes = {"basicaa", "SearchTimes"
, "Number of times a GEP is decomposed", {0}, {false}}
;
76
77/// Cutoff after which to stop analysing a set of phi nodes potentially involved
78/// in a cycle. Because we are analysing 'through' phi nodes, we need to be
79/// careful with value equivalence. We use reachability to make sure a value
80/// cannot be involved in a cycle.
81const unsigned MaxNumPhiBBsValueReachabilityCheck = 20;
82
83// The max limit of the search depth in DecomposeGEPExpression() and
84// GetUnderlyingObject(), both functions need to use the same search
85// depth otherwise the algorithm in aliasGEP will assert.
86static const unsigned MaxLookupSearchDepth = 6;
87
88bool BasicAAResult::invalidate(Function &Fn, const PreservedAnalyses &PA,
89 FunctionAnalysisManager::Invalidator &Inv) {
90 // We don't care if this analysis itself is preserved, it has no state. But
91 // we need to check that the analyses it depends on have been. Note that we
92 // may be created without handles to some analyses and in that case don't
93 // depend on them.
94 if (Inv.invalidate<AssumptionAnalysis>(Fn, PA) ||
95 (DT && Inv.invalidate<DominatorTreeAnalysis>(Fn, PA)) ||
96 (LI && Inv.invalidate<LoopAnalysis>(Fn, PA)))
97 return true;
98
99 // Otherwise this analysis result remains valid.
100 return false;
101}
102
103//===----------------------------------------------------------------------===//
104// Useful predicates
105//===----------------------------------------------------------------------===//
106
107/// Returns true if the pointer is to a function-local object that never
108/// escapes from the function.
109static bool isNonEscapingLocalObject(const Value *V) {
110 // If this is a local allocation, check to see if it escapes.
111 if (isa<AllocaInst>(V) || isNoAliasCall(V))
112 // Set StoreCaptures to True so that we can assume in our callers that the
113 // pointer is not the result of a load instruction. Currently
114 // PointerMayBeCaptured doesn't have any special analysis for the
115 // StoreCaptures=false case; if it did, our callers could be refined to be
116 // more precise.
117 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
118
119 // If this is an argument that corresponds to a byval or noalias argument,
120 // then it has not escaped before entering the function. Check if it escapes
121 // inside the function.
122 if (const Argument *A = dyn_cast<Argument>(V))
123 if (A->hasByValAttr() || A->hasNoAliasAttr())
124 // Note even if the argument is marked nocapture, we still need to check
125 // for copies made inside the function. The nocapture attribute only
126 // specifies that there are no copies made that outlive the function.
127 return !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
128
129 return false;
130}
131
132/// Returns true if the pointer is one which would have been considered an
133/// escape by isNonEscapingLocalObject.
134static bool isEscapeSource(const Value *V) {
135 if (ImmutableCallSite(V))
136 return true;
137
138 if (isa<Argument>(V))
139 return true;
140
141 // The load case works because isNonEscapingLocalObject considers all
142 // stores to be escapes (it passes true for the StoreCaptures argument
143 // to PointerMayBeCaptured).
144 if (isa<LoadInst>(V))
145 return true;
146
147 return false;
148}
149
150/// Returns the size of the object specified by V or UnknownSize if unknown.
151static uint64_t getObjectSize(const Value *V, const DataLayout &DL,
152 const TargetLibraryInfo &TLI,
153 bool NullIsValidLoc,
154 bool RoundToAlign = false) {
155 uint64_t Size;
156 ObjectSizeOpts Opts;
157 Opts.RoundToAlign = RoundToAlign;
158 Opts.NullIsUnknownSize = NullIsValidLoc;
159 if (getObjectSize(V, Size, DL, &TLI, Opts))
160 return Size;
161 return MemoryLocation::UnknownSize;
162}
163
164/// Returns true if we can prove that the object specified by V is smaller than
165/// Size.
166static bool isObjectSmallerThan(const Value *V, uint64_t Size,
167 const DataLayout &DL,
168 const TargetLibraryInfo &TLI,
169 bool NullIsValidLoc) {
170 // Note that the meanings of the "object" are slightly different in the
171 // following contexts:
172 // c1: llvm::getObjectSize()
173 // c2: llvm.objectsize() intrinsic
174 // c3: isObjectSmallerThan()
175 // c1 and c2 share the same meaning; however, the meaning of "object" in c3
176 // refers to the "entire object".
177 //
178 // Consider this example:
179 // char *p = (char*)malloc(100)
180 // char *q = p+80;
181 //
182 // In the context of c1 and c2, the "object" pointed by q refers to the
183 // stretch of memory of q[0:19]. So, getObjectSize(q) should return 20.
184 //
185 // However, in the context of c3, the "object" refers to the chunk of memory
186 // being allocated. So, the "object" has 100 bytes, and q points to the middle
187 // the "object". In case q is passed to isObjectSmallerThan() as the 1st
188 // parameter, before the llvm::getObjectSize() is called to get the size of
189 // entire object, we should:
190 // - either rewind the pointer q to the base-address of the object in
191 // question (in this case rewind to p), or
192 // - just give up. It is up to caller to make sure the pointer is pointing
193 // to the base address the object.
194 //
195 // We go for 2nd option for simplicity.
196 if (!isIdentifiedObject(V))
197 return false;
198
199 // This function needs to use the aligned object size because we allow
200 // reads a bit past the end given sufficient alignment.
201 uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc,
202 /*RoundToAlign*/ true);
203
204 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize < Size;
205}
206
207/// Returns true if we can prove that the object specified by V has size Size.
208static bool isObjectSize(const Value *V, uint64_t Size, const DataLayout &DL,
209 const TargetLibraryInfo &TLI, bool NullIsValidLoc) {
210 uint64_t ObjectSize = getObjectSize(V, DL, TLI, NullIsValidLoc);
211 return ObjectSize != MemoryLocation::UnknownSize && ObjectSize == Size;
212}
213
214//===----------------------------------------------------------------------===//
215// GetElementPtr Instruction Decomposition and Analysis
216//===----------------------------------------------------------------------===//
217
218/// Analyzes the specified value as a linear expression: "A*V + B", where A and
219/// B are constant integers.
220///
221/// Returns the scale and offset values as APInts and return V as a Value*, and
222/// return whether we looked through any sign or zero extends. The incoming
223/// Value is known to have IntegerType, and it may already be sign or zero
224/// extended.
225///
226/// Note that this looks through extends, so the high bits may not be
227/// represented in the result.
228/*static*/ const Value *BasicAAResult::GetLinearExpression(
229 const Value *V, APInt &Scale, APInt &Offset, unsigned &ZExtBits,
230 unsigned &SExtBits, const DataLayout &DL, unsigned Depth,
231 AssumptionCache *AC, DominatorTree *DT, bool &NSW, bool &NUW) {
232 assert(V->getType()->isIntegerTy() && "Not an integer value")(static_cast <bool> (V->getType()->isIntegerTy() &&
"Not an integer value") ? void (0) : __assert_fail ("V->getType()->isIntegerTy() && \"Not an integer value\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 232, __extension__ __PRETTY_FUNCTION__))
;
233
234 // Limit our recursion depth.
235 if (Depth == 6) {
7
Taking false branch
236 Scale = 1;
237 Offset = 0;
238 return V;
239 }
240
241 if (const ConstantInt *Const = dyn_cast<ConstantInt>(V)) {
8
Taking false branch
242 // If it's a constant, just convert it to an offset and remove the variable.
243 // If we've been called recursively, the Offset bit width will be greater
244 // than the constant's (the Offset's always as wide as the outermost call),
245 // so we'll zext here and process any extension in the isa<SExtInst> &
246 // isa<ZExtInst> cases below.
247 Offset += Const->getValue().zextOrSelf(Offset.getBitWidth());
248 assert(Scale == 0 && "Constant values don't have a scale")(static_cast <bool> (Scale == 0 && "Constant values don't have a scale"
) ? void (0) : __assert_fail ("Scale == 0 && \"Constant values don't have a scale\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 248, __extension__ __PRETTY_FUNCTION__))
;
249 return V;
250 }
251
252 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(V)) {
9
Assuming 'BOp' is non-null
10
Taking true branch
253 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(BOp->getOperand(1))) {
11
Assuming 'RHSC' is non-null
12
Taking true branch
254 // If we've been called recursively, then Offset and Scale will be wider
255 // than the BOp operands. We'll always zext it here as we'll process sign
256 // extensions below (see the isa<SExtInst> / isa<ZExtInst> cases).
257 APInt RHS = RHSC->getValue().zextOrSelf(Offset.getBitWidth());
258
259 switch (BOp->getOpcode()) {
13
Control jumps to 'case Shl:' at line 292
260 default:
261 // We don't understand this instruction, so we can't decompose it any
262 // further.
263 Scale = 1;
264 Offset = 0;
265 return V;
266 case Instruction::Or:
267 // X|C == X+C if all the bits in C are unset in X. Otherwise we can't
268 // analyze it.
269 if (!MaskedValueIsZero(BOp->getOperand(0), RHSC->getValue(), DL, 0, AC,
270 BOp, DT)) {
271 Scale = 1;
272 Offset = 0;
273 return V;
274 }
275 LLVM_FALLTHROUGH[[clang::fallthrough]];
276 case Instruction::Add:
277 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
278 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
279 Offset += RHS;
280 break;
281 case Instruction::Sub:
282 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
283 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
284 Offset -= RHS;
285 break;
286 case Instruction::Mul:
287 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
288 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
289 Offset *= RHS;
290 Scale *= RHS;
291 break;
292 case Instruction::Shl:
293 V = GetLinearExpression(BOp->getOperand(0), Scale, Offset, ZExtBits,
294 SExtBits, DL, Depth + 1, AC, DT, NSW, NUW);
295
296 // We're trying to linearize an expression of the kind:
297 // shl i8 -128, 36
298 // where the shift count exceeds the bitwidth of the type.
299 // We can't decompose this further (the expression would return
300 // a poison value).
301 if (Offset.getBitWidth() < RHS.getLimitedValue() ||
14
Taking false branch
302 Scale.getBitWidth() < RHS.getLimitedValue()) {
303 Scale = 1;
304 Offset = 0;
305 return V;
306 }
307
308 Offset <<= RHS.getLimitedValue();
15
Calling 'APInt::getLimitedValue'
17
Returning from 'APInt::getLimitedValue'
18
Passing the value 4294967295 via 1st parameter 'ShiftAmt'
19
Calling 'APInt::operator<<='
309 Scale <<= RHS.getLimitedValue();
310 // the semantics of nsw and nuw for left shifts don't match those of
311 // multiplications, so we won't propagate them.
312 NSW = NUW = false;
313 return V;
314 }
315
316 if (isa<OverflowingBinaryOperator>(BOp)) {
317 NUW &= BOp->hasNoUnsignedWrap();
318 NSW &= BOp->hasNoSignedWrap();
319 }
320 return V;
321 }
322 }
323
324 // Since GEP indices are sign extended anyway, we don't care about the high
325 // bits of a sign or zero extended value - just scales and offsets. The
326 // extensions have to be consistent though.
327 if (isa<SExtInst>(V) || isa<ZExtInst>(V)) {
328 Value *CastOp = cast<CastInst>(V)->getOperand(0);
329 unsigned NewWidth = V->getType()->getPrimitiveSizeInBits();
330 unsigned SmallWidth = CastOp->getType()->getPrimitiveSizeInBits();
331 unsigned OldZExtBits = ZExtBits, OldSExtBits = SExtBits;
332 const Value *Result =
333 GetLinearExpression(CastOp, Scale, Offset, ZExtBits, SExtBits, DL,
334 Depth + 1, AC, DT, NSW, NUW);
335
336 // zext(zext(%x)) == zext(%x), and similarly for sext; we'll handle this
337 // by just incrementing the number of bits we've extended by.
338 unsigned ExtendedBy = NewWidth - SmallWidth;
339
340 if (isa<SExtInst>(V) && ZExtBits == 0) {
341 // sext(sext(%x, a), b) == sext(%x, a + b)
342
343 if (NSW) {
344 // We haven't sign-wrapped, so it's valid to decompose sext(%x + c)
345 // into sext(%x) + sext(c). We'll sext the Offset ourselves:
346 unsigned OldWidth = Offset.getBitWidth();
347 Offset = Offset.trunc(SmallWidth).sext(NewWidth).zextOrSelf(OldWidth);
348 } else {
349 // We may have signed-wrapped, so don't decompose sext(%x + c) into
350 // sext(%x) + sext(c)
351 Scale = 1;
352 Offset = 0;
353 Result = CastOp;
354 ZExtBits = OldZExtBits;
355 SExtBits = OldSExtBits;
356 }
357 SExtBits += ExtendedBy;
358 } else {
359 // sext(zext(%x, a), b) = zext(zext(%x, a), b) = zext(%x, a + b)
360
361 if (!NUW) {
362 // We may have unsigned-wrapped, so don't decompose zext(%x + c) into
363 // zext(%x) + zext(c)
364 Scale = 1;
365 Offset = 0;
366 Result = CastOp;
367 ZExtBits = OldZExtBits;
368 SExtBits = OldSExtBits;
369 }
370 ZExtBits += ExtendedBy;
371 }
372
373 return Result;
374 }
375
376 Scale = 1;
377 Offset = 0;
378 return V;
379}
380
381/// To ensure a pointer offset fits in an integer of size PointerSize
382/// (in bits) when that size is smaller than 64. This is an issue in
383/// particular for 32b programs with negative indices that rely on two's
384/// complement wrap-arounds for precise alias information.
385static int64_t adjustToPointerSize(int64_t Offset, unsigned PointerSize) {
386 assert(PointerSize <= 64 && "Invalid PointerSize!")(static_cast <bool> (PointerSize <= 64 && "Invalid PointerSize!"
) ? void (0) : __assert_fail ("PointerSize <= 64 && \"Invalid PointerSize!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 386, __extension__ __PRETTY_FUNCTION__))
;
387 unsigned ShiftBits = 64 - PointerSize;
388 return (int64_t)((uint64_t)Offset << ShiftBits) >> ShiftBits;
389}
390
391/// If V is a symbolic pointer expression, decompose it into a base pointer
392/// with a constant offset and a number of scaled symbolic offsets.
393///
394/// The scaled symbolic offsets (represented by pairs of a Value* and a scale
395/// in the VarIndices vector) are Value*'s that are known to be scaled by the
396/// specified amount, but which may have other unrepresented high bits. As
397/// such, the gep cannot necessarily be reconstructed from its decomposed form.
398///
399/// When DataLayout is around, this function is capable of analyzing everything
400/// that GetUnderlyingObject can look through. To be able to do that
401/// GetUnderlyingObject and DecomposeGEPExpression must use the same search
402/// depth (MaxLookupSearchDepth). When DataLayout not is around, it just looks
403/// through pointer casts.
404bool BasicAAResult::DecomposeGEPExpression(const Value *V,
405 DecomposedGEP &Decomposed, const DataLayout &DL, AssumptionCache *AC,
406 DominatorTree *DT) {
407 // Limit recursion depth to limit compile time in crazy cases.
408 unsigned MaxLookup = MaxLookupSearchDepth;
409 SearchTimes++;
410
411 Decomposed.StructOffset = 0;
412 Decomposed.OtherOffset = 0;
413 Decomposed.VarIndices.clear();
414 do {
415 // See if this is a bitcast or GEP.
416 const Operator *Op = dyn_cast<Operator>(V);
417 if (!Op) {
418 // The only non-operator case we can handle are GlobalAliases.
419 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
420 if (!GA->isInterposable()) {
421 V = GA->getAliasee();
422 continue;
423 }
424 }
425 Decomposed.Base = V;
426 return false;
427 }
428
429 if (Op->getOpcode() == Instruction::BitCast ||
430 Op->getOpcode() == Instruction::AddrSpaceCast) {
431 V = Op->getOperand(0);
432 continue;
433 }
434
435 const GEPOperator *GEPOp = dyn_cast<GEPOperator>(Op);
436 if (!GEPOp) {
437 if (auto CS = ImmutableCallSite(V)) {
438 // CaptureTracking can know about special capturing properties of some
439 // intrinsics like launder.invariant.group, that can't be expressed with
440 // the attributes, but have properties like returning aliasing pointer.
441 // Because some analysis may assume that nocaptured pointer is not
442 // returned from some special intrinsic (because function would have to
443 // be marked with returns attribute), it is crucial to use this function
444 // because it should be in sync with CaptureTracking. Not using it may
445 // cause weird miscompilations where 2 aliasing pointers are assumed to
446 // noalias.
447 if (auto *RP = getArgumentAliasingToReturnedPointer(CS)) {
448 V = RP;
449 continue;
450 }
451 }
452
453 // If it's not a GEP, hand it off to SimplifyInstruction to see if it
454 // can come up with something. This matches what GetUnderlyingObject does.
455 if (const Instruction *I = dyn_cast<Instruction>(V))
456 // TODO: Get a DominatorTree and AssumptionCache and use them here
457 // (these are both now available in this function, but this should be
458 // updated when GetUnderlyingObject is updated). TLI should be
459 // provided also.
460 if (const Value *Simplified =
461 SimplifyInstruction(const_cast<Instruction *>(I), DL)) {
462 V = Simplified;
463 continue;
464 }
465
466 Decomposed.Base = V;
467 return false;
468 }
469
470 // Don't attempt to analyze GEPs over unsized objects.
471 if (!GEPOp->getSourceElementType()->isSized()) {
472 Decomposed.Base = V;
473 return false;
474 }
475
476 unsigned AS = GEPOp->getPointerAddressSpace();
477 // Walk the indices of the GEP, accumulating them into BaseOff/VarIndices.
478 gep_type_iterator GTI = gep_type_begin(GEPOp);
479 unsigned PointerSize = DL.getPointerSizeInBits(AS);
480 // Assume all GEP operands are constants until proven otherwise.
481 bool GepHasConstantOffset = true;
482 for (User::const_op_iterator I = GEPOp->op_begin() + 1, E = GEPOp->op_end();
483 I != E; ++I, ++GTI) {
484 const Value *Index = *I;
485 // Compute the (potentially symbolic) offset in bytes for this index.
486 if (StructType *STy = GTI.getStructTypeOrNull()) {
487 // For a struct, add the member offset.
488 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
489 if (FieldNo == 0)
490 continue;
491
492 Decomposed.StructOffset +=
493 DL.getStructLayout(STy)->getElementOffset(FieldNo);
494 continue;
495 }
496
497 // For an array/pointer, add the element offset, explicitly scaled.
498 if (const ConstantInt *CIdx = dyn_cast<ConstantInt>(Index)) {
499 if (CIdx->isZero())
500 continue;
501 Decomposed.OtherOffset +=
502 DL.getTypeAllocSize(GTI.getIndexedType()) * CIdx->getSExtValue();
503 continue;
504 }
505
506 GepHasConstantOffset = false;
507
508 uint64_t Scale = DL.getTypeAllocSize(GTI.getIndexedType());
509 unsigned ZExtBits = 0, SExtBits = 0;
510
511 // If the integer type is smaller than the pointer size, it is implicitly
512 // sign extended to pointer size.
513 unsigned Width = Index->getType()->getIntegerBitWidth();
514 if (PointerSize > Width)
515 SExtBits += PointerSize - Width;
516
517 // Use GetLinearExpression to decompose the index into a C1*V+C2 form.
518 APInt IndexScale(Width, 0), IndexOffset(Width, 0);
519 bool NSW = true, NUW = true;
520 Index = GetLinearExpression(Index, IndexScale, IndexOffset, ZExtBits,
521 SExtBits, DL, 0, AC, DT, NSW, NUW);
522
523 // All GEP math happens in the width of the pointer type,
524 // so we can truncate the value to 64-bits as we don't handle
525 // currently pointers larger than 64 bits and we would crash
526 // later. TODO: Make `Scale` an APInt to avoid this problem.
527 if (IndexScale.getBitWidth() > 64)
528 IndexScale = IndexScale.sextOrTrunc(64);
529
530 // The GEP index scale ("Scale") scales C1*V+C2, yielding (C1*V+C2)*Scale.
531 // This gives us an aggregate computation of (C1*Scale)*V + C2*Scale.
532 Decomposed.OtherOffset += IndexOffset.getSExtValue() * Scale;
533 Scale *= IndexScale.getSExtValue();
534
535 // If we already had an occurrence of this index variable, merge this
536 // scale into it. For example, we want to handle:
537 // A[x][x] -> x*16 + x*4 -> x*20
538 // This also ensures that 'x' only appears in the index list once.
539 for (unsigned i = 0, e = Decomposed.VarIndices.size(); i != e; ++i) {
540 if (Decomposed.VarIndices[i].V == Index &&
541 Decomposed.VarIndices[i].ZExtBits == ZExtBits &&
542 Decomposed.VarIndices[i].SExtBits == SExtBits) {
543 Scale += Decomposed.VarIndices[i].Scale;
544 Decomposed.VarIndices.erase(Decomposed.VarIndices.begin() + i);
545 break;
546 }
547 }
548
549 // Make sure that we have a scale that makes sense for this target's
550 // pointer size.
551 Scale = adjustToPointerSize(Scale, PointerSize);
552
553 if (Scale) {
554 VariableGEPIndex Entry = {Index, ZExtBits, SExtBits,
555 static_cast<int64_t>(Scale)};
556 Decomposed.VarIndices.push_back(Entry);
557 }
558 }
559
560 // Take care of wrap-arounds
561 if (GepHasConstantOffset) {
562 Decomposed.StructOffset =
563 adjustToPointerSize(Decomposed.StructOffset, PointerSize);
564 Decomposed.OtherOffset =
565 adjustToPointerSize(Decomposed.OtherOffset, PointerSize);
566 }
567
568 // Analyze the base pointer next.
569 V = GEPOp->getOperand(0);
570 } while (--MaxLookup);
571
572 // If the chain of expressions is too deep, just return early.
573 Decomposed.Base = V;
574 SearchLimitReached++;
575 return true;
576}
577
578/// Returns whether the given pointer value points to memory that is local to
579/// the function, with global constants being considered local to all
580/// functions.
581bool BasicAAResult::pointsToConstantMemory(const MemoryLocation &Loc,
582 bool OrLocal) {
583 assert(Visited.empty() && "Visited must be cleared after use!")(static_cast <bool> (Visited.empty() && "Visited must be cleared after use!"
) ? void (0) : __assert_fail ("Visited.empty() && \"Visited must be cleared after use!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 583, __extension__ __PRETTY_FUNCTION__))
;
584
585 unsigned MaxLookup = 8;
586 SmallVector<const Value *, 16> Worklist;
587 Worklist.push_back(Loc.Ptr);
588 do {
589 const Value *V = GetUnderlyingObject(Worklist.pop_back_val(), DL);
590 if (!Visited.insert(V).second) {
591 Visited.clear();
592 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
593 }
594
595 // An alloca instruction defines local memory.
596 if (OrLocal && isa<AllocaInst>(V))
597 continue;
598
599 // A global constant counts as local memory for our purposes.
600 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
601 // Note: this doesn't require GV to be "ODR" because it isn't legal for a
602 // global to be marked constant in some modules and non-constant in
603 // others. GV may even be a declaration, not a definition.
604 if (!GV->isConstant()) {
605 Visited.clear();
606 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
607 }
608 continue;
609 }
610
611 // If both select values point to local memory, then so does the select.
612 if (const SelectInst *SI = dyn_cast<SelectInst>(V)) {
613 Worklist.push_back(SI->getTrueValue());
614 Worklist.push_back(SI->getFalseValue());
615 continue;
616 }
617
618 // If all values incoming to a phi node point to local memory, then so does
619 // the phi.
620 if (const PHINode *PN = dyn_cast<PHINode>(V)) {
621 // Don't bother inspecting phi nodes with many operands.
622 if (PN->getNumIncomingValues() > MaxLookup) {
623 Visited.clear();
624 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
625 }
626 for (Value *IncValue : PN->incoming_values())
627 Worklist.push_back(IncValue);
628 continue;
629 }
630
631 // Otherwise be conservative.
632 Visited.clear();
633 return AAResultBase::pointsToConstantMemory(Loc, OrLocal);
634 } while (!Worklist.empty() && --MaxLookup);
635
636 Visited.clear();
637 return Worklist.empty();
638}
639
640/// Returns the behavior when calling the given call site.
641FunctionModRefBehavior BasicAAResult::getModRefBehavior(ImmutableCallSite CS) {
642 if (CS.doesNotAccessMemory())
643 // Can't do better than this.
644 return FMRB_DoesNotAccessMemory;
645
646 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
647
648 // If the callsite knows it only reads memory, don't return worse
649 // than that.
650 if (CS.onlyReadsMemory())
651 Min = FMRB_OnlyReadsMemory;
652 else if (CS.doesNotReadMemory())
653 Min = FMRB_DoesNotReadMemory;
654
655 if (CS.onlyAccessesArgMemory())
656 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
657 else if (CS.onlyAccessesInaccessibleMemory())
658 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
659 else if (CS.onlyAccessesInaccessibleMemOrArgMem())
660 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
661
662 // If CS has operand bundles then aliasing attributes from the function it
663 // calls do not directly apply to the CallSite. This can be made more
664 // precise in the future.
665 if (!CS.hasOperandBundles())
666 if (const Function *F = CS.getCalledFunction())
667 Min =
668 FunctionModRefBehavior(Min & getBestAAResults().getModRefBehavior(F));
669
670 return Min;
671}
672
673/// Returns the behavior when calling the given function. For use when the call
674/// site is not known.
675FunctionModRefBehavior BasicAAResult::getModRefBehavior(const Function *F) {
676 // If the function declares it doesn't access memory, we can't do better.
677 if (F->doesNotAccessMemory())
678 return FMRB_DoesNotAccessMemory;
679
680 FunctionModRefBehavior Min = FMRB_UnknownModRefBehavior;
681
682 // If the function declares it only reads memory, go with that.
683 if (F->onlyReadsMemory())
684 Min = FMRB_OnlyReadsMemory;
685 else if (F->doesNotReadMemory())
686 Min = FMRB_DoesNotReadMemory;
687
688 if (F->onlyAccessesArgMemory())
689 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesArgumentPointees);
690 else if (F->onlyAccessesInaccessibleMemory())
691 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleMem);
692 else if (F->onlyAccessesInaccessibleMemOrArgMem())
693 Min = FunctionModRefBehavior(Min & FMRB_OnlyAccessesInaccessibleOrArgMem);
694
695 return Min;
696}
697
698/// Returns true if this is a writeonly (i.e Mod only) parameter.
699static bool isWriteOnlyParam(ImmutableCallSite CS, unsigned ArgIdx,
700 const TargetLibraryInfo &TLI) {
701 if (CS.paramHasAttr(ArgIdx, Attribute::WriteOnly))
702 return true;
703
704 // We can bound the aliasing properties of memset_pattern16 just as we can
705 // for memcpy/memset. This is particularly important because the
706 // LoopIdiomRecognizer likes to turn loops into calls to memset_pattern16
707 // whenever possible.
708 // FIXME Consider handling this in InferFunctionAttr.cpp together with other
709 // attributes.
710 LibFunc F;
711 if (CS.getCalledFunction() && TLI.getLibFunc(*CS.getCalledFunction(), F) &&
712 F == LibFunc_memset_pattern16 && TLI.has(F))
713 if (ArgIdx == 0)
714 return true;
715
716 // TODO: memset_pattern4, memset_pattern8
717 // TODO: _chk variants
718 // TODO: strcmp, strcpy
719
720 return false;
721}
722
723ModRefInfo BasicAAResult::getArgModRefInfo(ImmutableCallSite CS,
724 unsigned ArgIdx) {
725 // Checking for known builtin intrinsics and target library functions.
726 if (isWriteOnlyParam(CS, ArgIdx, TLI))
727 return ModRefInfo::Mod;
728
729 if (CS.paramHasAttr(ArgIdx, Attribute::ReadOnly))
730 return ModRefInfo::Ref;
731
732 if (CS.paramHasAttr(ArgIdx, Attribute::ReadNone))
733 return ModRefInfo::NoModRef;
734
735 return AAResultBase::getArgModRefInfo(CS, ArgIdx);
736}
737
738static bool isIntrinsicCall(ImmutableCallSite CS, Intrinsic::ID IID) {
739 const IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction());
740 return II && II->getIntrinsicID() == IID;
741}
742
743#ifndef NDEBUG
744static const Function *getParent(const Value *V) {
745 if (const Instruction *inst = dyn_cast<Instruction>(V)) {
746 if (!inst->getParent())
747 return nullptr;
748 return inst->getParent()->getParent();
749 }
750
751 if (const Argument *arg = dyn_cast<Argument>(V))
752 return arg->getParent();
753
754 return nullptr;
755}
756
757static bool notDifferentParent(const Value *O1, const Value *O2) {
758
759 const Function *F1 = getParent(O1);
760 const Function *F2 = getParent(O2);
761
762 return !F1 || !F2 || F1 == F2;
763}
764#endif
765
766AliasResult BasicAAResult::alias(const MemoryLocation &LocA,
767 const MemoryLocation &LocB) {
768 assert(notDifferentParent(LocA.Ptr, LocB.Ptr) &&(static_cast <bool> (notDifferentParent(LocA.Ptr, LocB.
Ptr) && "BasicAliasAnalysis doesn't support interprocedural queries."
) ? void (0) : __assert_fail ("notDifferentParent(LocA.Ptr, LocB.Ptr) && \"BasicAliasAnalysis doesn't support interprocedural queries.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 769, __extension__ __PRETTY_FUNCTION__))
769 "BasicAliasAnalysis doesn't support interprocedural queries.")(static_cast <bool> (notDifferentParent(LocA.Ptr, LocB.
Ptr) && "BasicAliasAnalysis doesn't support interprocedural queries."
) ? void (0) : __assert_fail ("notDifferentParent(LocA.Ptr, LocB.Ptr) && \"BasicAliasAnalysis doesn't support interprocedural queries.\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 769, __extension__ __PRETTY_FUNCTION__))
;
770
771 // If we have a directly cached entry for these locations, we have recursed
772 // through this once, so just return the cached results. Notably, when this
773 // happens, we don't clear the cache.
774 auto CacheIt = AliasCache.find(LocPair(LocA, LocB));
775 if (CacheIt != AliasCache.end())
776 return CacheIt->second;
777
778 AliasResult Alias = aliasCheck(LocA.Ptr, LocA.Size, LocA.AATags, LocB.Ptr,
779 LocB.Size, LocB.AATags);
780 // AliasCache rarely has more than 1 or 2 elements, always use
781 // shrink_and_clear so it quickly returns to the inline capacity of the
782 // SmallDenseMap if it ever grows larger.
783 // FIXME: This should really be shrink_to_inline_capacity_and_clear().
784 AliasCache.shrink_and_clear();
785 VisitedPhiBBs.clear();
786 return Alias;
787}
788
789/// Checks to see if the specified callsite can clobber the specified memory
790/// object.
791///
792/// Since we only look at local properties of this function, we really can't
793/// say much about this query. We do, however, use simple "address taken"
794/// analysis on local objects.
795ModRefInfo BasicAAResult::getModRefInfo(ImmutableCallSite CS,
796 const MemoryLocation &Loc) {
797 assert(notDifferentParent(CS.getInstruction(), Loc.Ptr) &&(static_cast <bool> (notDifferentParent(CS.getInstruction
(), Loc.Ptr) && "AliasAnalysis query involving multiple functions!"
) ? void (0) : __assert_fail ("notDifferentParent(CS.getInstruction(), Loc.Ptr) && \"AliasAnalysis query involving multiple functions!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 798, __extension__ __PRETTY_FUNCTION__))
798 "AliasAnalysis query involving multiple functions!")(static_cast <bool> (notDifferentParent(CS.getInstruction
(), Loc.Ptr) && "AliasAnalysis query involving multiple functions!"
) ? void (0) : __assert_fail ("notDifferentParent(CS.getInstruction(), Loc.Ptr) && \"AliasAnalysis query involving multiple functions!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 798, __extension__ __PRETTY_FUNCTION__))
;
799
800 const Value *Object = GetUnderlyingObject(Loc.Ptr, DL);
801
802 // If this is a tail call and Loc.Ptr points to a stack location, we know that
803 // the tail call cannot access or modify the local stack.
804 // We cannot exclude byval arguments here; these belong to the caller of
805 // the current function not to the current function, and a tail callee
806 // may reference them.
807 if (isa<AllocaInst>(Object))
808 if (const CallInst *CI = dyn_cast<CallInst>(CS.getInstruction()))
809 if (CI->isTailCall())
810 return ModRefInfo::NoModRef;
811
812 // If the pointer is to a locally allocated object that does not escape,
813 // then the call can not mod/ref the pointer unless the call takes the pointer
814 // as an argument, and itself doesn't capture it.
815 if (!isa<Constant>(Object) && CS.getInstruction() != Object &&
816 isNonEscapingLocalObject(Object)) {
817
818 // Optimistically assume that call doesn't touch Object and check this
819 // assumption in the following loop.
820 ModRefInfo Result = ModRefInfo::NoModRef;
821 bool IsMustAlias = true;
822
823 unsigned OperandNo = 0;
824 for (auto CI = CS.data_operands_begin(), CE = CS.data_operands_end();
825 CI != CE; ++CI, ++OperandNo) {
826 // Only look at the no-capture or byval pointer arguments. If this
827 // pointer were passed to arguments that were neither of these, then it
828 // couldn't be no-capture.
829 if (!(*CI)->getType()->isPointerTy() ||
830 (!CS.doesNotCapture(OperandNo) &&
831 OperandNo < CS.getNumArgOperands() && !CS.isByValArgument(OperandNo)))
832 continue;
833
834 // Call doesn't access memory through this operand, so we don't care
835 // if it aliases with Object.
836 if (CS.doesNotAccessMemory(OperandNo))
837 continue;
838
839 // If this is a no-capture pointer argument, see if we can tell that it
840 // is impossible to alias the pointer we're checking.
841 AliasResult AR =
842 getBestAAResults().alias(MemoryLocation(*CI), MemoryLocation(Object));
843 if (AR != MustAlias)
844 IsMustAlias = false;
845 // Operand doesnt alias 'Object', continue looking for other aliases
846 if (AR == NoAlias)
847 continue;
848 // Operand aliases 'Object', but call doesn't modify it. Strengthen
849 // initial assumption and keep looking in case if there are more aliases.
850 if (CS.onlyReadsMemory(OperandNo)) {
851 Result = setRef(Result);
852 continue;
853 }
854 // Operand aliases 'Object' but call only writes into it.
855 if (CS.doesNotReadMemory(OperandNo)) {
856 Result = setMod(Result);
857 continue;
858 }
859 // This operand aliases 'Object' and call reads and writes into it.
860 // Setting ModRef will not yield an early return below, MustAlias is not
861 // used further.
862 Result = ModRefInfo::ModRef;
863 break;
864 }
865
866 // No operand aliases, reset Must bit. Add below if at least one aliases
867 // and all aliases found are MustAlias.
868 if (isNoModRef(Result))
869 IsMustAlias = false;
870
871 // Early return if we improved mod ref information
872 if (!isModAndRefSet(Result)) {
873 if (isNoModRef(Result))
874 return ModRefInfo::NoModRef;
875 return IsMustAlias ? setMust(Result) : clearMust(Result);
876 }
877 }
878
879 // If the CallSite is to malloc or calloc, we can assume that it doesn't
880 // modify any IR visible value. This is only valid because we assume these
881 // routines do not read values visible in the IR. TODO: Consider special
882 // casing realloc and strdup routines which access only their arguments as
883 // well. Or alternatively, replace all of this with inaccessiblememonly once
884 // that's implemented fully.
885 auto *Inst = CS.getInstruction();
886 if (isMallocOrCallocLikeFn(Inst, &TLI)) {
887 // Be conservative if the accessed pointer may alias the allocation -
888 // fallback to the generic handling below.
889 if (getBestAAResults().alias(MemoryLocation(Inst), Loc) == NoAlias)
890 return ModRefInfo::NoModRef;
891 }
892
893 // The semantics of memcpy intrinsics forbid overlap between their respective
894 // operands, i.e., source and destination of any given memcpy must no-alias.
895 // If Loc must-aliases either one of these two locations, then it necessarily
896 // no-aliases the other.
897 if (auto *Inst = dyn_cast<AnyMemCpyInst>(CS.getInstruction())) {
898 AliasResult SrcAA, DestAA;
899
900 if ((SrcAA = getBestAAResults().alias(MemoryLocation::getForSource(Inst),
901 Loc)) == MustAlias)
902 // Loc is exactly the memcpy source thus disjoint from memcpy dest.
903 return ModRefInfo::Ref;
904 if ((DestAA = getBestAAResults().alias(MemoryLocation::getForDest(Inst),
905 Loc)) == MustAlias)
906 // The converse case.
907 return ModRefInfo::Mod;
908
909 // It's also possible for Loc to alias both src and dest, or neither.
910 ModRefInfo rv = ModRefInfo::NoModRef;
911 if (SrcAA != NoAlias)
912 rv = setRef(rv);
913 if (DestAA != NoAlias)
914 rv = setMod(rv);
915 return rv;
916 }
917
918 // While the assume intrinsic is marked as arbitrarily writing so that
919 // proper control dependencies will be maintained, it never aliases any
920 // particular memory location.
921 if (isIntrinsicCall(CS, Intrinsic::assume))
922 return ModRefInfo::NoModRef;
923
924 // Like assumes, guard intrinsics are also marked as arbitrarily writing so
925 // that proper control dependencies are maintained but they never mods any
926 // particular memory location.
927 //
928 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
929 // heap state at the point the guard is issued needs to be consistent in case
930 // the guard invokes the "deopt" continuation.
931 if (isIntrinsicCall(CS, Intrinsic::experimental_guard))
932 return ModRefInfo::Ref;
933
934 // Like assumes, invariant.start intrinsics were also marked as arbitrarily
935 // writing so that proper control dependencies are maintained but they never
936 // mod any particular memory location visible to the IR.
937 // *Unlike* assumes (which are now modeled as NoModRef), invariant.start
938 // intrinsic is now modeled as reading memory. This prevents hoisting the
939 // invariant.start intrinsic over stores. Consider:
940 // *ptr = 40;
941 // *ptr = 50;
942 // invariant_start(ptr)
943 // int val = *ptr;
944 // print(val);
945 //
946 // This cannot be transformed to:
947 //
948 // *ptr = 40;
949 // invariant_start(ptr)
950 // *ptr = 50;
951 // int val = *ptr;
952 // print(val);
953 //
954 // The transformation will cause the second store to be ignored (based on
955 // rules of invariant.start) and print 40, while the first program always
956 // prints 50.
957 if (isIntrinsicCall(CS, Intrinsic::invariant_start))
958 return ModRefInfo::Ref;
959
960 // The AAResultBase base class has some smarts, lets use them.
961 return AAResultBase::getModRefInfo(CS, Loc);
962}
963
964ModRefInfo BasicAAResult::getModRefInfo(ImmutableCallSite CS1,
965 ImmutableCallSite CS2) {
966 // While the assume intrinsic is marked as arbitrarily writing so that
967 // proper control dependencies will be maintained, it never aliases any
968 // particular memory location.
969 if (isIntrinsicCall(CS1, Intrinsic::assume) ||
970 isIntrinsicCall(CS2, Intrinsic::assume))
971 return ModRefInfo::NoModRef;
972
973 // Like assumes, guard intrinsics are also marked as arbitrarily writing so
974 // that proper control dependencies are maintained but they never mod any
975 // particular memory location.
976 //
977 // *Unlike* assumes, guard intrinsics are modeled as reading memory since the
978 // heap state at the point the guard is issued needs to be consistent in case
979 // the guard invokes the "deopt" continuation.
980
981 // NB! This function is *not* commutative, so we specical case two
982 // possibilities for guard intrinsics.
983
984 if (isIntrinsicCall(CS1, Intrinsic::experimental_guard))
985 return isModSet(createModRefInfo(getModRefBehavior(CS2)))
986 ? ModRefInfo::Ref
987 : ModRefInfo::NoModRef;
988
989 if (isIntrinsicCall(CS2, Intrinsic::experimental_guard))
990 return isModSet(createModRefInfo(getModRefBehavior(CS1)))
991 ? ModRefInfo::Mod
992 : ModRefInfo::NoModRef;
993
994 // The AAResultBase base class has some smarts, lets use them.
995 return AAResultBase::getModRefInfo(CS1, CS2);
996}
997
998/// Provide ad-hoc rules to disambiguate accesses through two GEP operators,
999/// both having the exact same pointer operand.
1000static AliasResult aliasSameBasePointerGEPs(const GEPOperator *GEP1,
1001 LocationSize V1Size,
1002 const GEPOperator *GEP2,
1003 LocationSize V2Size,
1004 const DataLayout &DL) {
1005 assert(GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==(static_cast <bool> (GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups
() == GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups
() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType
() && "Expected GEPs with the same pointer operand") ?
void (0) : __assert_fail ("GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() == GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType() && \"Expected GEPs with the same pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1008, __extension__ __PRETTY_FUNCTION__))
1006 GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&(static_cast <bool> (GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups
() == GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups
() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType
() && "Expected GEPs with the same pointer operand") ?
void (0) : __assert_fail ("GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() == GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType() && \"Expected GEPs with the same pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1008, __extension__ __PRETTY_FUNCTION__))
1007 GEP1->getPointerOperandType() == GEP2->getPointerOperandType() &&(static_cast <bool> (GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups
() == GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups
() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType
() && "Expected GEPs with the same pointer operand") ?
void (0) : __assert_fail ("GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() == GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType() && \"Expected GEPs with the same pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1008, __extension__ __PRETTY_FUNCTION__))
1008 "Expected GEPs with the same pointer operand")(static_cast <bool> (GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups
() == GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups
() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType
() && "Expected GEPs with the same pointer operand") ?
void (0) : __assert_fail ("GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() == GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() && GEP1->getPointerOperandType() == GEP2->getPointerOperandType() && \"Expected GEPs with the same pointer operand\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1008, __extension__ __PRETTY_FUNCTION__))
;
1009
1010 // Try to determine whether GEP1 and GEP2 index through arrays, into structs,
1011 // such that the struct field accesses provably cannot alias.
1012 // We also need at least two indices (the pointer, and the struct field).
1013 if (GEP1->getNumIndices() != GEP2->getNumIndices() ||
1014 GEP1->getNumIndices() < 2)
1015 return MayAlias;
1016
1017 // If we don't know the size of the accesses through both GEPs, we can't
1018 // determine whether the struct fields accessed can't alias.
1019 if (V1Size == MemoryLocation::UnknownSize ||
1020 V2Size == MemoryLocation::UnknownSize)
1021 return MayAlias;
1022
1023 ConstantInt *C1 =
1024 dyn_cast<ConstantInt>(GEP1->getOperand(GEP1->getNumOperands() - 1));
1025 ConstantInt *C2 =
1026 dyn_cast<ConstantInt>(GEP2->getOperand(GEP2->getNumOperands() - 1));
1027
1028 // If the last (struct) indices are constants and are equal, the other indices
1029 // might be also be dynamically equal, so the GEPs can alias.
1030 if (C1 && C2 && C1->getSExtValue() == C2->getSExtValue())
1031 return MayAlias;
1032
1033 // Find the last-indexed type of the GEP, i.e., the type you'd get if
1034 // you stripped the last index.
1035 // On the way, look at each indexed type. If there's something other
1036 // than an array, different indices can lead to different final types.
1037 SmallVector<Value *, 8> IntermediateIndices;
1038
1039 // Insert the first index; we don't need to check the type indexed
1040 // through it as it only drops the pointer indirection.
1041 assert(GEP1->getNumIndices() > 1 && "Not enough GEP indices to examine")(static_cast <bool> (GEP1->getNumIndices() > 1 &&
"Not enough GEP indices to examine") ? void (0) : __assert_fail
("GEP1->getNumIndices() > 1 && \"Not enough GEP indices to examine\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1041, __extension__ __PRETTY_FUNCTION__))
;
1042 IntermediateIndices.push_back(GEP1->getOperand(1));
1043
1044 // Insert all the remaining indices but the last one.
1045 // Also, check that they all index through arrays.
1046 for (unsigned i = 1, e = GEP1->getNumIndices() - 1; i != e; ++i) {
1047 if (!isa<ArrayType>(GetElementPtrInst::getIndexedType(
1048 GEP1->getSourceElementType(), IntermediateIndices)))
1049 return MayAlias;
1050 IntermediateIndices.push_back(GEP1->getOperand(i + 1));
1051 }
1052
1053 auto *Ty = GetElementPtrInst::getIndexedType(
1054 GEP1->getSourceElementType(), IntermediateIndices);
1055 StructType *LastIndexedStruct = dyn_cast<StructType>(Ty);
1056
1057 if (isa<SequentialType>(Ty)) {
1058 // We know that:
1059 // - both GEPs begin indexing from the exact same pointer;
1060 // - the last indices in both GEPs are constants, indexing into a sequential
1061 // type (array or pointer);
1062 // - both GEPs only index through arrays prior to that.
1063 //
1064 // Because array indices greater than the number of elements are valid in
1065 // GEPs, unless we know the intermediate indices are identical between
1066 // GEP1 and GEP2 we cannot guarantee that the last indexed arrays don't
1067 // partially overlap. We also need to check that the loaded size matches
1068 // the element size, otherwise we could still have overlap.
1069 const uint64_t ElementSize =
1070 DL.getTypeStoreSize(cast<SequentialType>(Ty)->getElementType());
1071 if (V1Size != ElementSize || V2Size != ElementSize)
1072 return MayAlias;
1073
1074 for (unsigned i = 0, e = GEP1->getNumIndices() - 1; i != e; ++i)
1075 if (GEP1->getOperand(i + 1) != GEP2->getOperand(i + 1))
1076 return MayAlias;
1077
1078 // Now we know that the array/pointer that GEP1 indexes into and that
1079 // that GEP2 indexes into must either precisely overlap or be disjoint.
1080 // Because they cannot partially overlap and because fields in an array
1081 // cannot overlap, if we can prove the final indices are different between
1082 // GEP1 and GEP2, we can conclude GEP1 and GEP2 don't alias.
1083
1084 // If the last indices are constants, we've already checked they don't
1085 // equal each other so we can exit early.
1086 if (C1 && C2)
1087 return NoAlias;
1088 {
1089 Value *GEP1LastIdx = GEP1->getOperand(GEP1->getNumOperands() - 1);
1090 Value *GEP2LastIdx = GEP2->getOperand(GEP2->getNumOperands() - 1);
1091 if (isa<PHINode>(GEP1LastIdx) || isa<PHINode>(GEP2LastIdx)) {
1092 // If one of the indices is a PHI node, be safe and only use
1093 // computeKnownBits so we don't make any assumptions about the
1094 // relationships between the two indices. This is important if we're
1095 // asking about values from different loop iterations. See PR32314.
1096 // TODO: We may be able to change the check so we only do this when
1097 // we definitely looked through a PHINode.
1098 if (GEP1LastIdx != GEP2LastIdx &&
1099 GEP1LastIdx->getType() == GEP2LastIdx->getType()) {
1100 KnownBits Known1 = computeKnownBits(GEP1LastIdx, DL);
1101 KnownBits Known2 = computeKnownBits(GEP2LastIdx, DL);
1102 if (Known1.Zero.intersects(Known2.One) ||
1103 Known1.One.intersects(Known2.Zero))
1104 return NoAlias;
1105 }
1106 } else if (isKnownNonEqual(GEP1LastIdx, GEP2LastIdx, DL))
1107 return NoAlias;
1108 }
1109 return MayAlias;
1110 } else if (!LastIndexedStruct || !C1 || !C2) {
1111 return MayAlias;
1112 }
1113
1114 // We know that:
1115 // - both GEPs begin indexing from the exact same pointer;
1116 // - the last indices in both GEPs are constants, indexing into a struct;
1117 // - said indices are different, hence, the pointed-to fields are different;
1118 // - both GEPs only index through arrays prior to that.
1119 //
1120 // This lets us determine that the struct that GEP1 indexes into and the
1121 // struct that GEP2 indexes into must either precisely overlap or be
1122 // completely disjoint. Because they cannot partially overlap, indexing into
1123 // different non-overlapping fields of the struct will never alias.
1124
1125 // Therefore, the only remaining thing needed to show that both GEPs can't
1126 // alias is that the fields are not overlapping.
1127 const StructLayout *SL = DL.getStructLayout(LastIndexedStruct);
1128 const uint64_t StructSize = SL->getSizeInBytes();
1129 const uint64_t V1Off = SL->getElementOffset(C1->getZExtValue());
1130 const uint64_t V2Off = SL->getElementOffset(C2->getZExtValue());
1131
1132 auto EltsDontOverlap = [StructSize](uint64_t V1Off, uint64_t V1Size,
1133 uint64_t V2Off, uint64_t V2Size) {
1134 return V1Off < V2Off && V1Off + V1Size <= V2Off &&
1135 ((V2Off + V2Size <= StructSize) ||
1136 (V2Off + V2Size - StructSize <= V1Off));
1137 };
1138
1139 if (EltsDontOverlap(V1Off, V1Size, V2Off, V2Size) ||
1140 EltsDontOverlap(V2Off, V2Size, V1Off, V1Size))
1141 return NoAlias;
1142
1143 return MayAlias;
1144}
1145
1146// If a we have (a) a GEP and (b) a pointer based on an alloca, and the
1147// beginning of the object the GEP points would have a negative offset with
1148// repsect to the alloca, that means the GEP can not alias pointer (b).
1149// Note that the pointer based on the alloca may not be a GEP. For
1150// example, it may be the alloca itself.
1151// The same applies if (b) is based on a GlobalVariable. Note that just being
1152// based on isIdentifiedObject() is not enough - we need an identified object
1153// that does not permit access to negative offsets. For example, a negative
1154// offset from a noalias argument or call can be inbounds w.r.t the actual
1155// underlying object.
1156//
1157// For example, consider:
1158//
1159// struct { int f0, int f1, ...} foo;
1160// foo alloca;
1161// foo* random = bar(alloca);
1162// int *f0 = &alloca.f0
1163// int *f1 = &random->f1;
1164//
1165// Which is lowered, approximately, to:
1166//
1167// %alloca = alloca %struct.foo
1168// %random = call %struct.foo* @random(%struct.foo* %alloca)
1169// %f0 = getelementptr inbounds %struct, %struct.foo* %alloca, i32 0, i32 0
1170// %f1 = getelementptr inbounds %struct, %struct.foo* %random, i32 0, i32 1
1171//
1172// Assume %f1 and %f0 alias. Then %f1 would point into the object allocated
1173// by %alloca. Since the %f1 GEP is inbounds, that means %random must also
1174// point into the same object. But since %f0 points to the beginning of %alloca,
1175// the highest %f1 can be is (%alloca + 3). This means %random can not be higher
1176// than (%alloca - 1), and so is not inbounds, a contradiction.
1177bool BasicAAResult::isGEPBaseAtNegativeOffset(const GEPOperator *GEPOp,
1178 const DecomposedGEP &DecompGEP, const DecomposedGEP &DecompObject,
1179 LocationSize ObjectAccessSize) {
1180 // If the object access size is unknown, or the GEP isn't inbounds, bail.
1181 if (ObjectAccessSize == MemoryLocation::UnknownSize || !GEPOp->isInBounds())
1182 return false;
1183
1184 // We need the object to be an alloca or a globalvariable, and want to know
1185 // the offset of the pointer from the object precisely, so no variable
1186 // indices are allowed.
1187 if (!(isa<AllocaInst>(DecompObject.Base) ||
1188 isa<GlobalVariable>(DecompObject.Base)) ||
1189 !DecompObject.VarIndices.empty())
1190 return false;
1191
1192 int64_t ObjectBaseOffset = DecompObject.StructOffset +
1193 DecompObject.OtherOffset;
1194
1195 // If the GEP has no variable indices, we know the precise offset
1196 // from the base, then use it. If the GEP has variable indices,
1197 // we can't get exact GEP offset to identify pointer alias. So return
1198 // false in that case.
1199 if (!DecompGEP.VarIndices.empty())
1200 return false;
1201 int64_t GEPBaseOffset = DecompGEP.StructOffset;
1202 GEPBaseOffset += DecompGEP.OtherOffset;
1203
1204 return (GEPBaseOffset >= ObjectBaseOffset + (int64_t)ObjectAccessSize);
1205}
1206
1207/// Provides a bunch of ad-hoc rules to disambiguate a GEP instruction against
1208/// another pointer.
1209///
1210/// We know that V1 is a GEP, but we don't know anything about V2.
1211/// UnderlyingV1 is GetUnderlyingObject(GEP1, DL), UnderlyingV2 is the same for
1212/// V2.
1213AliasResult
1214BasicAAResult::aliasGEP(const GEPOperator *GEP1, LocationSize V1Size,
1215 const AAMDNodes &V1AAInfo, const Value *V2,
1216 LocationSize V2Size, const AAMDNodes &V2AAInfo,
1217 const Value *UnderlyingV1, const Value *UnderlyingV2) {
1218 DecomposedGEP DecompGEP1, DecompGEP2;
1219 bool GEP1MaxLookupReached =
1220 DecomposeGEPExpression(GEP1, DecompGEP1, DL, &AC, DT);
1221 bool GEP2MaxLookupReached =
1222 DecomposeGEPExpression(V2, DecompGEP2, DL, &AC, DT);
1223
1224 int64_t GEP1BaseOffset = DecompGEP1.StructOffset + DecompGEP1.OtherOffset;
1225 int64_t GEP2BaseOffset = DecompGEP2.StructOffset + DecompGEP2.OtherOffset;
1226
1227 assert(DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 &&(static_cast <bool> (DecompGEP1.Base == UnderlyingV1 &&
DecompGEP2.Base == UnderlyingV2 && "DecomposeGEPExpression returned a result different from "
"GetUnderlyingObject") ? void (0) : __assert_fail ("DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 && \"DecomposeGEPExpression returned a result different from \" \"GetUnderlyingObject\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1229, __extension__ __PRETTY_FUNCTION__))
1228 "DecomposeGEPExpression returned a result different from "(static_cast <bool> (DecompGEP1.Base == UnderlyingV1 &&
DecompGEP2.Base == UnderlyingV2 && "DecomposeGEPExpression returned a result different from "
"GetUnderlyingObject") ? void (0) : __assert_fail ("DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 && \"DecomposeGEPExpression returned a result different from \" \"GetUnderlyingObject\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1229, __extension__ __PRETTY_FUNCTION__))
1229 "GetUnderlyingObject")(static_cast <bool> (DecompGEP1.Base == UnderlyingV1 &&
DecompGEP2.Base == UnderlyingV2 && "DecomposeGEPExpression returned a result different from "
"GetUnderlyingObject") ? void (0) : __assert_fail ("DecompGEP1.Base == UnderlyingV1 && DecompGEP2.Base == UnderlyingV2 && \"DecomposeGEPExpression returned a result different from \" \"GetUnderlyingObject\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1229, __extension__ __PRETTY_FUNCTION__))
;
1230
1231 // If the GEP's offset relative to its base is such that the base would
1232 // fall below the start of the object underlying V2, then the GEP and V2
1233 // cannot alias.
1234 if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
1235 isGEPBaseAtNegativeOffset(GEP1, DecompGEP1, DecompGEP2, V2Size))
1236 return NoAlias;
1237 // If we have two gep instructions with must-alias or not-alias'ing base
1238 // pointers, figure out if the indexes to the GEP tell us anything about the
1239 // derived pointer.
1240 if (const GEPOperator *GEP2 = dyn_cast<GEPOperator>(V2)) {
1241 // Check for the GEP base being at a negative offset, this time in the other
1242 // direction.
1243 if (!GEP1MaxLookupReached && !GEP2MaxLookupReached &&
1244 isGEPBaseAtNegativeOffset(GEP2, DecompGEP2, DecompGEP1, V1Size))
1245 return NoAlias;
1246 // Do the base pointers alias?
1247 AliasResult BaseAlias =
1248 aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize, AAMDNodes(),
1249 UnderlyingV2, MemoryLocation::UnknownSize, AAMDNodes());
1250
1251 // Check for geps of non-aliasing underlying pointers where the offsets are
1252 // identical.
1253 if ((BaseAlias == MayAlias) && V1Size == V2Size) {
1254 // Do the base pointers alias assuming type and size.
1255 AliasResult PreciseBaseAlias = aliasCheck(UnderlyingV1, V1Size, V1AAInfo,
1256 UnderlyingV2, V2Size, V2AAInfo);
1257 if (PreciseBaseAlias == NoAlias) {
1258 // See if the computed offset from the common pointer tells us about the
1259 // relation of the resulting pointer.
1260 // If the max search depth is reached the result is undefined
1261 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1262 return MayAlias;
1263
1264 // Same offsets.
1265 if (GEP1BaseOffset == GEP2BaseOffset &&
1266 DecompGEP1.VarIndices == DecompGEP2.VarIndices)
1267 return NoAlias;
1268 }
1269 }
1270
1271 // If we get a No or May, then return it immediately, no amount of analysis
1272 // will improve this situation.
1273 if (BaseAlias != MustAlias) {
1274 assert(BaseAlias == NoAlias || BaseAlias == MayAlias)(static_cast <bool> (BaseAlias == NoAlias || BaseAlias ==
MayAlias) ? void (0) : __assert_fail ("BaseAlias == NoAlias || BaseAlias == MayAlias"
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1274, __extension__ __PRETTY_FUNCTION__))
;
1275 return BaseAlias;
1276 }
1277
1278 // Otherwise, we have a MustAlias. Since the base pointers alias each other
1279 // exactly, see if the computed offset from the common pointer tells us
1280 // about the relation of the resulting pointer.
1281 // If we know the two GEPs are based off of the exact same pointer (and not
1282 // just the same underlying object), see if that tells us anything about
1283 // the resulting pointers.
1284 if (GEP1->getPointerOperand()->stripPointerCastsAndInvariantGroups() ==
1285 GEP2->getPointerOperand()->stripPointerCastsAndInvariantGroups() &&
1286 GEP1->getPointerOperandType() == GEP2->getPointerOperandType()) {
1287 AliasResult R = aliasSameBasePointerGEPs(GEP1, V1Size, GEP2, V2Size, DL);
1288 // If we couldn't find anything interesting, don't abandon just yet.
1289 if (R != MayAlias)
1290 return R;
1291 }
1292
1293 // If the max search depth is reached, the result is undefined
1294 if (GEP2MaxLookupReached || GEP1MaxLookupReached)
1295 return MayAlias;
1296
1297 // Subtract the GEP2 pointer from the GEP1 pointer to find out their
1298 // symbolic difference.
1299 GEP1BaseOffset -= GEP2BaseOffset;
1300 GetIndexDifference(DecompGEP1.VarIndices, DecompGEP2.VarIndices);
1301
1302 } else {
1303 // Check to see if these two pointers are related by the getelementptr
1304 // instruction. If one pointer is a GEP with a non-zero index of the other
1305 // pointer, we know they cannot alias.
1306
1307 // If both accesses are unknown size, we can't do anything useful here.
1308 if (V1Size == MemoryLocation::UnknownSize &&
1309 V2Size == MemoryLocation::UnknownSize)
1310 return MayAlias;
1311
1312 AliasResult R = aliasCheck(UnderlyingV1, MemoryLocation::UnknownSize,
1313 AAMDNodes(), V2, MemoryLocation::UnknownSize,
1314 V2AAInfo, nullptr, UnderlyingV2);
1315 if (R != MustAlias) {
1316 // If V2 may alias GEP base pointer, conservatively returns MayAlias.
1317 // If V2 is known not to alias GEP base pointer, then the two values
1318 // cannot alias per GEP semantics: "Any memory access must be done through
1319 // a pointer value associated with an address range of the memory access,
1320 // otherwise the behavior is undefined.".
1321 assert(R == NoAlias || R == MayAlias)(static_cast <bool> (R == NoAlias || R == MayAlias) ? void
(0) : __assert_fail ("R == NoAlias || R == MayAlias", "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1321, __extension__ __PRETTY_FUNCTION__))
;
1322 return R;
1323 }
1324
1325 // If the max search depth is reached the result is undefined
1326 if (GEP1MaxLookupReached)
1327 return MayAlias;
1328 }
1329
1330 // In the two GEP Case, if there is no difference in the offsets of the
1331 // computed pointers, the resultant pointers are a must alias. This
1332 // happens when we have two lexically identical GEP's (for example).
1333 //
1334 // In the other case, if we have getelementptr <ptr>, 0, 0, 0, 0, ... and V2
1335 // must aliases the GEP, the end result is a must alias also.
1336 if (GEP1BaseOffset == 0 && DecompGEP1.VarIndices.empty())
1337 return MustAlias;
1338
1339 // If there is a constant difference between the pointers, but the difference
1340 // is less than the size of the associated memory object, then we know
1341 // that the objects are partially overlapping. If the difference is
1342 // greater, we know they do not overlap.
1343 if (GEP1BaseOffset != 0 && DecompGEP1.VarIndices.empty()) {
1344 if (GEP1BaseOffset >= 0) {
1345 if (V2Size != MemoryLocation::UnknownSize) {
1346 if ((uint64_t)GEP1BaseOffset < V2Size)
1347 return PartialAlias;
1348 return NoAlias;
1349 }
1350 } else {
1351 // We have the situation where:
1352 // + +
1353 // | BaseOffset |
1354 // ---------------->|
1355 // |-->V1Size |-------> V2Size
1356 // GEP1 V2
1357 // We need to know that V2Size is not unknown, otherwise we might have
1358 // stripped a gep with negative index ('gep <ptr>, -1, ...).
1359 if (V1Size != MemoryLocation::UnknownSize &&
1360 V2Size != MemoryLocation::UnknownSize) {
1361 if (-(uint64_t)GEP1BaseOffset < V1Size)
1362 return PartialAlias;
1363 return NoAlias;
1364 }
1365 }
1366 }
1367
1368 if (!DecompGEP1.VarIndices.empty()) {
1369 uint64_t Modulo = 0;
1370 bool AllPositive = true;
1371 for (unsigned i = 0, e = DecompGEP1.VarIndices.size(); i != e; ++i) {
1372
1373 // Try to distinguish something like &A[i][1] against &A[42][0].
1374 // Grab the least significant bit set in any of the scales. We
1375 // don't need std::abs here (even if the scale's negative) as we'll
1376 // be ^'ing Modulo with itself later.
1377 Modulo |= (uint64_t)DecompGEP1.VarIndices[i].Scale;
1378
1379 if (AllPositive) {
1380 // If the Value could change between cycles, then any reasoning about
1381 // the Value this cycle may not hold in the next cycle. We'll just
1382 // give up if we can't determine conditions that hold for every cycle:
1383 const Value *V = DecompGEP1.VarIndices[i].V;
1384
1385 KnownBits Known = computeKnownBits(V, DL, 0, &AC, nullptr, DT);
1386 bool SignKnownZero = Known.isNonNegative();
1387 bool SignKnownOne = Known.isNegative();
1388
1389 // Zero-extension widens the variable, and so forces the sign
1390 // bit to zero.
1391 bool IsZExt = DecompGEP1.VarIndices[i].ZExtBits > 0 || isa<ZExtInst>(V);
1392 SignKnownZero |= IsZExt;
1393 SignKnownOne &= !IsZExt;
1394
1395 // If the variable begins with a zero then we know it's
1396 // positive, regardless of whether the value is signed or
1397 // unsigned.
1398 int64_t Scale = DecompGEP1.VarIndices[i].Scale;
1399 AllPositive =
1400 (SignKnownZero && Scale >= 0) || (SignKnownOne && Scale < 0);
1401 }
1402 }
1403
1404 Modulo = Modulo ^ (Modulo & (Modulo - 1));
1405
1406 // We can compute the difference between the two addresses
1407 // mod Modulo. Check whether that difference guarantees that the
1408 // two locations do not alias.
1409 uint64_t ModOffset = (uint64_t)GEP1BaseOffset & (Modulo - 1);
1410 if (V1Size != MemoryLocation::UnknownSize &&
1411 V2Size != MemoryLocation::UnknownSize && ModOffset >= V2Size &&
1412 V1Size <= Modulo - ModOffset)
1413 return NoAlias;
1414
1415 // If we know all the variables are positive, then GEP1 >= GEP1BasePtr.
1416 // If GEP1BasePtr > V2 (GEP1BaseOffset > 0) then we know the pointers
1417 // don't alias if V2Size can fit in the gap between V2 and GEP1BasePtr.
1418 if (AllPositive && GEP1BaseOffset > 0 && V2Size <= (uint64_t)GEP1BaseOffset)
1419 return NoAlias;
1420
1421 if (constantOffsetHeuristic(DecompGEP1.VarIndices, V1Size, V2Size,
1422 GEP1BaseOffset, &AC, DT))
1423 return NoAlias;
1424 }
1425
1426 // Statically, we can see that the base objects are the same, but the
1427 // pointers have dynamic offsets which we can't resolve. And none of our
1428 // little tricks above worked.
1429 return MayAlias;
1430}
1431
1432static AliasResult MergeAliasResults(AliasResult A, AliasResult B) {
1433 // If the results agree, take it.
1434 if (A == B)
1435 return A;
1436 // A mix of PartialAlias and MustAlias is PartialAlias.
1437 if ((A == PartialAlias && B == MustAlias) ||
1438 (B == PartialAlias && A == MustAlias))
1439 return PartialAlias;
1440 // Otherwise, we don't know anything.
1441 return MayAlias;
1442}
1443
1444/// Provides a bunch of ad-hoc rules to disambiguate a Select instruction
1445/// against another.
1446AliasResult BasicAAResult::aliasSelect(const SelectInst *SI,
1447 LocationSize SISize,
1448 const AAMDNodes &SIAAInfo,
1449 const Value *V2, LocationSize V2Size,
1450 const AAMDNodes &V2AAInfo,
1451 const Value *UnderV2) {
1452 // If the values are Selects with the same condition, we can do a more precise
1453 // check: just check for aliases between the values on corresponding arms.
1454 if (const SelectInst *SI2 = dyn_cast<SelectInst>(V2))
1455 if (SI->getCondition() == SI2->getCondition()) {
1456 AliasResult Alias = aliasCheck(SI->getTrueValue(), SISize, SIAAInfo,
1457 SI2->getTrueValue(), V2Size, V2AAInfo);
1458 if (Alias == MayAlias)
1459 return MayAlias;
1460 AliasResult ThisAlias =
1461 aliasCheck(SI->getFalseValue(), SISize, SIAAInfo,
1462 SI2->getFalseValue(), V2Size, V2AAInfo);
1463 return MergeAliasResults(ThisAlias, Alias);
1464 }
1465
1466 // If both arms of the Select node NoAlias or MustAlias V2, then returns
1467 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1468 AliasResult Alias =
1469 aliasCheck(V2, V2Size, V2AAInfo, SI->getTrueValue(),
1470 SISize, SIAAInfo, UnderV2);
1471 if (Alias == MayAlias)
1472 return MayAlias;
1473
1474 AliasResult ThisAlias =
1475 aliasCheck(V2, V2Size, V2AAInfo, SI->getFalseValue(), SISize, SIAAInfo,
1476 UnderV2);
1477 return MergeAliasResults(ThisAlias, Alias);
1478}
1479
1480/// Provide a bunch of ad-hoc rules to disambiguate a PHI instruction against
1481/// another.
1482AliasResult BasicAAResult::aliasPHI(const PHINode *PN, LocationSize PNSize,
1483 const AAMDNodes &PNAAInfo, const Value *V2,
1484 LocationSize V2Size,
1485 const AAMDNodes &V2AAInfo,
1486 const Value *UnderV2) {
1487 // Track phi nodes we have visited. We use this information when we determine
1488 // value equivalence.
1489 VisitedPhiBBs.insert(PN->getParent());
1490
1491 // If the values are PHIs in the same block, we can do a more precise
1492 // as well as efficient check: just check for aliases between the values
1493 // on corresponding edges.
1494 if (const PHINode *PN2 = dyn_cast<PHINode>(V2))
1495 if (PN2->getParent() == PN->getParent()) {
1496 LocPair Locs(MemoryLocation(PN, PNSize, PNAAInfo),
1497 MemoryLocation(V2, V2Size, V2AAInfo));
1498 if (PN > V2)
1499 std::swap(Locs.first, Locs.second);
1500 // Analyse the PHIs' inputs under the assumption that the PHIs are
1501 // NoAlias.
1502 // If the PHIs are May/MustAlias there must be (recursively) an input
1503 // operand from outside the PHIs' cycle that is MayAlias/MustAlias or
1504 // there must be an operation on the PHIs within the PHIs' value cycle
1505 // that causes a MayAlias.
1506 // Pretend the phis do not alias.
1507 AliasResult Alias = NoAlias;
1508 assert(AliasCache.count(Locs) &&(static_cast <bool> (AliasCache.count(Locs) && "There must exist an entry for the phi node"
) ? void (0) : __assert_fail ("AliasCache.count(Locs) && \"There must exist an entry for the phi node\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1509, __extension__ __PRETTY_FUNCTION__))
1509 "There must exist an entry for the phi node")(static_cast <bool> (AliasCache.count(Locs) && "There must exist an entry for the phi node"
) ? void (0) : __assert_fail ("AliasCache.count(Locs) && \"There must exist an entry for the phi node\""
, "/build/llvm-toolchain-snapshot-7~svn337204/lib/Analysis/BasicAliasAnalysis.cpp"
, 1509, __extension__ __PRETTY_FUNCTION__))
;
1510 AliasResult OrigAliasResult = AliasCache[Locs];
1511 AliasCache[Locs] = NoAlias;
1512
1513 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1514 AliasResult ThisAlias =
1515 aliasCheck(PN->getIncomingValue(i), PNSize, PNAAInfo,
1516 PN2->getIncomingValueForBlock(PN->getIncomingBlock(i)),
1517 V2Size, V2AAInfo);
1518 Alias = MergeAliasResults(ThisAlias, Alias);
1519 if (Alias == MayAlias)
1520 break;
1521 }
1522
1523 // Reset if speculation failed.
1524 if (Alias != NoAlias)
1525 AliasCache[Locs] = OrigAliasResult;
1526
1527 return Alias;
1528 }
1529
1530 SmallPtrSet<Value *, 4> UniqueSrc;
1531 SmallVector<Value *, 4> V1Srcs;
1532 bool isRecursive = false;
1533 for (Value *PV1 : PN->incoming_values()) {
1534 if (isa<PHINode>(PV1))
1535 // If any of the source itself is a PHI, return MayAlias conservatively
1536 // to avoid compile time explosion. The worst possible case is if both
1537 // sides are PHI nodes. In which case, this is O(m x n) time where 'm'
1538 // and 'n' are the number of PHI sources.
1539 return MayAlias;
1540
1541 if (EnableRecPhiAnalysis)
1542 if (GEPOperator *PV1GEP = dyn_cast<GEPOperator>(PV1)) {
1543 // Check whether the incoming value is a GEP that advances the pointer
1544 // result of this PHI node (e.g. in a loop). If this is the case, we
1545 // would recurse and always get a MayAlias. Handle this case specially
1546 // below.
1547 if (PV1GEP->getPointerOperand() == PN && PV1GEP->getNumIndices() == 1 &&
1548 isa<ConstantInt>(PV1GEP->idx_begin())) {
1549 isRecursive = true;
1550 continue;
1551 }
1552 }
1553
1554 if (UniqueSrc.insert(PV1).second)
1555 V1Srcs.push_back(PV1);
1556 }
1557
1558 // If this PHI node is recursive, set the size of the accessed memory to
1559 // unknown to represent all the possible values the GEP could advance the
1560 // pointer to.
1561 if (isRecursive)
1562 PNSize = MemoryLocation::UnknownSize;
1563
1564 AliasResult Alias =
1565 aliasCheck(V2, V2Size, V2AAInfo, V1Srcs[0],
1566 PNSize, PNAAInfo, UnderV2);
1567
1568 // Early exit if the check of the first PHI source against V2 is MayAlias.
1569 // Other results are not possible.
1570 if (Alias == MayAlias)
1571 return MayAlias;
1572
1573 // If all sources of the PHI node NoAlias or MustAlias V2, then returns
1574 // NoAlias / MustAlias. Otherwise, returns MayAlias.
1575 for (unsigned i = 1, e = V1Srcs.size(); i != e; ++i) {
1576 Value *V = V1Srcs[i];
1577
1578 AliasResult ThisAlias =
1579 aliasCheck(V2, V2Size, V2AAInfo, V, PNSize, PNAAInfo, UnderV2);
1580 Alias = MergeAliasResults(ThisAlias, Alias);
1581 if (Alias == MayAlias)
1582 break;
1583 }
1584
1585 return Alias;
1586}
1587
1588/// Provides a bunch of ad-hoc rules to disambiguate in common cases, such as
1589/// array references.
1590AliasResult BasicAAResult::aliasCheck(const Value *V1, LocationSize V1Size,
1591 AAMDNodes V1AAInfo, const Value *V2,
1592 LocationSize V2Size, AAMDNodes V2AAInfo,
1593 const Value *O1, const Value *O2) {
1594 // If either of the memory references is empty, it doesn't matter what the
1595 // pointer values are.
1596 if (V1Size == 0 || V2Size == 0)
1597 return NoAlias;
1598
1599 // Strip off any casts if they exist.
1600 V1 = V1->stripPointerCastsAndInvariantGroups();
1601 V2 = V2->stripPointerCastsAndInvariantGroups();
1602
1603 // If V1 or V2 is undef, the result is NoAlias because we can always pick a
1604 // value for undef that aliases nothing in the program.
1605 if (isa<UndefValue>(V1) || isa<UndefValue>(V2))
1606 return NoAlias;
1607
1608 // Are we checking for alias of the same value?
1609 // Because we look 'through' phi nodes, we could look at "Value" pointers from
1610 // different iterations. We must therefore make sure that this is not the
1611 // case. The function isValueEqualInPotentialCycles ensures that this cannot
1612 // happen by looking at the visited phi nodes and making sure they cannot
1613 // reach the value.
1614 if (isValueEqualInPotentialCycles(V1, V2))
1615 return MustAlias;
1616
1617 if (!V1->getType()->isPointerTy() || !V2->getType()->isPointerTy())
1618 return NoAlias; // Scalars cannot alias each other
1619
1620 // Figure out what objects these things are pointing to if we can.
1621 if (O1 == nullptr)
1622 O1 = GetUnderlyingObject(V1, DL, MaxLookupSearchDepth);
1623
1624 if (O2 == nullptr)
1625 O2 = GetUnderlyingObject(V2, DL, MaxLookupSearchDepth);
1626
1627 // Null values in the default address space don't point to any object, so they
1628 // don't alias any other pointer.
1629 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O1))
1630 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1631 return NoAlias;
1632 if (const ConstantPointerNull *CPN = dyn_cast<ConstantPointerNull>(O2))
1633 if (!NullPointerIsDefined(&F, CPN->getType()->getAddressSpace()))
1634 return NoAlias;
1635
1636 if (O1 != O2) {
1637 // If V1/V2 point to two different objects, we know that we have no alias.
1638 if (isIdentifiedObject(O1) && isIdentifiedObject(O2))
1639 return NoAlias;
1640
1641 // Constant pointers can't alias with non-const isIdentifiedObject objects.
1642 if ((isa<Constant>(O1) && isIdentifiedObject(O2) && !isa<Constant>(O2)) ||
1643 (isa<Constant>(O2) && isIdentifiedObject(O1) && !isa<Constant>(O1)))
1644 return NoAlias;
1645
1646 // Function arguments can't alias with things that are known to be
1647 // unambigously identified at the function level.
1648 if ((isa<Argument>(O1) && isIdentifiedFunctionLocal(O2)) ||
1649 (isa<Argument>(O2) && isIdentifiedFunctionLocal(O1)))
1650 return NoAlias;
1651
1652 // If one pointer is the result of a call/invoke or load and the other is a
1653 // non-escaping local object within the same function, then we know the
1654 // object couldn't escape to a point where the call could return it.
1655 //
1656 // Note that if the pointers are in different functions, there are a
1657 // variety of complications. A call with a nocapture argument may still
1658 // temporary store the nocapture argument's value in a temporary memory
1659 // location if that memory location doesn't escape. Or it may pass a
1660 // nocapture value to other functions as long as they don't capture it.
1661 if (isEscapeSource(O1) && isNonEscapingLocalObject(O2))
1662 return NoAlias;
1663 if (isEscapeSource(O2) && isNonEscapingLocalObject(O1))
1664 return NoAlias;
1665 }
1666
1667 // If the size of one access is larger than the entire object on the other
1668 // side, then we know such behavior is undefined and can assume no alias.
1669 bool NullIsValidLocation = NullPointerIsDefined(&F);
1670 if ((V1Size != MemoryLocation::UnknownSize &&
1671 isObjectSmallerThan(O2, V1Size, DL, TLI, NullIsValidLocation)) ||
1672 (V2Size != MemoryLocation::UnknownSize &&
1673 isObjectSmallerThan(O1, V2Size, DL, TLI, NullIsValidLocation)))
1674 return NoAlias;
1675
1676 // Check the cache before climbing up use-def chains. This also terminates
1677 // otherwise infinitely recursive queries.
1678 LocPair Locs(MemoryLocation(V1, V1Size, V1AAInfo),
1679 MemoryLocation(V2, V2Size, V2AAInfo));
1680 if (V1 > V2)
1681 std::swap(Locs.first, Locs.second);
1682 std::pair<AliasCacheTy::iterator, bool> Pair =
1683 AliasCache.insert(std::make_pair(Locs, MayAlias));
1684 if (!Pair.second)
1685 return Pair.first->second;
1686
1687 // FIXME: This isn't aggressively handling alias(GEP, PHI) for example: if the
1688 // GEP can't simplify, we don't even look at the PHI cases.
1689 if (!isa<GEPOperator>(V1) && isa<GEPOperator>(V2)) {
1690 std::swap(V1, V2);
1691 std::swap(V1Size, V2Size);
1692 std::swap(O1, O2);
1693 std::swap(V1AAInfo, V2AAInfo);
1694 }
1695 if (const GEPOperator *GV1 = dyn_cast<GEPOperator>(V1)) {
1696 AliasResult Result =
1697 aliasGEP(GV1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O1, O2);
1698 if (Result != MayAlias)
1699 return AliasCache[Locs] = Result;
1700 }
1701
1702 if (isa<PHINode>(V2) && !isa<PHINode>(V1)) {
1703 std::swap(V1, V2);
1704 std::swap(O1, O2);
1705 std::swap(V1Size, V2Size);
1706 std::swap(V1AAInfo, V2AAInfo);
1707 }
1708 if (const PHINode *PN = dyn_cast<PHINode>(V1)) {
1709 AliasResult Result = aliasPHI(PN, V1Size, V1AAInfo,
1710 V2, V2Size, V2AAInfo, O2);
1711 if (Result != MayAlias)
1712 return AliasCache[Locs] = Result;
1713 }
1714
1715 if (isa<SelectInst>(V2) && !isa<SelectInst>(V1)) {
1716 std::swap(V1, V2);
1717 std::swap(O1, O2);
1718 std::swap(V1Size, V2Size);
1719 std::swap(V1AAInfo, V2AAInfo);
1720 }
1721 if (const SelectInst *S1 = dyn_cast<SelectInst>(V1)) {
1722 AliasResult Result =
1723 aliasSelect(S1, V1Size, V1AAInfo, V2, V2Size, V2AAInfo, O2);
1724 if (Result != MayAlias)
1725 return AliasCache[Locs] = Result;
1726 }
1727
1728 // If both pointers are pointing into the same object and one of them
1729 // accesses the entire object, then the accesses must overlap in some way.
1730 if (O1 == O2)
1731 if (V1Size != MemoryLocation::UnknownSize &&
1732 V2Size != MemoryLocation::UnknownSize &&
1733 (isObjectSize(O1, V1Size, DL, TLI, NullIsValidLocation) ||
1734 isObjectSize(O2, V2Size, DL, TLI, NullIsValidLocation)))
1735 return AliasCache[Locs] = PartialAlias;
1736
1737 // Recurse back into the best AA results we have, potentially with refined
1738 // memory locations. We have already ensured that BasicAA has a MayAlias
1739 // cache result for these, so any recursion back into BasicAA won't loop.
1740 AliasResult Result = getBestAAResults().alias(Locs.first, Locs.second);
1741 return AliasCache[Locs] = Result;
1742}
1743
1744/// Check whether two Values can be considered equivalent.
1745///
1746/// In addition to pointer equivalence of \p V1 and \p V2 this checks whether
1747/// they can not be part of a cycle in the value graph by looking at all
1748/// visited phi nodes an making sure that the phis cannot reach the value. We
1749/// have to do this because we are looking through phi nodes (That is we say
1750/// noalias(V, phi(VA, VB)) if noalias(V, VA) and noalias(V, VB).
1751bool BasicAAResult::isValueEqualInPotentialCycles(const Value *V,
1752 const Value *V2) {
1753 if (V != V2)
1754 return false;
1755
1756 const Instruction *Inst = dyn_cast<Instruction>(V);
1757 if (!Inst)
1758 return true;
1759
1760 if (VisitedPhiBBs.empty())
1761 return true;
1762
1763 if (VisitedPhiBBs.size() > MaxNumPhiBBsValueReachabilityCheck)
1764 return false;
1765
1766 // Make sure that the visited phis cannot reach the Value. This ensures that
1767 // the Values cannot come from different iterations of a potential cycle the
1768 // phi nodes could be involved in.
1769 for (auto *P : VisitedPhiBBs)
1770 if (isPotentiallyReachable(&P->front(), Inst, DT, LI))
1771 return false;
1772
1773 return true;
1774}
1775
1776/// Computes the symbolic difference between two de-composed GEPs.
1777///
1778/// Dest and Src are the variable indices from two decomposed GetElementPtr
1779/// instructions GEP1 and GEP2 which have common base pointers.
1780void BasicAAResult::GetIndexDifference(
1781 SmallVectorImpl<VariableGEPIndex> &Dest,
1782 const SmallVectorImpl<VariableGEPIndex> &Src) {
1783 if (Src.empty())
1784 return;
1785
1786 for (unsigned i = 0, e = Src.size(); i != e; ++i) {
1787 const Value *V = Src[i].V;
1788 unsigned ZExtBits = Src[i].ZExtBits, SExtBits = Src[i].SExtBits;
1789 int64_t Scale = Src[i].Scale;
1790
1791 // Find V in Dest. This is N^2, but pointer indices almost never have more
1792 // than a few variable indexes.
1793 for (unsigned j = 0, e = Dest.size(); j != e; ++j) {
1794 if (!isValueEqualInPotentialCycles(Dest[j].V, V) ||
1795 Dest[j].ZExtBits != ZExtBits || Dest[j].SExtBits != SExtBits)
1796 continue;
1797
1798 // If we found it, subtract off Scale V's from the entry in Dest. If it
1799 // goes to zero, remove the entry.
1800 if (Dest[j].Scale != Scale)
1801 Dest[j].Scale -= Scale;
1802 else
1803 Dest.erase(Dest.begin() + j);
1804 Scale = 0;
1805 break;
1806 }
1807
1808 // If we didn't consume this entry, add it to the end of the Dest list.
1809 if (Scale) {
1810 VariableGEPIndex Entry = {V, ZExtBits, SExtBits, -Scale};
1811 Dest.push_back(Entry);
1812 }
1813 }
1814}
1815
1816bool BasicAAResult::constantOffsetHeuristic(
1817 const SmallVectorImpl<VariableGEPIndex> &VarIndices, LocationSize V1Size,
1818 LocationSize V2Size, int64_t BaseOffset, AssumptionCache *AC,
1819 DominatorTree *DT) {
1820 if (VarIndices.size() != 2 || V1Size == MemoryLocation::UnknownSize ||
1
Assuming the condition is false
2
Assuming 'V1Size' is not equal to UnknownSize
4
Taking false branch
1821 V2Size == MemoryLocation::UnknownSize)
3
Assuming 'V2Size' is not equal to UnknownSize
1822 return false;
1823
1824 const VariableGEPIndex &Var0 = VarIndices[0], &Var1 = VarIndices[1];
1825
1826 if (Var0.ZExtBits != Var1.ZExtBits || Var0.SExtBits != Var1.SExtBits ||
5
Taking false branch
1827 Var0.Scale != -Var1.Scale)
1828 return false;
1829
1830 unsigned Width = Var1.V->getType()->getIntegerBitWidth();
1831
1832 // We'll strip off the Extensions of Var0 and Var1 and do another round
1833 // of GetLinearExpression decomposition. In the example above, if Var0
1834 // is zext(%x + 1) we should get V1 == %x and V1Offset == 1.
1835
1836 APInt V0Scale(Width, 0), V0Offset(Width, 0), V1Scale(Width, 0),
1837 V1Offset(Width, 0);
1838 bool NSW = true, NUW = true;
1839 unsigned V0ZExtBits = 0, V0SExtBits = 0, V1ZExtBits = 0, V1SExtBits = 0;
1840 const Value *V0 = GetLinearExpression(Var0.V, V0Scale, V0Offset, V0ZExtBits,
6
Calling 'BasicAAResult::GetLinearExpression'
1841 V0SExtBits, DL, 0, AC, DT, NSW, NUW);
1842 NSW = true;
1843 NUW = true;
1844 const Value *V1 = GetLinearExpression(Var1.V, V1Scale, V1Offset, V1ZExtBits,
1845 V1SExtBits, DL, 0, AC, DT, NSW, NUW);
1846
1847 if (V0Scale != V1Scale || V0ZExtBits != V1ZExtBits ||
1848 V0SExtBits != V1SExtBits || !isValueEqualInPotentialCycles(V0, V1))
1849 return false;
1850
1851 // We have a hit - Var0 and Var1 only differ by a constant offset!
1852
1853 // If we've been sext'ed then zext'd the maximum difference between Var0 and
1854 // Var1 is possible to calculate, but we're just interested in the absolute
1855 // minimum difference between the two. The minimum distance may occur due to
1856 // wrapping; consider "add i3 %i, 5": if %i == 7 then 7 + 5 mod 8 == 4, and so
1857 // the minimum distance between %i and %i + 5 is 3.
1858 APInt MinDiff = V0Offset - V1Offset, Wrapped = -MinDiff;
1859 MinDiff = APIntOps::umin(MinDiff, Wrapped);
1860 uint64_t MinDiffBytes = MinDiff.getZExtValue() * std::abs(Var0.Scale);
1861
1862 // We can't definitely say whether GEP1 is before or after V2 due to wrapping
1863 // arithmetic (i.e. for some values of GEP1 and V2 GEP1 < V2, and for other
1864 // values GEP1 > V2). We'll therefore only declare NoAlias if both V1Size and
1865 // V2Size can fit in the MinDiffBytes gap.
1866 return V1Size + std::abs(BaseOffset) <= MinDiffBytes &&
1867 V2Size + std::abs(BaseOffset) <= MinDiffBytes;
1868}
1869
1870//===----------------------------------------------------------------------===//
1871// BasicAliasAnalysis Pass
1872//===----------------------------------------------------------------------===//
1873
1874AnalysisKey BasicAA::Key;
1875
1876BasicAAResult BasicAA::run(Function &F, FunctionAnalysisManager &AM) {
1877 return BasicAAResult(F.getParent()->getDataLayout(),
1878 F,
1879 AM.getResult<TargetLibraryAnalysis>(F),
1880 AM.getResult<AssumptionAnalysis>(F),
1881 &AM.getResult<DominatorTreeAnalysis>(F),
1882 AM.getCachedResult<LoopAnalysis>(F));
1883}
1884
1885BasicAAWrapperPass::BasicAAWrapperPass() : FunctionPass(ID) {
1886 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
1887}
1888
1889char BasicAAWrapperPass::ID = 0;
1890
1891void BasicAAWrapperPass::anchor() {}
1892
1893INITIALIZE_PASS_BEGIN(BasicAAWrapperPass, "basicaa",static void *initializeBasicAAWrapperPassPassOnce(PassRegistry
&Registry) {
1894 "Basic Alias Analysis (stateless AA impl)", true, true)static void *initializeBasicAAWrapperPassPassOnce(PassRegistry
&Registry) {
1895INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
1896INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
1897INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
1898INITIALIZE_PASS_END(BasicAAWrapperPass, "basicaa",PassInfo *PI = new PassInfo( "Basic Alias Analysis (stateless AA impl)"
, "basicaa", &BasicAAWrapperPass::ID, PassInfo::NormalCtor_t
(callDefaultCtor<BasicAAWrapperPass>), true, true); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeBasicAAWrapperPassPassFlag; void llvm::initializeBasicAAWrapperPassPass
(PassRegistry &Registry) { llvm::call_once(InitializeBasicAAWrapperPassPassFlag
, initializeBasicAAWrapperPassPassOnce, std::ref(Registry)); }
1899 "Basic Alias Analysis (stateless AA impl)", true, true)PassInfo *PI = new PassInfo( "Basic Alias Analysis (stateless AA impl)"
, "basicaa", &BasicAAWrapperPass::ID, PassInfo::NormalCtor_t
(callDefaultCtor<BasicAAWrapperPass>), true, true); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeBasicAAWrapperPassPassFlag; void llvm::initializeBasicAAWrapperPassPass
(PassRegistry &Registry) { llvm::call_once(InitializeBasicAAWrapperPassPassFlag
, initializeBasicAAWrapperPassPassOnce, std::ref(Registry)); }
1900
1901FunctionPass *llvm::createBasicAAWrapperPass() {
1902 return new BasicAAWrapperPass();
1903}
1904
1905bool BasicAAWrapperPass::runOnFunction(Function &F) {
1906 auto &ACT = getAnalysis<AssumptionCacheTracker>();
1907 auto &TLIWP = getAnalysis<TargetLibraryInfoWrapperPass>();
1908 auto &DTWP = getAnalysis<DominatorTreeWrapperPass>();
1909 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
1910
1911 Result.reset(new BasicAAResult(F.getParent()->getDataLayout(), F, TLIWP.getTLI(),
1912 ACT.getAssumptionCache(F), &DTWP.getDomTree(),
1913 LIWP ? &LIWP->getLoopInfo() : nullptr));
1914
1915 return false;
1916}
1917
1918void BasicAAWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1919 AU.setPreservesAll();
1920 AU.addRequired<AssumptionCacheTracker>();
1921 AU.addRequired<DominatorTreeWrapperPass>();
1922 AU.addRequired<TargetLibraryInfoWrapperPass>();
1923}
1924
1925BasicAAResult llvm::createLegacyPMBasicAAResult(Pass &P, Function &F) {
1926 return BasicAAResult(
1927 F.getParent()->getDataLayout(),
1928 F,
1929 P.getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
1930 P.getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F));
1931}

/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h

1//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
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/// \file
11/// This file implements a class to represent arbitrary precision
12/// integral constant values and operations on them.
13///
14//===----------------------------------------------------------------------===//
15
16#ifndef LLVM_ADT_APINT_H
17#define LLVM_ADT_APINT_H
18
19#include "llvm/Support/Compiler.h"
20#include "llvm/Support/MathExtras.h"
21#include <cassert>
22#include <climits>
23#include <cstring>
24#include <string>
25
26namespace llvm {
27class FoldingSetNodeID;
28class StringRef;
29class hash_code;
30class raw_ostream;
31
32template <typename T> class SmallVectorImpl;
33template <typename T> class ArrayRef;
34
35class APInt;
36
37inline APInt operator-(APInt);
38
39//===----------------------------------------------------------------------===//
40// APInt Class
41//===----------------------------------------------------------------------===//
42
43/// Class for arbitrary precision integers.
44///
45/// APInt is a functional replacement for common case unsigned integer type like
46/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
47/// integer sizes and large integer value types such as 3-bits, 15-bits, or more
48/// than 64-bits of precision. APInt provides a variety of arithmetic operators
49/// and methods to manipulate integer values of any bit-width. It supports both
50/// the typical integer arithmetic and comparison operations as well as bitwise
51/// manipulation.
52///
53/// The class has several invariants worth noting:
54/// * All bit, byte, and word positions are zero-based.
55/// * Once the bit width is set, it doesn't change except by the Truncate,
56/// SignExtend, or ZeroExtend operations.
57/// * All binary operators must be on APInt instances of the same bit width.
58/// Attempting to use these operators on instances with different bit
59/// widths will yield an assertion.
60/// * The value is stored canonically as an unsigned value. For operations
61/// where it makes a difference, there are both signed and unsigned variants
62/// of the operation. For example, sdiv and udiv. However, because the bit
63/// widths must be the same, operations such as Mul and Add produce the same
64/// results regardless of whether the values are interpreted as signed or
65/// not.
66/// * In general, the class tries to follow the style of computation that LLVM
67/// uses in its IR. This simplifies its use for LLVM.
68///
69class LLVM_NODISCARD[[clang::warn_unused_result]] APInt {
70public:
71 typedef uint64_t WordType;
72
73 /// This enum is used to hold the constants we needed for APInt.
74 enum : unsigned {
75 /// Byte size of a word.
76 APINT_WORD_SIZE = sizeof(WordType),
77 /// Bits in a word.
78 APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT8
79 };
80
81 enum class Rounding {
82 DOWN,
83 TOWARD_ZERO,
84 UP,
85 };
86
87 static const WordType WORD_MAX = ~WordType(0);
88
89private:
90 /// This union is used to store the integer value. When the
91 /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal.
92 union {
93 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
94 uint64_t *pVal; ///< Used to store the >64 bits integer value.
95 } U;
96
97 unsigned BitWidth; ///< The number of bits in this APInt.
98
99 friend struct DenseMapAPIntKeyInfo;
100
101 friend class APSInt;
102
103 /// Fast internal constructor
104 ///
105 /// This constructor is used only internally for speed of construction of
106 /// temporaries. It is unsafe for general use so it is not public.
107 APInt(uint64_t *val, unsigned bits) : BitWidth(bits) {
108 U.pVal = val;
109 }
110
111 /// Determine if this APInt just has one word to store value.
112 ///
113 /// \returns true if the number of bits <= 64, false otherwise.
114 bool isSingleWord() const { return BitWidth <= APINT_BITS_PER_WORD; }
115
116 /// Determine which word a bit is in.
117 ///
118 /// \returns the word position for the specified bit position.
119 static unsigned whichWord(unsigned bitPosition) {
120 return bitPosition / APINT_BITS_PER_WORD;
121 }
122
123 /// Determine which bit in a word a bit is in.
124 ///
125 /// \returns the bit position in a word for the specified bit position
126 /// in the APInt.
127 static unsigned whichBit(unsigned bitPosition) {
128 return bitPosition % APINT_BITS_PER_WORD;
129 }
130
131 /// Get a single bit mask.
132 ///
133 /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set
134 /// This method generates and returns a uint64_t (word) mask for a single
135 /// bit at a specific bit position. This is used to mask the bit in the
136 /// corresponding word.
137 static uint64_t maskBit(unsigned bitPosition) {
138 return 1ULL << whichBit(bitPosition);
139 }
140
141 /// Clear unused high order bits
142 ///
143 /// This method is used internally to clear the top "N" bits in the high order
144 /// word that are not used by the APInt. This is needed after the most
145 /// significant word is assigned a value to ensure that those bits are
146 /// zero'd out.
147 APInt &clearUnusedBits() {
148 // Compute how many bits are used in the final word
149 unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1;
150
151 // Mask out the high bits.
152 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - WordBits);
153 if (isSingleWord())
154 U.VAL &= mask;
155 else
156 U.pVal[getNumWords() - 1] &= mask;
157 return *this;
158 }
159
160 /// Get the word corresponding to a bit position
161 /// \returns the corresponding word for the specified bit position.
162 uint64_t getWord(unsigned bitPosition) const {
163 return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)];
164 }
165
166 /// Utility method to change the bit width of this APInt to new bit width,
167 /// allocating and/or deallocating as necessary. There is no guarantee on the
168 /// value of any bits upon return. Caller should populate the bits after.
169 void reallocate(unsigned NewBitWidth);
170
171 /// Convert a char array into an APInt
172 ///
173 /// \param radix 2, 8, 10, 16, or 36
174 /// Converts a string into a number. The string must be non-empty
175 /// and well-formed as a number of the given base. The bit-width
176 /// must be sufficient to hold the result.
177 ///
178 /// This is used by the constructors that take string arguments.
179 ///
180 /// StringRef::getAsInteger is superficially similar but (1) does
181 /// not assume that the string is well-formed and (2) grows the
182 /// result to hold the input.
183 void fromString(unsigned numBits, StringRef str, uint8_t radix);
184
185 /// An internal division function for dividing APInts.
186 ///
187 /// This is used by the toString method to divide by the radix. It simply
188 /// provides a more convenient form of divide for internal use since KnuthDiv
189 /// has specific constraints on its inputs. If those constraints are not met
190 /// then it provides a simpler form of divide.
191 static void divide(const WordType *LHS, unsigned lhsWords,
192 const WordType *RHS, unsigned rhsWords, WordType *Quotient,
193 WordType *Remainder);
194
195 /// out-of-line slow case for inline constructor
196 void initSlowCase(uint64_t val, bool isSigned);
197
198 /// shared code between two array constructors
199 void initFromArray(ArrayRef<uint64_t> array);
200
201 /// out-of-line slow case for inline copy constructor
202 void initSlowCase(const APInt &that);
203
204 /// out-of-line slow case for shl
205 void shlSlowCase(unsigned ShiftAmt);
206
207 /// out-of-line slow case for lshr.
208 void lshrSlowCase(unsigned ShiftAmt);
209
210 /// out-of-line slow case for ashr.
211 void ashrSlowCase(unsigned ShiftAmt);
212
213 /// out-of-line slow case for operator=
214 void AssignSlowCase(const APInt &RHS);
215
216 /// out-of-line slow case for operator==
217 bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
218
219 /// out-of-line slow case for countLeadingZeros
220 unsigned countLeadingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
221
222 /// out-of-line slow case for countLeadingOnes.
223 unsigned countLeadingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
224
225 /// out-of-line slow case for countTrailingZeros.
226 unsigned countTrailingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__));
227
228 /// out-of-line slow case for countTrailingOnes
229 unsigned countTrailingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__));
230
231 /// out-of-line slow case for countPopulation
232 unsigned countPopulationSlowCase() const LLVM_READONLY__attribute__((__pure__));
233
234 /// out-of-line slow case for intersects.
235 bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
236
237 /// out-of-line slow case for isSubsetOf.
238 bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
239
240 /// out-of-line slow case for setBits.
241 void setBitsSlowCase(unsigned loBit, unsigned hiBit);
242
243 /// out-of-line slow case for flipAllBits.
244 void flipAllBitsSlowCase();
245
246 /// out-of-line slow case for operator&=.
247 void AndAssignSlowCase(const APInt& RHS);
248
249 /// out-of-line slow case for operator|=.
250 void OrAssignSlowCase(const APInt& RHS);
251
252 /// out-of-line slow case for operator^=.
253 void XorAssignSlowCase(const APInt& RHS);
254
255 /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal
256 /// to, or greater than RHS.
257 int compare(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
258
259 /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal
260 /// to, or greater than RHS.
261 int compareSigned(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__));
262
263public:
264 /// \name Constructors
265 /// @{
266
267 /// Create a new APInt of numBits width, initialized as val.
268 ///
269 /// If isSigned is true then val is treated as if it were a signed value
270 /// (i.e. as an int64_t) and the appropriate sign extension to the bit width
271 /// will be done. Otherwise, no sign extension occurs (high order bits beyond
272 /// the range of val are zero filled).
273 ///
274 /// \param numBits the bit width of the constructed APInt
275 /// \param val the initial value of the APInt
276 /// \param isSigned how to treat signedness of val
277 APInt(unsigned numBits, uint64_t val, bool isSigned = false)
278 : BitWidth(numBits) {
279 assert(BitWidth && "bitwidth too small")(static_cast <bool> (BitWidth && "bitwidth too small"
) ? void (0) : __assert_fail ("BitWidth && \"bitwidth too small\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 279, __extension__ __PRETTY_FUNCTION__))
;
280 if (isSingleWord()) {
281 U.VAL = val;
282 clearUnusedBits();
283 } else {
284 initSlowCase(val, isSigned);
285 }
286 }
287
288 /// Construct an APInt of numBits width, initialized as bigVal[].
289 ///
290 /// Note that bigVal.size() can be smaller or larger than the corresponding
291 /// bit width but any extraneous bits will be dropped.
292 ///
293 /// \param numBits the bit width of the constructed APInt
294 /// \param bigVal a sequence of words to form the initial value of the APInt
295 APInt(unsigned numBits, ArrayRef<uint64_t> bigVal);
296
297 /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but
298 /// deprecated because this constructor is prone to ambiguity with the
299 /// APInt(unsigned, uint64_t, bool) constructor.
300 ///
301 /// If this overload is ever deleted, care should be taken to prevent calls
302 /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool)
303 /// constructor.
304 APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]);
305
306 /// Construct an APInt from a string representation.
307 ///
308 /// This constructor interprets the string \p str in the given radix. The
309 /// interpretation stops when the first character that is not suitable for the
310 /// radix is encountered, or the end of the string. Acceptable radix values
311 /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the
312 /// string to require more bits than numBits.
313 ///
314 /// \param numBits the bit width of the constructed APInt
315 /// \param str the string to be interpreted
316 /// \param radix the radix to use for the conversion
317 APInt(unsigned numBits, StringRef str, uint8_t radix);
318
319 /// Simply makes *this a copy of that.
320 /// Copy Constructor.
321 APInt(const APInt &that) : BitWidth(that.BitWidth) {
322 if (isSingleWord())
323 U.VAL = that.U.VAL;
324 else
325 initSlowCase(that);
326 }
327
328 /// Move Constructor.
329 APInt(APInt &&that) : BitWidth(that.BitWidth) {
330 memcpy(&U, &that.U, sizeof(U));
331 that.BitWidth = 0;
332 }
333
334 /// Destructor.
335 ~APInt() {
336 if (needsCleanup())
337 delete[] U.pVal;
338 }
339
340 /// Default constructor that creates an uninteresting APInt
341 /// representing a 1-bit zero value.
342 ///
343 /// This is useful for object deserialization (pair this with the static
344 /// method Read).
345 explicit APInt() : BitWidth(1) { U.VAL = 0; }
346
347 /// Returns whether this instance allocated memory.
348 bool needsCleanup() const { return !isSingleWord(); }
349
350 /// Used to insert APInt objects, or objects that contain APInt objects, into
351 /// FoldingSets.
352 void Profile(FoldingSetNodeID &id) const;
353
354 /// @}
355 /// \name Value Tests
356 /// @{
357
358 /// Determine sign of this APInt.
359 ///
360 /// This tests the high bit of this APInt to determine if it is set.
361 ///
362 /// \returns true if this APInt is negative, false otherwise
363 bool isNegative() const { return (*this)[BitWidth - 1]; }
364
365 /// Determine if this APInt Value is non-negative (>= 0)
366 ///
367 /// This tests the high bit of the APInt to determine if it is unset.
368 bool isNonNegative() const { return !isNegative(); }
369
370 /// Determine if sign bit of this APInt is set.
371 ///
372 /// This tests the high bit of this APInt to determine if it is set.
373 ///
374 /// \returns true if this APInt has its sign bit set, false otherwise.
375 bool isSignBitSet() const { return (*this)[BitWidth-1]; }
376
377 /// Determine if sign bit of this APInt is clear.
378 ///
379 /// This tests the high bit of this APInt to determine if it is clear.
380 ///
381 /// \returns true if this APInt has its sign bit clear, false otherwise.
382 bool isSignBitClear() const { return !isSignBitSet(); }
383
384 /// Determine if this APInt Value is positive.
385 ///
386 /// This tests if the value of this APInt is positive (> 0). Note
387 /// that 0 is not a positive value.
388 ///
389 /// \returns true if this APInt is positive.
390 bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); }
391
392 /// Determine if all bits are set
393 ///
394 /// This checks to see if the value has all bits of the APInt are set or not.
395 bool isAllOnesValue() const {
396 if (isSingleWord())
397 return U.VAL == WORD_MAX >> (APINT_BITS_PER_WORD - BitWidth);
398 return countTrailingOnesSlowCase() == BitWidth;
399 }
400
401 /// Determine if all bits are clear
402 ///
403 /// This checks to see if the value has all bits of the APInt are clear or
404 /// not.
405 bool isNullValue() const { return !*this; }
406
407 /// Determine if this is a value of 1.
408 ///
409 /// This checks to see if the value of this APInt is one.
410 bool isOneValue() const {
411 if (isSingleWord())
412 return U.VAL == 1;
413 return countLeadingZerosSlowCase() == BitWidth - 1;
414 }
415
416 /// Determine if this is the largest unsigned value.
417 ///
418 /// This checks to see if the value of this APInt is the maximum unsigned
419 /// value for the APInt's bit width.
420 bool isMaxValue() const { return isAllOnesValue(); }
421
422 /// Determine if this is the largest signed value.
423 ///
424 /// This checks to see if the value of this APInt is the maximum signed
425 /// value for the APInt's bit width.
426 bool isMaxSignedValue() const {
427 if (isSingleWord())
428 return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1);
429 return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1;
430 }
431
432 /// Determine if this is the smallest unsigned value.
433 ///
434 /// This checks to see if the value of this APInt is the minimum unsigned
435 /// value for the APInt's bit width.
436 bool isMinValue() const { return isNullValue(); }
437
438 /// Determine if this is the smallest signed value.
439 ///
440 /// This checks to see if the value of this APInt is the minimum signed
441 /// value for the APInt's bit width.
442 bool isMinSignedValue() const {
443 if (isSingleWord())
444 return U.VAL == (WordType(1) << (BitWidth - 1));
445 return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1;
446 }
447
448 /// Check if this APInt has an N-bits unsigned integer value.
449 bool isIntN(unsigned N) const {
450 assert(N && "N == 0 ???")(static_cast <bool> (N && "N == 0 ???") ? void (
0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 450, __extension__ __PRETTY_FUNCTION__))
;
451 return getActiveBits() <= N;
452 }
453
454 /// Check if this APInt has an N-bits signed integer value.
455 bool isSignedIntN(unsigned N) const {
456 assert(N && "N == 0 ???")(static_cast <bool> (N && "N == 0 ???") ? void (
0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 456, __extension__ __PRETTY_FUNCTION__))
;
457 return getMinSignedBits() <= N;
458 }
459
460 /// Check if this APInt's value is a power of two greater than zero.
461 ///
462 /// \returns true if the argument APInt value is a power of two > 0.
463 bool isPowerOf2() const {
464 if (isSingleWord())
465 return isPowerOf2_64(U.VAL);
466 return countPopulationSlowCase() == 1;
467 }
468
469 /// Check if the APInt's value is returned by getSignMask.
470 ///
471 /// \returns true if this is the value returned by getSignMask.
472 bool isSignMask() const { return isMinSignedValue(); }
473
474 /// Convert APInt to a boolean value.
475 ///
476 /// This converts the APInt to a boolean value as a test against zero.
477 bool getBoolValue() const { return !!*this; }
478
479 /// If this value is smaller than the specified limit, return it, otherwise
480 /// return the limit value. This causes the value to saturate to the limit.
481 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) const {
482 return ugt(Limit) ? Limit : getZExtValue();
16
'?' condition is true
483 }
484
485 /// Check if the APInt consists of a repeated bit pattern.
486 ///
487 /// e.g. 0x01010101 satisfies isSplat(8).
488 /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit
489 /// width without remainder.
490 bool isSplat(unsigned SplatSizeInBits) const;
491
492 /// \returns true if this APInt value is a sequence of \param numBits ones
493 /// starting at the least significant bit with the remainder zero.
494 bool isMask(unsigned numBits) const {
495 assert(numBits != 0 && "numBits must be non-zero")(static_cast <bool> (numBits != 0 && "numBits must be non-zero"
) ? void (0) : __assert_fail ("numBits != 0 && \"numBits must be non-zero\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 495, __extension__ __PRETTY_FUNCTION__))
;
496 assert(numBits <= BitWidth && "numBits out of range")(static_cast <bool> (numBits <= BitWidth && "numBits out of range"
) ? void (0) : __assert_fail ("numBits <= BitWidth && \"numBits out of range\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 496, __extension__ __PRETTY_FUNCTION__))
;
497 if (isSingleWord())
498 return U.VAL == (WORD_MAX >> (APINT_BITS_PER_WORD - numBits));
499 unsigned Ones = countTrailingOnesSlowCase();
500 return (numBits == Ones) &&
501 ((Ones + countLeadingZerosSlowCase()) == BitWidth);
502 }
503
504 /// \returns true if this APInt is a non-empty sequence of ones starting at
505 /// the least significant bit with the remainder zero.
506 /// Ex. isMask(0x0000FFFFU) == true.
507 bool isMask() const {
508 if (isSingleWord())
509 return isMask_64(U.VAL);
510 unsigned Ones = countTrailingOnesSlowCase();
511 return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth);
512 }
513
514 /// Return true if this APInt value contains a sequence of ones with
515 /// the remainder zero.
516 bool isShiftedMask() const {
517 if (isSingleWord())
518 return isShiftedMask_64(U.VAL);
519 unsigned Ones = countPopulationSlowCase();
520 unsigned LeadZ = countLeadingZerosSlowCase();
521 return (Ones + LeadZ + countTrailingZeros()) == BitWidth;
522 }
523
524 /// @}
525 /// \name Value Generators
526 /// @{
527
528 /// Gets maximum unsigned value of APInt for specific bit width.
529 static APInt getMaxValue(unsigned numBits) {
530 return getAllOnesValue(numBits);
531 }
532
533 /// Gets maximum signed value of APInt for a specific bit width.
534 static APInt getSignedMaxValue(unsigned numBits) {
535 APInt API = getAllOnesValue(numBits);
536 API.clearBit(numBits - 1);
537 return API;
538 }
539
540 /// Gets minimum unsigned value of APInt for a specific bit width.
541 static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); }
542
543 /// Gets minimum signed value of APInt for a specific bit width.
544 static APInt getSignedMinValue(unsigned numBits) {
545 APInt API(numBits, 0);
546 API.setBit(numBits - 1);
547 return API;
548 }
549
550 /// Get the SignMask for a specific bit width.
551 ///
552 /// This is just a wrapper function of getSignedMinValue(), and it helps code
553 /// readability when we want to get a SignMask.
554 static APInt getSignMask(unsigned BitWidth) {
555 return getSignedMinValue(BitWidth);
556 }
557
558 /// Get the all-ones value.
559 ///
560 /// \returns the all-ones value for an APInt of the specified bit-width.
561 static APInt getAllOnesValue(unsigned numBits) {
562 return APInt(numBits, WORD_MAX, true);
563 }
564
565 /// Get the '0' value.
566 ///
567 /// \returns the '0' value for an APInt of the specified bit-width.
568 static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); }
569
570 /// Compute an APInt containing numBits highbits from this APInt.
571 ///
572 /// Get an APInt with the same BitWidth as this APInt, just zero mask
573 /// the low bits and right shift to the least significant bit.
574 ///
575 /// \returns the high "numBits" bits of this APInt.
576 APInt getHiBits(unsigned numBits) const;
577
578 /// Compute an APInt containing numBits lowbits from this APInt.
579 ///
580 /// Get an APInt with the same BitWidth as this APInt, just zero mask
581 /// the high bits.
582 ///
583 /// \returns the low "numBits" bits of this APInt.
584 APInt getLoBits(unsigned numBits) const;
585
586 /// Return an APInt with exactly one bit set in the result.
587 static APInt getOneBitSet(unsigned numBits, unsigned BitNo) {
588 APInt Res(numBits, 0);
589 Res.setBit(BitNo);
590 return Res;
591 }
592
593 /// Get a value with a block of bits set.
594 ///
595 /// Constructs an APInt value that has a contiguous range of bits set. The
596 /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other
597 /// bits will be zero. For example, with parameters(32, 0, 16) you would get
598 /// 0x0000FFFF. If hiBit is less than loBit then the set bits "wrap". For
599 /// example, with parameters (32, 28, 4), you would get 0xF000000F.
600 ///
601 /// \param numBits the intended bit width of the result
602 /// \param loBit the index of the lowest bit set.
603 /// \param hiBit the index of the highest bit set.
604 ///
605 /// \returns An APInt value with the requested bits set.
606 static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) {
607 APInt Res(numBits, 0);
608 Res.setBits(loBit, hiBit);
609 return Res;
610 }
611
612 /// Get a value with upper bits starting at loBit set.
613 ///
614 /// Constructs an APInt value that has a contiguous range of bits set. The
615 /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other
616 /// bits will be zero. For example, with parameters(32, 12) you would get
617 /// 0xFFFFF000.
618 ///
619 /// \param numBits the intended bit width of the result
620 /// \param loBit the index of the lowest bit to set.
621 ///
622 /// \returns An APInt value with the requested bits set.
623 static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) {
624 APInt Res(numBits, 0);
625 Res.setBitsFrom(loBit);
626 return Res;
627 }
628
629 /// Get a value with high bits set
630 ///
631 /// Constructs an APInt value that has the top hiBitsSet bits set.
632 ///
633 /// \param numBits the bitwidth of the result
634 /// \param hiBitsSet the number of high-order bits set in the result.
635 static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) {
636 APInt Res(numBits, 0);
637 Res.setHighBits(hiBitsSet);
638 return Res;
639 }
640
641 /// Get a value with low bits set
642 ///
643 /// Constructs an APInt value that has the bottom loBitsSet bits set.
644 ///
645 /// \param numBits the bitwidth of the result
646 /// \param loBitsSet the number of low-order bits set in the result.
647 static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) {
648 APInt Res(numBits, 0);
649 Res.setLowBits(loBitsSet);
650 return Res;
651 }
652
653 /// Return a value containing V broadcasted over NewLen bits.
654 static APInt getSplat(unsigned NewLen, const APInt &V);
655
656 /// Determine if two APInts have the same value, after zero-extending
657 /// one of them (if needed!) to ensure that the bit-widths match.
658 static bool isSameValue(const APInt &I1, const APInt &I2) {
659 if (I1.getBitWidth() == I2.getBitWidth())
660 return I1 == I2;
661
662 if (I1.getBitWidth() > I2.getBitWidth())
663 return I1 == I2.zext(I1.getBitWidth());
664
665 return I1.zext(I2.getBitWidth()) == I2;
666 }
667
668 /// Overload to compute a hash_code for an APInt value.
669 friend hash_code hash_value(const APInt &Arg);
670
671 /// This function returns a pointer to the internal storage of the APInt.
672 /// This is useful for writing out the APInt in binary form without any
673 /// conversions.
674 const uint64_t *getRawData() const {
675 if (isSingleWord())
676 return &U.VAL;
677 return &U.pVal[0];
678 }
679
680 /// @}
681 /// \name Unary Operators
682 /// @{
683
684 /// Postfix increment operator.
685 ///
686 /// Increments *this by 1.
687 ///
688 /// \returns a new APInt value representing the original value of *this.
689 const APInt operator++(int) {
690 APInt API(*this);
691 ++(*this);
692 return API;
693 }
694
695 /// Prefix increment operator.
696 ///
697 /// \returns *this incremented by one
698 APInt &operator++();
699
700 /// Postfix decrement operator.
701 ///
702 /// Decrements *this by 1.
703 ///
704 /// \returns a new APInt value representing the original value of *this.
705 const APInt operator--(int) {
706 APInt API(*this);
707 --(*this);
708 return API;
709 }
710
711 /// Prefix decrement operator.
712 ///
713 /// \returns *this decremented by one.
714 APInt &operator--();
715
716 /// Logical negation operator.
717 ///
718 /// Performs logical negation operation on this APInt.
719 ///
720 /// \returns true if *this is zero, false otherwise.
721 bool operator!() const {
722 if (isSingleWord())
723 return U.VAL == 0;
724 return countLeadingZerosSlowCase() == BitWidth;
725 }
726
727 /// @}
728 /// \name Assignment Operators
729 /// @{
730
731 /// Copy assignment operator.
732 ///
733 /// \returns *this after assignment of RHS.
734 APInt &operator=(const APInt &RHS) {
735 // If the bitwidths are the same, we can avoid mucking with memory
736 if (isSingleWord() && RHS.isSingleWord()) {
737 U.VAL = RHS.U.VAL;
738 BitWidth = RHS.BitWidth;
739 return clearUnusedBits();
740 }
741
742 AssignSlowCase(RHS);
743 return *this;
744 }
745
746 /// Move assignment operator.
747 APInt &operator=(APInt &&that) {
748#ifdef _MSC_VER
749 // The MSVC std::shuffle implementation still does self-assignment.
750 if (this == &that)
751 return *this;
752#endif
753 assert(this != &that && "Self-move not supported")(static_cast <bool> (this != &that && "Self-move not supported"
) ? void (0) : __assert_fail ("this != &that && \"Self-move not supported\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 753, __extension__ __PRETTY_FUNCTION__))
;
754 if (!isSingleWord())
755 delete[] U.pVal;
756
757 // Use memcpy so that type based alias analysis sees both VAL and pVal
758 // as modified.
759 memcpy(&U, &that.U, sizeof(U));
760
761 BitWidth = that.BitWidth;
762 that.BitWidth = 0;
763
764 return *this;
765 }
766
767 /// Assignment operator.
768 ///
769 /// The RHS value is assigned to *this. If the significant bits in RHS exceed
770 /// the bit width, the excess bits are truncated. If the bit width is larger
771 /// than 64, the value is zero filled in the unspecified high order bits.
772 ///
773 /// \returns *this after assignment of RHS value.
774 APInt &operator=(uint64_t RHS) {
775 if (isSingleWord()) {
776 U.VAL = RHS;
777 clearUnusedBits();
778 } else {
779 U.pVal[0] = RHS;
780 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
781 }
782 return *this;
783 }
784
785 /// Bitwise AND assignment operator.
786 ///
787 /// Performs a bitwise AND operation on this APInt and RHS. The result is
788 /// assigned to *this.
789 ///
790 /// \returns *this after ANDing with RHS.
791 APInt &operator&=(const APInt &RHS) {
792 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 792, __extension__ __PRETTY_FUNCTION__))
;
793 if (isSingleWord())
794 U.VAL &= RHS.U.VAL;
795 else
796 AndAssignSlowCase(RHS);
797 return *this;
798 }
799
800 /// Bitwise AND assignment operator.
801 ///
802 /// Performs a bitwise AND operation on this APInt and RHS. RHS is
803 /// logically zero-extended or truncated to match the bit-width of
804 /// the LHS.
805 APInt &operator&=(uint64_t RHS) {
806 if (isSingleWord()) {
807 U.VAL &= RHS;
808 return *this;
809 }
810 U.pVal[0] &= RHS;
811 memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE);
812 return *this;
813 }
814
815 /// Bitwise OR assignment operator.
816 ///
817 /// Performs a bitwise OR operation on this APInt and RHS. The result is
818 /// assigned *this;
819 ///
820 /// \returns *this after ORing with RHS.
821 APInt &operator|=(const APInt &RHS) {
822 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 822, __extension__ __PRETTY_FUNCTION__))
;
823 if (isSingleWord())
824 U.VAL |= RHS.U.VAL;
825 else
826 OrAssignSlowCase(RHS);
827 return *this;
828 }
829
830 /// Bitwise OR assignment operator.
831 ///
832 /// Performs a bitwise OR operation on this APInt and RHS. RHS is
833 /// logically zero-extended or truncated to match the bit-width of
834 /// the LHS.
835 APInt &operator|=(uint64_t RHS) {
836 if (isSingleWord()) {
837 U.VAL |= RHS;
838 clearUnusedBits();
839 } else {
840 U.pVal[0] |= RHS;
841 }
842 return *this;
843 }
844
845 /// Bitwise XOR assignment operator.
846 ///
847 /// Performs a bitwise XOR operation on this APInt and RHS. The result is
848 /// assigned to *this.
849 ///
850 /// \returns *this after XORing with RHS.
851 APInt &operator^=(const APInt &RHS) {
852 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 852, __extension__ __PRETTY_FUNCTION__))
;
853 if (isSingleWord())
854 U.VAL ^= RHS.U.VAL;
855 else
856 XorAssignSlowCase(RHS);
857 return *this;
858 }
859
860 /// Bitwise XOR assignment operator.
861 ///
862 /// Performs a bitwise XOR operation on this APInt and RHS. RHS is
863 /// logically zero-extended or truncated to match the bit-width of
864 /// the LHS.
865 APInt &operator^=(uint64_t RHS) {
866 if (isSingleWord()) {
867 U.VAL ^= RHS;
868 clearUnusedBits();
869 } else {
870 U.pVal[0] ^= RHS;
871 }
872 return *this;
873 }
874
875 /// Multiplication assignment operator.
876 ///
877 /// Multiplies this APInt by RHS and assigns the result to *this.
878 ///
879 /// \returns *this
880 APInt &operator*=(const APInt &RHS);
881 APInt &operator*=(uint64_t RHS);
882
883 /// Addition assignment operator.
884 ///
885 /// Adds RHS to *this and assigns the result to *this.
886 ///
887 /// \returns *this
888 APInt &operator+=(const APInt &RHS);
889 APInt &operator+=(uint64_t RHS);
890
891 /// Subtraction assignment operator.
892 ///
893 /// Subtracts RHS from *this and assigns the result to *this.
894 ///
895 /// \returns *this
896 APInt &operator-=(const APInt &RHS);
897 APInt &operator-=(uint64_t RHS);
898
899 /// Left-shift assignment function.
900 ///
901 /// Shifts *this left by shiftAmt and assigns the result to *this.
902 ///
903 /// \returns *this after shifting left by ShiftAmt
904 APInt &operator<<=(unsigned ShiftAmt) {
905 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 905, __extension__ __PRETTY_FUNCTION__))
;
906 if (isSingleWord()) {
20
Taking true branch
907 if (ShiftAmt == BitWidth)
21
Taking false branch
908 U.VAL = 0;
909 else
910 U.VAL <<= ShiftAmt;
22
Assigned value is garbage or undefined
911 return clearUnusedBits();
912 }
913 shlSlowCase(ShiftAmt);
914 return *this;
915 }
916
917 /// Left-shift assignment function.
918 ///
919 /// Shifts *this left by shiftAmt and assigns the result to *this.
920 ///
921 /// \returns *this after shifting left by ShiftAmt
922 APInt &operator<<=(const APInt &ShiftAmt);
923
924 /// @}
925 /// \name Binary Operators
926 /// @{
927
928 /// Multiplication operator.
929 ///
930 /// Multiplies this APInt by RHS and returns the result.
931 APInt operator*(const APInt &RHS) const;
932
933 /// Left logical shift operator.
934 ///
935 /// Shifts this APInt left by \p Bits and returns the result.
936 APInt operator<<(unsigned Bits) const { return shl(Bits); }
937
938 /// Left logical shift operator.
939 ///
940 /// Shifts this APInt left by \p Bits and returns the result.
941 APInt operator<<(const APInt &Bits) const { return shl(Bits); }
942
943 /// Arithmetic right-shift function.
944 ///
945 /// Arithmetic right-shift this APInt by shiftAmt.
946 APInt ashr(unsigned ShiftAmt) const {
947 APInt R(*this);
948 R.ashrInPlace(ShiftAmt);
949 return R;
950 }
951
952 /// Arithmetic right-shift this APInt by ShiftAmt in place.
953 void ashrInPlace(unsigned ShiftAmt) {
954 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 954, __extension__ __PRETTY_FUNCTION__))
;
955 if (isSingleWord()) {
956 int64_t SExtVAL = SignExtend64(U.VAL, BitWidth);
957 if (ShiftAmt == BitWidth)
958 U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit.
959 else
960 U.VAL = SExtVAL >> ShiftAmt;
961 clearUnusedBits();
962 return;
963 }
964 ashrSlowCase(ShiftAmt);
965 }
966
967 /// Logical right-shift function.
968 ///
969 /// Logical right-shift this APInt by shiftAmt.
970 APInt lshr(unsigned shiftAmt) const {
971 APInt R(*this);
972 R.lshrInPlace(shiftAmt);
973 return R;
974 }
975
976 /// Logical right-shift this APInt by ShiftAmt in place.
977 void lshrInPlace(unsigned ShiftAmt) {
978 assert(ShiftAmt <= BitWidth && "Invalid shift amount")(static_cast <bool> (ShiftAmt <= BitWidth &&
"Invalid shift amount") ? void (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 978, __extension__ __PRETTY_FUNCTION__))
;
979 if (isSingleWord()) {
980 if (ShiftAmt == BitWidth)
981 U.VAL = 0;
982 else
983 U.VAL >>= ShiftAmt;
984 return;
985 }
986 lshrSlowCase(ShiftAmt);
987 }
988
989 /// Left-shift function.
990 ///
991 /// Left-shift this APInt by shiftAmt.
992 APInt shl(unsigned shiftAmt) const {
993 APInt R(*this);
994 R <<= shiftAmt;
995 return R;
996 }
997
998 /// Rotate left by rotateAmt.
999 APInt rotl(unsigned rotateAmt) const;
1000
1001 /// Rotate right by rotateAmt.
1002 APInt rotr(unsigned rotateAmt) const;
1003
1004 /// Arithmetic right-shift function.
1005 ///
1006 /// Arithmetic right-shift this APInt by shiftAmt.
1007 APInt ashr(const APInt &ShiftAmt) const {
1008 APInt R(*this);
1009 R.ashrInPlace(ShiftAmt);
1010 return R;
1011 }
1012
1013 /// Arithmetic right-shift this APInt by shiftAmt in place.
1014 void ashrInPlace(const APInt &shiftAmt);
1015
1016 /// Logical right-shift function.
1017 ///
1018 /// Logical right-shift this APInt by shiftAmt.
1019 APInt lshr(const APInt &ShiftAmt) const {
1020 APInt R(*this);
1021 R.lshrInPlace(ShiftAmt);
1022 return R;
1023 }
1024
1025 /// Logical right-shift this APInt by ShiftAmt in place.
1026 void lshrInPlace(const APInt &ShiftAmt);
1027
1028 /// Left-shift function.
1029 ///
1030 /// Left-shift this APInt by shiftAmt.
1031 APInt shl(const APInt &ShiftAmt) const {
1032 APInt R(*this);
1033 R <<= ShiftAmt;
1034 return R;
1035 }
1036
1037 /// Rotate left by rotateAmt.
1038 APInt rotl(const APInt &rotateAmt) const;
1039
1040 /// Rotate right by rotateAmt.
1041 APInt rotr(const APInt &rotateAmt) const;
1042
1043 /// Unsigned division operation.
1044 ///
1045 /// Perform an unsigned divide operation on this APInt by RHS. Both this and
1046 /// RHS are treated as unsigned quantities for purposes of this division.
1047 ///
1048 /// \returns a new APInt value containing the division result, rounded towards
1049 /// zero.
1050 APInt udiv(const APInt &RHS) const;
1051 APInt udiv(uint64_t RHS) const;
1052
1053 /// Signed division function for APInt.
1054 ///
1055 /// Signed divide this APInt by APInt RHS.
1056 ///
1057 /// The result is rounded towards zero.
1058 APInt sdiv(const APInt &RHS) const;
1059 APInt sdiv(int64_t RHS) const;
1060
1061 /// Unsigned remainder operation.
1062 ///
1063 /// Perform an unsigned remainder operation on this APInt with RHS being the
1064 /// divisor. Both this and RHS are treated as unsigned quantities for purposes
1065 /// of this operation. Note that this is a true remainder operation and not a
1066 /// modulo operation because the sign follows the sign of the dividend which
1067 /// is *this.
1068 ///
1069 /// \returns a new APInt value containing the remainder result
1070 APInt urem(const APInt &RHS) const;
1071 uint64_t urem(uint64_t RHS) const;
1072
1073 /// Function for signed remainder operation.
1074 ///
1075 /// Signed remainder operation on APInt.
1076 APInt srem(const APInt &RHS) const;
1077 int64_t srem(int64_t RHS) const;
1078
1079 /// Dual division/remainder interface.
1080 ///
1081 /// Sometimes it is convenient to divide two APInt values and obtain both the
1082 /// quotient and remainder. This function does both operations in the same
1083 /// computation making it a little more efficient. The pair of input arguments
1084 /// may overlap with the pair of output arguments. It is safe to call
1085 /// udivrem(X, Y, X, Y), for example.
1086 static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1087 APInt &Remainder);
1088 static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient,
1089 uint64_t &Remainder);
1090
1091 static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient,
1092 APInt &Remainder);
1093 static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient,
1094 int64_t &Remainder);
1095
1096 // Operations that return overflow indicators.
1097 APInt sadd_ov(const APInt &RHS, bool &Overflow) const;
1098 APInt uadd_ov(const APInt &RHS, bool &Overflow) const;
1099 APInt ssub_ov(const APInt &RHS, bool &Overflow) const;
1100 APInt usub_ov(const APInt &RHS, bool &Overflow) const;
1101 APInt sdiv_ov(const APInt &RHS, bool &Overflow) const;
1102 APInt smul_ov(const APInt &RHS, bool &Overflow) const;
1103 APInt umul_ov(const APInt &RHS, bool &Overflow) const;
1104 APInt sshl_ov(const APInt &Amt, bool &Overflow) const;
1105 APInt ushl_ov(const APInt &Amt, bool &Overflow) const;
1106
1107 /// Array-indexing support.
1108 ///
1109 /// \returns the bit value at bitPosition
1110 bool operator[](unsigned bitPosition) const {
1111 assert(bitPosition < getBitWidth() && "Bit position out of bounds!")(static_cast <bool> (bitPosition < getBitWidth() &&
"Bit position out of bounds!") ? void (0) : __assert_fail ("bitPosition < getBitWidth() && \"Bit position out of bounds!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1111, __extension__ __PRETTY_FUNCTION__))
;
1112 return (maskBit(bitPosition) & getWord(bitPosition)) != 0;
1113 }
1114
1115 /// @}
1116 /// \name Comparison Operators
1117 /// @{
1118
1119 /// Equality operator.
1120 ///
1121 /// Compares this APInt with RHS for the validity of the equality
1122 /// relationship.
1123 bool operator==(const APInt &RHS) const {
1124 assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Comparison requires equal bit widths") ? void (0) : __assert_fail
("BitWidth == RHS.BitWidth && \"Comparison requires equal bit widths\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1124, __extension__ __PRETTY_FUNCTION__))
;
1125 if (isSingleWord())
1126 return U.VAL == RHS.U.VAL;
1127 return EqualSlowCase(RHS);
1128 }
1129
1130 /// Equality operator.
1131 ///
1132 /// Compares this APInt with a uint64_t for the validity of the equality
1133 /// relationship.
1134 ///
1135 /// \returns true if *this == Val
1136 bool operator==(uint64_t Val) const {
1137 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val;
1138 }
1139
1140 /// Equality comparison.
1141 ///
1142 /// Compares this APInt with RHS for the validity of the equality
1143 /// relationship.
1144 ///
1145 /// \returns true if *this == Val
1146 bool eq(const APInt &RHS) const { return (*this) == RHS; }
1147
1148 /// Inequality operator.
1149 ///
1150 /// Compares this APInt with RHS for the validity of the inequality
1151 /// relationship.
1152 ///
1153 /// \returns true if *this != Val
1154 bool operator!=(const APInt &RHS) const { return !((*this) == RHS); }
1155
1156 /// Inequality operator.
1157 ///
1158 /// Compares this APInt with a uint64_t for the validity of the inequality
1159 /// relationship.
1160 ///
1161 /// \returns true if *this != Val
1162 bool operator!=(uint64_t Val) const { return !((*this) == Val); }
1163
1164 /// Inequality comparison
1165 ///
1166 /// Compares this APInt with RHS for the validity of the inequality
1167 /// relationship.
1168 ///
1169 /// \returns true if *this != Val
1170 bool ne(const APInt &RHS) const { return !((*this) == RHS); }
1171
1172 /// Unsigned less than comparison
1173 ///
1174 /// Regards both *this and RHS as unsigned quantities and compares them for
1175 /// the validity of the less-than relationship.
1176 ///
1177 /// \returns true if *this < RHS when both are considered unsigned.
1178 bool ult(const APInt &RHS) const { return compare(RHS) < 0; }
1179
1180 /// Unsigned less than comparison
1181 ///
1182 /// Regards both *this as an unsigned quantity and compares it with RHS for
1183 /// the validity of the less-than relationship.
1184 ///
1185 /// \returns true if *this < RHS when considered unsigned.
1186 bool ult(uint64_t RHS) const {
1187 // Only need to check active bits if not a single word.
1188 return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS;
1189 }
1190
1191 /// Signed less than comparison
1192 ///
1193 /// Regards both *this and RHS as signed quantities and compares them for
1194 /// validity of the less-than relationship.
1195 ///
1196 /// \returns true if *this < RHS when both are considered signed.
1197 bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; }
1198
1199 /// Signed less than comparison
1200 ///
1201 /// Regards both *this as a signed quantity and compares it with RHS for
1202 /// the validity of the less-than relationship.
1203 ///
1204 /// \returns true if *this < RHS when considered signed.
1205 bool slt(int64_t RHS) const {
1206 return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative()
1207 : getSExtValue() < RHS;
1208 }
1209
1210 /// Unsigned less or equal comparison
1211 ///
1212 /// Regards both *this and RHS as unsigned quantities and compares them for
1213 /// validity of the less-or-equal relationship.
1214 ///
1215 /// \returns true if *this <= RHS when both are considered unsigned.
1216 bool ule(const APInt &RHS) const { return compare(RHS) <= 0; }
1217
1218 /// Unsigned less or equal comparison
1219 ///
1220 /// Regards both *this as an unsigned quantity and compares it with RHS for
1221 /// the validity of the less-or-equal relationship.
1222 ///
1223 /// \returns true if *this <= RHS when considered unsigned.
1224 bool ule(uint64_t RHS) const { return !ugt(RHS); }
1225
1226 /// Signed less or equal comparison
1227 ///
1228 /// Regards both *this and RHS as signed quantities and compares them for
1229 /// validity of the less-or-equal relationship.
1230 ///
1231 /// \returns true if *this <= RHS when both are considered signed.
1232 bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; }
1233
1234 /// Signed less or equal comparison
1235 ///
1236 /// Regards both *this as a signed quantity and compares it with RHS for the
1237 /// validity of the less-or-equal relationship.
1238 ///
1239 /// \returns true if *this <= RHS when considered signed.
1240 bool sle(uint64_t RHS) const { return !sgt(RHS); }
1241
1242 /// Unsigned greather than comparison
1243 ///
1244 /// Regards both *this and RHS as unsigned quantities and compares them for
1245 /// the validity of the greater-than relationship.
1246 ///
1247 /// \returns true if *this > RHS when both are considered unsigned.
1248 bool ugt(const APInt &RHS) const { return !ule(RHS); }
1249
1250 /// Unsigned greater than comparison
1251 ///
1252 /// Regards both *this as an unsigned quantity and compares it with RHS for
1253 /// the validity of the greater-than relationship.
1254 ///
1255 /// \returns true if *this > RHS when considered unsigned.
1256 bool ugt(uint64_t RHS) const {
1257 // Only need to check active bits if not a single word.
1258 return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS;
1259 }
1260
1261 /// Signed greather than comparison
1262 ///
1263 /// Regards both *this and RHS as signed quantities and compares them for the
1264 /// validity of the greater-than relationship.
1265 ///
1266 /// \returns true if *this > RHS when both are considered signed.
1267 bool sgt(const APInt &RHS) const { return !sle(RHS); }
1268
1269 /// Signed greater than comparison
1270 ///
1271 /// Regards both *this as a signed quantity and compares it with RHS for
1272 /// the validity of the greater-than relationship.
1273 ///
1274 /// \returns true if *this > RHS when considered signed.
1275 bool sgt(int64_t RHS) const {
1276 return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative()
1277 : getSExtValue() > RHS;
1278 }
1279
1280 /// Unsigned greater or equal comparison
1281 ///
1282 /// Regards both *this and RHS as unsigned quantities and compares them for
1283 /// validity of the greater-or-equal relationship.
1284 ///
1285 /// \returns true if *this >= RHS when both are considered unsigned.
1286 bool uge(const APInt &RHS) const { return !ult(RHS); }
1287
1288 /// Unsigned greater or equal comparison
1289 ///
1290 /// Regards both *this as an unsigned quantity and compares it with RHS for
1291 /// the validity of the greater-or-equal relationship.
1292 ///
1293 /// \returns true if *this >= RHS when considered unsigned.
1294 bool uge(uint64_t RHS) const { return !ult(RHS); }
1295
1296 /// Signed greater or equal comparison
1297 ///
1298 /// Regards both *this and RHS as signed quantities and compares them for
1299 /// validity of the greater-or-equal relationship.
1300 ///
1301 /// \returns true if *this >= RHS when both are considered signed.
1302 bool sge(const APInt &RHS) const { return !slt(RHS); }
1303
1304 /// Signed greater or equal comparison
1305 ///
1306 /// Regards both *this as a signed quantity and compares it with RHS for
1307 /// the validity of the greater-or-equal relationship.
1308 ///
1309 /// \returns true if *this >= RHS when considered signed.
1310 bool sge(int64_t RHS) const { return !slt(RHS); }
1311
1312 /// This operation tests if there are any pairs of corresponding bits
1313 /// between this APInt and RHS that are both set.
1314 bool intersects(const APInt &RHS) const {
1315 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1315, __extension__ __PRETTY_FUNCTION__))
;
1316 if (isSingleWord())
1317 return (U.VAL & RHS.U.VAL) != 0;
1318 return intersectsSlowCase(RHS);
1319 }
1320
1321 /// This operation checks that all bits set in this APInt are also set in RHS.
1322 bool isSubsetOf(const APInt &RHS) const {
1323 assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")(static_cast <bool> (BitWidth == RHS.BitWidth &&
"Bit widths must be the same") ? void (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1323, __extension__ __PRETTY_FUNCTION__))
;
1324 if (isSingleWord())
1325 return (U.VAL & ~RHS.U.VAL) == 0;
1326 return isSubsetOfSlowCase(RHS);
1327 }
1328
1329 /// @}
1330 /// \name Resizing Operators
1331 /// @{
1332
1333 /// Truncate to new width.
1334 ///
1335 /// Truncate the APInt to a specified width. It is an error to specify a width
1336 /// that is greater than or equal to the current width.
1337 APInt trunc(unsigned width) const;
1338
1339 /// Sign extend to a new width.
1340 ///
1341 /// This operation sign extends the APInt to a new width. If the high order
1342 /// bit is set, the fill on the left will be done with 1 bits, otherwise zero.
1343 /// It is an error to specify a width that is less than or equal to the
1344 /// current width.
1345 APInt sext(unsigned width) const;
1346
1347 /// Zero extend to a new width.
1348 ///
1349 /// This operation zero extends the APInt to a new width. The high order bits
1350 /// are filled with 0 bits. It is an error to specify a width that is less
1351 /// than or equal to the current width.
1352 APInt zext(unsigned width) const;
1353
1354 /// Sign extend or truncate to width
1355 ///
1356 /// Make this APInt have the bit width given by \p width. The value is sign
1357 /// extended, truncated, or left alone to make it that width.
1358 APInt sextOrTrunc(unsigned width) const;
1359
1360 /// Zero extend or truncate to width
1361 ///
1362 /// Make this APInt have the bit width given by \p width. The value is zero
1363 /// extended, truncated, or left alone to make it that width.
1364 APInt zextOrTrunc(unsigned width) const;
1365
1366 /// Sign extend or truncate to width
1367 ///
1368 /// Make this APInt have the bit width given by \p width. The value is sign
1369 /// extended, or left alone to make it that width.
1370 APInt sextOrSelf(unsigned width) const;
1371
1372 /// Zero extend or truncate to width
1373 ///
1374 /// Make this APInt have the bit width given by \p width. The value is zero
1375 /// extended, or left alone to make it that width.
1376 APInt zextOrSelf(unsigned width) const;
1377
1378 /// @}
1379 /// \name Bit Manipulation Operators
1380 /// @{
1381
1382 /// Set every bit to 1.
1383 void setAllBits() {
1384 if (isSingleWord())
1385 U.VAL = WORD_MAX;
1386 else
1387 // Set all the bits in all the words.
1388 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1389 // Clear the unused ones
1390 clearUnusedBits();
1391 }
1392
1393 /// Set a given bit to 1.
1394 ///
1395 /// Set the given bit to 1 whose position is given as "bitPosition".
1396 void setBit(unsigned BitPosition) {
1397 assert(BitPosition <= BitWidth && "BitPosition out of range")(static_cast <bool> (BitPosition <= BitWidth &&
"BitPosition out of range") ? void (0) : __assert_fail ("BitPosition <= BitWidth && \"BitPosition out of range\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1397, __extension__ __PRETTY_FUNCTION__))
;
1398 WordType Mask = maskBit(BitPosition);
1399 if (isSingleWord())
1400 U.VAL |= Mask;
1401 else
1402 U.pVal[whichWord(BitPosition)] |= Mask;
1403 }
1404
1405 /// Set the sign bit to 1.
1406 void setSignBit() {
1407 setBit(BitWidth - 1);
1408 }
1409
1410 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1411 void setBits(unsigned loBit, unsigned hiBit) {
1412 assert(hiBit <= BitWidth && "hiBit out of range")(static_cast <bool> (hiBit <= BitWidth && "hiBit out of range"
) ? void (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1412, __extension__ __PRETTY_FUNCTION__))
;
1413 assert(loBit <= BitWidth && "loBit out of range")(static_cast <bool> (loBit <= BitWidth && "loBit out of range"
) ? void (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1413, __extension__ __PRETTY_FUNCTION__))
;
1414 assert(loBit <= hiBit && "loBit greater than hiBit")(static_cast <bool> (loBit <= hiBit && "loBit greater than hiBit"
) ? void (0) : __assert_fail ("loBit <= hiBit && \"loBit greater than hiBit\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1414, __extension__ __PRETTY_FUNCTION__))
;
1415 if (loBit == hiBit)
1416 return;
1417 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1418 uint64_t mask = WORD_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1419 mask <<= loBit;
1420 if (isSingleWord())
1421 U.VAL |= mask;
1422 else
1423 U.pVal[0] |= mask;
1424 } else {
1425 setBitsSlowCase(loBit, hiBit);
1426 }
1427 }
1428
1429 /// Set the top bits starting from loBit.
1430 void setBitsFrom(unsigned loBit) {
1431 return setBits(loBit, BitWidth);
1432 }
1433
1434 /// Set the bottom loBits bits.
1435 void setLowBits(unsigned loBits) {
1436 return setBits(0, loBits);
1437 }
1438
1439 /// Set the top hiBits bits.
1440 void setHighBits(unsigned hiBits) {
1441 return setBits(BitWidth - hiBits, BitWidth);
1442 }
1443
1444 /// Set every bit to 0.
1445 void clearAllBits() {
1446 if (isSingleWord())
1447 U.VAL = 0;
1448 else
1449 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1450 }
1451
1452 /// Set a given bit to 0.
1453 ///
1454 /// Set the given bit to 0 whose position is given as "bitPosition".
1455 void clearBit(unsigned BitPosition) {
1456 assert(BitPosition <= BitWidth && "BitPosition out of range")(static_cast <bool> (BitPosition <= BitWidth &&
"BitPosition out of range") ? void (0) : __assert_fail ("BitPosition <= BitWidth && \"BitPosition out of range\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1456, __extension__ __PRETTY_FUNCTION__))
;
1457 WordType Mask = ~maskBit(BitPosition);
1458 if (isSingleWord())
1459 U.VAL &= Mask;
1460 else
1461 U.pVal[whichWord(BitPosition)] &= Mask;
1462 }
1463
1464 /// Set the sign bit to 0.
1465 void clearSignBit() {
1466 clearBit(BitWidth - 1);
1467 }
1468
1469 /// Toggle every bit to its opposite value.
1470 void flipAllBits() {
1471 if (isSingleWord()) {
1472 U.VAL ^= WORD_MAX;
1473 clearUnusedBits();
1474 } else {
1475 flipAllBitsSlowCase();
1476 }
1477 }
1478
1479 /// Toggles a given bit to its opposite value.
1480 ///
1481 /// Toggle a given bit to its opposite value whose position is given
1482 /// as "bitPosition".
1483 void flipBit(unsigned bitPosition);
1484
1485 /// Negate this APInt in place.
1486 void negate() {
1487 flipAllBits();
1488 ++(*this);
1489 }
1490
1491 /// Insert the bits from a smaller APInt starting at bitPosition.
1492 void insertBits(const APInt &SubBits, unsigned bitPosition);
1493
1494 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1495 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1496
1497 /// @}
1498 /// \name Value Characterization Functions
1499 /// @{
1500
1501 /// Return the number of bits in the APInt.
1502 unsigned getBitWidth() const { return BitWidth; }
1503
1504 /// Get the number of words.
1505 ///
1506 /// Here one word's bitwidth equals to that of uint64_t.
1507 ///
1508 /// \returns the number of words to hold the integer value of this APInt.
1509 unsigned getNumWords() const { return getNumWords(BitWidth); }
1510
1511 /// Get the number of words.
1512 ///
1513 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1514 ///
1515 /// \returns the number of words to hold the integer value with a given bit
1516 /// width.
1517 static unsigned getNumWords(unsigned BitWidth) {
1518 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1519 }
1520
1521 /// Compute the number of active bits in the value
1522 ///
1523 /// This function returns the number of active bits which is defined as the
1524 /// bit width minus the number of leading zeros. This is used in several
1525 /// computations to see how "wide" the value is.
1526 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1527
1528 /// Compute the number of active words in the value of this APInt.
1529 ///
1530 /// This is used in conjunction with getActiveData to extract the raw value of
1531 /// the APInt.
1532 unsigned getActiveWords() const {
1533 unsigned numActiveBits = getActiveBits();
1534 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1535 }
1536
1537 /// Get the minimum bit size for this signed APInt
1538 ///
1539 /// Computes the minimum bit width for this APInt while considering it to be a
1540 /// signed (and probably negative) value. If the value is not negative, this
1541 /// function returns the same value as getActiveBits()+1. Otherwise, it
1542 /// returns the smallest bit width that will retain the negative value. For
1543 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1544 /// for -1, this function will always return 1.
1545 unsigned getMinSignedBits() const {
1546 if (isNegative())
1547 return BitWidth - countLeadingOnes() + 1;
1548 return getActiveBits() + 1;
1549 }
1550
1551 /// Get zero extended value
1552 ///
1553 /// This method attempts to return the value of this APInt as a zero extended
1554 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1555 /// uint64_t. Otherwise an assertion will result.
1556 uint64_t getZExtValue() const {
1557 if (isSingleWord())
1558 return U.VAL;
1559 assert(getActiveBits() <= 64 && "Too many bits for uint64_t")(static_cast <bool> (getActiveBits() <= 64 &&
"Too many bits for uint64_t") ? void (0) : __assert_fail ("getActiveBits() <= 64 && \"Too many bits for uint64_t\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1559, __extension__ __PRETTY_FUNCTION__))
;
1560 return U.pVal[0];
1561 }
1562
1563 /// Get sign extended value
1564 ///
1565 /// This method attempts to return the value of this APInt as a sign extended
1566 /// int64_t. The bit width must be <= 64 or the value must fit within an
1567 /// int64_t. Otherwise an assertion will result.
1568 int64_t getSExtValue() const {
1569 if (isSingleWord())
1570 return SignExtend64(U.VAL, BitWidth);
1571 assert(getMinSignedBits() <= 64 && "Too many bits for int64_t")(static_cast <bool> (getMinSignedBits() <= 64 &&
"Too many bits for int64_t") ? void (0) : __assert_fail ("getMinSignedBits() <= 64 && \"Too many bits for int64_t\""
, "/build/llvm-toolchain-snapshot-7~svn337204/include/llvm/ADT/APInt.h"
, 1571, __extension__ __PRETTY_FUNCTION__))
;
1572 return int64_t(U.pVal[0]);
1573 }
1574
1575 /// Get bits required for string value.
1576 ///
1577 /// This method determines how many bits are required to hold the APInt
1578 /// equivalent of the string given by \p str.
1579 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1580
1581 /// The APInt version of the countLeadingZeros functions in
1582 /// MathExtras.h.
1583 ///
1584 /// It counts the number of zeros from the most significant bit to the first
1585 /// one bit.
1586 ///
1587 /// \returns BitWidth if the value is zero, otherwise returns the number of
1588 /// zeros from the most significant bit to the first one bits.
1589 unsigned countLeadingZeros() const {
1590 if (isSingleWord()) {
1591 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1592 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1593 }
1594 return countLeadingZerosSlowCase();
1595 }
1596
1597 /// Count the number of leading one bits.
1598 ///
1599 /// This function is an APInt version of the countLeadingOnes
1600 /// functions in MathExtras.h. It counts the number of ones from the most
1601 /// significant bit to the first zero bit.
1602 ///
1603 /// \returns 0 if the high order bit is not set, otherwise returns the number
1604 /// of 1 bits from the most significant to the least
1605 unsigned countLeadingOnes() const {
1606 if (isSingleWord())
1607 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1608 return countLeadingOnesSlowCase();
1609 }
1610
1611 /// Computes the number of leading bits of this APInt that are equal to its
1612 /// sign bit.
1613 unsigned getNumSignBits() const {
1614 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1615 }
1616
1617 /// Count the number of trailing zero bits.
1618 ///
1619 /// This function is an APInt version of the countTrailingZeros
1620 /// functions in MathExtras.h. It counts the number of zeros from the least
1621 /// significant bit to the first set bit.
1622 ///
1623 /// \returns BitWidth if the value is zero, otherwise returns the number of
1624 /// zeros from the least significant bit to the first one bit.
1625 unsigned countTrailingZeros() const {
1626 if (isSingleWord())
1627 return std::min(unsigned(llvm::countTrailingZeros(U.VAL)), BitWidth);
1628 return countTrailingZerosSlowCase();
1629 }
1630
1631 /// Count the number of trailing one bits.
1632 ///
1633 /// This function is an APInt version of the countTrailingOnes
1634 /// functions in MathExtras.h. It counts the number of ones from the least
1635 /// significant bit to the first zero bit.
1636 ///
1637 /// \returns BitWidth if the value is all ones, otherwise returns the number
1638 /// of ones from the least significant bit to the first zero bit.
1639 unsigned countTrailingOnes() const {
1640 if (isSingleWord())
1641 return llvm::countTrailingOnes(U.VAL);
1642 return countTrailingOnesSlowCase();
1643 }
1644
1645 /// Count the number of bits set.
1646 ///
1647 /// This function is an APInt version of the countPopulation functions
1648 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1649 ///
1650 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1651 unsigned countPopulation() const {
1652 if (isSingleWord())
1653 return llvm::countPopulation(U.VAL);
1654 return countPopulationSlowCase();
1655 }
1656
1657 /// @}
1658 /// \name Conversion Functions
1659 /// @{
1660 void print(raw_ostream &OS, bool isSigned) const;
1661
1662 /// Converts an APInt to a string and append it to Str. Str is commonly a
1663 /// SmallString.
1664 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1665 bool formatAsCLiteral = false) const;
1666
1667 /// Considers the APInt to be unsigned and converts it into a string in the
1668 /// radix given. The radix can be 2, 8, 10 16, or 36.
1669 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1670 toString(Str, Radix, false, false);
1671 }
1672
1673 /// Considers the APInt to be signed and converts it into a string in the
1674 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1675 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1676 toString(Str, Radix, true, false);
1677 }
1678
1679 /// Return the APInt as a std::string.
1680 ///
1681 /// Note that this is an inefficient method. It is better to pass in a
1682 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1683 /// for the string.
1684 std::string toString(unsigned Radix, bool Signed) const;
1685
1686 /// \returns a byte-swapped representation of this APInt Value.
1687 APInt byteSwap() const;
1688
1689 /// \returns the value with the bit representation reversed of this APInt
1690 /// Value.
1691 APInt reverseBits() const;
1692
1693 /// Converts this APInt to a double value.
1694 double roundToDouble(bool isSigned) const;
1695
1696 /// Converts this unsigned APInt to a double value.
1697 double roundToDouble() const { return roundToDouble(false); }
1698
1699 /// Converts this signed APInt to a double value.
1700 double signedRoundToDouble() const { return roundToDouble(true); }
1701
1702 /// Converts APInt bits to a double
1703 ///
1704 /// The conversion does not do a translation from integer to double, it just
1705 /// re-interprets the bits as a double. Note that it is valid to do this on
1706 /// any bit width. Exactly 64 bits will be translated.
1707 double bitsToDouble() const {
1708 return BitsToDouble(getWord(0));
1709 }
1710
1711 /// Converts APInt bits to a double
1712 ///
1713 /// The conversion does not do a translation from integer to float, it just
1714 /// re-interprets the bits as a float. Note that it is valid to do this on
1715 /// any bit width. Exactly 32 bits will be translated.
1716 float bitsToFloat() const {
1717 return BitsToFloat(getWord(0));
1718 }
1719
1720 /// Converts a double to APInt bits.
1721 ///
1722 /// The conversion does not do a translation from double to integer, it just
1723 /// re-interprets the bits of the double.
1724 static APInt doubleToBits(double V) {
1725 return APInt(sizeof(double) * CHAR_BIT8, DoubleToBits(V));
1726 }
1727
1728 /// Converts a float to APInt bits.
1729 ///
1730 /// The conversion does not do a translation from float to integer, it just
1731 /// re-interprets the bits of the float.
1732 static APInt floatToBits(float V) {
1733 return APInt(sizeof(float) * CHAR_BIT8, FloatToBits(V));
1734 }
1735
1736 /// @}
1737 /// \name Mathematics Operations
1738 /// @{
1739
1740 /// \returns the floor log base 2 of this APInt.
1741 unsigned logBase2() const { return getActiveBits() - 1; }
1742
1743 /// \returns the ceil log base 2 of this APInt.
1744 unsigned ceilLogBase2() const {
1745 APInt temp(*this);
1746 --temp;
1747 return temp.getActiveBits();
1748 }
1749
1750 /// \returns the nearest log base 2 of this APInt. Ties round up.
1751 ///
1752 /// NOTE: When we have a BitWidth of 1, we define:
1753 ///
1754 /// log2(0) = UINT32_MAX
1755 /// log2(1) = 0
1756 ///
1757 /// to get around any mathematical concerns resulting from
1758 /// referencing 2 in a space where 2 does no exist.
1759 unsigned nearestLogBase2() const {
1760 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1761 // get 0. If VAL is 0, we get WORD_MAX which gets truncated to
1762 // UINT32_MAX.
1763 if (BitWidth == 1)
1764 return U.VAL - 1;
1765
1766 // Handle the zero case.
1767 if (isNullValue())
1768 return UINT32_MAX(4294967295U);
1769
1770 // The non-zero case is handled by computing:
1771 //
1772 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1773 //
1774 // where x[i] is referring to the value of the ith bit of x.
1775 unsigned lg = logBase2();
1776 return lg + unsigned((*this)[lg - 1]);
1777 }
1778
1779 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1780 /// otherwise
1781 int32_t exactLogBase2() const {
1782 if (!isPowerOf2())
1783 return -1;
1784 return logBase2();
1785 }
1786
1787 /// Compute the square root
1788 APInt sqrt() const;
1789
1790 /// Get the absolute value;
1791 ///
1792 /// If *this is < 0 then return -(*this), otherwise *this;
1793 APInt abs() const {
1794 if (isNegative())
1795 return -(*this);
1796 return *this;
1797 }
1798
1799 /// \returns the multiplicative inverse for a given modulo.
1800 APInt multiplicativeInverse(const APInt &modulo) const;
1801
1802 /// @}
1803 /// \name Support for division by constant
1804 /// @{
1805
1806 /// Calculate the magic number for signed division by a constant.
1807 struct ms;
1808 ms magic() const;
1809
1810 /// Calculate the magic number for unsigned division by a constant.
1811 struct mu;
1812 mu magicu(unsigned LeadingZeros = 0) const;
1813
1814 /// @}
1815 /// \name Building-block Operations for APInt and APFloat
1816 /// @{
1817
1818 // These building block operations operate on a representation of arbitrary
1819 // precision, two's-complement, bignum integer values. They should be
1820 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1821 // generally a pointer to the base of an array of integer parts, representing
1822 // an unsigned bignum, and a count of how many parts there are.
1823
1824 /// Sets the least significant part of a bignum to the input value, and zeroes
1825 /// out higher parts.
1826 static void tcSet(WordType *, WordType, unsigned);
1827
1828 /// Assign one bignum to another.
1829 static void tcAssign(WordType *, const WordType *, unsigned);
1830
1831 /// Returns true if a bignum is zero, false otherwise.
1832 static bool tcIsZero(const WordType *, unsigned);
1833
1834 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1835 static int tcExtractBit(const WordType *, unsigned bit);
1836
1837 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1838 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1839 /// significant bit of DST. All high bits above srcBITS in DST are
1840 /// zero-filled.
1841 static void tcExtract(WordType *, unsigned dstCount,
1842 const WordType *, unsigned srcBits,
1843 unsigned srcLSB);
1844
1845 /// Set the given bit of a bignum. Zero-based.
1846 static void tcSetBit(WordType *, unsigned bit);
1847
1848 /// Clear the given bit of a bignum. Zero-based.
1849 static void tcClearBit(WordType *, unsigned bit);
1850
1851 /// Returns the bit number of the least or most significant set bit of a
1852 /// number. If the input number has no bits set -1U is returned.
1853 static unsigned tcLSB(const WordType *, unsigned n);
1854 static unsigned tcMSB(const WordType *parts, unsigned n);
1855
1856 /// Negate a bignum in-place.
1857 static void tcNegate(WordType *, unsigned);
1858
1859 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1860 static WordType tcAdd(WordType *, const WordType *,
1861 WordType carry, unsigned);
1862 /// DST += RHS. Returns the carry flag.
1863 static WordType tcAddPart(WordType *, WordType, unsigned);
1864
1865 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1866 static WordType tcSubtract(WordType *, const WordType *,
1867 WordType carry, unsigned);
1868 /// DST -= RHS. Returns the carry flag.
1869 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1870
1871 /// DST += SRC * MULTIPLIER + PART if add is true
1872 /// DST = SRC * MULTIPLIER + PART if add is false
1873 ///
1874 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1875 /// start at the same point, i.e. DST == SRC.
1876 ///
1877 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1878 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1879 /// result, and if all of the omitted higher parts were zero return zero,
1880 /// otherwise overflow occurred and return one.
1881 static int tcMultiplyPart(WordType *dst, const WordType *src,
1882 WordType multiplier, WordType carry,
1883 unsigned srcParts, unsigned dstParts,
1884 bool add);
1885
1886 /// DST = LHS * RHS, where DST has the same width as the operands and is
1887 /// filled with the least significant parts of the result. Returns one if
1888 /// overflow occurred, otherwise zero. DST must be disjoint from both
1889 /// operands.
1890 static int tcMultiply(WordType *, const WordType *, const WordType *,
1891 unsigned);
1892
1893 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1894 /// operands. No overflow occurs. DST must be disjoint from both operands.
1895 static void tcFullMultiply(WordType *, const WordType *,
1896 const WordType *, unsigned, unsigned);
1897
1898 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1899 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1900 /// REMAINDER to the remainder, return zero. i.e.
1901 ///
1902 /// OLD_LHS = RHS * LHS + REMAINDER
1903 ///
1904 /// SCRATCH is a bignum of the same size as the operands and result for use by
1905 /// the routine; its contents need not be initialized and are destroyed. LHS,
1906 /// REMAINDER and SCRATCH must be distinct.
1907 static int tcDivide(WordType *lhs, const WordType *rhs,
1908 WordType *remainder, WordType *scratch,
1909 unsigned parts);
1910
1911 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1912 /// restrictions on Count.
1913 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1914
1915 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1916 /// restrictions on Count.
1917 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1918
1919 /// The obvious AND, OR and XOR and complement operations.
1920 static void tcAnd(WordType *, const WordType *, unsigned);
1921 static void tcOr(WordType *, const WordType *, unsigned);
1922 static void tcXor(WordType *, const WordType *, unsigned);
1923 static void tcComplement(WordType *, unsigned);
1924
1925 /// Comparison (unsigned) of two bignums.
1926 static int tcCompare(const WordType *, const WordType *, unsigned);
1927
1928 /// Increment a bignum in-place. Return the carry flag.
1929 static WordType tcIncrement(WordType *dst, unsigned parts) {
1930 return tcAddPart(dst, 1, parts);
1931 }
1932
1933 /// Decrement a bignum in-place. Return the borrow flag.
1934 static WordType tcDecrement(WordType *dst, unsigned parts) {
1935 return tcSubtractPart(dst, 1, parts);
1936 }
1937
1938 /// Set the least significant BITS and clear the rest.
1939 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
1940
1941 /// debug method
1942 void dump() const;
1943
1944 /// @}
1945};
1946
1947/// Magic data for optimising signed division by a constant.
1948struct APInt::ms {
1949 APInt m; ///< magic number
1950 unsigned s; ///< shift amount
1951};
1952
1953/// Magic data for optimising unsigned division by a constant.
1954struct APInt::mu {
1955 APInt m; ///< magic number
1956 bool a; ///< add indicator
1957 unsigned s; ///< shift amount
1958};
1959
1960inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
1961
1962inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
1963
1964/// Unary bitwise complement operator.
1965///
1966/// \returns an APInt that is the bitwise complement of \p v.
1967inline APInt operator~(APInt v) {
1968 v.flipAllBits();
1969 return v;
1970}
1971
1972inline APInt operator&(APInt a, const APInt &b) {
1973 a &= b;
1974 return a;
1975}
1976
1977inline APInt operator&(const APInt &a, APInt &&b) {
1978 b &= a;
1979 return std::move(b);
1980}
1981
1982inline APInt operator&(APInt a, uint64_t RHS) {
1983 a &= RHS;
1984 return a;
1985}
1986
1987inline APInt operator&(uint64_t LHS, APInt b) {
1988 b &= LHS;
1989 return b;
1990}
1991
1992inline APInt operator|(APInt a, const APInt &b) {
1993 a |= b;
1994 return a;
1995}
1996
1997inline APInt operator|(const APInt &a, APInt &&b) {
1998 b |= a;
1999 return std::move(b);
2000}
2001
2002inline APInt operator|(APInt a, uint64_t RHS) {
2003 a |= RHS;
2004 return a;
2005}
2006
2007inline APInt operator|(uint64_t LHS, APInt b) {
2008 b |= LHS;
2009 return b;
2010}
2011
2012inline APInt operator^(APInt a, const APInt &b) {
2013 a ^= b;
2014 return a;
2015}
2016
2017inline APInt operator^(const APInt &a, APInt &&b) {
2018 b ^= a;
2019 return std::move(b);
2020}
2021
2022inline APInt operator^(APInt a, uint64_t RHS) {
2023 a ^= RHS;
2024 return a;
2025}
2026
2027inline APInt operator^(uint64_t LHS, APInt b) {
2028 b ^= LHS;
2029 return b;
2030}
2031
2032inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2033 I.print(OS, true);
2034 return OS;
2035}
2036
2037inline APInt operator-(APInt v) {
2038 v.negate();
2039 return v;
2040}
2041
2042inline APInt operator+(APInt a, const APInt &b) {
2043 a += b;
2044 return a;
2045}
2046
2047inline APInt operator+(const APInt &a, APInt &&b) {
2048 b += a;
2049 return std::move(b);
2050}
2051
2052inline APInt operator+(APInt a, uint64_t RHS) {
2053 a += RHS;
2054 return a;
2055}
2056
2057inline APInt operator+(uint64_t LHS, APInt b) {
2058 b += LHS;
2059 return b;
2060}
2061
2062inline APInt operator-(APInt a, const APInt &b) {
2063 a -= b;
2064 return a;
2065}
2066
2067inline APInt operator-(const APInt &a, APInt &&b) {
2068 b.negate();
2069 b += a;
2070 return std::move(b);
2071}
2072
2073inline APInt operator-(APInt a, uint64_t RHS) {
2074 a -= RHS;
2075 return a;
2076}
2077
2078inline APInt operator-(uint64_t LHS, APInt b) {
2079 b.negate();
2080 b += LHS;
2081 return b;
2082}
2083
2084inline APInt operator*(APInt a, uint64_t RHS) {
2085 a *= RHS;
2086 return a;
2087}
2088
2089inline APInt operator*(uint64_t LHS, APInt b) {
2090 b *= LHS;
2091 return b;
2092}
2093
2094
2095namespace APIntOps {
2096
2097/// Determine the smaller of two APInts considered to be signed.
2098inline const APInt &smin(const APInt &A, const APInt &B) {
2099 return A.slt(B) ? A : B;
2100}
2101
2102/// Determine the larger of two APInts considered to be signed.
2103inline const APInt &smax(const APInt &A, const APInt &B) {
2104 return A.sgt(B) ? A : B;
2105}
2106
2107/// Determine the smaller of two APInts considered to be signed.
2108inline const APInt &umin(const APInt &A, const APInt &B) {
2109 return A.ult(B) ? A : B;
2110}
2111
2112/// Determine the larger of two APInts considered to be unsigned.
2113inline const APInt &umax(const APInt &A, const APInt &B) {
2114 return A.ugt(B) ? A : B;
2115}
2116
2117/// Compute GCD of two unsigned APInt values.
2118///
2119/// This function returns the greatest common divisor of the two APInt values
2120/// using Stein's algorithm.
2121///
2122/// \returns the greatest common divisor of A and B.
2123APInt GreatestCommonDivisor(APInt A, APInt B);
2124
2125/// Converts the given APInt to a double value.
2126///
2127/// Treats the APInt as an unsigned value for conversion purposes.
2128inline double RoundAPIntToDouble(const APInt &APIVal) {
2129 return APIVal.roundToDouble();
2130}
2131
2132/// Converts the given APInt to a double value.
2133///
2134/// Treats the APInt as a signed value for conversion purposes.
2135inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2136 return APIVal.signedRoundToDouble();
2137}
2138
2139/// Converts the given APInt to a float vlalue.
2140inline float RoundAPIntToFloat(const APInt &APIVal) {
2141 return float(RoundAPIntToDouble(APIVal));
2142}
2143
2144/// Converts the given APInt to a float value.
2145///
2146/// Treast the APInt as a signed value for conversion purposes.
2147inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2148 return float(APIVal.signedRoundToDouble());
2149}
2150
2151/// Converts the given double value into a APInt.
2152///
2153/// This function convert a double value to an APInt value.
2154APInt RoundDoubleToAPInt(double Double, unsigned width);
2155
2156/// Converts a float value into a APInt.
2157///
2158/// Converts a float value into an APInt value.
2159inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2160 return RoundDoubleToAPInt(double(Float), width);
2161}
2162
2163/// Return A unsign-divided by B, rounded by the given rounding mode.
2164APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2165
2166/// Return A sign-divided by B, rounded by the given rounding mode.
2167APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2168
2169} // End of APIntOps namespace
2170
2171// See friend declaration above. This additional declaration is required in
2172// order to compile LLVM with IBM xlC compiler.
2173hash_code hash_value(const APInt &Arg);
2174} // End of llvm namespace
2175
2176#endif