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 -clear-ast-before-backend -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/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~++20220126101029+f487a76430a0/llvm/lib/Frontend/OpenMP -I include -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-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 -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-26-233846-219801-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/lib/Frontend/OpenMP/OMPContext.cpp

/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/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!\""
, "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!\""
, "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!\""
, "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!\""
, "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!\""
, "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!\""
, "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!\""
, "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!\""
, "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!"
, "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!\""
, "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!\""
, "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!\""
, "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!\""
, "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!\""
, "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!", "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!", "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!", "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!", "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!", "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!", "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!", "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!", "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!", "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~++20220126101029+f487a76430a0/llvm/include/llvm/ADT/APInt.h

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