Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include/llvm/ADT/APInt.h
Warning:line 153, column 39
Assigned value is garbage or undefined

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name LazyValueInfo.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Analysis -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Analysis -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Analysis/LazyValueInfo.cpp

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Analysis/LazyValueInfo.cpp

1//===- LazyValueInfo.cpp - Value constraint analysis ------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the interface for lazy computation of value constraint
10// information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Analysis/LazyValueInfo.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/Analysis/AssumptionCache.h"
19#include "llvm/Analysis/ConstantFolding.h"
20#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/TargetLibraryInfo.h"
22#include "llvm/Analysis/ValueLattice.h"
23#include "llvm/Analysis/ValueTracking.h"
24#include "llvm/IR/AssemblyAnnotationWriter.h"
25#include "llvm/IR/CFG.h"
26#include "llvm/IR/ConstantRange.h"
27#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/Instructions.h"
31#include "llvm/IR/IntrinsicInst.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/PatternMatch.h"
35#include "llvm/IR/ValueHandle.h"
36#include "llvm/InitializePasses.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/FormattedStream.h"
39#include "llvm/Support/KnownBits.h"
40#include "llvm/Support/raw_ostream.h"
41using namespace llvm;
42using namespace PatternMatch;
43
44#define DEBUG_TYPE"lazy-value-info" "lazy-value-info"
45
46// This is the number of worklist items we will process to try to discover an
47// answer for a given value.
48static const unsigned MaxProcessedPerValue = 500;
49
50char LazyValueInfoWrapperPass::ID = 0;
51LazyValueInfoWrapperPass::LazyValueInfoWrapperPass() : FunctionPass(ID) {
52 initializeLazyValueInfoWrapperPassPass(*PassRegistry::getPassRegistry());
53}
54INITIALIZE_PASS_BEGIN(LazyValueInfoWrapperPass, "lazy-value-info",static void *initializeLazyValueInfoWrapperPassPassOnce(PassRegistry
&Registry) {
55 "Lazy Value Information Analysis", false, true)static void *initializeLazyValueInfoWrapperPassPassOnce(PassRegistry
&Registry) {
56INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
57INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
58INITIALIZE_PASS_END(LazyValueInfoWrapperPass, "lazy-value-info",PassInfo *PI = new PassInfo( "Lazy Value Information Analysis"
, "lazy-value-info", &LazyValueInfoWrapperPass::ID, PassInfo
::NormalCtor_t(callDefaultCtor<LazyValueInfoWrapperPass>
), false, true); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeLazyValueInfoWrapperPassPassFlag
; void llvm::initializeLazyValueInfoWrapperPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeLazyValueInfoWrapperPassPassFlag
, initializeLazyValueInfoWrapperPassPassOnce, std::ref(Registry
)); }
59 "Lazy Value Information Analysis", false, true)PassInfo *PI = new PassInfo( "Lazy Value Information Analysis"
, "lazy-value-info", &LazyValueInfoWrapperPass::ID, PassInfo
::NormalCtor_t(callDefaultCtor<LazyValueInfoWrapperPass>
), false, true); Registry.registerPass(*PI, true); return PI;
} static llvm::once_flag InitializeLazyValueInfoWrapperPassPassFlag
; void llvm::initializeLazyValueInfoWrapperPassPass(PassRegistry
&Registry) { llvm::call_once(InitializeLazyValueInfoWrapperPassPassFlag
, initializeLazyValueInfoWrapperPassPassOnce, std::ref(Registry
)); }
60
61namespace llvm {
62 FunctionPass *createLazyValueInfoPass() { return new LazyValueInfoWrapperPass(); }
63}
64
65AnalysisKey LazyValueAnalysis::Key;
66
67/// Returns true if this lattice value represents at most one possible value.
68/// This is as precise as any lattice value can get while still representing
69/// reachable code.
70static bool hasSingleValue(const ValueLatticeElement &Val) {
71 if (Val.isConstantRange() &&
72 Val.getConstantRange().isSingleElement())
73 // Integer constants are single element ranges
74 return true;
75 if (Val.isConstant())
76 // Non integer constants
77 return true;
78 return false;
79}
80
81/// Combine two sets of facts about the same value into a single set of
82/// facts. Note that this method is not suitable for merging facts along
83/// different paths in a CFG; that's what the mergeIn function is for. This
84/// is for merging facts gathered about the same value at the same location
85/// through two independent means.
86/// Notes:
87/// * This method does not promise to return the most precise possible lattice
88/// value implied by A and B. It is allowed to return any lattice element
89/// which is at least as strong as *either* A or B (unless our facts
90/// conflict, see below).
91/// * Due to unreachable code, the intersection of two lattice values could be
92/// contradictory. If this happens, we return some valid lattice value so as
93/// not confuse the rest of LVI. Ideally, we'd always return Undefined, but
94/// we do not make this guarantee. TODO: This would be a useful enhancement.
95static ValueLatticeElement intersect(const ValueLatticeElement &A,
96 const ValueLatticeElement &B) {
97 // Undefined is the strongest state. It means the value is known to be along
98 // an unreachable path.
99 if (A.isUnknown())
100 return A;
101 if (B.isUnknown())
102 return B;
103
104 // If we gave up for one, but got a useable fact from the other, use it.
105 if (A.isOverdefined())
106 return B;
107 if (B.isOverdefined())
108 return A;
109
110 // Can't get any more precise than constants.
111 if (hasSingleValue(A))
112 return A;
113 if (hasSingleValue(B))
114 return B;
115
116 // Could be either constant range or not constant here.
117 if (!A.isConstantRange() || !B.isConstantRange()) {
118 // TODO: Arbitrary choice, could be improved
119 return A;
120 }
121
122 // Intersect two constant ranges
123 ConstantRange Range =
124 A.getConstantRange().intersectWith(B.getConstantRange());
125 // Note: An empty range is implicitly converted to unknown or undef depending
126 // on MayIncludeUndef internally.
127 return ValueLatticeElement::getRange(
128 std::move(Range), /*MayIncludeUndef=*/A.isConstantRangeIncludingUndef() ||
129 B.isConstantRangeIncludingUndef());
130}
131
132//===----------------------------------------------------------------------===//
133// LazyValueInfoCache Decl
134//===----------------------------------------------------------------------===//
135
136namespace {
137 /// A callback value handle updates the cache when values are erased.
138 class LazyValueInfoCache;
139 struct LVIValueHandle final : public CallbackVH {
140 LazyValueInfoCache *Parent;
141
142 LVIValueHandle(Value *V, LazyValueInfoCache *P = nullptr)
143 : CallbackVH(V), Parent(P) { }
144
145 void deleted() override;
146 void allUsesReplacedWith(Value *V) override {
147 deleted();
148 }
149 };
150} // end anonymous namespace
151
152namespace {
153 using NonNullPointerSet = SmallDenseSet<AssertingVH<Value>, 2>;
154
155 /// This is the cache kept by LazyValueInfo which
156 /// maintains information about queries across the clients' queries.
157 class LazyValueInfoCache {
158 /// This is all of the cached information for one basic block. It contains
159 /// the per-value lattice elements, as well as a separate set for
160 /// overdefined values to reduce memory usage. Additionally pointers
161 /// dereferenced in the block are cached for nullability queries.
162 struct BlockCacheEntry {
163 SmallDenseMap<AssertingVH<Value>, ValueLatticeElement, 4> LatticeElements;
164 SmallDenseSet<AssertingVH<Value>, 4> OverDefined;
165 // None indicates that the nonnull pointers for this basic block
166 // block have not been computed yet.
167 Optional<NonNullPointerSet> NonNullPointers;
168 };
169
170 /// Cached information per basic block.
171 DenseMap<PoisoningVH<BasicBlock>, std::unique_ptr<BlockCacheEntry>>
172 BlockCache;
173 /// Set of value handles used to erase values from the cache on deletion.
174 DenseSet<LVIValueHandle, DenseMapInfo<Value *>> ValueHandles;
175
176 const BlockCacheEntry *getBlockEntry(BasicBlock *BB) const {
177 auto It = BlockCache.find_as(BB);
178 if (It == BlockCache.end())
179 return nullptr;
180 return It->second.get();
181 }
182
183 BlockCacheEntry *getOrCreateBlockEntry(BasicBlock *BB) {
184 auto It = BlockCache.find_as(BB);
185 if (It == BlockCache.end())
186 It = BlockCache.insert({ BB, std::make_unique<BlockCacheEntry>() })
187 .first;
188
189 return It->second.get();
190 }
191
192 void addValueHandle(Value *Val) {
193 auto HandleIt = ValueHandles.find_as(Val);
194 if (HandleIt == ValueHandles.end())
195 ValueHandles.insert({ Val, this });
196 }
197
198 public:
199 void insertResult(Value *Val, BasicBlock *BB,
200 const ValueLatticeElement &Result) {
201 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
202
203 // Insert over-defined values into their own cache to reduce memory
204 // overhead.
205 if (Result.isOverdefined())
206 Entry->OverDefined.insert(Val);
207 else
208 Entry->LatticeElements.insert({ Val, Result });
209
210 addValueHandle(Val);
211 }
212
213 Optional<ValueLatticeElement> getCachedValueInfo(Value *V,
214 BasicBlock *BB) const {
215 const BlockCacheEntry *Entry = getBlockEntry(BB);
216 if (!Entry)
217 return None;
218
219 if (Entry->OverDefined.count(V))
220 return ValueLatticeElement::getOverdefined();
221
222 auto LatticeIt = Entry->LatticeElements.find_as(V);
223 if (LatticeIt == Entry->LatticeElements.end())
224 return None;
225
226 return LatticeIt->second;
227 }
228
229 bool isNonNullAtEndOfBlock(
230 Value *V, BasicBlock *BB,
231 function_ref<NonNullPointerSet(BasicBlock *)> InitFn) {
232 BlockCacheEntry *Entry = getOrCreateBlockEntry(BB);
233 if (!Entry->NonNullPointers) {
234 Entry->NonNullPointers = InitFn(BB);
235 for (Value *V : *Entry->NonNullPointers)
236 addValueHandle(V);
237 }
238
239 return Entry->NonNullPointers->count(V);
240 }
241
242 /// clear - Empty the cache.
243 void clear() {
244 BlockCache.clear();
245 ValueHandles.clear();
246 }
247
248 /// Inform the cache that a given value has been deleted.
249 void eraseValue(Value *V);
250
251 /// This is part of the update interface to inform the cache
252 /// that a block has been deleted.
253 void eraseBlock(BasicBlock *BB);
254
255 /// Updates the cache to remove any influence an overdefined value in
256 /// OldSucc might have (unless also overdefined in NewSucc). This just
257 /// flushes elements from the cache and does not add any.
258 void threadEdgeImpl(BasicBlock *OldSucc,BasicBlock *NewSucc);
259 };
260}
261
262void LazyValueInfoCache::eraseValue(Value *V) {
263 for (auto &Pair : BlockCache) {
264 Pair.second->LatticeElements.erase(V);
265 Pair.second->OverDefined.erase(V);
266 if (Pair.second->NonNullPointers)
267 Pair.second->NonNullPointers->erase(V);
268 }
269
270 auto HandleIt = ValueHandles.find_as(V);
271 if (HandleIt != ValueHandles.end())
272 ValueHandles.erase(HandleIt);
273}
274
275void LVIValueHandle::deleted() {
276 // This erasure deallocates *this, so it MUST happen after we're done
277 // using any and all members of *this.
278 Parent->eraseValue(*this);
279}
280
281void LazyValueInfoCache::eraseBlock(BasicBlock *BB) {
282 BlockCache.erase(BB);
283}
284
285void LazyValueInfoCache::threadEdgeImpl(BasicBlock *OldSucc,
286 BasicBlock *NewSucc) {
287 // When an edge in the graph has been threaded, values that we could not
288 // determine a value for before (i.e. were marked overdefined) may be
289 // possible to solve now. We do NOT try to proactively update these values.
290 // Instead, we clear their entries from the cache, and allow lazy updating to
291 // recompute them when needed.
292
293 // The updating process is fairly simple: we need to drop cached info
294 // for all values that were marked overdefined in OldSucc, and for those same
295 // values in any successor of OldSucc (except NewSucc) in which they were
296 // also marked overdefined.
297 std::vector<BasicBlock*> worklist;
298 worklist.push_back(OldSucc);
299
300 const BlockCacheEntry *Entry = getBlockEntry(OldSucc);
301 if (!Entry || Entry->OverDefined.empty())
302 return; // Nothing to process here.
303 SmallVector<Value *, 4> ValsToClear(Entry->OverDefined.begin(),
304 Entry->OverDefined.end());
305
306 // Use a worklist to perform a depth-first search of OldSucc's successors.
307 // NOTE: We do not need a visited list since any blocks we have already
308 // visited will have had their overdefined markers cleared already, and we
309 // thus won't loop to their successors.
310 while (!worklist.empty()) {
311 BasicBlock *ToUpdate = worklist.back();
312 worklist.pop_back();
313
314 // Skip blocks only accessible through NewSucc.
315 if (ToUpdate == NewSucc) continue;
316
317 // If a value was marked overdefined in OldSucc, and is here too...
318 auto OI = BlockCache.find_as(ToUpdate);
319 if (OI == BlockCache.end() || OI->second->OverDefined.empty())
320 continue;
321 auto &ValueSet = OI->second->OverDefined;
322
323 bool changed = false;
324 for (Value *V : ValsToClear) {
325 if (!ValueSet.erase(V))
326 continue;
327
328 // If we removed anything, then we potentially need to update
329 // blocks successors too.
330 changed = true;
331 }
332
333 if (!changed) continue;
334
335 llvm::append_range(worklist, successors(ToUpdate));
336 }
337}
338
339
340namespace {
341/// An assembly annotator class to print LazyValueCache information in
342/// comments.
343class LazyValueInfoImpl;
344class LazyValueInfoAnnotatedWriter : public AssemblyAnnotationWriter {
345 LazyValueInfoImpl *LVIImpl;
346 // While analyzing which blocks we can solve values for, we need the dominator
347 // information.
348 DominatorTree &DT;
349
350public:
351 LazyValueInfoAnnotatedWriter(LazyValueInfoImpl *L, DominatorTree &DTree)
352 : LVIImpl(L), DT(DTree) {}
353
354 void emitBasicBlockStartAnnot(const BasicBlock *BB,
355 formatted_raw_ostream &OS) override;
356
357 void emitInstructionAnnot(const Instruction *I,
358 formatted_raw_ostream &OS) override;
359};
360}
361namespace {
362// The actual implementation of the lazy analysis and update. Note that the
363// inheritance from LazyValueInfoCache is intended to be temporary while
364// splitting the code and then transitioning to a has-a relationship.
365class LazyValueInfoImpl {
366
367 /// Cached results from previous queries
368 LazyValueInfoCache TheCache;
369
370 /// This stack holds the state of the value solver during a query.
371 /// It basically emulates the callstack of the naive
372 /// recursive value lookup process.
373 SmallVector<std::pair<BasicBlock*, Value*>, 8> BlockValueStack;
374
375 /// Keeps track of which block-value pairs are in BlockValueStack.
376 DenseSet<std::pair<BasicBlock*, Value*> > BlockValueSet;
377
378 /// Push BV onto BlockValueStack unless it's already in there.
379 /// Returns true on success.
380 bool pushBlockValue(const std::pair<BasicBlock *, Value *> &BV) {
381 if (!BlockValueSet.insert(BV).second)
382 return false; // It's already in the stack.
383
384 LLVM_DEBUG(dbgs() << "PUSH: " << *BV.second << " in "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "PUSH: " << *BV.
second << " in " << BV.first->getName() <<
"\n"; } } while (false)
385 << BV.first->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "PUSH: " << *BV.
second << " in " << BV.first->getName() <<
"\n"; } } while (false)
;
386 BlockValueStack.push_back(BV);
387 return true;
388 }
389
390 AssumptionCache *AC; ///< A pointer to the cache of @llvm.assume calls.
391 const DataLayout &DL; ///< A mandatory DataLayout
392
393 /// Declaration of the llvm.experimental.guard() intrinsic,
394 /// if it exists in the module.
395 Function *GuardDecl;
396
397 Optional<ValueLatticeElement> getBlockValue(Value *Val, BasicBlock *BB,
398 Instruction *CxtI);
399 Optional<ValueLatticeElement> getEdgeValue(Value *V, BasicBlock *F,
400 BasicBlock *T, Instruction *CxtI = nullptr);
401
402 // These methods process one work item and may add more. A false value
403 // returned means that the work item was not completely processed and must
404 // be revisited after going through the new items.
405 bool solveBlockValue(Value *Val, BasicBlock *BB);
406 Optional<ValueLatticeElement> solveBlockValueImpl(Value *Val, BasicBlock *BB);
407 Optional<ValueLatticeElement> solveBlockValueNonLocal(Value *Val,
408 BasicBlock *BB);
409 Optional<ValueLatticeElement> solveBlockValuePHINode(PHINode *PN,
410 BasicBlock *BB);
411 Optional<ValueLatticeElement> solveBlockValueSelect(SelectInst *S,
412 BasicBlock *BB);
413 Optional<ConstantRange> getRangeFor(Value *V, Instruction *CxtI,
414 BasicBlock *BB);
415 Optional<ValueLatticeElement> solveBlockValueBinaryOpImpl(
416 Instruction *I, BasicBlock *BB,
417 std::function<ConstantRange(const ConstantRange &,
418 const ConstantRange &)> OpFn);
419 Optional<ValueLatticeElement> solveBlockValueBinaryOp(BinaryOperator *BBI,
420 BasicBlock *BB);
421 Optional<ValueLatticeElement> solveBlockValueCast(CastInst *CI,
422 BasicBlock *BB);
423 Optional<ValueLatticeElement> solveBlockValueOverflowIntrinsic(
424 WithOverflowInst *WO, BasicBlock *BB);
425 Optional<ValueLatticeElement> solveBlockValueIntrinsic(IntrinsicInst *II,
426 BasicBlock *BB);
427 Optional<ValueLatticeElement> solveBlockValueExtractValue(
428 ExtractValueInst *EVI, BasicBlock *BB);
429 bool isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB);
430 void intersectAssumeOrGuardBlockValueConstantRange(Value *Val,
431 ValueLatticeElement &BBLV,
432 Instruction *BBI);
433
434 void solve();
435
436public:
437 /// This is the query interface to determine the lattice value for the
438 /// specified Value* at the context instruction (if specified) or at the
439 /// start of the block.
440 ValueLatticeElement getValueInBlock(Value *V, BasicBlock *BB,
441 Instruction *CxtI = nullptr);
442
443 /// This is the query interface to determine the lattice value for the
444 /// specified Value* at the specified instruction using only information
445 /// from assumes/guards and range metadata. Unlike getValueInBlock(), no
446 /// recursive query is performed.
447 ValueLatticeElement getValueAt(Value *V, Instruction *CxtI);
448
449 /// This is the query interface to determine the lattice
450 /// value for the specified Value* that is true on the specified edge.
451 ValueLatticeElement getValueOnEdge(Value *V, BasicBlock *FromBB,
452 BasicBlock *ToBB,
453 Instruction *CxtI = nullptr);
454
455 /// Complete flush all previously computed values
456 void clear() {
457 TheCache.clear();
458 }
459
460 /// Printing the LazyValueInfo Analysis.
461 void printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
462 LazyValueInfoAnnotatedWriter Writer(this, DTree);
463 F.print(OS, &Writer);
464 }
465
466 /// This is part of the update interface to inform the cache
467 /// that a block has been deleted.
468 void eraseBlock(BasicBlock *BB) {
469 TheCache.eraseBlock(BB);
470 }
471
472 /// This is the update interface to inform the cache that an edge from
473 /// PredBB to OldSucc has been threaded to be from PredBB to NewSucc.
474 void threadEdge(BasicBlock *PredBB,BasicBlock *OldSucc,BasicBlock *NewSucc);
475
476 LazyValueInfoImpl(AssumptionCache *AC, const DataLayout &DL,
477 Function *GuardDecl)
478 : AC(AC), DL(DL), GuardDecl(GuardDecl) {}
479};
480} // end anonymous namespace
481
482
483void LazyValueInfoImpl::solve() {
484 SmallVector<std::pair<BasicBlock *, Value *>, 8> StartingStack(
485 BlockValueStack.begin(), BlockValueStack.end());
486
487 unsigned processedCount = 0;
488 while (!BlockValueStack.empty()) {
489 processedCount++;
490 // Abort if we have to process too many values to get a result for this one.
491 // Because of the design of the overdefined cache currently being per-block
492 // to avoid naming-related issues (IE it wants to try to give different
493 // results for the same name in different blocks), overdefined results don't
494 // get cached globally, which in turn means we will often try to rediscover
495 // the same overdefined result again and again. Once something like
496 // PredicateInfo is used in LVI or CVP, we should be able to make the
497 // overdefined cache global, and remove this throttle.
498 if (processedCount > MaxProcessedPerValue) {
499 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "Giving up on stack because we are getting too deep\n"
; } } while (false)
500 dbgs() << "Giving up on stack because we are getting too deep\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "Giving up on stack because we are getting too deep\n"
; } } while (false)
;
501 // Fill in the original values
502 while (!StartingStack.empty()) {
503 std::pair<BasicBlock *, Value *> &e = StartingStack.back();
504 TheCache.insertResult(e.second, e.first,
505 ValueLatticeElement::getOverdefined());
506 StartingStack.pop_back();
507 }
508 BlockValueSet.clear();
509 BlockValueStack.clear();
510 return;
511 }
512 std::pair<BasicBlock *, Value *> e = BlockValueStack.back();
513 assert(BlockValueSet.count(e) && "Stack value should be in BlockValueSet!")(static_cast <bool> (BlockValueSet.count(e) && "Stack value should be in BlockValueSet!"
) ? void (0) : __assert_fail ("BlockValueSet.count(e) && \"Stack value should be in BlockValueSet!\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 513, __extension__ __PRETTY_FUNCTION__
))
;
514
515 if (solveBlockValue(e.second, e.first)) {
516 // The work item was completely processed.
517 assert(BlockValueStack.back() == e && "Nothing should have been pushed!")(static_cast <bool> (BlockValueStack.back() == e &&
"Nothing should have been pushed!") ? void (0) : __assert_fail
("BlockValueStack.back() == e && \"Nothing should have been pushed!\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 517, __extension__ __PRETTY_FUNCTION__
))
;
518#ifndef NDEBUG
519 Optional<ValueLatticeElement> BBLV =
520 TheCache.getCachedValueInfo(e.second, e.first);
521 assert(BBLV && "Result should be in cache!")(static_cast <bool> (BBLV && "Result should be in cache!"
) ? void (0) : __assert_fail ("BBLV && \"Result should be in cache!\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 521, __extension__ __PRETTY_FUNCTION__
))
;
522 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "POP " << *e.second
<< " in " << e.first->getName() << " = "
<< *BBLV << "\n"; } } while (false)
523 dbgs() << "POP " << *e.second << " in " << e.first->getName() << " = "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "POP " << *e.second
<< " in " << e.first->getName() << " = "
<< *BBLV << "\n"; } } while (false)
524 << *BBLV << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "POP " << *e.second
<< " in " << e.first->getName() << " = "
<< *BBLV << "\n"; } } while (false)
;
525#endif
526
527 BlockValueStack.pop_back();
528 BlockValueSet.erase(e);
529 } else {
530 // More work needs to be done before revisiting.
531 assert(BlockValueStack.back() != e && "Stack should have been pushed!")(static_cast <bool> (BlockValueStack.back() != e &&
"Stack should have been pushed!") ? void (0) : __assert_fail
("BlockValueStack.back() != e && \"Stack should have been pushed!\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 531, __extension__ __PRETTY_FUNCTION__
))
;
532 }
533 }
534}
535
536Optional<ValueLatticeElement> LazyValueInfoImpl::getBlockValue(
537 Value *Val, BasicBlock *BB, Instruction *CxtI) {
538 // If already a constant, there is nothing to compute.
539 if (Constant *VC = dyn_cast<Constant>(Val))
540 return ValueLatticeElement::get(VC);
541
542 if (Optional<ValueLatticeElement> OptLatticeVal =
543 TheCache.getCachedValueInfo(Val, BB)) {
544 intersectAssumeOrGuardBlockValueConstantRange(Val, *OptLatticeVal, CxtI);
545 return OptLatticeVal;
546 }
547
548 // We have hit a cycle, assume overdefined.
549 if (!pushBlockValue({ BB, Val }))
550 return ValueLatticeElement::getOverdefined();
551
552 // Yet to be resolved.
553 return None;
554}
555
556static ValueLatticeElement getFromRangeMetadata(Instruction *BBI) {
557 switch (BBI->getOpcode()) {
558 default: break;
559 case Instruction::Load:
560 case Instruction::Call:
561 case Instruction::Invoke:
562 if (MDNode *Ranges = BBI->getMetadata(LLVMContext::MD_range))
563 if (isa<IntegerType>(BBI->getType())) {
564 return ValueLatticeElement::getRange(
565 getConstantRangeFromMetadata(*Ranges));
566 }
567 break;
568 };
569 // Nothing known - will be intersected with other facts
570 return ValueLatticeElement::getOverdefined();
571}
572
573bool LazyValueInfoImpl::solveBlockValue(Value *Val, BasicBlock *BB) {
574 assert(!isa<Constant>(Val) && "Value should not be constant")(static_cast <bool> (!isa<Constant>(Val) &&
"Value should not be constant") ? void (0) : __assert_fail (
"!isa<Constant>(Val) && \"Value should not be constant\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 574, __extension__ __PRETTY_FUNCTION__
))
;
575 assert(!TheCache.getCachedValueInfo(Val, BB) &&(static_cast <bool> (!TheCache.getCachedValueInfo(Val, BB
) && "Value should not be in cache") ? void (0) : __assert_fail
("!TheCache.getCachedValueInfo(Val, BB) && \"Value should not be in cache\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 576, __extension__ __PRETTY_FUNCTION__
))
576 "Value should not be in cache")(static_cast <bool> (!TheCache.getCachedValueInfo(Val, BB
) && "Value should not be in cache") ? void (0) : __assert_fail
("!TheCache.getCachedValueInfo(Val, BB) && \"Value should not be in cache\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 576, __extension__ __PRETTY_FUNCTION__
))
;
577
578 // Hold off inserting this value into the Cache in case we have to return
579 // false and come back later.
580 Optional<ValueLatticeElement> Res = solveBlockValueImpl(Val, BB);
581 if (!Res)
582 // Work pushed, will revisit
583 return false;
584
585 TheCache.insertResult(Val, BB, *Res);
586 return true;
587}
588
589Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueImpl(
590 Value *Val, BasicBlock *BB) {
591 Instruction *BBI = dyn_cast<Instruction>(Val);
592 if (!BBI || BBI->getParent() != BB)
593 return solveBlockValueNonLocal(Val, BB);
594
595 if (PHINode *PN = dyn_cast<PHINode>(BBI))
596 return solveBlockValuePHINode(PN, BB);
597
598 if (auto *SI = dyn_cast<SelectInst>(BBI))
599 return solveBlockValueSelect(SI, BB);
600
601 // If this value is a nonnull pointer, record it's range and bailout. Note
602 // that for all other pointer typed values, we terminate the search at the
603 // definition. We could easily extend this to look through geps, bitcasts,
604 // and the like to prove non-nullness, but it's not clear that's worth it
605 // compile time wise. The context-insensitive value walk done inside
606 // isKnownNonZero gets most of the profitable cases at much less expense.
607 // This does mean that we have a sensitivity to where the defining
608 // instruction is placed, even if it could legally be hoisted much higher.
609 // That is unfortunate.
610 PointerType *PT = dyn_cast<PointerType>(BBI->getType());
611 if (PT && isKnownNonZero(BBI, DL))
612 return ValueLatticeElement::getNot(ConstantPointerNull::get(PT));
613
614 if (BBI->getType()->isIntegerTy()) {
615 if (auto *CI = dyn_cast<CastInst>(BBI))
616 return solveBlockValueCast(CI, BB);
617
618 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(BBI))
619 return solveBlockValueBinaryOp(BO, BB);
620
621 if (auto *EVI = dyn_cast<ExtractValueInst>(BBI))
622 return solveBlockValueExtractValue(EVI, BB);
623
624 if (auto *II = dyn_cast<IntrinsicInst>(BBI))
625 return solveBlockValueIntrinsic(II, BB);
626 }
627
628 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown inst def found.\n"; }
} while (false)
629 << "' - unknown inst def found.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown inst def found.\n"; }
} while (false)
;
630 return getFromRangeMetadata(BBI);
631}
632
633static void AddNonNullPointer(Value *Ptr, NonNullPointerSet &PtrSet) {
634 // TODO: Use NullPointerIsDefined instead.
635 if (Ptr->getType()->getPointerAddressSpace() == 0)
636 PtrSet.insert(getUnderlyingObject(Ptr));
637}
638
639static void AddNonNullPointersByInstruction(
640 Instruction *I, NonNullPointerSet &PtrSet) {
641 if (LoadInst *L = dyn_cast<LoadInst>(I)) {
642 AddNonNullPointer(L->getPointerOperand(), PtrSet);
643 } else if (StoreInst *S = dyn_cast<StoreInst>(I)) {
644 AddNonNullPointer(S->getPointerOperand(), PtrSet);
645 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) {
646 if (MI->isVolatile()) return;
647
648 // FIXME: check whether it has a valuerange that excludes zero?
649 ConstantInt *Len = dyn_cast<ConstantInt>(MI->getLength());
650 if (!Len || Len->isZero()) return;
651
652 AddNonNullPointer(MI->getRawDest(), PtrSet);
653 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
654 AddNonNullPointer(MTI->getRawSource(), PtrSet);
655 }
656}
657
658bool LazyValueInfoImpl::isNonNullAtEndOfBlock(Value *Val, BasicBlock *BB) {
659 if (NullPointerIsDefined(BB->getParent(),
660 Val->getType()->getPointerAddressSpace()))
661 return false;
662
663 Val = Val->stripInBoundsOffsets();
664 return TheCache.isNonNullAtEndOfBlock(Val, BB, [](BasicBlock *BB) {
665 NonNullPointerSet NonNullPointers;
666 for (Instruction &I : *BB)
667 AddNonNullPointersByInstruction(&I, NonNullPointers);
668 return NonNullPointers;
669 });
670}
671
672Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueNonLocal(
673 Value *Val, BasicBlock *BB) {
674 ValueLatticeElement Result; // Start Undefined.
675
676 // If this is the entry block, we must be asking about an argument. The
677 // value is overdefined.
678 if (BB->isEntryBlock()) {
679 assert(isa<Argument>(Val) && "Unknown live-in to the entry block")(static_cast <bool> (isa<Argument>(Val) &&
"Unknown live-in to the entry block") ? void (0) : __assert_fail
("isa<Argument>(Val) && \"Unknown live-in to the entry block\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 679, __extension__ __PRETTY_FUNCTION__
))
;
680 return ValueLatticeElement::getOverdefined();
681 }
682
683 // Loop over all of our predecessors, merging what we know from them into
684 // result. If we encounter an unexplored predecessor, we eagerly explore it
685 // in a depth first manner. In practice, this has the effect of discovering
686 // paths we can't analyze eagerly without spending compile times analyzing
687 // other paths. This heuristic benefits from the fact that predecessors are
688 // frequently arranged such that dominating ones come first and we quickly
689 // find a path to function entry. TODO: We should consider explicitly
690 // canonicalizing to make this true rather than relying on this happy
691 // accident.
692 for (BasicBlock *Pred : predecessors(BB)) {
693 Optional<ValueLatticeElement> EdgeResult = getEdgeValue(Val, Pred, BB);
694 if (!EdgeResult)
695 // Explore that input, then return here
696 return None;
697
698 Result.mergeIn(*EdgeResult);
699
700 // If we hit overdefined, exit early. The BlockVals entry is already set
701 // to overdefined.
702 if (Result.isOverdefined()) {
703 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (non local).\n"
; } } while (false)
704 << "' - overdefined because of pred (non local).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (non local).\n"
; } } while (false)
;
705 return Result;
706 }
707 }
708
709 // Return the merged value, which is more precise than 'overdefined'.
710 assert(!Result.isOverdefined())(static_cast <bool> (!Result.isOverdefined()) ? void (0
) : __assert_fail ("!Result.isOverdefined()", "llvm/lib/Analysis/LazyValueInfo.cpp"
, 710, __extension__ __PRETTY_FUNCTION__))
;
711 return Result;
712}
713
714Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValuePHINode(
715 PHINode *PN, BasicBlock *BB) {
716 ValueLatticeElement Result; // Start Undefined.
717
718 // Loop over all of our predecessors, merging what we know from them into
719 // result. See the comment about the chosen traversal order in
720 // solveBlockValueNonLocal; the same reasoning applies here.
721 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
722 BasicBlock *PhiBB = PN->getIncomingBlock(i);
723 Value *PhiVal = PN->getIncomingValue(i);
724 // Note that we can provide PN as the context value to getEdgeValue, even
725 // though the results will be cached, because PN is the value being used as
726 // the cache key in the caller.
727 Optional<ValueLatticeElement> EdgeResult =
728 getEdgeValue(PhiVal, PhiBB, BB, PN);
729 if (!EdgeResult)
730 // Explore that input, then return here
731 return None;
732
733 Result.mergeIn(*EdgeResult);
734
735 // If we hit overdefined, exit early. The BlockVals entry is already set
736 // to overdefined.
737 if (Result.isOverdefined()) {
738 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (local).\n"
; } } while (false)
739 << "' - overdefined because of pred (local).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined because of pred (local).\n"
; } } while (false)
;
740
741 return Result;
742 }
743 }
744
745 // Return the merged value, which is more precise than 'overdefined'.
746 assert(!Result.isOverdefined() && "Possible PHI in entry block?")(static_cast <bool> (!Result.isOverdefined() &&
"Possible PHI in entry block?") ? void (0) : __assert_fail (
"!Result.isOverdefined() && \"Possible PHI in entry block?\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 746, __extension__ __PRETTY_FUNCTION__
))
;
747 return Result;
748}
749
750static ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
751 bool isTrueDest = true);
752
753// If we can determine a constraint on the value given conditions assumed by
754// the program, intersect those constraints with BBLV
755void LazyValueInfoImpl::intersectAssumeOrGuardBlockValueConstantRange(
756 Value *Val, ValueLatticeElement &BBLV, Instruction *BBI) {
757 BBI = BBI ? BBI : dyn_cast<Instruction>(Val);
758 if (!BBI)
759 return;
760
761 BasicBlock *BB = BBI->getParent();
762 for (auto &AssumeVH : AC->assumptionsFor(Val)) {
763 if (!AssumeVH)
764 continue;
765
766 // Only check assumes in the block of the context instruction. Other
767 // assumes will have already been taken into account when the value was
768 // propagated from predecessor blocks.
769 auto *I = cast<CallInst>(AssumeVH);
770 if (I->getParent() != BB || !isValidAssumeForContext(I, BBI))
771 continue;
772
773 BBLV = intersect(BBLV, getValueFromCondition(Val, I->getArgOperand(0)));
774 }
775
776 // If guards are not used in the module, don't spend time looking for them
777 if (GuardDecl && !GuardDecl->use_empty() &&
778 BBI->getIterator() != BB->begin()) {
779 for (Instruction &I : make_range(std::next(BBI->getIterator().getReverse()),
780 BB->rend())) {
781 Value *Cond = nullptr;
782 if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(Cond))))
783 BBLV = intersect(BBLV, getValueFromCondition(Val, Cond));
784 }
785 }
786
787 if (BBLV.isOverdefined()) {
788 // Check whether we're checking at the terminator, and the pointer has
789 // been dereferenced in this block.
790 PointerType *PTy = dyn_cast<PointerType>(Val->getType());
791 if (PTy && BB->getTerminator() == BBI &&
792 isNonNullAtEndOfBlock(Val, BB))
793 BBLV = ValueLatticeElement::getNot(ConstantPointerNull::get(PTy));
794 }
795}
796
797static ConstantRange getConstantRangeOrFull(const ValueLatticeElement &Val,
798 Type *Ty, const DataLayout &DL) {
799 if (Val.isConstantRange())
800 return Val.getConstantRange();
801 return ConstantRange::getFull(DL.getTypeSizeInBits(Ty));
802}
803
804Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueSelect(
805 SelectInst *SI, BasicBlock *BB) {
806 // Recurse on our inputs if needed
807 Optional<ValueLatticeElement> OptTrueVal =
808 getBlockValue(SI->getTrueValue(), BB, SI);
809 if (!OptTrueVal)
810 return None;
811 ValueLatticeElement &TrueVal = *OptTrueVal;
812
813 Optional<ValueLatticeElement> OptFalseVal =
814 getBlockValue(SI->getFalseValue(), BB, SI);
815 if (!OptFalseVal)
816 return None;
817 ValueLatticeElement &FalseVal = *OptFalseVal;
818
819 if (TrueVal.isConstantRange() || FalseVal.isConstantRange()) {
820 const ConstantRange &TrueCR =
821 getConstantRangeOrFull(TrueVal, SI->getType(), DL);
822 const ConstantRange &FalseCR =
823 getConstantRangeOrFull(FalseVal, SI->getType(), DL);
824 Value *LHS = nullptr;
825 Value *RHS = nullptr;
826 SelectPatternResult SPR = matchSelectPattern(SI, LHS, RHS);
827 // Is this a min specifically of our two inputs? (Avoid the risk of
828 // ValueTracking getting smarter looking back past our immediate inputs.)
829 if (SelectPatternResult::isMinOrMax(SPR.Flavor) &&
830 ((LHS == SI->getTrueValue() && RHS == SI->getFalseValue()) ||
831 (RHS == SI->getTrueValue() && LHS == SI->getFalseValue()))) {
832 ConstantRange ResultCR = [&]() {
833 switch (SPR.Flavor) {
834 default:
835 llvm_unreachable("unexpected minmax type!")::llvm::llvm_unreachable_internal("unexpected minmax type!", "llvm/lib/Analysis/LazyValueInfo.cpp"
, 835)
;
836 case SPF_SMIN: /// Signed minimum
837 return TrueCR.smin(FalseCR);
838 case SPF_UMIN: /// Unsigned minimum
839 return TrueCR.umin(FalseCR);
840 case SPF_SMAX: /// Signed maximum
841 return TrueCR.smax(FalseCR);
842 case SPF_UMAX: /// Unsigned maximum
843 return TrueCR.umax(FalseCR);
844 };
845 }();
846 return ValueLatticeElement::getRange(
847 ResultCR, TrueVal.isConstantRangeIncludingUndef() ||
848 FalseVal.isConstantRangeIncludingUndef());
849 }
850
851 if (SPR.Flavor == SPF_ABS) {
852 if (LHS == SI->getTrueValue())
853 return ValueLatticeElement::getRange(
854 TrueCR.abs(), TrueVal.isConstantRangeIncludingUndef());
855 if (LHS == SI->getFalseValue())
856 return ValueLatticeElement::getRange(
857 FalseCR.abs(), FalseVal.isConstantRangeIncludingUndef());
858 }
859
860 if (SPR.Flavor == SPF_NABS) {
861 ConstantRange Zero(APInt::getZero(TrueCR.getBitWidth()));
862 if (LHS == SI->getTrueValue())
863 return ValueLatticeElement::getRange(
864 Zero.sub(TrueCR.abs()), FalseVal.isConstantRangeIncludingUndef());
865 if (LHS == SI->getFalseValue())
866 return ValueLatticeElement::getRange(
867 Zero.sub(FalseCR.abs()), FalseVal.isConstantRangeIncludingUndef());
868 }
869 }
870
871 // Can we constrain the facts about the true and false values by using the
872 // condition itself? This shows up with idioms like e.g. select(a > 5, a, 5).
873 // TODO: We could potentially refine an overdefined true value above.
874 Value *Cond = SI->getCondition();
875 TrueVal = intersect(TrueVal,
876 getValueFromCondition(SI->getTrueValue(), Cond, true));
877 FalseVal = intersect(FalseVal,
878 getValueFromCondition(SI->getFalseValue(), Cond, false));
879
880 ValueLatticeElement Result = TrueVal;
881 Result.mergeIn(FalseVal);
882 return Result;
883}
884
885Optional<ConstantRange> LazyValueInfoImpl::getRangeFor(Value *V,
886 Instruction *CxtI,
887 BasicBlock *BB) {
888 Optional<ValueLatticeElement> OptVal = getBlockValue(V, BB, CxtI);
889 if (!OptVal)
890 return None;
891 return getConstantRangeOrFull(*OptVal, V->getType(), DL);
892}
893
894Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueCast(
895 CastInst *CI, BasicBlock *BB) {
896 // Without knowing how wide the input is, we can't analyze it in any useful
897 // way.
898 if (!CI->getOperand(0)->getType()->isSized())
899 return ValueLatticeElement::getOverdefined();
900
901 // Filter out casts we don't know how to reason about before attempting to
902 // recurse on our operand. This can cut a long search short if we know we're
903 // not going to be able to get any useful information anways.
904 switch (CI->getOpcode()) {
905 case Instruction::Trunc:
906 case Instruction::SExt:
907 case Instruction::ZExt:
908 case Instruction::BitCast:
909 break;
910 default:
911 // Unhandled instructions are overdefined.
912 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown cast).\n"
; } } while (false)
913 << "' - overdefined (unknown cast).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown cast).\n"
; } } while (false)
;
914 return ValueLatticeElement::getOverdefined();
915 }
916
917 // Figure out the range of the LHS. If that fails, we still apply the
918 // transfer rule on the full set since we may be able to locally infer
919 // interesting facts.
920 Optional<ConstantRange> LHSRes = getRangeFor(CI->getOperand(0), CI, BB);
921 if (!LHSRes.hasValue())
922 // More work to do before applying this transfer rule.
923 return None;
924 const ConstantRange &LHSRange = LHSRes.getValue();
925
926 const unsigned ResultBitWidth = CI->getType()->getIntegerBitWidth();
927
928 // NOTE: We're currently limited by the set of operations that ConstantRange
929 // can evaluate symbolically. Enhancing that set will allows us to analyze
930 // more definitions.
931 return ValueLatticeElement::getRange(LHSRange.castOp(CI->getOpcode(),
932 ResultBitWidth));
933}
934
935Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOpImpl(
936 Instruction *I, BasicBlock *BB,
937 std::function<ConstantRange(const ConstantRange &,
938 const ConstantRange &)> OpFn) {
939 // Figure out the ranges of the operands. If that fails, use a
940 // conservative range, but apply the transfer rule anyways. This
941 // lets us pick up facts from expressions like "and i32 (call i32
942 // @foo()), 32"
943 Optional<ConstantRange> LHSRes = getRangeFor(I->getOperand(0), I, BB);
944 Optional<ConstantRange> RHSRes = getRangeFor(I->getOperand(1), I, BB);
945 if (!LHSRes.hasValue() || !RHSRes.hasValue())
946 // More work to do before applying this transfer rule.
947 return None;
948
949 const ConstantRange &LHSRange = LHSRes.getValue();
950 const ConstantRange &RHSRange = RHSRes.getValue();
951 return ValueLatticeElement::getRange(OpFn(LHSRange, RHSRange));
952}
953
954Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueBinaryOp(
955 BinaryOperator *BO, BasicBlock *BB) {
956 assert(BO->getOperand(0)->getType()->isSized() &&(static_cast <bool> (BO->getOperand(0)->getType()
->isSized() && "all operands to binary operators are sized"
) ? void (0) : __assert_fail ("BO->getOperand(0)->getType()->isSized() && \"all operands to binary operators are sized\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 957, __extension__ __PRETTY_FUNCTION__
))
957 "all operands to binary operators are sized")(static_cast <bool> (BO->getOperand(0)->getType()
->isSized() && "all operands to binary operators are sized"
) ? void (0) : __assert_fail ("BO->getOperand(0)->getType()->isSized() && \"all operands to binary operators are sized\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 957, __extension__ __PRETTY_FUNCTION__
))
;
958 if (BO->getOpcode() == Instruction::Xor) {
959 // Xor is the only operation not supported by ConstantRange::binaryOp().
960 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown binary operator).\n"
; } } while (false)
961 << "' - overdefined (unknown binary operator).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown binary operator).\n"
; } } while (false)
;
962 return ValueLatticeElement::getOverdefined();
963 }
964
965 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(BO)) {
966 unsigned NoWrapKind = 0;
967 if (OBO->hasNoUnsignedWrap())
968 NoWrapKind |= OverflowingBinaryOperator::NoUnsignedWrap;
969 if (OBO->hasNoSignedWrap())
970 NoWrapKind |= OverflowingBinaryOperator::NoSignedWrap;
971
972 return solveBlockValueBinaryOpImpl(
973 BO, BB,
974 [BO, NoWrapKind](const ConstantRange &CR1, const ConstantRange &CR2) {
975 return CR1.overflowingBinaryOp(BO->getOpcode(), CR2, NoWrapKind);
976 });
977 }
978
979 return solveBlockValueBinaryOpImpl(
980 BO, BB, [BO](const ConstantRange &CR1, const ConstantRange &CR2) {
981 return CR1.binaryOp(BO->getOpcode(), CR2);
982 });
983}
984
985Optional<ValueLatticeElement>
986LazyValueInfoImpl::solveBlockValueOverflowIntrinsic(WithOverflowInst *WO,
987 BasicBlock *BB) {
988 return solveBlockValueBinaryOpImpl(
989 WO, BB, [WO](const ConstantRange &CR1, const ConstantRange &CR2) {
990 return CR1.binaryOp(WO->getBinaryOp(), CR2);
991 });
992}
993
994Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueIntrinsic(
995 IntrinsicInst *II, BasicBlock *BB) {
996 if (!ConstantRange::isIntrinsicSupported(II->getIntrinsicID())) {
997 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown intrinsic.\n"; } } while
(false)
998 << "' - unknown intrinsic.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - unknown intrinsic.\n"; } } while
(false)
;
999 return getFromRangeMetadata(II);
1000 }
1001
1002 SmallVector<ConstantRange, 2> OpRanges;
1003 for (Value *Op : II->args()) {
1004 Optional<ConstantRange> Range = getRangeFor(Op, II, BB);
1005 if (!Range)
1006 return None;
1007 OpRanges.push_back(*Range);
1008 }
1009
1010 return ValueLatticeElement::getRange(
1011 ConstantRange::intrinsic(II->getIntrinsicID(), OpRanges));
1012}
1013
1014Optional<ValueLatticeElement> LazyValueInfoImpl::solveBlockValueExtractValue(
1015 ExtractValueInst *EVI, BasicBlock *BB) {
1016 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1017 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 0)
1018 return solveBlockValueOverflowIntrinsic(WO, BB);
1019
1020 // Handle extractvalue of insertvalue to allow further simplification
1021 // based on replaced with.overflow intrinsics.
1022 if (Value *V = SimplifyExtractValueInst(
1023 EVI->getAggregateOperand(), EVI->getIndices(),
1024 EVI->getModule()->getDataLayout()))
1025 return getBlockValue(V, BB, EVI);
1026
1027 LLVM_DEBUG(dbgs() << " compute BB '" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown extractvalue).\n"
; } } while (false)
1028 << "' - overdefined (unknown extractvalue).\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " compute BB '" <<
BB->getName() << "' - overdefined (unknown extractvalue).\n"
; } } while (false)
;
1029 return ValueLatticeElement::getOverdefined();
1030}
1031
1032static bool matchICmpOperand(APInt &Offset, Value *LHS, Value *Val,
1033 ICmpInst::Predicate Pred) {
1034 if (LHS == Val)
1035 return true;
1036
1037 // Handle range checking idiom produced by InstCombine. We will subtract the
1038 // offset from the allowed range for RHS in this case.
1039 const APInt *C;
1040 if (match(LHS, m_Add(m_Specific(Val), m_APInt(C)))) {
1041 Offset = *C;
1042 return true;
1043 }
1044
1045 // Handle the symmetric case. This appears in saturation patterns like
1046 // (x == 16) ? 16 : (x + 1).
1047 if (match(Val, m_Add(m_Specific(LHS), m_APInt(C)))) {
1048 Offset = -*C;
1049 return true;
1050 }
1051
1052 // If (x | y) < C, then (x < C) && (y < C).
1053 if (match(LHS, m_c_Or(m_Specific(Val), m_Value())) &&
1054 (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE))
1055 return true;
1056
1057 // If (x & y) > C, then (x > C) && (y > C).
1058 if (match(LHS, m_c_And(m_Specific(Val), m_Value())) &&
1059 (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE))
1060 return true;
1061
1062 return false;
1063}
1064
1065/// Get value range for a "(Val + Offset) Pred RHS" condition.
1066static ValueLatticeElement getValueFromSimpleICmpCondition(
1067 CmpInst::Predicate Pred, Value *RHS, const APInt &Offset) {
1068 ConstantRange RHSRange(RHS->getType()->getIntegerBitWidth(),
1069 /*isFullSet=*/true);
1070 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS))
1071 RHSRange = ConstantRange(CI->getValue());
1072 else if (Instruction *I = dyn_cast<Instruction>(RHS))
1073 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
1074 RHSRange = getConstantRangeFromMetadata(*Ranges);
1075
1076 ConstantRange TrueValues =
1077 ConstantRange::makeAllowedICmpRegion(Pred, RHSRange);
1078 return ValueLatticeElement::getRange(TrueValues.subtract(Offset));
1079}
1080
1081static ValueLatticeElement getValueFromICmpCondition(Value *Val, ICmpInst *ICI,
1082 bool isTrueDest) {
1083 Value *LHS = ICI->getOperand(0);
1084 Value *RHS = ICI->getOperand(1);
1085
1086 // Get the predicate that must hold along the considered edge.
1087 CmpInst::Predicate EdgePred =
1088 isTrueDest ? ICI->getPredicate() : ICI->getInversePredicate();
1089
1090 if (isa<Constant>(RHS)) {
1091 if (ICI->isEquality() && LHS == Val) {
1092 if (EdgePred == ICmpInst::ICMP_EQ)
1093 return ValueLatticeElement::get(cast<Constant>(RHS));
1094 else if (!isa<UndefValue>(RHS))
1095 return ValueLatticeElement::getNot(cast<Constant>(RHS));
1096 }
1097 }
1098
1099 Type *Ty = Val->getType();
1100 if (!Ty->isIntegerTy())
1101 return ValueLatticeElement::getOverdefined();
1102
1103 unsigned BitWidth = Ty->getScalarSizeInBits();
1104 APInt Offset(BitWidth, 0);
1105 if (matchICmpOperand(Offset, LHS, Val, EdgePred))
1106 return getValueFromSimpleICmpCondition(EdgePred, RHS, Offset);
1107
1108 CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(EdgePred);
1109 if (matchICmpOperand(Offset, RHS, Val, SwappedPred))
1110 return getValueFromSimpleICmpCondition(SwappedPred, LHS, Offset);
1111
1112 const APInt *Mask, *C;
1113 if (match(LHS, m_And(m_Specific(Val), m_APInt(Mask))) &&
1114 match(RHS, m_APInt(C))) {
1115 // If (Val & Mask) == C then all the masked bits are known and we can
1116 // compute a value range based on that.
1117 if (EdgePred == ICmpInst::ICMP_EQ) {
1118 KnownBits Known;
1119 Known.Zero = ~*C & *Mask;
1120 Known.One = *C & *Mask;
1121 return ValueLatticeElement::getRange(
1122 ConstantRange::fromKnownBits(Known, /*IsSigned*/ false));
1123 }
1124 // If (Val & Mask) != 0 then the value must be larger than the lowest set
1125 // bit of Mask.
1126 if (EdgePred == ICmpInst::ICMP_NE && !Mask->isZero() && C->isZero()) {
1127 return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
1128 APInt::getOneBitSet(BitWidth, Mask->countTrailingZeros()),
1129 APInt::getZero(BitWidth)));
1130 }
1131 }
1132
1133 // If (X urem Modulus) >= C, then X >= C.
1134 // If trunc X >= C, then X >= C.
1135 // TODO: An upper bound could be computed as well.
1136 if (match(LHS, m_CombineOr(m_URem(m_Specific(Val), m_Value()),
1137 m_Trunc(m_Specific(Val)))) &&
1138 match(RHS, m_APInt(C))) {
1139 // Use the icmp region so we don't have to deal with different predicates.
1140 ConstantRange CR = ConstantRange::makeExactICmpRegion(EdgePred, *C);
1141 if (!CR.isEmptySet())
1142 return ValueLatticeElement::getRange(ConstantRange::getNonEmpty(
1143 CR.getUnsignedMin().zextOrSelf(BitWidth), APInt(BitWidth, 0)));
1144 }
1145
1146 return ValueLatticeElement::getOverdefined();
1147}
1148
1149// Handle conditions of the form
1150// extractvalue(op.with.overflow(%x, C), 1).
1151static ValueLatticeElement getValueFromOverflowCondition(
1152 Value *Val, WithOverflowInst *WO, bool IsTrueDest) {
1153 // TODO: This only works with a constant RHS for now. We could also compute
1154 // the range of the RHS, but this doesn't fit into the current structure of
1155 // the edge value calculation.
1156 const APInt *C;
1157 if (WO->getLHS() != Val || !match(WO->getRHS(), m_APInt(C)))
1158 return ValueLatticeElement::getOverdefined();
1159
1160 // Calculate the possible values of %x for which no overflow occurs.
1161 ConstantRange NWR = ConstantRange::makeExactNoWrapRegion(
1162 WO->getBinaryOp(), *C, WO->getNoWrapKind());
1163
1164 // If overflow is false, %x is constrained to NWR. If overflow is true, %x is
1165 // constrained to it's inverse (all values that might cause overflow).
1166 if (IsTrueDest)
1167 NWR = NWR.inverse();
1168 return ValueLatticeElement::getRange(NWR);
1169}
1170
1171static Optional<ValueLatticeElement>
1172getValueFromConditionImpl(Value *Val, Value *Cond, bool isTrueDest,
1173 bool isRevisit,
1174 SmallDenseMap<Value *, ValueLatticeElement> &Visited,
1175 SmallVectorImpl<Value *> &Worklist) {
1176 if (!isRevisit) {
1177 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Cond))
1178 return getValueFromICmpCondition(Val, ICI, isTrueDest);
1179
1180 if (auto *EVI = dyn_cast<ExtractValueInst>(Cond))
1181 if (auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand()))
1182 if (EVI->getNumIndices() == 1 && *EVI->idx_begin() == 1)
1183 return getValueFromOverflowCondition(Val, WO, isTrueDest);
1184 }
1185
1186 Value *L, *R;
1187 bool IsAnd;
1188 if (match(Cond, m_LogicalAnd(m_Value(L), m_Value(R))))
1189 IsAnd = true;
1190 else if (match(Cond, m_LogicalOr(m_Value(L), m_Value(R))))
1191 IsAnd = false;
1192 else
1193 return ValueLatticeElement::getOverdefined();
1194
1195 auto LV = Visited.find(L);
1196 auto RV = Visited.find(R);
1197
1198 // if (L && R) -> intersect L and R
1199 // if (!(L || R)) -> intersect L and R
1200 // if (L || R) -> union L and R
1201 // if (!(L && R)) -> union L and R
1202 if ((isTrueDest ^ IsAnd) && (LV != Visited.end())) {
1203 ValueLatticeElement V = LV->second;
1204 if (V.isOverdefined())
1205 return V;
1206 if (RV != Visited.end()) {
1207 V.mergeIn(RV->second);
1208 return V;
1209 }
1210 }
1211
1212 if (LV == Visited.end() || RV == Visited.end()) {
1213 assert(!isRevisit)(static_cast <bool> (!isRevisit) ? void (0) : __assert_fail
("!isRevisit", "llvm/lib/Analysis/LazyValueInfo.cpp", 1213, __extension__
__PRETTY_FUNCTION__))
;
1214 if (LV == Visited.end())
1215 Worklist.push_back(L);
1216 if (RV == Visited.end())
1217 Worklist.push_back(R);
1218 return None;
1219 }
1220
1221 return intersect(LV->second, RV->second);
1222}
1223
1224ValueLatticeElement getValueFromCondition(Value *Val, Value *Cond,
1225 bool isTrueDest) {
1226 assert(Cond && "precondition")(static_cast <bool> (Cond && "precondition") ? void
(0) : __assert_fail ("Cond && \"precondition\"", "llvm/lib/Analysis/LazyValueInfo.cpp"
, 1226, __extension__ __PRETTY_FUNCTION__))
;
1227 SmallDenseMap<Value*, ValueLatticeElement> Visited;
1228 SmallVector<Value *> Worklist;
1229
1230 Worklist.push_back(Cond);
1231 do {
1232 Value *CurrentCond = Worklist.back();
1233 // Insert an Overdefined placeholder into the set to prevent
1234 // infinite recursion if there exists IRs that use not
1235 // dominated by its def as in this example:
1236 // "%tmp3 = or i1 undef, %tmp4"
1237 // "%tmp4 = or i1 undef, %tmp3"
1238 auto Iter =
1239 Visited.try_emplace(CurrentCond, ValueLatticeElement::getOverdefined());
1240 bool isRevisit = !Iter.second;
1241 Optional<ValueLatticeElement> Result = getValueFromConditionImpl(
1242 Val, CurrentCond, isTrueDest, isRevisit, Visited, Worklist);
1243 if (Result) {
1244 Visited[CurrentCond] = *Result;
1245 Worklist.pop_back();
1246 }
1247 } while (!Worklist.empty());
1248
1249 auto Result = Visited.find(Cond);
1250 assert(Result != Visited.end())(static_cast <bool> (Result != Visited.end()) ? void (0
) : __assert_fail ("Result != Visited.end()", "llvm/lib/Analysis/LazyValueInfo.cpp"
, 1250, __extension__ __PRETTY_FUNCTION__))
;
1251 return Result->second;
1252}
1253
1254// Return true if Usr has Op as an operand, otherwise false.
1255static bool usesOperand(User *Usr, Value *Op) {
1256 return is_contained(Usr->operands(), Op);
1257}
1258
1259// Return true if the instruction type of Val is supported by
1260// constantFoldUser(). Currently CastInst, BinaryOperator and FreezeInst only.
1261// Call this before calling constantFoldUser() to find out if it's even worth
1262// attempting to call it.
1263static bool isOperationFoldable(User *Usr) {
1264 return isa<CastInst>(Usr) || isa<BinaryOperator>(Usr) || isa<FreezeInst>(Usr);
1265}
1266
1267// Check if Usr can be simplified to an integer constant when the value of one
1268// of its operands Op is an integer constant OpConstVal. If so, return it as an
1269// lattice value range with a single element or otherwise return an overdefined
1270// lattice value.
1271static ValueLatticeElement constantFoldUser(User *Usr, Value *Op,
1272 const APInt &OpConstVal,
1273 const DataLayout &DL) {
1274 assert(isOperationFoldable(Usr) && "Precondition")(static_cast <bool> (isOperationFoldable(Usr) &&
"Precondition") ? void (0) : __assert_fail ("isOperationFoldable(Usr) && \"Precondition\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1274, __extension__ __PRETTY_FUNCTION__
))
;
1275 Constant* OpConst = Constant::getIntegerValue(Op->getType(), OpConstVal);
1276 // Check if Usr can be simplified to a constant.
1277 if (auto *CI = dyn_cast<CastInst>(Usr)) {
1278 assert(CI->getOperand(0) == Op && "Operand 0 isn't Op")(static_cast <bool> (CI->getOperand(0) == Op &&
"Operand 0 isn't Op") ? void (0) : __assert_fail ("CI->getOperand(0) == Op && \"Operand 0 isn't Op\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1278, __extension__ __PRETTY_FUNCTION__
))
;
1279 if (auto *C = dyn_cast_or_null<ConstantInt>(
1280 SimplifyCastInst(CI->getOpcode(), OpConst,
1281 CI->getDestTy(), DL))) {
1282 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1283 }
1284 } else if (auto *BO = dyn_cast<BinaryOperator>(Usr)) {
1285 bool Op0Match = BO->getOperand(0) == Op;
1286 bool Op1Match = BO->getOperand(1) == Op;
1287 assert((Op0Match || Op1Match) &&(static_cast <bool> ((Op0Match || Op1Match) && "Operand 0 nor Operand 1 isn't a match"
) ? void (0) : __assert_fail ("(Op0Match || Op1Match) && \"Operand 0 nor Operand 1 isn't a match\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1288, __extension__ __PRETTY_FUNCTION__
))
1288 "Operand 0 nor Operand 1 isn't a match")(static_cast <bool> ((Op0Match || Op1Match) && "Operand 0 nor Operand 1 isn't a match"
) ? void (0) : __assert_fail ("(Op0Match || Op1Match) && \"Operand 0 nor Operand 1 isn't a match\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1288, __extension__ __PRETTY_FUNCTION__
))
;
1289 Value *LHS = Op0Match ? OpConst : BO->getOperand(0);
1290 Value *RHS = Op1Match ? OpConst : BO->getOperand(1);
1291 if (auto *C = dyn_cast_or_null<ConstantInt>(
1292 SimplifyBinOp(BO->getOpcode(), LHS, RHS, DL))) {
1293 return ValueLatticeElement::getRange(ConstantRange(C->getValue()));
1294 }
1295 } else if (isa<FreezeInst>(Usr)) {
1296 assert(cast<FreezeInst>(Usr)->getOperand(0) == Op && "Operand 0 isn't Op")(static_cast <bool> (cast<FreezeInst>(Usr)->getOperand
(0) == Op && "Operand 0 isn't Op") ? void (0) : __assert_fail
("cast<FreezeInst>(Usr)->getOperand(0) == Op && \"Operand 0 isn't Op\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1296, __extension__ __PRETTY_FUNCTION__
))
;
1297 return ValueLatticeElement::getRange(ConstantRange(OpConstVal));
1298 }
1299 return ValueLatticeElement::getOverdefined();
1300}
1301
1302/// Compute the value of Val on the edge BBFrom -> BBTo. Returns false if
1303/// Val is not constrained on the edge. Result is unspecified if return value
1304/// is false.
1305static Optional<ValueLatticeElement> getEdgeValueLocal(Value *Val,
1306 BasicBlock *BBFrom,
1307 BasicBlock *BBTo) {
1308 // TODO: Handle more complex conditionals. If (v == 0 || v2 < 1) is false, we
1309 // know that v != 0.
1310 if (BranchInst *BI = dyn_cast<BranchInst>(BBFrom->getTerminator())) {
1311 // If this is a conditional branch and only one successor goes to BBTo, then
1312 // we may be able to infer something from the condition.
1313 if (BI->isConditional() &&
1314 BI->getSuccessor(0) != BI->getSuccessor(1)) {
1315 bool isTrueDest = BI->getSuccessor(0) == BBTo;
1316 assert(BI->getSuccessor(!isTrueDest) == BBTo &&(static_cast <bool> (BI->getSuccessor(!isTrueDest) ==
BBTo && "BBTo isn't a successor of BBFrom") ? void (
0) : __assert_fail ("BI->getSuccessor(!isTrueDest) == BBTo && \"BBTo isn't a successor of BBFrom\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1317, __extension__ __PRETTY_FUNCTION__
))
1317 "BBTo isn't a successor of BBFrom")(static_cast <bool> (BI->getSuccessor(!isTrueDest) ==
BBTo && "BBTo isn't a successor of BBFrom") ? void (
0) : __assert_fail ("BI->getSuccessor(!isTrueDest) == BBTo && \"BBTo isn't a successor of BBFrom\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1317, __extension__ __PRETTY_FUNCTION__
))
;
1318 Value *Condition = BI->getCondition();
1319
1320 // If V is the condition of the branch itself, then we know exactly what
1321 // it is.
1322 if (Condition == Val)
1323 return ValueLatticeElement::get(ConstantInt::get(
1324 Type::getInt1Ty(Val->getContext()), isTrueDest));
1325
1326 // If the condition of the branch is an equality comparison, we may be
1327 // able to infer the value.
1328 ValueLatticeElement Result = getValueFromCondition(Val, Condition,
1329 isTrueDest);
1330 if (!Result.isOverdefined())
1331 return Result;
1332
1333 if (User *Usr = dyn_cast<User>(Val)) {
1334 assert(Result.isOverdefined() && "Result isn't overdefined")(static_cast <bool> (Result.isOverdefined() && "Result isn't overdefined"
) ? void (0) : __assert_fail ("Result.isOverdefined() && \"Result isn't overdefined\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1334, __extension__ __PRETTY_FUNCTION__
))
;
1335 // Check with isOperationFoldable() first to avoid linearly iterating
1336 // over the operands unnecessarily which can be expensive for
1337 // instructions with many operands.
1338 if (isa<IntegerType>(Usr->getType()) && isOperationFoldable(Usr)) {
1339 const DataLayout &DL = BBTo->getModule()->getDataLayout();
1340 if (usesOperand(Usr, Condition)) {
1341 // If Val has Condition as an operand and Val can be folded into a
1342 // constant with either Condition == true or Condition == false,
1343 // propagate the constant.
1344 // eg.
1345 // ; %Val is true on the edge to %then.
1346 // %Val = and i1 %Condition, true.
1347 // br %Condition, label %then, label %else
1348 APInt ConditionVal(1, isTrueDest ? 1 : 0);
1349 Result = constantFoldUser(Usr, Condition, ConditionVal, DL);
1350 } else {
1351 // If one of Val's operand has an inferred value, we may be able to
1352 // infer the value of Val.
1353 // eg.
1354 // ; %Val is 94 on the edge to %then.
1355 // %Val = add i8 %Op, 1
1356 // %Condition = icmp eq i8 %Op, 93
1357 // br i1 %Condition, label %then, label %else
1358 for (unsigned i = 0; i < Usr->getNumOperands(); ++i) {
1359 Value *Op = Usr->getOperand(i);
1360 ValueLatticeElement OpLatticeVal =
1361 getValueFromCondition(Op, Condition, isTrueDest);
1362 if (Optional<APInt> OpConst = OpLatticeVal.asConstantInteger()) {
1363 Result = constantFoldUser(Usr, Op, OpConst.getValue(), DL);
1364 break;
1365 }
1366 }
1367 }
1368 }
1369 }
1370 if (!Result.isOverdefined())
1371 return Result;
1372 }
1373 }
1374
1375 // If the edge was formed by a switch on the value, then we may know exactly
1376 // what it is.
1377 if (SwitchInst *SI = dyn_cast<SwitchInst>(BBFrom->getTerminator())) {
1378 Value *Condition = SI->getCondition();
1379 if (!isa<IntegerType>(Val->getType()))
1380 return None;
1381 bool ValUsesConditionAndMayBeFoldable = false;
1382 if (Condition != Val) {
1383 // Check if Val has Condition as an operand.
1384 if (User *Usr = dyn_cast<User>(Val))
1385 ValUsesConditionAndMayBeFoldable = isOperationFoldable(Usr) &&
1386 usesOperand(Usr, Condition);
1387 if (!ValUsesConditionAndMayBeFoldable)
1388 return None;
1389 }
1390 assert((Condition == Val || ValUsesConditionAndMayBeFoldable) &&(static_cast <bool> ((Condition == Val || ValUsesConditionAndMayBeFoldable
) && "Condition != Val nor Val doesn't use Condition"
) ? void (0) : __assert_fail ("(Condition == Val || ValUsesConditionAndMayBeFoldable) && \"Condition != Val nor Val doesn't use Condition\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1391, __extension__ __PRETTY_FUNCTION__
))
1391 "Condition != Val nor Val doesn't use Condition")(static_cast <bool> ((Condition == Val || ValUsesConditionAndMayBeFoldable
) && "Condition != Val nor Val doesn't use Condition"
) ? void (0) : __assert_fail ("(Condition == Val || ValUsesConditionAndMayBeFoldable) && \"Condition != Val nor Val doesn't use Condition\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1391, __extension__ __PRETTY_FUNCTION__
))
;
1392
1393 bool DefaultCase = SI->getDefaultDest() == BBTo;
1394 unsigned BitWidth = Val->getType()->getIntegerBitWidth();
1395 ConstantRange EdgesVals(BitWidth, DefaultCase/*isFullSet*/);
1396
1397 for (auto Case : SI->cases()) {
1398 APInt CaseValue = Case.getCaseValue()->getValue();
1399 ConstantRange EdgeVal(CaseValue);
1400 if (ValUsesConditionAndMayBeFoldable) {
1401 User *Usr = cast<User>(Val);
1402 const DataLayout &DL = BBTo->getModule()->getDataLayout();
1403 ValueLatticeElement EdgeLatticeVal =
1404 constantFoldUser(Usr, Condition, CaseValue, DL);
1405 if (EdgeLatticeVal.isOverdefined())
1406 return None;
1407 EdgeVal = EdgeLatticeVal.getConstantRange();
1408 }
1409 if (DefaultCase) {
1410 // It is possible that the default destination is the destination of
1411 // some cases. We cannot perform difference for those cases.
1412 // We know Condition != CaseValue in BBTo. In some cases we can use
1413 // this to infer Val == f(Condition) is != f(CaseValue). For now, we
1414 // only do this when f is identity (i.e. Val == Condition), but we
1415 // should be able to do this for any injective f.
1416 if (Case.getCaseSuccessor() != BBTo && Condition == Val)
1417 EdgesVals = EdgesVals.difference(EdgeVal);
1418 } else if (Case.getCaseSuccessor() == BBTo)
1419 EdgesVals = EdgesVals.unionWith(EdgeVal);
1420 }
1421 return ValueLatticeElement::getRange(std::move(EdgesVals));
1422 }
1423 return None;
1424}
1425
1426/// Compute the value of Val on the edge BBFrom -> BBTo or the value at
1427/// the basic block if the edge does not constrain Val.
1428Optional<ValueLatticeElement> LazyValueInfoImpl::getEdgeValue(
1429 Value *Val, BasicBlock *BBFrom, BasicBlock *BBTo, Instruction *CxtI) {
1430 // If already a constant, there is nothing to compute.
1431 if (Constant *VC = dyn_cast<Constant>(Val))
1432 return ValueLatticeElement::get(VC);
1433
1434 ValueLatticeElement LocalResult = getEdgeValueLocal(Val, BBFrom, BBTo)
1435 .getValueOr(ValueLatticeElement::getOverdefined());
1436 if (hasSingleValue(LocalResult))
1437 // Can't get any more precise here
1438 return LocalResult;
1439
1440 Optional<ValueLatticeElement> OptInBlock =
1441 getBlockValue(Val, BBFrom, BBFrom->getTerminator());
1442 if (!OptInBlock)
1443 return None;
1444 ValueLatticeElement &InBlock = *OptInBlock;
1445
1446 // We can use the context instruction (generically the ultimate instruction
1447 // the calling pass is trying to simplify) here, even though the result of
1448 // this function is generally cached when called from the solve* functions
1449 // (and that cached result might be used with queries using a different
1450 // context instruction), because when this function is called from the solve*
1451 // functions, the context instruction is not provided. When called from
1452 // LazyValueInfoImpl::getValueOnEdge, the context instruction is provided,
1453 // but then the result is not cached.
1454 intersectAssumeOrGuardBlockValueConstantRange(Val, InBlock, CxtI);
1455
1456 return intersect(LocalResult, InBlock);
1457}
1458
1459ValueLatticeElement LazyValueInfoImpl::getValueInBlock(Value *V, BasicBlock *BB,
1460 Instruction *CxtI) {
1461 LLVM_DEBUG(dbgs() << "LVI Getting block end value " << *V << " at '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting block end value "
<< *V << " at '" << BB->getName() <<
"'\n"; } } while (false)
1462 << BB->getName() << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting block end value "
<< *V << " at '" << BB->getName() <<
"'\n"; } } while (false)
;
1463
1464 assert(BlockValueStack.empty() && BlockValueSet.empty())(static_cast <bool> (BlockValueStack.empty() &&
BlockValueSet.empty()) ? void (0) : __assert_fail ("BlockValueStack.empty() && BlockValueSet.empty()"
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1464, __extension__ __PRETTY_FUNCTION__
))
;
1465 Optional<ValueLatticeElement> OptResult = getBlockValue(V, BB, CxtI);
1466 if (!OptResult) {
1467 solve();
1468 OptResult = getBlockValue(V, BB, CxtI);
1469 assert(OptResult && "Value not available after solving")(static_cast <bool> (OptResult && "Value not available after solving"
) ? void (0) : __assert_fail ("OptResult && \"Value not available after solving\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1469, __extension__ __PRETTY_FUNCTION__
))
;
1470 }
1471
1472 ValueLatticeElement Result = *OptResult;
1473 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " Result = " <<
Result << "\n"; } } while (false)
;
1474 return Result;
1475}
1476
1477ValueLatticeElement LazyValueInfoImpl::getValueAt(Value *V, Instruction *CxtI) {
1478 LLVM_DEBUG(dbgs() << "LVI Getting value " << *V << " at '" << CxtI->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting value " <<
*V << " at '" << CxtI->getName() << "'\n"
; } } while (false)
1479 << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting value " <<
*V << " at '" << CxtI->getName() << "'\n"
; } } while (false)
;
1480
1481 if (auto *C = dyn_cast<Constant>(V))
1482 return ValueLatticeElement::get(C);
1483
1484 ValueLatticeElement Result = ValueLatticeElement::getOverdefined();
1485 if (auto *I = dyn_cast<Instruction>(V))
1486 Result = getFromRangeMetadata(I);
1487 intersectAssumeOrGuardBlockValueConstantRange(V, Result, CxtI);
1488
1489 LLVM_DEBUG(dbgs() << " Result = " << Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " Result = " <<
Result << "\n"; } } while (false)
;
1490 return Result;
1491}
1492
1493ValueLatticeElement LazyValueInfoImpl::
1494getValueOnEdge(Value *V, BasicBlock *FromBB, BasicBlock *ToBB,
1495 Instruction *CxtI) {
1496 LLVM_DEBUG(dbgs() << "LVI Getting edge value " << *V << " from '"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting edge value "
<< *V << " from '" << FromBB->getName()
<< "' to '" << ToBB->getName() << "'\n"
; } } while (false)
1497 << FromBB->getName() << "' to '" << ToBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting edge value "
<< *V << " from '" << FromBB->getName()
<< "' to '" << ToBB->getName() << "'\n"
; } } while (false)
1498 << "'\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << "LVI Getting edge value "
<< *V << " from '" << FromBB->getName()
<< "' to '" << ToBB->getName() << "'\n"
; } } while (false)
;
1499
1500 Optional<ValueLatticeElement> Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1501 if (!Result) {
1502 solve();
1503 Result = getEdgeValue(V, FromBB, ToBB, CxtI);
1504 assert(Result && "More work to do after problem solved?")(static_cast <bool> (Result && "More work to do after problem solved?"
) ? void (0) : __assert_fail ("Result && \"More work to do after problem solved?\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1504, __extension__ __PRETTY_FUNCTION__
))
;
1505 }
1506
1507 LLVM_DEBUG(dbgs() << " Result = " << *Result << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("lazy-value-info")) { dbgs() << " Result = " <<
*Result << "\n"; } } while (false)
;
1508 return *Result;
1509}
1510
1511void LazyValueInfoImpl::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1512 BasicBlock *NewSucc) {
1513 TheCache.threadEdgeImpl(OldSucc, NewSucc);
1514}
1515
1516//===----------------------------------------------------------------------===//
1517// LazyValueInfo Impl
1518//===----------------------------------------------------------------------===//
1519
1520/// This lazily constructs the LazyValueInfoImpl.
1521static LazyValueInfoImpl &getImpl(void *&PImpl, AssumptionCache *AC,
1522 const Module *M) {
1523 if (!PImpl) {
1524 assert(M && "getCache() called with a null Module")(static_cast <bool> (M && "getCache() called with a null Module"
) ? void (0) : __assert_fail ("M && \"getCache() called with a null Module\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1524, __extension__ __PRETTY_FUNCTION__
))
;
1525 const DataLayout &DL = M->getDataLayout();
1526 Function *GuardDecl = M->getFunction(
1527 Intrinsic::getName(Intrinsic::experimental_guard));
1528 PImpl = new LazyValueInfoImpl(AC, DL, GuardDecl);
1529 }
1530 return *static_cast<LazyValueInfoImpl*>(PImpl);
1531}
1532
1533bool LazyValueInfoWrapperPass::runOnFunction(Function &F) {
1534 Info.AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1535 Info.TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1536
1537 if (Info.PImpl)
1538 getImpl(Info.PImpl, Info.AC, F.getParent()).clear();
1539
1540 // Fully lazy.
1541 return false;
1542}
1543
1544void LazyValueInfoWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
1545 AU.setPreservesAll();
1546 AU.addRequired<AssumptionCacheTracker>();
1547 AU.addRequired<TargetLibraryInfoWrapperPass>();
1548}
1549
1550LazyValueInfo &LazyValueInfoWrapperPass::getLVI() { return Info; }
1551
1552LazyValueInfo::~LazyValueInfo() { releaseMemory(); }
1553
1554void LazyValueInfo::releaseMemory() {
1555 // If the cache was allocated, free it.
1556 if (PImpl) {
1557 delete &getImpl(PImpl, AC, nullptr);
1558 PImpl = nullptr;
1559 }
1560}
1561
1562bool LazyValueInfo::invalidate(Function &F, const PreservedAnalyses &PA,
1563 FunctionAnalysisManager::Invalidator &Inv) {
1564 // We need to invalidate if we have either failed to preserve this analyses
1565 // result directly or if any of its dependencies have been invalidated.
1566 auto PAC = PA.getChecker<LazyValueAnalysis>();
1567 if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()))
1568 return true;
1569
1570 return false;
1571}
1572
1573void LazyValueInfoWrapperPass::releaseMemory() { Info.releaseMemory(); }
1574
1575LazyValueInfo LazyValueAnalysis::run(Function &F,
1576 FunctionAnalysisManager &FAM) {
1577 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1578 auto &TLI = FAM.getResult<TargetLibraryAnalysis>(F);
1579
1580 return LazyValueInfo(&AC, &F.getParent()->getDataLayout(), &TLI);
1581}
1582
1583/// Returns true if we can statically tell that this value will never be a
1584/// "useful" constant. In practice, this means we've got something like an
1585/// alloca or a malloc call for which a comparison against a constant can
1586/// only be guarding dead code. Note that we are potentially giving up some
1587/// precision in dead code (a constant result) in favour of avoiding a
1588/// expensive search for a easily answered common query.
1589static bool isKnownNonConstant(Value *V) {
1590 V = V->stripPointerCasts();
1591 // The return val of alloc cannot be a Constant.
1592 if (isa<AllocaInst>(V))
1593 return true;
1594 return false;
1595}
1596
1597Constant *LazyValueInfo::getConstant(Value *V, Instruction *CxtI) {
1598 // Bail out early if V is known not to be a Constant.
1599 if (isKnownNonConstant(V))
1600 return nullptr;
1601
1602 BasicBlock *BB = CxtI->getParent();
1603 ValueLatticeElement Result =
1604 getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
1605
1606 if (Result.isConstant())
1607 return Result.getConstant();
1608 if (Result.isConstantRange()) {
1609 const ConstantRange &CR = Result.getConstantRange();
1610 if (const APInt *SingleVal = CR.getSingleElement())
1611 return ConstantInt::get(V->getContext(), *SingleVal);
1612 }
1613 return nullptr;
1614}
1615
1616ConstantRange LazyValueInfo::getConstantRange(Value *V, Instruction *CxtI,
1617 bool UndefAllowed) {
1618 assert(V->getType()->isIntegerTy())(static_cast <bool> (V->getType()->isIntegerTy())
? void (0) : __assert_fail ("V->getType()->isIntegerTy()"
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1618, __extension__ __PRETTY_FUNCTION__
))
;
1619 unsigned Width = V->getType()->getIntegerBitWidth();
1620 BasicBlock *BB = CxtI->getParent();
1621 ValueLatticeElement Result =
1622 getImpl(PImpl, AC, BB->getModule()).getValueInBlock(V, BB, CxtI);
1623 if (Result.isUnknown())
1624 return ConstantRange::getEmpty(Width);
1625 if (Result.isConstantRange(UndefAllowed))
1626 return Result.getConstantRange(UndefAllowed);
1627 // We represent ConstantInt constants as constant ranges but other kinds
1628 // of integer constants, i.e. ConstantExpr will be tagged as constants
1629 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&(static_cast <bool> (!(Result.isConstant() && isa
<ConstantInt>(Result.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? void (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1630, __extension__ __PRETTY_FUNCTION__
))
1630 "ConstantInt value must be represented as constantrange")(static_cast <bool> (!(Result.isConstant() && isa
<ConstantInt>(Result.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? void (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1630, __extension__ __PRETTY_FUNCTION__
))
;
1631 return ConstantRange::getFull(Width);
1632}
1633
1634/// Determine whether the specified value is known to be a
1635/// constant on the specified edge. Return null if not.
1636Constant *LazyValueInfo::getConstantOnEdge(Value *V, BasicBlock *FromBB,
1637 BasicBlock *ToBB,
1638 Instruction *CxtI) {
1639 Module *M = FromBB->getModule();
1640 ValueLatticeElement Result =
1641 getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1642
1643 if (Result.isConstant())
1644 return Result.getConstant();
1645 if (Result.isConstantRange()) {
1646 const ConstantRange &CR = Result.getConstantRange();
1647 if (const APInt *SingleVal = CR.getSingleElement())
1648 return ConstantInt::get(V->getContext(), *SingleVal);
1649 }
1650 return nullptr;
1651}
1652
1653ConstantRange LazyValueInfo::getConstantRangeOnEdge(Value *V,
1654 BasicBlock *FromBB,
1655 BasicBlock *ToBB,
1656 Instruction *CxtI) {
1657 unsigned Width = V->getType()->getIntegerBitWidth();
1658 Module *M = FromBB->getModule();
1659 ValueLatticeElement Result =
1660 getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1661
1662 if (Result.isUnknown())
1
Assuming the condition is false
2
Taking false branch
1663 return ConstantRange::getEmpty(Width);
1664 if (Result.isConstantRange())
3
Taking true branch
1665 return Result.getConstantRange();
4
Calling implicit copy constructor for 'ConstantRange'
5
Calling copy constructor for 'APInt'
1666 // We represent ConstantInt constants as constant ranges but other kinds
1667 // of integer constants, i.e. ConstantExpr will be tagged as constants
1668 assert(!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) &&(static_cast <bool> (!(Result.isConstant() && isa
<ConstantInt>(Result.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? void (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1669, __extension__ __PRETTY_FUNCTION__
))
1669 "ConstantInt value must be represented as constantrange")(static_cast <bool> (!(Result.isConstant() && isa
<ConstantInt>(Result.getConstant())) && "ConstantInt value must be represented as constantrange"
) ? void (0) : __assert_fail ("!(Result.isConstant() && isa<ConstantInt>(Result.getConstant())) && \"ConstantInt value must be represented as constantrange\""
, "llvm/lib/Analysis/LazyValueInfo.cpp", 1669, __extension__ __PRETTY_FUNCTION__
))
;
1670 return ConstantRange::getFull(Width);
1671}
1672
1673static LazyValueInfo::Tristate
1674getPredicateResult(unsigned Pred, Constant *C, const ValueLatticeElement &Val,
1675 const DataLayout &DL, TargetLibraryInfo *TLI) {
1676 // If we know the value is a constant, evaluate the conditional.
1677 Constant *Res = nullptr;
1678 if (Val.isConstant()) {
1679 Res = ConstantFoldCompareInstOperands(Pred, Val.getConstant(), C, DL, TLI);
1680 if (ConstantInt *ResCI = dyn_cast<ConstantInt>(Res))
1681 return ResCI->isZero() ? LazyValueInfo::False : LazyValueInfo::True;
1682 return LazyValueInfo::Unknown;
1683 }
1684
1685 if (Val.isConstantRange()) {
1686 ConstantInt *CI = dyn_cast<ConstantInt>(C);
1687 if (!CI) return LazyValueInfo::Unknown;
1688
1689 const ConstantRange &CR = Val.getConstantRange();
1690 if (Pred == ICmpInst::ICMP_EQ) {
1691 if (!CR.contains(CI->getValue()))
1692 return LazyValueInfo::False;
1693
1694 if (CR.isSingleElement())
1695 return LazyValueInfo::True;
1696 } else if (Pred == ICmpInst::ICMP_NE) {
1697 if (!CR.contains(CI->getValue()))
1698 return LazyValueInfo::True;
1699
1700 if (CR.isSingleElement())
1701 return LazyValueInfo::False;
1702 } else {
1703 // Handle more complex predicates.
1704 ConstantRange TrueValues = ConstantRange::makeExactICmpRegion(
1705 (ICmpInst::Predicate)Pred, CI->getValue());
1706 if (TrueValues.contains(CR))
1707 return LazyValueInfo::True;
1708 if (TrueValues.inverse().contains(CR))
1709 return LazyValueInfo::False;
1710 }
1711 return LazyValueInfo::Unknown;
1712 }
1713
1714 if (Val.isNotConstant()) {
1715 // If this is an equality comparison, we can try to fold it knowing that
1716 // "V != C1".
1717 if (Pred == ICmpInst::ICMP_EQ) {
1718 // !C1 == C -> false iff C1 == C.
1719 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1720 Val.getNotConstant(), C, DL,
1721 TLI);
1722 if (Res->isNullValue())
1723 return LazyValueInfo::False;
1724 } else if (Pred == ICmpInst::ICMP_NE) {
1725 // !C1 != C -> true iff C1 == C.
1726 Res = ConstantFoldCompareInstOperands(ICmpInst::ICMP_NE,
1727 Val.getNotConstant(), C, DL,
1728 TLI);
1729 if (Res->isNullValue())
1730 return LazyValueInfo::True;
1731 }
1732 return LazyValueInfo::Unknown;
1733 }
1734
1735 return LazyValueInfo::Unknown;
1736}
1737
1738/// Determine whether the specified value comparison with a constant is known to
1739/// be true or false on the specified CFG edge. Pred is a CmpInst predicate.
1740LazyValueInfo::Tristate
1741LazyValueInfo::getPredicateOnEdge(unsigned Pred, Value *V, Constant *C,
1742 BasicBlock *FromBB, BasicBlock *ToBB,
1743 Instruction *CxtI) {
1744 Module *M = FromBB->getModule();
1745 ValueLatticeElement Result =
1746 getImpl(PImpl, AC, M).getValueOnEdge(V, FromBB, ToBB, CxtI);
1747
1748 return getPredicateResult(Pred, C, Result, M->getDataLayout(), TLI);
1749}
1750
1751LazyValueInfo::Tristate
1752LazyValueInfo::getPredicateAt(unsigned Pred, Value *V, Constant *C,
1753 Instruction *CxtI, bool UseBlockValue) {
1754 // Is or is not NonNull are common predicates being queried. If
1755 // isKnownNonZero can tell us the result of the predicate, we can
1756 // return it quickly. But this is only a fastpath, and falling
1757 // through would still be correct.
1758 Module *M = CxtI->getModule();
1759 const DataLayout &DL = M->getDataLayout();
1760 if (V->getType()->isPointerTy() && C->isNullValue() &&
1761 isKnownNonZero(V->stripPointerCastsSameRepresentation(), DL)) {
1762 if (Pred == ICmpInst::ICMP_EQ)
1763 return LazyValueInfo::False;
1764 else if (Pred == ICmpInst::ICMP_NE)
1765 return LazyValueInfo::True;
1766 }
1767
1768 ValueLatticeElement Result = UseBlockValue
1769 ? getImpl(PImpl, AC, M).getValueInBlock(V, CxtI->getParent(), CxtI)
1770 : getImpl(PImpl, AC, M).getValueAt(V, CxtI);
1771 Tristate Ret = getPredicateResult(Pred, C, Result, DL, TLI);
1772 if (Ret != Unknown)
1773 return Ret;
1774
1775 // Note: The following bit of code is somewhat distinct from the rest of LVI;
1776 // LVI as a whole tries to compute a lattice value which is conservatively
1777 // correct at a given location. In this case, we have a predicate which we
1778 // weren't able to prove about the merged result, and we're pushing that
1779 // predicate back along each incoming edge to see if we can prove it
1780 // separately for each input. As a motivating example, consider:
1781 // bb1:
1782 // %v1 = ... ; constantrange<1, 5>
1783 // br label %merge
1784 // bb2:
1785 // %v2 = ... ; constantrange<10, 20>
1786 // br label %merge
1787 // merge:
1788 // %phi = phi [%v1, %v2] ; constantrange<1,20>
1789 // %pred = icmp eq i32 %phi, 8
1790 // We can't tell from the lattice value for '%phi' that '%pred' is false
1791 // along each path, but by checking the predicate over each input separately,
1792 // we can.
1793 // We limit the search to one step backwards from the current BB and value.
1794 // We could consider extending this to search further backwards through the
1795 // CFG and/or value graph, but there are non-obvious compile time vs quality
1796 // tradeoffs.
1797 BasicBlock *BB = CxtI->getParent();
1798
1799 // Function entry or an unreachable block. Bail to avoid confusing
1800 // analysis below.
1801 pred_iterator PI = pred_begin(BB), PE = pred_end(BB);
1802 if (PI == PE)
1803 return Unknown;
1804
1805 // If V is a PHI node in the same block as the context, we need to ask
1806 // questions about the predicate as applied to the incoming value along
1807 // each edge. This is useful for eliminating cases where the predicate is
1808 // known along all incoming edges.
1809 if (auto *PHI = dyn_cast<PHINode>(V))
1810 if (PHI->getParent() == BB) {
1811 Tristate Baseline = Unknown;
1812 for (unsigned i = 0, e = PHI->getNumIncomingValues(); i < e; i++) {
1813 Value *Incoming = PHI->getIncomingValue(i);
1814 BasicBlock *PredBB = PHI->getIncomingBlock(i);
1815 // Note that PredBB may be BB itself.
1816 Tristate Result =
1817 getPredicateOnEdge(Pred, Incoming, C, PredBB, BB, CxtI);
1818
1819 // Keep going as long as we've seen a consistent known result for
1820 // all inputs.
1821 Baseline = (i == 0) ? Result /* First iteration */
1822 : (Baseline == Result ? Baseline
1823 : Unknown); /* All others */
1824 if (Baseline == Unknown)
1825 break;
1826 }
1827 if (Baseline != Unknown)
1828 return Baseline;
1829 }
1830
1831 // For a comparison where the V is outside this block, it's possible
1832 // that we've branched on it before. Look to see if the value is known
1833 // on all incoming edges.
1834 if (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB) {
1835 // For predecessor edge, determine if the comparison is true or false
1836 // on that edge. If they're all true or all false, we can conclude
1837 // the value of the comparison in this block.
1838 Tristate Baseline = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1839 if (Baseline != Unknown) {
1840 // Check that all remaining incoming values match the first one.
1841 while (++PI != PE) {
1842 Tristate Ret = getPredicateOnEdge(Pred, V, C, *PI, BB, CxtI);
1843 if (Ret != Baseline)
1844 break;
1845 }
1846 // If we terminated early, then one of the values didn't match.
1847 if (PI == PE) {
1848 return Baseline;
1849 }
1850 }
1851 }
1852
1853 return Unknown;
1854}
1855
1856LazyValueInfo::Tristate LazyValueInfo::getPredicateAt(unsigned P, Value *LHS,
1857 Value *RHS,
1858 Instruction *CxtI,
1859 bool UseBlockValue) {
1860 CmpInst::Predicate Pred = (CmpInst::Predicate)P;
1861
1862 if (auto *C = dyn_cast<Constant>(RHS))
1863 return getPredicateAt(P, LHS, C, CxtI, UseBlockValue);
1864 if (auto *C = dyn_cast<Constant>(LHS))
1865 return getPredicateAt(CmpInst::getSwappedPredicate(Pred), RHS, C, CxtI,
1866 UseBlockValue);
1867
1868 // Got two non-Constant values. While we could handle them somewhat,
1869 // by getting their constant ranges, and applying ConstantRange::icmp(),
1870 // so far it did not appear to be profitable.
1871 return LazyValueInfo::Unknown;
1872}
1873
1874void LazyValueInfo::threadEdge(BasicBlock *PredBB, BasicBlock *OldSucc,
1875 BasicBlock *NewSucc) {
1876 if (PImpl) {
1877 getImpl(PImpl, AC, PredBB->getModule())
1878 .threadEdge(PredBB, OldSucc, NewSucc);
1879 }
1880}
1881
1882void LazyValueInfo::eraseBlock(BasicBlock *BB) {
1883 if (PImpl) {
1884 getImpl(PImpl, AC, BB->getModule()).eraseBlock(BB);
1885 }
1886}
1887
1888void LazyValueInfo::clear(const Module *M) {
1889 if (PImpl) {
1890 getImpl(PImpl, AC, M).clear();
1891 }
1892}
1893
1894void LazyValueInfo::printLVI(Function &F, DominatorTree &DTree, raw_ostream &OS) {
1895 if (PImpl) {
1896 getImpl(PImpl, AC, F.getParent()).printLVI(F, DTree, OS);
1897 }
1898}
1899
1900// Print the LVI for the function arguments at the start of each basic block.
1901void LazyValueInfoAnnotatedWriter::emitBasicBlockStartAnnot(
1902 const BasicBlock *BB, formatted_raw_ostream &OS) {
1903 // Find if there are latticevalues defined for arguments of the function.
1904 auto *F = BB->getParent();
1905 for (auto &Arg : F->args()) {
1906 ValueLatticeElement Result = LVIImpl->getValueInBlock(
1907 const_cast<Argument *>(&Arg), const_cast<BasicBlock *>(BB));
1908 if (Result.isUnknown())
1909 continue;
1910 OS << "; LatticeVal for: '" << Arg << "' is: " << Result << "\n";
1911 }
1912}
1913
1914// This function prints the LVI analysis for the instruction I at the beginning
1915// of various basic blocks. It relies on calculated values that are stored in
1916// the LazyValueInfoCache, and in the absence of cached values, recalculate the
1917// LazyValueInfo for `I`, and print that info.
1918void LazyValueInfoAnnotatedWriter::emitInstructionAnnot(
1919 const Instruction *I, formatted_raw_ostream &OS) {
1920
1921 auto *ParentBB = I->getParent();
1922 SmallPtrSet<const BasicBlock*, 16> BlocksContainingLVI;
1923 // We can generate (solve) LVI values only for blocks that are dominated by
1924 // the I's parent. However, to avoid generating LVI for all dominating blocks,
1925 // that contain redundant/uninteresting information, we print LVI for
1926 // blocks that may use this LVI information (such as immediate successor
1927 // blocks, and blocks that contain uses of `I`).
1928 auto printResult = [&](const BasicBlock *BB) {
1929 if (!BlocksContainingLVI.insert(BB).second)
1930 return;
1931 ValueLatticeElement Result = LVIImpl->getValueInBlock(
1932 const_cast<Instruction *>(I), const_cast<BasicBlock *>(BB));
1933 OS << "; LatticeVal for: '" << *I << "' in BB: '";
1934 BB->printAsOperand(OS, false);
1935 OS << "' is: " << Result << "\n";
1936 };
1937
1938 printResult(ParentBB);
1939 // Print the LVI analysis results for the immediate successor blocks, that
1940 // are dominated by `ParentBB`.
1941 for (auto *BBSucc : successors(ParentBB))
1942 if (DT.dominates(ParentBB, BBSucc))
1943 printResult(BBSucc);
1944
1945 // Print LVI in blocks where `I` is used.
1946 for (auto *U : I->users())
1947 if (auto *UseI = dyn_cast<Instruction>(U))
1948 if (!isa<PHINode>(UseI) || DT.dominates(ParentBB, UseI->getParent()))
1949 printResult(UseI->getParent());
1950
1951}
1952
1953namespace {
1954// Printer class for LazyValueInfo results.
1955class LazyValueInfoPrinter : public FunctionPass {
1956public:
1957 static char ID; // Pass identification, replacement for typeid
1958 LazyValueInfoPrinter() : FunctionPass(ID) {
1959 initializeLazyValueInfoPrinterPass(*PassRegistry::getPassRegistry());
1960 }
1961
1962 void getAnalysisUsage(AnalysisUsage &AU) const override {
1963 AU.setPreservesAll();
1964 AU.addRequired<LazyValueInfoWrapperPass>();
1965 AU.addRequired<DominatorTreeWrapperPass>();
1966 }
1967
1968 // Get the mandatory dominator tree analysis and pass this in to the
1969 // LVIPrinter. We cannot rely on the LVI's DT, since it's optional.
1970 bool runOnFunction(Function &F) override {
1971 dbgs() << "LVI for function '" << F.getName() << "':\n";
1972 auto &LVI = getAnalysis<LazyValueInfoWrapperPass>().getLVI();
1973 auto &DTree = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1974 LVI.printLVI(F, DTree, dbgs());
1975 return false;
1976 }
1977};
1978}
1979
1980char LazyValueInfoPrinter::ID = 0;
1981INITIALIZE_PASS_BEGIN(LazyValueInfoPrinter, "print-lazy-value-info",static void *initializeLazyValueInfoPrinterPassOnce(PassRegistry
&Registry) {
1982 "Lazy Value Info Printer Pass", false, false)static void *initializeLazyValueInfoPrinterPassOnce(PassRegistry
&Registry) {
1983INITIALIZE_PASS_DEPENDENCY(LazyValueInfoWrapperPass)initializeLazyValueInfoWrapperPassPass(Registry);
1984INITIALIZE_PASS_END(LazyValueInfoPrinter, "print-lazy-value-info",PassInfo *PI = new PassInfo( "Lazy Value Info Printer Pass", "print-lazy-value-info"
, &LazyValueInfoPrinter::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LazyValueInfoPrinter>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLazyValueInfoPrinterPassFlag
; void llvm::initializeLazyValueInfoPrinterPass(PassRegistry &
Registry) { llvm::call_once(InitializeLazyValueInfoPrinterPassFlag
, initializeLazyValueInfoPrinterPassOnce, std::ref(Registry))
; }
1985 "Lazy Value Info Printer Pass", false, false)PassInfo *PI = new PassInfo( "Lazy Value Info Printer Pass", "print-lazy-value-info"
, &LazyValueInfoPrinter::ID, PassInfo::NormalCtor_t(callDefaultCtor
<LazyValueInfoPrinter>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeLazyValueInfoPrinterPassFlag
; void llvm::initializeLazyValueInfoPrinterPass(PassRegistry &
Registry) { llvm::call_once(InitializeLazyValueInfoPrinterPassFlag
, initializeLazyValueInfoPrinterPassOnce, std::ref(Registry))
; }

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include/llvm/IR/ConstantRange.h

1//===- ConstantRange.h - Represent a range ----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// Represent a range of possible values that may occur when the program is run
10// for an integral value. This keeps track of a lower and upper bound for the
11// constant, which MAY wrap around the end of the numeric range. To do this, it
12// keeps track of a [lower, upper) bound, which specifies an interval just like
13// STL iterators. When used with boolean values, the following are important
14// ranges: :
15//
16// [F, F) = {} = Empty set
17// [T, F) = {T}
18// [F, T) = {F}
19// [T, T) = {F, T} = Full set
20//
21// The other integral ranges use min/max values for special range values. For
22// example, for 8-bit types, it uses:
23// [0, 0) = {} = Empty set
24// [255, 255) = {0..255} = Full Set
25//
26// Note that ConstantRange can be used to represent either signed or
27// unsigned ranges.
28//
29//===----------------------------------------------------------------------===//
30
31#ifndef LLVM_IR_CONSTANTRANGE_H
32#define LLVM_IR_CONSTANTRANGE_H
33
34#include "llvm/ADT/APInt.h"
35#include "llvm/IR/InstrTypes.h"
36#include "llvm/IR/Instruction.h"
37#include "llvm/Support/Compiler.h"
38#include <cstdint>
39
40namespace llvm {
41
42class MDNode;
43class raw_ostream;
44struct KnownBits;
45
46/// This class represents a range of values.
47class LLVM_NODISCARD[[clang::warn_unused_result]] ConstantRange {
48 APInt Lower, Upper;
49
50 /// Create empty constant range with same bitwidth.
51 ConstantRange getEmpty() const {
52 return ConstantRange(getBitWidth(), false);
53 }
54
55 /// Create full constant range with same bitwidth.
56 ConstantRange getFull() const {
57 return ConstantRange(getBitWidth(), true);
58 }
59
60public:
61 /// Initialize a full or empty set for the specified bit width.
62 explicit ConstantRange(uint32_t BitWidth, bool isFullSet);
63
64 /// Initialize a range to hold the single specified value.
65 ConstantRange(APInt Value);
66
67 /// Initialize a range of values explicitly. This will assert out if
68 /// Lower==Upper and Lower != Min or Max value for its type. It will also
69 /// assert out if the two APInt's are not the same bit width.
70 ConstantRange(APInt Lower, APInt Upper);
71
72 /// Create empty constant range with the given bit width.
73 static ConstantRange getEmpty(uint32_t BitWidth) {
74 return ConstantRange(BitWidth, false);
75 }
76
77 /// Create full constant range with the given bit width.
78 static ConstantRange getFull(uint32_t BitWidth) {
79 return ConstantRange(BitWidth, true);
80 }
81
82 /// Create non-empty constant range with the given bounds. If Lower and
83 /// Upper are the same, a full range is returned.
84 static ConstantRange getNonEmpty(APInt Lower, APInt Upper) {
85 if (Lower == Upper)
86 return getFull(Lower.getBitWidth());
87 return ConstantRange(std::move(Lower), std::move(Upper));
88 }
89
90 /// Initialize a range based on a known bits constraint. The IsSigned flag
91 /// indicates whether the constant range should not wrap in the signed or
92 /// unsigned domain.
93 static ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned);
94
95 /// Produce the smallest range such that all values that may satisfy the given
96 /// predicate with any value contained within Other is contained in the
97 /// returned range. Formally, this returns a superset of
98 /// 'union over all y in Other . { x : icmp op x y is true }'. If the exact
99 /// answer is not representable as a ConstantRange, the return value will be a
100 /// proper superset of the above.
101 ///
102 /// Example: Pred = ult and Other = i8 [2, 5) returns Result = [0, 4)
103 static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred,
104 const ConstantRange &Other);
105
106 /// Produce the largest range such that all values in the returned range
107 /// satisfy the given predicate with all values contained within Other.
108 /// Formally, this returns a subset of
109 /// 'intersection over all y in Other . { x : icmp op x y is true }'. If the
110 /// exact answer is not representable as a ConstantRange, the return value
111 /// will be a proper subset of the above.
112 ///
113 /// Example: Pred = ult and Other = i8 [2, 5) returns [0, 2)
114 static ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
115 const ConstantRange &Other);
116
117 /// Produce the exact range such that all values in the returned range satisfy
118 /// the given predicate with any value contained within Other. Formally, this
119 /// returns the exact answer when the superset of 'union over all y in Other
120 /// is exactly same as the subset of intersection over all y in Other.
121 /// { x : icmp op x y is true}'.
122 ///
123 /// Example: Pred = ult and Other = i8 3 returns [0, 3)
124 static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred,
125 const APInt &Other);
126
127 /// Does the predicate \p Pred hold between ranges this and \p Other?
128 /// NOTE: false does not mean that inverse predicate holds!
129 bool icmp(CmpInst::Predicate Pred, const ConstantRange &Other) const;
130
131 /// Return true iff CR1 ult CR2 is equivalent to CR1 slt CR2.
132 /// Does not depend on strictness/direction of the predicate.
133 static bool
134 areInsensitiveToSignednessOfICmpPredicate(const ConstantRange &CR1,
135 const ConstantRange &CR2);
136
137 /// Return true iff CR1 ult CR2 is equivalent to CR1 sge CR2.
138 /// Does not depend on strictness/direction of the predicate.
139 static bool
140 areInsensitiveToSignednessOfInvertedICmpPredicate(const ConstantRange &CR1,
141 const ConstantRange &CR2);
142
143 /// If the comparison between constant ranges this and Other
144 /// is insensitive to the signedness of the comparison predicate,
145 /// return a predicate equivalent to \p Pred, with flipped signedness
146 /// (i.e. unsigned instead of signed or vice versa), and maybe inverted,
147 /// otherwise returns CmpInst::Predicate::BAD_ICMP_PREDICATE.
148 static CmpInst::Predicate
149 getEquivalentPredWithFlippedSignedness(CmpInst::Predicate Pred,
150 const ConstantRange &CR1,
151 const ConstantRange &CR2);
152
153 /// Produce the largest range containing all X such that "X BinOp Y" is
154 /// guaranteed not to wrap (overflow) for *all* Y in Other. However, there may
155 /// be *some* Y in Other for which additional X not contained in the result
156 /// also do not overflow.
157 ///
158 /// NoWrapKind must be one of OBO::NoUnsignedWrap or OBO::NoSignedWrap.
159 ///
160 /// Examples:
161 /// typedef OverflowingBinaryOperator OBO;
162 /// #define MGNR makeGuaranteedNoWrapRegion
163 /// MGNR(Add, [i8 1, 2), OBO::NoSignedWrap) == [-128, 127)
164 /// MGNR(Add, [i8 1, 2), OBO::NoUnsignedWrap) == [0, -1)
165 /// MGNR(Add, [i8 0, 1), OBO::NoUnsignedWrap) == Full Set
166 /// MGNR(Add, [i8 -1, 6), OBO::NoSignedWrap) == [INT_MIN+1, INT_MAX-4)
167 /// MGNR(Sub, [i8 1, 2), OBO::NoSignedWrap) == [-127, 128)
168 /// MGNR(Sub, [i8 1, 2), OBO::NoUnsignedWrap) == [1, 0)
169 static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
170 const ConstantRange &Other,
171 unsigned NoWrapKind);
172
173 /// Produce the range that contains X if and only if "X BinOp Other" does
174 /// not wrap.
175 static ConstantRange makeExactNoWrapRegion(Instruction::BinaryOps BinOp,
176 const APInt &Other,
177 unsigned NoWrapKind);
178
179 /// Returns true if ConstantRange calculations are supported for intrinsic
180 /// with \p IntrinsicID.
181 static bool isIntrinsicSupported(Intrinsic::ID IntrinsicID);
182
183 /// Compute range of intrinsic result for the given operand ranges.
184 static ConstantRange intrinsic(Intrinsic::ID IntrinsicID,
185 ArrayRef<ConstantRange> Ops);
186
187 /// Set up \p Pred and \p RHS such that
188 /// ConstantRange::makeExactICmpRegion(Pred, RHS) == *this. Return true if
189 /// successful.
190 bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const;
191
192 /// Set up \p Pred, \p RHS and \p Offset such that (V + Offset) Pred RHS
193 /// is true iff V is in the range. Prefers using Offset == 0 if possible.
194 void
195 getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS, APInt &Offset) const;
196
197 /// Return the lower value for this range.
198 const APInt &getLower() const { return Lower; }
199
200 /// Return the upper value for this range.
201 const APInt &getUpper() const { return Upper; }
202
203 /// Get the bit width of this ConstantRange.
204 uint32_t getBitWidth() const { return Lower.getBitWidth(); }
205
206 /// Return true if this set contains all of the elements possible
207 /// for this data-type.
208 bool isFullSet() const;
209
210 /// Return true if this set contains no members.
211 bool isEmptySet() const;
212
213 /// Return true if this set wraps around the unsigned domain. Special cases:
214 /// * Empty set: Not wrapped.
215 /// * Full set: Not wrapped.
216 /// * [X, 0) == [X, Max]: Not wrapped.
217 bool isWrappedSet() const;
218
219 /// Return true if the exclusive upper bound wraps around the unsigned
220 /// domain. Special cases:
221 /// * Empty set: Not wrapped.
222 /// * Full set: Not wrapped.
223 /// * [X, 0): Wrapped.
224 bool isUpperWrapped() const;
225
226 /// Return true if this set wraps around the signed domain. Special cases:
227 /// * Empty set: Not wrapped.
228 /// * Full set: Not wrapped.
229 /// * [X, SignedMin) == [X, SignedMax]: Not wrapped.
230 bool isSignWrappedSet() const;
231
232 /// Return true if the (exclusive) upper bound wraps around the signed
233 /// domain. Special cases:
234 /// * Empty set: Not wrapped.
235 /// * Full set: Not wrapped.
236 /// * [X, SignedMin): Wrapped.
237 bool isUpperSignWrapped() const;
238
239 /// Return true if the specified value is in the set.
240 bool contains(const APInt &Val) const;
241
242 /// Return true if the other range is a subset of this one.
243 bool contains(const ConstantRange &CR) const;
244
245 /// If this set contains a single element, return it, otherwise return null.
246 const APInt *getSingleElement() const {
247 if (Upper == Lower + 1)
248 return &Lower;
249 return nullptr;
250 }
251
252 /// If this set contains all but a single element, return it, otherwise return
253 /// null.
254 const APInt *getSingleMissingElement() const {
255 if (Lower == Upper + 1)
256 return &Upper;
257 return nullptr;
258 }
259
260 /// Return true if this set contains exactly one member.
261 bool isSingleElement() const { return getSingleElement() != nullptr; }
262
263 /// Compare set size of this range with the range CR.
264 bool isSizeStrictlySmallerThan(const ConstantRange &CR) const;
265
266 /// Compare set size of this range with Value.
267 bool isSizeLargerThan(uint64_t MaxSize) const;
268
269 /// Return true if all values in this range are negative.
270 bool isAllNegative() const;
271
272 /// Return true if all values in this range are non-negative.
273 bool isAllNonNegative() const;
274
275 /// Return the largest unsigned value contained in the ConstantRange.
276 APInt getUnsignedMax() const;
277
278 /// Return the smallest unsigned value contained in the ConstantRange.
279 APInt getUnsignedMin() const;
280
281 /// Return the largest signed value contained in the ConstantRange.
282 APInt getSignedMax() const;
283
284 /// Return the smallest signed value contained in the ConstantRange.
285 APInt getSignedMin() const;
286
287 /// Return true if this range is equal to another range.
288 bool operator==(const ConstantRange &CR) const {
289 return Lower == CR.Lower && Upper == CR.Upper;
290 }
291 bool operator!=(const ConstantRange &CR) const {
292 return !operator==(CR);
293 }
294
295 /// Compute the maximal number of active bits needed to represent every value
296 /// in this range.
297 unsigned getActiveBits() const;
298
299 /// Compute the maximal number of bits needed to represent every value
300 /// in this signed range.
301 unsigned getMinSignedBits() const;
302
303 /// Subtract the specified constant from the endpoints of this constant range.
304 ConstantRange subtract(const APInt &CI) const;
305
306 /// Subtract the specified range from this range (aka relative complement of
307 /// the sets).
308 ConstantRange difference(const ConstantRange &CR) const;
309
310 /// If represented precisely, the result of some range operations may consist
311 /// of multiple disjoint ranges. As only a single range may be returned, any
312 /// range covering these disjoint ranges constitutes a valid result, but some
313 /// may be more useful than others depending on context. The preferred range
314 /// type specifies whether a range that is non-wrapping in the unsigned or
315 /// signed domain, or has the smallest size, is preferred. If a signedness is
316 /// preferred but all ranges are non-wrapping or all wrapping, then the
317 /// smallest set size is preferred. If there are multiple smallest sets, any
318 /// one of them may be returned.
319 enum PreferredRangeType { Smallest, Unsigned, Signed };
320
321 /// Return the range that results from the intersection of this range with
322 /// another range. If the intersection is disjoint, such that two results
323 /// are possible, the preferred range is determined by the PreferredRangeType.
324 ConstantRange intersectWith(const ConstantRange &CR,
325 PreferredRangeType Type = Smallest) const;
326
327 /// Return the range that results from the union of this range
328 /// with another range. The resultant range is guaranteed to include the
329 /// elements of both sets, but may contain more. For example, [3, 9) union
330 /// [12,15) is [3, 15), which includes 9, 10, and 11, which were not included
331 /// in either set before.
332 ConstantRange unionWith(const ConstantRange &CR,
333 PreferredRangeType Type = Smallest) const;
334
335 /// Intersect the two ranges and return the result if it can be represented
336 /// exactly, otherwise return None.
337 Optional<ConstantRange> exactIntersectWith(const ConstantRange &CR) const;
338
339 /// Union the two ranges and return the result if it can be represented
340 /// exactly, otherwise return None.
341 Optional<ConstantRange> exactUnionWith(const ConstantRange &CR) const;
342
343 /// Return a new range representing the possible values resulting
344 /// from an application of the specified cast operator to this range. \p
345 /// BitWidth is the target bitwidth of the cast. For casts which don't
346 /// change bitwidth, it must be the same as the source bitwidth. For casts
347 /// which do change bitwidth, the bitwidth must be consistent with the
348 /// requested cast and source bitwidth.
349 ConstantRange castOp(Instruction::CastOps CastOp,
350 uint32_t BitWidth) const;
351
352 /// Return a new range in the specified integer type, which must
353 /// be strictly larger than the current type. The returned range will
354 /// correspond to the possible range of values if the source range had been
355 /// zero extended to BitWidth.
356 ConstantRange zeroExtend(uint32_t BitWidth) const;
357
358 /// Return a new range in the specified integer type, which must
359 /// be strictly larger than the current type. The returned range will
360 /// correspond to the possible range of values if the source range had been
361 /// sign extended to BitWidth.
362 ConstantRange signExtend(uint32_t BitWidth) const;
363
364 /// Return a new range in the specified integer type, which must be
365 /// strictly smaller than the current type. The returned range will
366 /// correspond to the possible range of values if the source range had been
367 /// truncated to the specified type.
368 ConstantRange truncate(uint32_t BitWidth) const;
369
370 /// Make this range have the bit width given by \p BitWidth. The
371 /// value is zero extended, truncated, or left alone to make it that width.
372 ConstantRange zextOrTrunc(uint32_t BitWidth) const;
373
374 /// Make this range have the bit width given by \p BitWidth. The
375 /// value is sign extended, truncated, or left alone to make it that width.
376 ConstantRange sextOrTrunc(uint32_t BitWidth) const;
377
378 /// Return a new range representing the possible values resulting
379 /// from an application of the specified binary operator to an left hand side
380 /// of this range and a right hand side of \p Other.
381 ConstantRange binaryOp(Instruction::BinaryOps BinOp,
382 const ConstantRange &Other) const;
383
384 /// Return a new range representing the possible values resulting
385 /// from an application of the specified overflowing binary operator to a
386 /// left hand side of this range and a right hand side of \p Other given
387 /// the provided knowledge about lack of wrapping \p NoWrapKind.
388 ConstantRange overflowingBinaryOp(Instruction::BinaryOps BinOp,
389 const ConstantRange &Other,
390 unsigned NoWrapKind) const;
391
392 /// Return a new range representing the possible values resulting
393 /// from an addition of a value in this range and a value in \p Other.
394 ConstantRange add(const ConstantRange &Other) const;
395
396 /// Return a new range representing the possible values resulting
397 /// from an addition with wrap type \p NoWrapKind of a value in this
398 /// range and a value in \p Other.
399 /// If the result range is disjoint, the preferred range is determined by the
400 /// \p PreferredRangeType.
401 ConstantRange addWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind,
402 PreferredRangeType RangeType = Smallest) const;
403
404 /// Return a new range representing the possible values resulting
405 /// from a subtraction of a value in this range and a value in \p Other.
406 ConstantRange sub(const ConstantRange &Other) const;
407
408 /// Return a new range representing the possible values resulting
409 /// from an subtraction with wrap type \p NoWrapKind of a value in this
410 /// range and a value in \p Other.
411 /// If the result range is disjoint, the preferred range is determined by the
412 /// \p PreferredRangeType.
413 ConstantRange subWithNoWrap(const ConstantRange &Other, unsigned NoWrapKind,
414 PreferredRangeType RangeType = Smallest) const;
415
416 /// Return a new range representing the possible values resulting
417 /// from a multiplication of a value in this range and a value in \p Other,
418 /// treating both this and \p Other as unsigned ranges.
419 ConstantRange multiply(const ConstantRange &Other) const;
420
421 /// Return range of possible values for a signed multiplication of this and
422 /// \p Other. However, if overflow is possible always return a full range
423 /// rather than trying to determine a more precise result.
424 ConstantRange smul_fast(const ConstantRange &Other) const;
425
426 /// Return a new range representing the possible values resulting
427 /// from a signed maximum of a value in this range and a value in \p Other.
428 ConstantRange smax(const ConstantRange &Other) const;
429
430 /// Return a new range representing the possible values resulting
431 /// from an unsigned maximum of a value in this range and a value in \p Other.
432 ConstantRange umax(const ConstantRange &Other) const;
433
434 /// Return a new range representing the possible values resulting
435 /// from a signed minimum of a value in this range and a value in \p Other.
436 ConstantRange smin(const ConstantRange &Other) const;
437
438 /// Return a new range representing the possible values resulting
439 /// from an unsigned minimum of a value in this range and a value in \p Other.
440 ConstantRange umin(const ConstantRange &Other) const;
441
442 /// Return a new range representing the possible values resulting
443 /// from an unsigned division of a value in this range and a value in
444 /// \p Other.
445 ConstantRange udiv(const ConstantRange &Other) const;
446
447 /// Return a new range representing the possible values resulting
448 /// from a signed division of a value in this range and a value in
449 /// \p Other. Division by zero and division of SignedMin by -1 are considered
450 /// undefined behavior, in line with IR, and do not contribute towards the
451 /// result.
452 ConstantRange sdiv(const ConstantRange &Other) const;
453
454 /// Return a new range representing the possible values resulting
455 /// from an unsigned remainder operation of a value in this range and a
456 /// value in \p Other.
457 ConstantRange urem(const ConstantRange &Other) const;
458
459 /// Return a new range representing the possible values resulting
460 /// from a signed remainder operation of a value in this range and a
461 /// value in \p Other.
462 ConstantRange srem(const ConstantRange &Other) const;
463
464 /// Return a new range representing the possible values resulting from
465 /// a binary-xor of a value in this range by an all-one value,
466 /// aka bitwise complement operation.
467 ConstantRange binaryNot() const;
468
469 /// Return a new range representing the possible values resulting
470 /// from a binary-and of a value in this range by a value in \p Other.
471 ConstantRange binaryAnd(const ConstantRange &Other) const;
472
473 /// Return a new range representing the possible values resulting
474 /// from a binary-or of a value in this range by a value in \p Other.
475 ConstantRange binaryOr(const ConstantRange &Other) const;
476
477 /// Return a new range representing the possible values resulting
478 /// from a binary-xor of a value in this range by a value in \p Other.
479 ConstantRange binaryXor(const ConstantRange &Other) const;
480
481 /// Return a new range representing the possible values resulting
482 /// from a left shift of a value in this range by a value in \p Other.
483 /// TODO: This isn't fully implemented yet.
484 ConstantRange shl(const ConstantRange &Other) const;
485
486 /// Return a new range representing the possible values resulting from a
487 /// logical right shift of a value in this range and a value in \p Other.
488 ConstantRange lshr(const ConstantRange &Other) const;
489
490 /// Return a new range representing the possible values resulting from a
491 /// arithmetic right shift of a value in this range and a value in \p Other.
492 ConstantRange ashr(const ConstantRange &Other) const;
493
494 /// Perform an unsigned saturating addition of two constant ranges.
495 ConstantRange uadd_sat(const ConstantRange &Other) const;
496
497 /// Perform a signed saturating addition of two constant ranges.
498 ConstantRange sadd_sat(const ConstantRange &Other) const;
499
500 /// Perform an unsigned saturating subtraction of two constant ranges.
501 ConstantRange usub_sat(const ConstantRange &Other) const;
502
503 /// Perform a signed saturating subtraction of two constant ranges.
504 ConstantRange ssub_sat(const ConstantRange &Other) const;
505
506 /// Perform an unsigned saturating multiplication of two constant ranges.
507 ConstantRange umul_sat(const ConstantRange &Other) const;
508
509 /// Perform a signed saturating multiplication of two constant ranges.
510 ConstantRange smul_sat(const ConstantRange &Other) const;
511
512 /// Perform an unsigned saturating left shift of this constant range by a
513 /// value in \p Other.
514 ConstantRange ushl_sat(const ConstantRange &Other) const;
515
516 /// Perform a signed saturating left shift of this constant range by a
517 /// value in \p Other.
518 ConstantRange sshl_sat(const ConstantRange &Other) const;
519
520 /// Return a new range that is the logical not of the current set.
521 ConstantRange inverse() const;
522
523 /// Calculate absolute value range. If the original range contains signed
524 /// min, then the resulting range will contain signed min if and only if
525 /// \p IntMinIsPoison is false.
526 ConstantRange abs(bool IntMinIsPoison = false) const;
527
528 /// Represents whether an operation on the given constant range is known to
529 /// always or never overflow.
530 enum class OverflowResult {
531 /// Always overflows in the direction of signed/unsigned min value.
532 AlwaysOverflowsLow,
533 /// Always overflows in the direction of signed/unsigned max value.
534 AlwaysOverflowsHigh,
535 /// May or may not overflow.
536 MayOverflow,
537 /// Never overflows.
538 NeverOverflows,
539 };
540
541 /// Return whether unsigned add of the two ranges always/never overflows.
542 OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const;
543
544 /// Return whether signed add of the two ranges always/never overflows.
545 OverflowResult signedAddMayOverflow(const ConstantRange &Other) const;
546
547 /// Return whether unsigned sub of the two ranges always/never overflows.
548 OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const;
549
550 /// Return whether signed sub of the two ranges always/never overflows.
551 OverflowResult signedSubMayOverflow(const ConstantRange &Other) const;
552
553 /// Return whether unsigned mul of the two ranges always/never overflows.
554 OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const;
555
556 /// Print out the bounds to a stream.
557 void print(raw_ostream &OS) const;
558
559 /// Allow printing from a debugger easily.
560 void dump() const;
561};
562
563inline raw_ostream &operator<<(raw_ostream &OS, const ConstantRange &CR) {
564 CR.print(OS);
565 return OS;
566}
567
568/// Parse out a conservative ConstantRange from !range metadata.
569///
570/// E.g. if RangeMD is !{i32 0, i32 10, i32 15, i32 20} then return [0, 20).
571ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD);
572
573} // end namespace llvm
574
575#endif // LLVM_IR_CONSTANTRANGE_H

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include/llvm/ADT/APInt.h

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