Bug Summary

File:llvm/lib/Frontend/OpenMP/OMPContext.cpp
Warning:line 364, column 11
Forming reference to null pointer

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name OMPContext.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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Frontend/OpenMP -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP -I include -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/include -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-14/lib/clang/14.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 -O2 -Wno-unused-command-line-argument -Wno-unknown-warning-option -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-14~++20210926122410+d23fd8ae8906/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -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-2021-09-26-234817-15343-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp

/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp

1//===- OMPContext.cpp ------ Collection of helpers for OpenMP contexts ----===//
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/// \file
9///
10/// This file implements helper functions and classes to deal with OpenMP
11/// contexts as used by `[begin/end] declare variant` and `metadirective`.
12///
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Frontend/OpenMP/OMPContext.h"
16#include "llvm/ADT/SetOperations.h"
17#include "llvm/ADT/StringRef.h"
18#include "llvm/ADT/StringSwitch.h"
19#include "llvm/ADT/Triple.h"
20#include "llvm/Support/Debug.h"
21#include "llvm/Support/raw_ostream.h"
22
23#define DEBUG_TYPE"openmp-ir-builder" "openmp-ir-builder"
24
25using namespace llvm;
26using namespace omp;
27
28OMPContext::OMPContext(bool IsDeviceCompilation, Triple TargetTriple) {
29 // Add the appropriate device kind trait based on the triple and the
30 // IsDeviceCompilation flag.
31 ActiveTraits.set(unsigned(IsDeviceCompilation
32 ? TraitProperty::device_kind_nohost
33 : TraitProperty::device_kind_host));
34 switch (TargetTriple.getArch()) {
35 case Triple::arm:
36 case Triple::armeb:
37 case Triple::aarch64:
38 case Triple::aarch64_be:
39 case Triple::aarch64_32:
40 case Triple::mips:
41 case Triple::mipsel:
42 case Triple::mips64:
43 case Triple::mips64el:
44 case Triple::ppc:
45 case Triple::ppcle:
46 case Triple::ppc64:
47 case Triple::ppc64le:
48 case Triple::x86:
49 case Triple::x86_64:
50 ActiveTraits.set(unsigned(TraitProperty::device_kind_cpu));
51 break;
52 case Triple::amdgcn:
53 case Triple::nvptx:
54 case Triple::nvptx64:
55 ActiveTraits.set(unsigned(TraitProperty::device_kind_gpu));
56 break;
57 default:
58 break;
59 }
60
61 // Add the appropriate device architecture trait based on the triple.
62#define OMP_TRAIT_PROPERTY(Enum, TraitSetEnum, TraitSelectorEnum, Str) \
63 if (TraitSelector::TraitSelectorEnum == TraitSelector::device_arch) { \
64 if (TargetTriple.getArch() == TargetTriple.getArchTypeForLLVMName(Str)) \
65 ActiveTraits.set(unsigned(TraitProperty::Enum)); \
66 if (StringRef(Str) == StringRef("x86_64") && \
67 TargetTriple.getArch() == Triple::x86_64) \
68 ActiveTraits.set(unsigned(TraitProperty::Enum)); \
69 }
70#include "llvm/Frontend/OpenMP/OMPKinds.def"
71
72 // TODO: What exactly do we want to see as device ISA trait?
73 // The discussion on the list did not seem to have come to an agreed
74 // upon solution.
75
76 // LLVM is the "OpenMP vendor" but we could also interpret vendor as the
77 // target vendor.
78 ActiveTraits.set(unsigned(TraitProperty::implementation_vendor_llvm));
79
80 // The user condition true is accepted but not false.
81 ActiveTraits.set(unsigned(TraitProperty::user_condition_true));
82
83 // This is for sure some device.
84 ActiveTraits.set(unsigned(TraitProperty::device_kind_any));
85
86 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { dbgs() << "[" << "openmp-ir-builder"
<< "] New OpenMP context with the following properties:\n"
; for (unsigned Bit : ActiveTraits.set_bits()) { TraitProperty
Property = TraitProperty(Bit); dbgs() << "\t " <<
getOpenMPContextTraitPropertyFullName(Property) << "\n"
; } }; } } while (false)
87 dbgs() << "[" << DEBUG_TYPEdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { dbgs() << "[" << "openmp-ir-builder"
<< "] New OpenMP context with the following properties:\n"
; for (unsigned Bit : ActiveTraits.set_bits()) { TraitProperty
Property = TraitProperty(Bit); dbgs() << "\t " <<
getOpenMPContextTraitPropertyFullName(Property) << "\n"
; } }; } } while (false)
88 << "] New OpenMP context with the following properties:\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { dbgs() << "[" << "openmp-ir-builder"
<< "] New OpenMP context with the following properties:\n"
; for (unsigned Bit : ActiveTraits.set_bits()) { TraitProperty
Property = TraitProperty(Bit); dbgs() << "\t " <<
getOpenMPContextTraitPropertyFullName(Property) << "\n"
; } }; } } while (false)
89 for (unsigned Bit : ActiveTraits.set_bits()) {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { dbgs() << "[" << "openmp-ir-builder"
<< "] New OpenMP context with the following properties:\n"
; for (unsigned Bit : ActiveTraits.set_bits()) { TraitProperty
Property = TraitProperty(Bit); dbgs() << "\t " <<
getOpenMPContextTraitPropertyFullName(Property) << "\n"
; } }; } } while (false)
90 TraitProperty Property = TraitProperty(Bit);do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { dbgs() << "[" << "openmp-ir-builder"
<< "] New OpenMP context with the following properties:\n"
; for (unsigned Bit : ActiveTraits.set_bits()) { TraitProperty
Property = TraitProperty(Bit); dbgs() << "\t " <<
getOpenMPContextTraitPropertyFullName(Property) << "\n"
; } }; } } while (false)
91 dbgs() << "\t " << getOpenMPContextTraitPropertyFullName(Property)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { dbgs() << "[" << "openmp-ir-builder"
<< "] New OpenMP context with the following properties:\n"
; for (unsigned Bit : ActiveTraits.set_bits()) { TraitProperty
Property = TraitProperty(Bit); dbgs() << "\t " <<
getOpenMPContextTraitPropertyFullName(Property) << "\n"
; } }; } } while (false)
92 << "\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { dbgs() << "[" << "openmp-ir-builder"
<< "] New OpenMP context with the following properties:\n"
; for (unsigned Bit : ActiveTraits.set_bits()) { TraitProperty
Property = TraitProperty(Bit); dbgs() << "\t " <<
getOpenMPContextTraitPropertyFullName(Property) << "\n"
; } }; } } while (false)
93 }do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { dbgs() << "[" << "openmp-ir-builder"
<< "] New OpenMP context with the following properties:\n"
; for (unsigned Bit : ActiveTraits.set_bits()) { TraitProperty
Property = TraitProperty(Bit); dbgs() << "\t " <<
getOpenMPContextTraitPropertyFullName(Property) << "\n"
; } }; } } while (false)
94 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { dbgs() << "[" << "openmp-ir-builder"
<< "] New OpenMP context with the following properties:\n"
; for (unsigned Bit : ActiveTraits.set_bits()) { TraitProperty
Property = TraitProperty(Bit); dbgs() << "\t " <<
getOpenMPContextTraitPropertyFullName(Property) << "\n"
; } }; } } while (false)
;
95}
96
97/// Return true if \p C0 is a subset of \p C1. Note that both arrays are
98/// expected to be sorted.
99template <typename T> static bool isSubset(ArrayRef<T> C0, ArrayRef<T> C1) {
100#ifdef EXPENSIVE_CHECKS
101 assert(llvm::is_sorted(C0) && llvm::is_sorted(C1) &&(static_cast <bool> (llvm::is_sorted(C0) && llvm
::is_sorted(C1) && "Expected sorted arrays!") ? void (
0) : __assert_fail ("llvm::is_sorted(C0) && llvm::is_sorted(C1) && \"Expected sorted arrays!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 102, __extension__ __PRETTY_FUNCTION__))
102 "Expected sorted arrays!")(static_cast <bool> (llvm::is_sorted(C0) && llvm
::is_sorted(C1) && "Expected sorted arrays!") ? void (
0) : __assert_fail ("llvm::is_sorted(C0) && llvm::is_sorted(C1) && \"Expected sorted arrays!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 102, __extension__ __PRETTY_FUNCTION__))
;
103#endif
104 if (C0.size() > C1.size())
105 return false;
106 auto It0 = C0.begin(), End0 = C0.end();
107 auto It1 = C1.begin(), End1 = C1.end();
108 while (It0 != End0) {
109 if (It1 == End1)
110 return false;
111 if (*It0 == *It1) {
112 ++It0;
113 ++It1;
114 continue;
115 }
116 ++It0;
117 }
118 return true;
119}
120
121/// Return true if \p C0 is a strict subset of \p C1. Note that both arrays are
122/// expected to be sorted.
123template <typename T>
124static bool isStrictSubset(ArrayRef<T> C0, ArrayRef<T> C1) {
125 if (C0.size() >= C1.size())
126 return false;
127 return isSubset<T>(C0, C1);
128}
129
130static bool isStrictSubset(const VariantMatchInfo &VMI0,
131 const VariantMatchInfo &VMI1) {
132 // If all required traits are a strict subset and the ordered vectors storing
133 // the construct traits, we say it is a strict subset. Note that the latter
134 // relation is not required to be strict.
135 if (VMI0.RequiredTraits.count() >= VMI1.RequiredTraits.count())
136 return false;
137 for (unsigned Bit : VMI0.RequiredTraits.set_bits())
138 if (!VMI1.RequiredTraits.test(Bit))
139 return false;
140 if (!isSubset<TraitProperty>(VMI0.ConstructTraits, VMI1.ConstructTraits))
141 return false;
142 return true;
143}
144
145static int isVariantApplicableInContextHelper(
146 const VariantMatchInfo &VMI, const OMPContext &Ctx,
147 SmallVectorImpl<unsigned> *ConstructMatches, bool DeviceSetOnly) {
148
149 // The match kind determines if we need to match all traits, any of the
150 // traits, or none of the traits for it to be an applicable context.
151 enum MatchKind { MK_ALL, MK_ANY, MK_NONE };
152
153 MatchKind MK = MK_ALL;
154 // Determine the match kind the user wants, "all" is the default and provided
155 // to the user only for completeness.
156 if (VMI.RequiredTraits.test(
5
Taking false branch
157 unsigned(TraitProperty::implementation_extension_match_any)))
158 MK = MK_ANY;
159 if (VMI.RequiredTraits.test(
6
Taking false branch
160 unsigned(TraitProperty::implementation_extension_match_none)))
161 MK = MK_NONE;
162
163 // Helper to deal with a single property that was (not) found in the OpenMP
164 // context based on the match kind selected by the user via
165 // `implementation={extensions(match_[all,any,none])}'
166 auto HandleTrait = [MK](TraitProperty Property,
167 bool WasFound) -> Optional<bool> /* Result */ {
168 // For kind "any" a single match is enough but we ignore non-matched
169 // properties.
170 if (MK == MK_ANY) {
171 if (WasFound)
172 return true;
173 return None;
174 }
175
176 // In "all" or "none" mode we accept a matching or non-matching property
177 // respectively and move on. We are not done yet!
178 if ((WasFound && MK == MK_ALL) || (!WasFound && MK == MK_NONE))
179 return None;
180
181 // We missed a property, provide some debug output and indicate failure.
182 LLVM_DEBUG({do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
183 if (MK == MK_ALL)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
184 dbgs() << "[" << DEBUG_TYPE << "] Property "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
185 << getOpenMPContextTraitPropertyName(Property, "")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
186 << " was not in the OpenMP context but match kind is all.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
187 if (MK == MK_NONE)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
188 dbgs() << "[" << DEBUG_TYPE << "] Property "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
189 << getOpenMPContextTraitPropertyName(Property, "")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
190 << " was in the OpenMP context but match kind is none.\n";do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
191 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { { if (MK == MK_ALL) dbgs() << "["
<< "openmp-ir-builder" << "] Property " <<
getOpenMPContextTraitPropertyName(Property, "") << " was not in the OpenMP context but match kind is all.\n"
; if (MK == MK_NONE) dbgs() << "[" << "openmp-ir-builder"
<< "] Property " << getOpenMPContextTraitPropertyName
(Property, "") << " was in the OpenMP context but match kind is none.\n"
; }; } } while (false)
;
192 return false;
193 };
194
195 for (unsigned Bit : VMI.RequiredTraits.set_bits()) {
196 TraitProperty Property = TraitProperty(Bit);
197 if (DeviceSetOnly &&
198 getOpenMPContextTraitSetForProperty(Property) != TraitSet::device)
199 continue;
200
201 // So far all extensions are handled elsewhere, we skip them here as they
202 // are not part of the OpenMP context.
203 if (getOpenMPContextTraitSelectorForProperty(Property) ==
204 TraitSelector::implementation_extension)
205 continue;
206
207 bool IsActiveTrait = Ctx.ActiveTraits.test(unsigned(Property));
208
209 // We overwrite the isa trait as it is actually up to the OMPContext hook to
210 // check the raw string(s).
211 if (Property == TraitProperty::device_isa___ANY)
212 IsActiveTrait = llvm::all_of(VMI.ISATraits, [&](StringRef RawString) {
213 return Ctx.matchesISATrait(RawString);
214 });
215
216 Optional<bool> Result = HandleTrait(Property, IsActiveTrait);
217 if (Result.hasValue())
218 return Result.getValue();
219 }
220
221 if (!DeviceSetOnly
6.1
'DeviceSetOnly' is false
6.1
'DeviceSetOnly' is false
) {
7
Taking true branch
222 // We could use isSubset here but we also want to record the match
223 // locations.
224 unsigned ConstructIdx = 0, NoConstructTraits = Ctx.ConstructTraits.size();
225 for (TraitProperty Property : VMI.ConstructTraits) {
8
Assuming '__begin2' is equal to '__end2'
226 assert(getOpenMPContextTraitSetForProperty(Property) ==(static_cast <bool> (getOpenMPContextTraitSetForProperty
(Property) == TraitSet::construct && "Variant context is ill-formed!"
) ? void (0) : __assert_fail ("getOpenMPContextTraitSetForProperty(Property) == TraitSet::construct && \"Variant context is ill-formed!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 228, __extension__ __PRETTY_FUNCTION__))
227 TraitSet::construct &&(static_cast <bool> (getOpenMPContextTraitSetForProperty
(Property) == TraitSet::construct && "Variant context is ill-formed!"
) ? void (0) : __assert_fail ("getOpenMPContextTraitSetForProperty(Property) == TraitSet::construct && \"Variant context is ill-formed!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 228, __extension__ __PRETTY_FUNCTION__))
228 "Variant context is ill-formed!")(static_cast <bool> (getOpenMPContextTraitSetForProperty
(Property) == TraitSet::construct && "Variant context is ill-formed!"
) ? void (0) : __assert_fail ("getOpenMPContextTraitSetForProperty(Property) == TraitSet::construct && \"Variant context is ill-formed!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 228, __extension__ __PRETTY_FUNCTION__))
;
229
230 // Verify the nesting.
231 bool FoundInOrder = false;
232 while (!FoundInOrder && ConstructIdx != NoConstructTraits)
233 FoundInOrder = (Ctx.ConstructTraits[ConstructIdx++] == Property);
234 if (ConstructMatches)
235 ConstructMatches->push_back(ConstructIdx - 1);
236
237 Optional<bool> Result = HandleTrait(Property, FoundInOrder);
238 if (Result.hasValue())
239 return Result.getValue();
240
241 if (!FoundInOrder) {
242 LLVM_DEBUG(dbgs() << "[" << DEBUG_TYPE << "] Construct property "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { dbgs() << "[" << "openmp-ir-builder"
<< "] Construct property " << getOpenMPContextTraitPropertyName
(Property, "") << " was not nested properly.\n"; } } while
(false)
243 << getOpenMPContextTraitPropertyName(Property, "")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { dbgs() << "[" << "openmp-ir-builder"
<< "] Construct property " << getOpenMPContextTraitPropertyName
(Property, "") << " was not nested properly.\n"; } } while
(false)
244 << " was not nested properly.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { dbgs() << "[" << "openmp-ir-builder"
<< "] Construct property " << getOpenMPContextTraitPropertyName
(Property, "") << " was not nested properly.\n"; } } while
(false)
;
245 return false;
246 }
247
248 // TODO: Verify SIMD
249 }
250
251 assert(isSubset<TraitProperty>(VMI.ConstructTraits, Ctx.ConstructTraits) &&(static_cast <bool> (isSubset<TraitProperty>(VMI.
ConstructTraits, Ctx.ConstructTraits) && "Broken invariant!"
) ? void (0) : __assert_fail ("isSubset<TraitProperty>(VMI.ConstructTraits, Ctx.ConstructTraits) && \"Broken invariant!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 252, __extension__ __PRETTY_FUNCTION__))
9
'?' condition is true
252 "Broken invariant!")(static_cast <bool> (isSubset<TraitProperty>(VMI.
ConstructTraits, Ctx.ConstructTraits) && "Broken invariant!"
) ? void (0) : __assert_fail ("isSubset<TraitProperty>(VMI.ConstructTraits, Ctx.ConstructTraits) && \"Broken invariant!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 252, __extension__ __PRETTY_FUNCTION__))
;
253 }
254
255 if (MK
9.1
'MK' is not equal to MK_ANY
9.1
'MK' is not equal to MK_ANY
== MK_ANY) {
10
Taking false branch
256 LLVM_DEBUG(dbgs() << "[" << DEBUG_TYPEdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { dbgs() << "[" << "openmp-ir-builder"
<< "] None of the properties was in the OpenMP context "
"but match kind is any.\n"; } } while (false)
257 << "] None of the properties was in the OpenMP context "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { dbgs() << "[" << "openmp-ir-builder"
<< "] None of the properties was in the OpenMP context "
"but match kind is any.\n"; } } while (false)
258 "but match kind is any.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { dbgs() << "[" << "openmp-ir-builder"
<< "] None of the properties was in the OpenMP context "
"but match kind is any.\n"; } } while (false)
;
259 return false;
260 }
261
262 return true;
11
Returning the value 1, which participates in a condition later
263}
264
265bool llvm::omp::isVariantApplicableInContext(const VariantMatchInfo &VMI,
266 const OMPContext &Ctx,
267 bool DeviceSetOnly) {
268 return isVariantApplicableInContextHelper(
269 VMI, Ctx, /* ConstructMatches */ nullptr, DeviceSetOnly);
270}
271
272static APInt getVariantMatchScore(const VariantMatchInfo &VMI,
273 const OMPContext &Ctx,
274 SmallVectorImpl<unsigned> &ConstructMatches) {
275 APInt Score(64, 1);
276
277 unsigned NoConstructTraits = VMI.ConstructTraits.size();
278 for (unsigned Bit : VMI.RequiredTraits.set_bits()) {
279 TraitProperty Property = TraitProperty(Bit);
280 // If there is a user score attached, use it.
281 if (VMI.ScoreMap.count(Property)) {
282 const APInt &UserScore = VMI.ScoreMap.lookup(Property);
283 assert(UserScore.uge(0) && "Expect non-negative user scores!")(static_cast <bool> (UserScore.uge(0) && "Expect non-negative user scores!"
) ? void (0) : __assert_fail ("UserScore.uge(0) && \"Expect non-negative user scores!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 283, __extension__ __PRETTY_FUNCTION__))
;
284 Score += UserScore.getZExtValue();
285 continue;
286 }
287
288 switch (getOpenMPContextTraitSetForProperty(Property)) {
289 case TraitSet::construct:
290 // We handle the construct traits later via the VMI.ConstructTraits
291 // container.
292 continue;
293 case TraitSet::implementation:
294 // No effect on the score (implementation defined).
295 continue;
296 case TraitSet::user:
297 // No effect on the score.
298 continue;
299 case TraitSet::device:
300 // Handled separately below.
301 break;
302 case TraitSet::invalid:
303 llvm_unreachable("Unknown trait set is not to be used!")::llvm::llvm_unreachable_internal("Unknown trait set is not to be used!"
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 303)
;
304 }
305
306 // device={kind(any)} is "as if" no kind selector was specified.
307 if (Property == TraitProperty::device_kind_any)
308 continue;
309
310 switch (getOpenMPContextTraitSelectorForProperty(Property)) {
311 case TraitSelector::device_kind:
312 Score += (1ULL << (NoConstructTraits + 0));
313 continue;
314 case TraitSelector::device_arch:
315 Score += (1ULL << (NoConstructTraits + 1));
316 continue;
317 case TraitSelector::device_isa:
318 Score += (1ULL << (NoConstructTraits + 2));
319 continue;
320 default:
321 continue;
322 }
323 }
324
325 unsigned ConstructIdx = 0;
326 assert(NoConstructTraits == ConstructMatches.size() &&(static_cast <bool> (NoConstructTraits == ConstructMatches
.size() && "Mismatch in the construct traits!") ? void
(0) : __assert_fail ("NoConstructTraits == ConstructMatches.size() && \"Mismatch in the construct traits!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 327, __extension__ __PRETTY_FUNCTION__))
327 "Mismatch in the construct traits!")(static_cast <bool> (NoConstructTraits == ConstructMatches
.size() && "Mismatch in the construct traits!") ? void
(0) : __assert_fail ("NoConstructTraits == ConstructMatches.size() && \"Mismatch in the construct traits!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 327, __extension__ __PRETTY_FUNCTION__))
;
328 for (TraitProperty Property : VMI.ConstructTraits) {
329 assert(getOpenMPContextTraitSetForProperty(Property) ==(static_cast <bool> (getOpenMPContextTraitSetForProperty
(Property) == TraitSet::construct && "Ill-formed variant match info!"
) ? void (0) : __assert_fail ("getOpenMPContextTraitSetForProperty(Property) == TraitSet::construct && \"Ill-formed variant match info!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 331, __extension__ __PRETTY_FUNCTION__))
330 TraitSet::construct &&(static_cast <bool> (getOpenMPContextTraitSetForProperty
(Property) == TraitSet::construct && "Ill-formed variant match info!"
) ? void (0) : __assert_fail ("getOpenMPContextTraitSetForProperty(Property) == TraitSet::construct && \"Ill-formed variant match info!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 331, __extension__ __PRETTY_FUNCTION__))
331 "Ill-formed variant match info!")(static_cast <bool> (getOpenMPContextTraitSetForProperty
(Property) == TraitSet::construct && "Ill-formed variant match info!"
) ? void (0) : __assert_fail ("getOpenMPContextTraitSetForProperty(Property) == TraitSet::construct && \"Ill-formed variant match info!\""
, "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 331, __extension__ __PRETTY_FUNCTION__))
;
332 (void)Property;
333 // ConstructMatches is the position p - 1 and we need 2^(p-1).
334 Score += (1ULL << ConstructMatches[ConstructIdx++]);
335 }
336
337 LLVM_DEBUG(dbgs() << "[" << DEBUG_TYPE << "] Variant has a score of " << Scoredo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { dbgs() << "[" << "openmp-ir-builder"
<< "] Variant has a score of " << Score <<
"\n"; } } while (false)
338 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("openmp-ir-builder")) { dbgs() << "[" << "openmp-ir-builder"
<< "] Variant has a score of " << Score <<
"\n"; } } while (false)
;
339 return Score;
340}
341
342int llvm::omp::getBestVariantMatchForContext(
343 const SmallVectorImpl<VariantMatchInfo> &VMIs, const OMPContext &Ctx) {
344
345 APInt BestScore(64, 0);
346 int BestVMIIdx = -1;
347 const VariantMatchInfo *BestVMI = nullptr;
1
'BestVMI' initialized to a null pointer value
348
349 for (unsigned u = 0, e = VMIs.size(); u < e; ++u) {
2
Assuming 'u' is < 'e'
3
Loop condition is true. Entering loop body
350 const VariantMatchInfo &VMI = VMIs[u];
351
352 SmallVector<unsigned, 8> ConstructMatches;
353 // If the variant is not applicable its not the best.
354 if (!isVariantApplicableInContextHelper(VMI, Ctx, &ConstructMatches,
4
Calling 'isVariantApplicableInContextHelper'
12
Returning from 'isVariantApplicableInContextHelper'
13
Taking false branch
355 /* DeviceSetOnly */ false))
356 continue;
357 // Check if its clearly not the best.
358 APInt Score = getVariantMatchScore(VMI, Ctx, ConstructMatches);
359 if (Score.ult(BestScore))
14
Calling 'APInt::ult'
17
Returning from 'APInt::ult'
18
Taking false branch
360 continue;
361 // Equal score need subset checks.
362 if (Score.eq(BestScore)) {
19
Calling 'APInt::eq'
30
Returning from 'APInt::eq'
31
Taking true branch
363 // Strict subset are never best.
364 if (isStrictSubset(VMI, *BestVMI))
32
Forming reference to null pointer
365 continue;
366 // Same score and the current best is no strict subset so we keep it.
367 if (!isStrictSubset(*BestVMI, VMI))
368 continue;
369 }
370 // New best found.
371 BestVMI = &VMI;
372 BestVMIIdx = u;
373 BestScore = Score;
374 }
375
376 return BestVMIIdx;
377}
378
379TraitSet llvm::omp::getOpenMPContextTraitSetKind(StringRef S) {
380 return StringSwitch<TraitSet>(S)
381#define OMP_TRAIT_SET(Enum, Str) .Case(Str, TraitSet::Enum)
382#include "llvm/Frontend/OpenMP/OMPKinds.def"
383 .Default(TraitSet::invalid);
384}
385
386TraitSet
387llvm::omp::getOpenMPContextTraitSetForSelector(TraitSelector Selector) {
388 switch (Selector) {
389#define OMP_TRAIT_SELECTOR(Enum, TraitSetEnum, Str, ReqProp) \
390 case TraitSelector::Enum: \
391 return TraitSet::TraitSetEnum;
392#include "llvm/Frontend/OpenMP/OMPKinds.def"
393 }
394 llvm_unreachable("Unknown trait selector!")::llvm::llvm_unreachable_internal("Unknown trait selector!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 394)
;
395}
396TraitSet
397llvm::omp::getOpenMPContextTraitSetForProperty(TraitProperty Property) {
398 switch (Property) {
399#define OMP_TRAIT_PROPERTY(Enum, TraitSetEnum, TraitSelectorEnum, Str) \
400 case TraitProperty::Enum: \
401 return TraitSet::TraitSetEnum;
402#include "llvm/Frontend/OpenMP/OMPKinds.def"
403 }
404 llvm_unreachable("Unknown trait set!")::llvm::llvm_unreachable_internal("Unknown trait set!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 404)
;
405}
406StringRef llvm::omp::getOpenMPContextTraitSetName(TraitSet Kind) {
407 switch (Kind) {
408#define OMP_TRAIT_SET(Enum, Str) \
409 case TraitSet::Enum: \
410 return Str;
411#include "llvm/Frontend/OpenMP/OMPKinds.def"
412 }
413 llvm_unreachable("Unknown trait set!")::llvm::llvm_unreachable_internal("Unknown trait set!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 413)
;
414}
415
416TraitSelector llvm::omp::getOpenMPContextTraitSelectorKind(StringRef S) {
417 return StringSwitch<TraitSelector>(S)
418#define OMP_TRAIT_SELECTOR(Enum, TraitSetEnum, Str, ReqProp) \
419 .Case(Str, TraitSelector::Enum)
420#include "llvm/Frontend/OpenMP/OMPKinds.def"
421 .Default(TraitSelector::invalid);
422}
423TraitSelector
424llvm::omp::getOpenMPContextTraitSelectorForProperty(TraitProperty Property) {
425 switch (Property) {
426#define OMP_TRAIT_PROPERTY(Enum, TraitSetEnum, TraitSelectorEnum, Str) \
427 case TraitProperty::Enum: \
428 return TraitSelector::TraitSelectorEnum;
429#include "llvm/Frontend/OpenMP/OMPKinds.def"
430 }
431 llvm_unreachable("Unknown trait set!")::llvm::llvm_unreachable_internal("Unknown trait set!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 431)
;
432}
433StringRef llvm::omp::getOpenMPContextTraitSelectorName(TraitSelector Kind) {
434 switch (Kind) {
435#define OMP_TRAIT_SELECTOR(Enum, TraitSetEnum, Str, ReqProp) \
436 case TraitSelector::Enum: \
437 return Str;
438#include "llvm/Frontend/OpenMP/OMPKinds.def"
439 }
440 llvm_unreachable("Unknown trait selector!")::llvm::llvm_unreachable_internal("Unknown trait selector!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 440)
;
441}
442
443TraitProperty llvm::omp::getOpenMPContextTraitPropertyKind(
444 TraitSet Set, TraitSelector Selector, StringRef S) {
445 // Special handling for `device={isa(...)}` as we accept anything here. It is
446 // up to the target to decide if the feature is available.
447 if (Set == TraitSet::device && Selector == TraitSelector::device_isa)
448 return TraitProperty::device_isa___ANY;
449#define OMP_TRAIT_PROPERTY(Enum, TraitSetEnum, TraitSelectorEnum, Str) \
450 if (Set == TraitSet::TraitSetEnum && Str == S) \
451 return TraitProperty::Enum;
452#include "llvm/Frontend/OpenMP/OMPKinds.def"
453 return TraitProperty::invalid;
454}
455TraitProperty
456llvm::omp::getOpenMPContextTraitPropertyForSelector(TraitSelector Selector) {
457 return StringSwitch<TraitProperty>(
458 getOpenMPContextTraitSelectorName(Selector))
459#define OMP_TRAIT_PROPERTY(Enum, TraitSetEnum, TraitSelectorEnum, Str) \
460 .Case(Str, Selector == TraitSelector::TraitSelectorEnum \
461 ? TraitProperty::Enum \
462 : TraitProperty::invalid)
463#include "llvm/Frontend/OpenMP/OMPKinds.def"
464 .Default(TraitProperty::invalid);
465}
466StringRef llvm::omp::getOpenMPContextTraitPropertyName(TraitProperty Kind,
467 StringRef RawString) {
468 if (Kind == TraitProperty::device_isa___ANY)
469 return RawString;
470 switch (Kind) {
471#define OMP_TRAIT_PROPERTY(Enum, TraitSetEnum, TraitSelectorEnum, Str) \
472 case TraitProperty::Enum: \
473 return Str;
474#include "llvm/Frontend/OpenMP/OMPKinds.def"
475 }
476 llvm_unreachable("Unknown trait property!")::llvm::llvm_unreachable_internal("Unknown trait property!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 476)
;
477}
478StringRef llvm::omp::getOpenMPContextTraitPropertyFullName(TraitProperty Kind) {
479 switch (Kind) {
480#define OMP_TRAIT_PROPERTY(Enum, TraitSetEnum, TraitSelectorEnum, Str) \
481 case TraitProperty::Enum: \
482 return "(" #TraitSetEnum "," #TraitSelectorEnum "," Str ")";
483#include "llvm/Frontend/OpenMP/OMPKinds.def"
484 }
485 llvm_unreachable("Unknown trait property!")::llvm::llvm_unreachable_internal("Unknown trait property!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 485)
;
486}
487
488bool llvm::omp::isValidTraitSelectorForTraitSet(TraitSelector Selector,
489 TraitSet Set,
490 bool &AllowsTraitScore,
491 bool &RequiresProperty) {
492 AllowsTraitScore = Set != TraitSet::construct && Set != TraitSet::device;
493 switch (Selector) {
494#define OMP_TRAIT_SELECTOR(Enum, TraitSetEnum, Str, ReqProp) \
495 case TraitSelector::Enum: \
496 RequiresProperty = ReqProp; \
497 return Set == TraitSet::TraitSetEnum;
498#include "llvm/Frontend/OpenMP/OMPKinds.def"
499 }
500 llvm_unreachable("Unknown trait selector!")::llvm::llvm_unreachable_internal("Unknown trait selector!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 500)
;
501}
502
503bool llvm::omp::isValidTraitPropertyForTraitSetAndSelector(
504 TraitProperty Property, TraitSelector Selector, TraitSet Set) {
505 switch (Property) {
506#define OMP_TRAIT_PROPERTY(Enum, TraitSetEnum, TraitSelectorEnum, Str) \
507 case TraitProperty::Enum: \
508 return Set == TraitSet::TraitSetEnum && \
509 Selector == TraitSelector::TraitSelectorEnum;
510#include "llvm/Frontend/OpenMP/OMPKinds.def"
511 }
512 llvm_unreachable("Unknown trait property!")::llvm::llvm_unreachable_internal("Unknown trait property!", "/build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/llvm/lib/Frontend/OpenMP/OMPContext.cpp"
, 512)
;
513}
514
515std::string llvm::omp::listOpenMPContextTraitSets() {
516 std::string S;
517#define OMP_TRAIT_SET(Enum, Str) \
518 if (StringRef(Str) != "invalid") \
519 S.append("'").append(Str).append("'").append(" ");
520#include "llvm/Frontend/OpenMP/OMPKinds.def"
521 S.pop_back();
522 return S;
523}
524
525std::string llvm::omp::listOpenMPContextTraitSelectors(TraitSet Set) {
526 std::string S;
527#define OMP_TRAIT_SELECTOR(Enum, TraitSetEnum, Str, ReqProp) \
528 if (TraitSet::TraitSetEnum == Set && StringRef(Str) != "Invalid") \
529 S.append("'").append(Str).append("'").append(" ");
530#include "llvm/Frontend/OpenMP/OMPKinds.def"
531 S.pop_back();
532 return S;
533}
534
535std::string
536llvm::omp::listOpenMPContextTraitProperties(TraitSet Set,
537 TraitSelector Selector) {
538 std::string S;
539#define OMP_TRAIT_PROPERTY(Enum, TraitSetEnum, TraitSelectorEnum, Str) \
540 if (TraitSet::TraitSetEnum == Set && \
541 TraitSelector::TraitSelectorEnum == Selector && \
542 StringRef(Str) != "invalid") \
543 S.append("'").append(Str).append("'").append(" ");
544#include "llvm/Frontend/OpenMP/OMPKinds.def"
545 if (S.empty())
546 return "<none>";
547 S.pop_back();
548 return S;
549}

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