File: | llvm/lib/Analysis/ConstantFolding.cpp |
Warning: | line 2561, column 35 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===-- ConstantFolding.cpp - Fold instructions into constants ------------===// | ||||||||||||
2 | // | ||||||||||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||||||||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||||||||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||||||||||
6 | // | ||||||||||||
7 | //===----------------------------------------------------------------------===// | ||||||||||||
8 | // | ||||||||||||
9 | // This file defines routines for folding instructions into constants. | ||||||||||||
10 | // | ||||||||||||
11 | // Also, to supplement the basic IR ConstantExpr simplifications, | ||||||||||||
12 | // this file defines some additional folding routines that can make use of | ||||||||||||
13 | // DataLayout information. These functions cannot go in IR due to library | ||||||||||||
14 | // dependency issues. | ||||||||||||
15 | // | ||||||||||||
16 | //===----------------------------------------------------------------------===// | ||||||||||||
17 | |||||||||||||
18 | #include "llvm/Analysis/ConstantFolding.h" | ||||||||||||
19 | #include "llvm/ADT/APFloat.h" | ||||||||||||
20 | #include "llvm/ADT/APInt.h" | ||||||||||||
21 | #include "llvm/ADT/APSInt.h" | ||||||||||||
22 | #include "llvm/ADT/ArrayRef.h" | ||||||||||||
23 | #include "llvm/ADT/DenseMap.h" | ||||||||||||
24 | #include "llvm/ADT/STLExtras.h" | ||||||||||||
25 | #include "llvm/ADT/SmallVector.h" | ||||||||||||
26 | #include "llvm/ADT/StringRef.h" | ||||||||||||
27 | #include "llvm/Analysis/TargetFolder.h" | ||||||||||||
28 | #include "llvm/Analysis/TargetLibraryInfo.h" | ||||||||||||
29 | #include "llvm/Analysis/ValueTracking.h" | ||||||||||||
30 | #include "llvm/Analysis/VectorUtils.h" | ||||||||||||
31 | #include "llvm/Config/config.h" | ||||||||||||
32 | #include "llvm/IR/Constant.h" | ||||||||||||
33 | #include "llvm/IR/Constants.h" | ||||||||||||
34 | #include "llvm/IR/DataLayout.h" | ||||||||||||
35 | #include "llvm/IR/DerivedTypes.h" | ||||||||||||
36 | #include "llvm/IR/Function.h" | ||||||||||||
37 | #include "llvm/IR/GlobalValue.h" | ||||||||||||
38 | #include "llvm/IR/GlobalVariable.h" | ||||||||||||
39 | #include "llvm/IR/InstrTypes.h" | ||||||||||||
40 | #include "llvm/IR/Instruction.h" | ||||||||||||
41 | #include "llvm/IR/Instructions.h" | ||||||||||||
42 | #include "llvm/IR/IntrinsicInst.h" | ||||||||||||
43 | #include "llvm/IR/Intrinsics.h" | ||||||||||||
44 | #include "llvm/IR/IntrinsicsAMDGPU.h" | ||||||||||||
45 | #include "llvm/IR/IntrinsicsARM.h" | ||||||||||||
46 | #include "llvm/IR/IntrinsicsWebAssembly.h" | ||||||||||||
47 | #include "llvm/IR/IntrinsicsX86.h" | ||||||||||||
48 | #include "llvm/IR/Operator.h" | ||||||||||||
49 | #include "llvm/IR/Type.h" | ||||||||||||
50 | #include "llvm/IR/Value.h" | ||||||||||||
51 | #include "llvm/Support/Casting.h" | ||||||||||||
52 | #include "llvm/Support/ErrorHandling.h" | ||||||||||||
53 | #include "llvm/Support/KnownBits.h" | ||||||||||||
54 | #include "llvm/Support/MathExtras.h" | ||||||||||||
55 | #include <cassert> | ||||||||||||
56 | #include <cerrno> | ||||||||||||
57 | #include <cfenv> | ||||||||||||
58 | #include <cmath> | ||||||||||||
59 | #include <cstddef> | ||||||||||||
60 | #include <cstdint> | ||||||||||||
61 | |||||||||||||
62 | using namespace llvm; | ||||||||||||
63 | |||||||||||||
64 | namespace { | ||||||||||||
65 | |||||||||||||
66 | //===----------------------------------------------------------------------===// | ||||||||||||
67 | // Constant Folding internal helper functions | ||||||||||||
68 | //===----------------------------------------------------------------------===// | ||||||||||||
69 | |||||||||||||
70 | static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy, | ||||||||||||
71 | Constant *C, Type *SrcEltTy, | ||||||||||||
72 | unsigned NumSrcElts, | ||||||||||||
73 | const DataLayout &DL) { | ||||||||||||
74 | // Now that we know that the input value is a vector of integers, just shift | ||||||||||||
75 | // and insert them into our result. | ||||||||||||
76 | unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy); | ||||||||||||
77 | for (unsigned i = 0; i != NumSrcElts; ++i) { | ||||||||||||
78 | Constant *Element; | ||||||||||||
79 | if (DL.isLittleEndian()) | ||||||||||||
80 | Element = C->getAggregateElement(NumSrcElts - i - 1); | ||||||||||||
81 | else | ||||||||||||
82 | Element = C->getAggregateElement(i); | ||||||||||||
83 | |||||||||||||
84 | if (Element && isa<UndefValue>(Element)) { | ||||||||||||
85 | Result <<= BitShift; | ||||||||||||
86 | continue; | ||||||||||||
87 | } | ||||||||||||
88 | |||||||||||||
89 | auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element); | ||||||||||||
90 | if (!ElementCI) | ||||||||||||
91 | return ConstantExpr::getBitCast(C, DestTy); | ||||||||||||
92 | |||||||||||||
93 | Result <<= BitShift; | ||||||||||||
94 | Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth()); | ||||||||||||
95 | } | ||||||||||||
96 | |||||||||||||
97 | return nullptr; | ||||||||||||
98 | } | ||||||||||||
99 | |||||||||||||
100 | /// Constant fold bitcast, symbolically evaluating it with DataLayout. | ||||||||||||
101 | /// This always returns a non-null constant, but it may be a | ||||||||||||
102 | /// ConstantExpr if unfoldable. | ||||||||||||
103 | Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) { | ||||||||||||
104 | assert(CastInst::castIsValid(Instruction::BitCast, C, DestTy) &&((CastInst::castIsValid(Instruction::BitCast, C, DestTy) && "Invalid constantexpr bitcast!") ? static_cast<void> ( 0) : __assert_fail ("CastInst::castIsValid(Instruction::BitCast, C, DestTy) && \"Invalid constantexpr bitcast!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 105, __PRETTY_FUNCTION__)) | ||||||||||||
105 | "Invalid constantexpr bitcast!")((CastInst::castIsValid(Instruction::BitCast, C, DestTy) && "Invalid constantexpr bitcast!") ? static_cast<void> ( 0) : __assert_fail ("CastInst::castIsValid(Instruction::BitCast, C, DestTy) && \"Invalid constantexpr bitcast!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 105, __PRETTY_FUNCTION__)); | ||||||||||||
106 | |||||||||||||
107 | // Catch the obvious splat cases. | ||||||||||||
108 | if (C->isNullValue() && !DestTy->isX86_MMXTy()) | ||||||||||||
109 | return Constant::getNullValue(DestTy); | ||||||||||||
110 | if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() && | ||||||||||||
111 | !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types! | ||||||||||||
112 | return Constant::getAllOnesValue(DestTy); | ||||||||||||
113 | |||||||||||||
114 | if (auto *VTy = dyn_cast<VectorType>(C->getType())) { | ||||||||||||
115 | // Handle a vector->scalar integer/fp cast. | ||||||||||||
116 | if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) { | ||||||||||||
117 | unsigned NumSrcElts = cast<FixedVectorType>(VTy)->getNumElements(); | ||||||||||||
118 | Type *SrcEltTy = VTy->getElementType(); | ||||||||||||
119 | |||||||||||||
120 | // If the vector is a vector of floating point, convert it to vector of int | ||||||||||||
121 | // to simplify things. | ||||||||||||
122 | if (SrcEltTy->isFloatingPointTy()) { | ||||||||||||
123 | unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits(); | ||||||||||||
124 | auto *SrcIVTy = FixedVectorType::get( | ||||||||||||
125 | IntegerType::get(C->getContext(), FPWidth), NumSrcElts); | ||||||||||||
126 | // Ask IR to do the conversion now that #elts line up. | ||||||||||||
127 | C = ConstantExpr::getBitCast(C, SrcIVTy); | ||||||||||||
128 | } | ||||||||||||
129 | |||||||||||||
130 | APInt Result(DL.getTypeSizeInBits(DestTy), 0); | ||||||||||||
131 | if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C, | ||||||||||||
132 | SrcEltTy, NumSrcElts, DL)) | ||||||||||||
133 | return CE; | ||||||||||||
134 | |||||||||||||
135 | if (isa<IntegerType>(DestTy)) | ||||||||||||
136 | return ConstantInt::get(DestTy, Result); | ||||||||||||
137 | |||||||||||||
138 | APFloat FP(DestTy->getFltSemantics(), Result); | ||||||||||||
139 | return ConstantFP::get(DestTy->getContext(), FP); | ||||||||||||
140 | } | ||||||||||||
141 | } | ||||||||||||
142 | |||||||||||||
143 | // The code below only handles casts to vectors currently. | ||||||||||||
144 | auto *DestVTy = dyn_cast<VectorType>(DestTy); | ||||||||||||
145 | if (!DestVTy) | ||||||||||||
146 | return ConstantExpr::getBitCast(C, DestTy); | ||||||||||||
147 | |||||||||||||
148 | // If this is a scalar -> vector cast, convert the input into a <1 x scalar> | ||||||||||||
149 | // vector so the code below can handle it uniformly. | ||||||||||||
150 | if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) { | ||||||||||||
151 | Constant *Ops = C; // don't take the address of C! | ||||||||||||
152 | return FoldBitCast(ConstantVector::get(Ops), DestTy, DL); | ||||||||||||
153 | } | ||||||||||||
154 | |||||||||||||
155 | // If this is a bitcast from constant vector -> vector, fold it. | ||||||||||||
156 | if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C)) | ||||||||||||
157 | return ConstantExpr::getBitCast(C, DestTy); | ||||||||||||
158 | |||||||||||||
159 | // If the element types match, IR can fold it. | ||||||||||||
160 | unsigned NumDstElt = cast<FixedVectorType>(DestVTy)->getNumElements(); | ||||||||||||
161 | unsigned NumSrcElt = cast<FixedVectorType>(C->getType())->getNumElements(); | ||||||||||||
162 | if (NumDstElt == NumSrcElt) | ||||||||||||
163 | return ConstantExpr::getBitCast(C, DestTy); | ||||||||||||
164 | |||||||||||||
165 | Type *SrcEltTy = cast<VectorType>(C->getType())->getElementType(); | ||||||||||||
166 | Type *DstEltTy = DestVTy->getElementType(); | ||||||||||||
167 | |||||||||||||
168 | // Otherwise, we're changing the number of elements in a vector, which | ||||||||||||
169 | // requires endianness information to do the right thing. For example, | ||||||||||||
170 | // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>) | ||||||||||||
171 | // folds to (little endian): | ||||||||||||
172 | // <4 x i32> <i32 0, i32 0, i32 1, i32 0> | ||||||||||||
173 | // and to (big endian): | ||||||||||||
174 | // <4 x i32> <i32 0, i32 0, i32 0, i32 1> | ||||||||||||
175 | |||||||||||||
176 | // First thing is first. We only want to think about integer here, so if | ||||||||||||
177 | // we have something in FP form, recast it as integer. | ||||||||||||
178 | if (DstEltTy->isFloatingPointTy()) { | ||||||||||||
179 | // Fold to an vector of integers with same size as our FP type. | ||||||||||||
180 | unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits(); | ||||||||||||
181 | auto *DestIVTy = FixedVectorType::get( | ||||||||||||
182 | IntegerType::get(C->getContext(), FPWidth), NumDstElt); | ||||||||||||
183 | // Recursively handle this integer conversion, if possible. | ||||||||||||
184 | C = FoldBitCast(C, DestIVTy, DL); | ||||||||||||
185 | |||||||||||||
186 | // Finally, IR can handle this now that #elts line up. | ||||||||||||
187 | return ConstantExpr::getBitCast(C, DestTy); | ||||||||||||
188 | } | ||||||||||||
189 | |||||||||||||
190 | // Okay, we know the destination is integer, if the input is FP, convert | ||||||||||||
191 | // it to integer first. | ||||||||||||
192 | if (SrcEltTy->isFloatingPointTy()) { | ||||||||||||
193 | unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits(); | ||||||||||||
194 | auto *SrcIVTy = FixedVectorType::get( | ||||||||||||
195 | IntegerType::get(C->getContext(), FPWidth), NumSrcElt); | ||||||||||||
196 | // Ask IR to do the conversion now that #elts line up. | ||||||||||||
197 | C = ConstantExpr::getBitCast(C, SrcIVTy); | ||||||||||||
198 | // If IR wasn't able to fold it, bail out. | ||||||||||||
199 | if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector. | ||||||||||||
200 | !isa<ConstantDataVector>(C)) | ||||||||||||
201 | return C; | ||||||||||||
202 | } | ||||||||||||
203 | |||||||||||||
204 | // Now we know that the input and output vectors are both integer vectors | ||||||||||||
205 | // of the same size, and that their #elements is not the same. Do the | ||||||||||||
206 | // conversion here, which depends on whether the input or output has | ||||||||||||
207 | // more elements. | ||||||||||||
208 | bool isLittleEndian = DL.isLittleEndian(); | ||||||||||||
209 | |||||||||||||
210 | SmallVector<Constant*, 32> Result; | ||||||||||||
211 | if (NumDstElt < NumSrcElt) { | ||||||||||||
212 | // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>) | ||||||||||||
213 | Constant *Zero = Constant::getNullValue(DstEltTy); | ||||||||||||
214 | unsigned Ratio = NumSrcElt/NumDstElt; | ||||||||||||
215 | unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits(); | ||||||||||||
216 | unsigned SrcElt = 0; | ||||||||||||
217 | for (unsigned i = 0; i != NumDstElt; ++i) { | ||||||||||||
218 | // Build each element of the result. | ||||||||||||
219 | Constant *Elt = Zero; | ||||||||||||
220 | unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1); | ||||||||||||
221 | for (unsigned j = 0; j != Ratio; ++j) { | ||||||||||||
222 | Constant *Src = C->getAggregateElement(SrcElt++); | ||||||||||||
223 | if (Src && isa<UndefValue>(Src)) | ||||||||||||
224 | Src = Constant::getNullValue( | ||||||||||||
225 | cast<VectorType>(C->getType())->getElementType()); | ||||||||||||
226 | else | ||||||||||||
227 | Src = dyn_cast_or_null<ConstantInt>(Src); | ||||||||||||
228 | if (!Src) // Reject constantexpr elements. | ||||||||||||
229 | return ConstantExpr::getBitCast(C, DestTy); | ||||||||||||
230 | |||||||||||||
231 | // Zero extend the element to the right size. | ||||||||||||
232 | Src = ConstantExpr::getZExt(Src, Elt->getType()); | ||||||||||||
233 | |||||||||||||
234 | // Shift it to the right place, depending on endianness. | ||||||||||||
235 | Src = ConstantExpr::getShl(Src, | ||||||||||||
236 | ConstantInt::get(Src->getType(), ShiftAmt)); | ||||||||||||
237 | ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize; | ||||||||||||
238 | |||||||||||||
239 | // Mix it in. | ||||||||||||
240 | Elt = ConstantExpr::getOr(Elt, Src); | ||||||||||||
241 | } | ||||||||||||
242 | Result.push_back(Elt); | ||||||||||||
243 | } | ||||||||||||
244 | return ConstantVector::get(Result); | ||||||||||||
245 | } | ||||||||||||
246 | |||||||||||||
247 | // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>) | ||||||||||||
248 | unsigned Ratio = NumDstElt/NumSrcElt; | ||||||||||||
249 | unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy); | ||||||||||||
250 | |||||||||||||
251 | // Loop over each source value, expanding into multiple results. | ||||||||||||
252 | for (unsigned i = 0; i != NumSrcElt; ++i) { | ||||||||||||
253 | auto *Element = C->getAggregateElement(i); | ||||||||||||
254 | |||||||||||||
255 | if (!Element) // Reject constantexpr elements. | ||||||||||||
256 | return ConstantExpr::getBitCast(C, DestTy); | ||||||||||||
257 | |||||||||||||
258 | if (isa<UndefValue>(Element)) { | ||||||||||||
259 | // Correctly Propagate undef values. | ||||||||||||
260 | Result.append(Ratio, UndefValue::get(DstEltTy)); | ||||||||||||
261 | continue; | ||||||||||||
262 | } | ||||||||||||
263 | |||||||||||||
264 | auto *Src = dyn_cast<ConstantInt>(Element); | ||||||||||||
265 | if (!Src) | ||||||||||||
266 | return ConstantExpr::getBitCast(C, DestTy); | ||||||||||||
267 | |||||||||||||
268 | unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1); | ||||||||||||
269 | for (unsigned j = 0; j != Ratio; ++j) { | ||||||||||||
270 | // Shift the piece of the value into the right place, depending on | ||||||||||||
271 | // endianness. | ||||||||||||
272 | Constant *Elt = ConstantExpr::getLShr(Src, | ||||||||||||
273 | ConstantInt::get(Src->getType(), ShiftAmt)); | ||||||||||||
274 | ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize; | ||||||||||||
275 | |||||||||||||
276 | // Truncate the element to an integer with the same pointer size and | ||||||||||||
277 | // convert the element back to a pointer using a inttoptr. | ||||||||||||
278 | if (DstEltTy->isPointerTy()) { | ||||||||||||
279 | IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize); | ||||||||||||
280 | Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy); | ||||||||||||
281 | Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy)); | ||||||||||||
282 | continue; | ||||||||||||
283 | } | ||||||||||||
284 | |||||||||||||
285 | // Truncate and remember this piece. | ||||||||||||
286 | Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy)); | ||||||||||||
287 | } | ||||||||||||
288 | } | ||||||||||||
289 | |||||||||||||
290 | return ConstantVector::get(Result); | ||||||||||||
291 | } | ||||||||||||
292 | |||||||||||||
293 | } // end anonymous namespace | ||||||||||||
294 | |||||||||||||
295 | /// If this constant is a constant offset from a global, return the global and | ||||||||||||
296 | /// the constant. Because of constantexprs, this function is recursive. | ||||||||||||
297 | bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, | ||||||||||||
298 | APInt &Offset, const DataLayout &DL) { | ||||||||||||
299 | // Trivial case, constant is the global. | ||||||||||||
300 | if ((GV = dyn_cast<GlobalValue>(C))) { | ||||||||||||
301 | unsigned BitWidth = DL.getIndexTypeSizeInBits(GV->getType()); | ||||||||||||
302 | Offset = APInt(BitWidth, 0); | ||||||||||||
303 | return true; | ||||||||||||
304 | } | ||||||||||||
305 | |||||||||||||
306 | // Otherwise, if this isn't a constant expr, bail out. | ||||||||||||
307 | auto *CE = dyn_cast<ConstantExpr>(C); | ||||||||||||
308 | if (!CE) return false; | ||||||||||||
309 | |||||||||||||
310 | // Look through ptr->int and ptr->ptr casts. | ||||||||||||
311 | if (CE->getOpcode() == Instruction::PtrToInt || | ||||||||||||
312 | CE->getOpcode() == Instruction::BitCast) | ||||||||||||
313 | return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL); | ||||||||||||
314 | |||||||||||||
315 | // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5) | ||||||||||||
316 | auto *GEP = dyn_cast<GEPOperator>(CE); | ||||||||||||
317 | if (!GEP) | ||||||||||||
318 | return false; | ||||||||||||
319 | |||||||||||||
320 | unsigned BitWidth = DL.getIndexTypeSizeInBits(GEP->getType()); | ||||||||||||
321 | APInt TmpOffset(BitWidth, 0); | ||||||||||||
322 | |||||||||||||
323 | // If the base isn't a global+constant, we aren't either. | ||||||||||||
324 | if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL)) | ||||||||||||
325 | return false; | ||||||||||||
326 | |||||||||||||
327 | // Otherwise, add any offset that our operands provide. | ||||||||||||
328 | if (!GEP->accumulateConstantOffset(DL, TmpOffset)) | ||||||||||||
329 | return false; | ||||||||||||
330 | |||||||||||||
331 | Offset = TmpOffset; | ||||||||||||
332 | return true; | ||||||||||||
333 | } | ||||||||||||
334 | |||||||||||||
335 | Constant *llvm::ConstantFoldLoadThroughBitcast(Constant *C, Type *DestTy, | ||||||||||||
336 | const DataLayout &DL) { | ||||||||||||
337 | do { | ||||||||||||
338 | Type *SrcTy = C->getType(); | ||||||||||||
339 | uint64_t DestSize = DL.getTypeSizeInBits(DestTy); | ||||||||||||
340 | uint64_t SrcSize = DL.getTypeSizeInBits(SrcTy); | ||||||||||||
341 | if (SrcSize < DestSize) | ||||||||||||
342 | return nullptr; | ||||||||||||
343 | |||||||||||||
344 | // Catch the obvious splat cases (since all-zeros can coerce non-integral | ||||||||||||
345 | // pointers legally). | ||||||||||||
346 | if (C->isNullValue() && !DestTy->isX86_MMXTy()) | ||||||||||||
347 | return Constant::getNullValue(DestTy); | ||||||||||||
348 | if (C->isAllOnesValue() && | ||||||||||||
349 | (DestTy->isIntegerTy() || DestTy->isFloatingPointTy() || | ||||||||||||
350 | DestTy->isVectorTy()) && | ||||||||||||
351 | !DestTy->isX86_MMXTy() && !DestTy->isPtrOrPtrVectorTy()) | ||||||||||||
352 | // Get ones when the input is trivial, but | ||||||||||||
353 | // only for supported types inside getAllOnesValue. | ||||||||||||
354 | return Constant::getAllOnesValue(DestTy); | ||||||||||||
355 | |||||||||||||
356 | // If the type sizes are the same and a cast is legal, just directly | ||||||||||||
357 | // cast the constant. | ||||||||||||
358 | // But be careful not to coerce non-integral pointers illegally. | ||||||||||||
359 | if (SrcSize == DestSize && | ||||||||||||
360 | DL.isNonIntegralPointerType(SrcTy->getScalarType()) == | ||||||||||||
361 | DL.isNonIntegralPointerType(DestTy->getScalarType())) { | ||||||||||||
362 | Instruction::CastOps Cast = Instruction::BitCast; | ||||||||||||
363 | // If we are going from a pointer to int or vice versa, we spell the cast | ||||||||||||
364 | // differently. | ||||||||||||
365 | if (SrcTy->isIntegerTy() && DestTy->isPointerTy()) | ||||||||||||
366 | Cast = Instruction::IntToPtr; | ||||||||||||
367 | else if (SrcTy->isPointerTy() && DestTy->isIntegerTy()) | ||||||||||||
368 | Cast = Instruction::PtrToInt; | ||||||||||||
369 | |||||||||||||
370 | if (CastInst::castIsValid(Cast, C, DestTy)) | ||||||||||||
371 | return ConstantExpr::getCast(Cast, C, DestTy); | ||||||||||||
372 | } | ||||||||||||
373 | |||||||||||||
374 | // If this isn't an aggregate type, there is nothing we can do to drill down | ||||||||||||
375 | // and find a bitcastable constant. | ||||||||||||
376 | if (!SrcTy->isAggregateType()) | ||||||||||||
377 | return nullptr; | ||||||||||||
378 | |||||||||||||
379 | // We're simulating a load through a pointer that was bitcast to point to | ||||||||||||
380 | // a different type, so we can try to walk down through the initial | ||||||||||||
381 | // elements of an aggregate to see if some part of the aggregate is | ||||||||||||
382 | // castable to implement the "load" semantic model. | ||||||||||||
383 | if (SrcTy->isStructTy()) { | ||||||||||||
384 | // Struct types might have leading zero-length elements like [0 x i32], | ||||||||||||
385 | // which are certainly not what we are looking for, so skip them. | ||||||||||||
386 | unsigned Elem = 0; | ||||||||||||
387 | Constant *ElemC; | ||||||||||||
388 | do { | ||||||||||||
389 | ElemC = C->getAggregateElement(Elem++); | ||||||||||||
390 | } while (ElemC && DL.getTypeSizeInBits(ElemC->getType()).isZero()); | ||||||||||||
391 | C = ElemC; | ||||||||||||
392 | } else { | ||||||||||||
393 | C = C->getAggregateElement(0u); | ||||||||||||
394 | } | ||||||||||||
395 | } while (C); | ||||||||||||
396 | |||||||||||||
397 | return nullptr; | ||||||||||||
398 | } | ||||||||||||
399 | |||||||||||||
400 | namespace { | ||||||||||||
401 | |||||||||||||
402 | /// Recursive helper to read bits out of global. C is the constant being copied | ||||||||||||
403 | /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy | ||||||||||||
404 | /// results into and BytesLeft is the number of bytes left in | ||||||||||||
405 | /// the CurPtr buffer. DL is the DataLayout. | ||||||||||||
406 | bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr, | ||||||||||||
407 | unsigned BytesLeft, const DataLayout &DL) { | ||||||||||||
408 | assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&((ByteOffset <= DL.getTypeAllocSize(C->getType()) && "Out of range access") ? static_cast<void> (0) : __assert_fail ("ByteOffset <= DL.getTypeAllocSize(C->getType()) && \"Out of range access\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 409, __PRETTY_FUNCTION__)) | ||||||||||||
409 | "Out of range access")((ByteOffset <= DL.getTypeAllocSize(C->getType()) && "Out of range access") ? static_cast<void> (0) : __assert_fail ("ByteOffset <= DL.getTypeAllocSize(C->getType()) && \"Out of range access\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 409, __PRETTY_FUNCTION__)); | ||||||||||||
410 | |||||||||||||
411 | // If this element is zero or undefined, we can just return since *CurPtr is | ||||||||||||
412 | // zero initialized. | ||||||||||||
413 | if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) | ||||||||||||
414 | return true; | ||||||||||||
415 | |||||||||||||
416 | if (auto *CI = dyn_cast<ConstantInt>(C)) { | ||||||||||||
417 | if (CI->getBitWidth() > 64 || | ||||||||||||
418 | (CI->getBitWidth() & 7) != 0) | ||||||||||||
419 | return false; | ||||||||||||
420 | |||||||||||||
421 | uint64_t Val = CI->getZExtValue(); | ||||||||||||
422 | unsigned IntBytes = unsigned(CI->getBitWidth()/8); | ||||||||||||
423 | |||||||||||||
424 | for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) { | ||||||||||||
425 | int n = ByteOffset; | ||||||||||||
426 | if (!DL.isLittleEndian()) | ||||||||||||
427 | n = IntBytes - n - 1; | ||||||||||||
428 | CurPtr[i] = (unsigned char)(Val >> (n * 8)); | ||||||||||||
429 | ++ByteOffset; | ||||||||||||
430 | } | ||||||||||||
431 | return true; | ||||||||||||
432 | } | ||||||||||||
433 | |||||||||||||
434 | if (auto *CFP = dyn_cast<ConstantFP>(C)) { | ||||||||||||
435 | if (CFP->getType()->isDoubleTy()) { | ||||||||||||
436 | C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL); | ||||||||||||
437 | return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); | ||||||||||||
438 | } | ||||||||||||
439 | if (CFP->getType()->isFloatTy()){ | ||||||||||||
440 | C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL); | ||||||||||||
441 | return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); | ||||||||||||
442 | } | ||||||||||||
443 | if (CFP->getType()->isHalfTy()){ | ||||||||||||
444 | C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL); | ||||||||||||
445 | return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL); | ||||||||||||
446 | } | ||||||||||||
447 | return false; | ||||||||||||
448 | } | ||||||||||||
449 | |||||||||||||
450 | if (auto *CS = dyn_cast<ConstantStruct>(C)) { | ||||||||||||
451 | const StructLayout *SL = DL.getStructLayout(CS->getType()); | ||||||||||||
452 | unsigned Index = SL->getElementContainingOffset(ByteOffset); | ||||||||||||
453 | uint64_t CurEltOffset = SL->getElementOffset(Index); | ||||||||||||
454 | ByteOffset -= CurEltOffset; | ||||||||||||
455 | |||||||||||||
456 | while (true) { | ||||||||||||
457 | // If the element access is to the element itself and not to tail padding, | ||||||||||||
458 | // read the bytes from the element. | ||||||||||||
459 | uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType()); | ||||||||||||
460 | |||||||||||||
461 | if (ByteOffset < EltSize && | ||||||||||||
462 | !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr, | ||||||||||||
463 | BytesLeft, DL)) | ||||||||||||
464 | return false; | ||||||||||||
465 | |||||||||||||
466 | ++Index; | ||||||||||||
467 | |||||||||||||
468 | // Check to see if we read from the last struct element, if so we're done. | ||||||||||||
469 | if (Index == CS->getType()->getNumElements()) | ||||||||||||
470 | return true; | ||||||||||||
471 | |||||||||||||
472 | // If we read all of the bytes we needed from this element we're done. | ||||||||||||
473 | uint64_t NextEltOffset = SL->getElementOffset(Index); | ||||||||||||
474 | |||||||||||||
475 | if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset) | ||||||||||||
476 | return true; | ||||||||||||
477 | |||||||||||||
478 | // Move to the next element of the struct. | ||||||||||||
479 | CurPtr += NextEltOffset - CurEltOffset - ByteOffset; | ||||||||||||
480 | BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset; | ||||||||||||
481 | ByteOffset = 0; | ||||||||||||
482 | CurEltOffset = NextEltOffset; | ||||||||||||
483 | } | ||||||||||||
484 | // not reached. | ||||||||||||
485 | } | ||||||||||||
486 | |||||||||||||
487 | if (isa<ConstantArray>(C) || isa<ConstantVector>(C) || | ||||||||||||
488 | isa<ConstantDataSequential>(C)) { | ||||||||||||
489 | uint64_t NumElts; | ||||||||||||
490 | Type *EltTy; | ||||||||||||
491 | if (auto *AT = dyn_cast<ArrayType>(C->getType())) { | ||||||||||||
492 | NumElts = AT->getNumElements(); | ||||||||||||
493 | EltTy = AT->getElementType(); | ||||||||||||
494 | } else { | ||||||||||||
495 | NumElts = cast<FixedVectorType>(C->getType())->getNumElements(); | ||||||||||||
496 | EltTy = cast<FixedVectorType>(C->getType())->getElementType(); | ||||||||||||
497 | } | ||||||||||||
498 | uint64_t EltSize = DL.getTypeAllocSize(EltTy); | ||||||||||||
499 | uint64_t Index = ByteOffset / EltSize; | ||||||||||||
500 | uint64_t Offset = ByteOffset - Index * EltSize; | ||||||||||||
501 | |||||||||||||
502 | for (; Index != NumElts; ++Index) { | ||||||||||||
503 | if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr, | ||||||||||||
504 | BytesLeft, DL)) | ||||||||||||
505 | return false; | ||||||||||||
506 | |||||||||||||
507 | uint64_t BytesWritten = EltSize - Offset; | ||||||||||||
508 | assert(BytesWritten <= EltSize && "Not indexing into this element?")((BytesWritten <= EltSize && "Not indexing into this element?" ) ? static_cast<void> (0) : __assert_fail ("BytesWritten <= EltSize && \"Not indexing into this element?\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 508, __PRETTY_FUNCTION__)); | ||||||||||||
509 | if (BytesWritten >= BytesLeft) | ||||||||||||
510 | return true; | ||||||||||||
511 | |||||||||||||
512 | Offset = 0; | ||||||||||||
513 | BytesLeft -= BytesWritten; | ||||||||||||
514 | CurPtr += BytesWritten; | ||||||||||||
515 | } | ||||||||||||
516 | return true; | ||||||||||||
517 | } | ||||||||||||
518 | |||||||||||||
519 | if (auto *CE = dyn_cast<ConstantExpr>(C)) { | ||||||||||||
520 | if (CE->getOpcode() == Instruction::IntToPtr && | ||||||||||||
521 | CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) { | ||||||||||||
522 | return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr, | ||||||||||||
523 | BytesLeft, DL); | ||||||||||||
524 | } | ||||||||||||
525 | } | ||||||||||||
526 | |||||||||||||
527 | // Otherwise, unknown initializer type. | ||||||||||||
528 | return false; | ||||||||||||
529 | } | ||||||||||||
530 | |||||||||||||
531 | Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy, | ||||||||||||
532 | const DataLayout &DL) { | ||||||||||||
533 | // Bail out early. Not expect to load from scalable global variable. | ||||||||||||
534 | if (isa<ScalableVectorType>(LoadTy)) | ||||||||||||
535 | return nullptr; | ||||||||||||
536 | |||||||||||||
537 | auto *PTy = cast<PointerType>(C->getType()); | ||||||||||||
538 | auto *IntType = dyn_cast<IntegerType>(LoadTy); | ||||||||||||
539 | |||||||||||||
540 | // If this isn't an integer load we can't fold it directly. | ||||||||||||
541 | if (!IntType) { | ||||||||||||
542 | unsigned AS = PTy->getAddressSpace(); | ||||||||||||
543 | |||||||||||||
544 | // If this is a float/double load, we can try folding it as an int32/64 load | ||||||||||||
545 | // and then bitcast the result. This can be useful for union cases. Note | ||||||||||||
546 | // that address spaces don't matter here since we're not going to result in | ||||||||||||
547 | // an actual new load. | ||||||||||||
548 | Type *MapTy; | ||||||||||||
549 | if (LoadTy->isHalfTy()) | ||||||||||||
550 | MapTy = Type::getInt16Ty(C->getContext()); | ||||||||||||
551 | else if (LoadTy->isFloatTy()) | ||||||||||||
552 | MapTy = Type::getInt32Ty(C->getContext()); | ||||||||||||
553 | else if (LoadTy->isDoubleTy()) | ||||||||||||
554 | MapTy = Type::getInt64Ty(C->getContext()); | ||||||||||||
555 | else if (LoadTy->isVectorTy()) { | ||||||||||||
556 | MapTy = PointerType::getIntNTy( | ||||||||||||
557 | C->getContext(), DL.getTypeSizeInBits(LoadTy).getFixedSize()); | ||||||||||||
558 | } else | ||||||||||||
559 | return nullptr; | ||||||||||||
560 | |||||||||||||
561 | C = FoldBitCast(C, MapTy->getPointerTo(AS), DL); | ||||||||||||
562 | if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL)) { | ||||||||||||
563 | if (Res->isNullValue() && !LoadTy->isX86_MMXTy()) | ||||||||||||
564 | // Materializing a zero can be done trivially without a bitcast | ||||||||||||
565 | return Constant::getNullValue(LoadTy); | ||||||||||||
566 | Type *CastTy = LoadTy->isPtrOrPtrVectorTy() ? DL.getIntPtrType(LoadTy) : LoadTy; | ||||||||||||
567 | Res = FoldBitCast(Res, CastTy, DL); | ||||||||||||
568 | if (LoadTy->isPtrOrPtrVectorTy()) { | ||||||||||||
569 | // For vector of pointer, we needed to first convert to a vector of integer, then do vector inttoptr | ||||||||||||
570 | if (Res->isNullValue() && !LoadTy->isX86_MMXTy()) | ||||||||||||
571 | return Constant::getNullValue(LoadTy); | ||||||||||||
572 | if (DL.isNonIntegralPointerType(LoadTy->getScalarType())) | ||||||||||||
573 | // Be careful not to replace a load of an addrspace value with an inttoptr here | ||||||||||||
574 | return nullptr; | ||||||||||||
575 | Res = ConstantExpr::getCast(Instruction::IntToPtr, Res, LoadTy); | ||||||||||||
576 | } | ||||||||||||
577 | return Res; | ||||||||||||
578 | } | ||||||||||||
579 | return nullptr; | ||||||||||||
580 | } | ||||||||||||
581 | |||||||||||||
582 | unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8; | ||||||||||||
583 | if (BytesLoaded > 32 || BytesLoaded == 0) | ||||||||||||
584 | return nullptr; | ||||||||||||
585 | |||||||||||||
586 | GlobalValue *GVal; | ||||||||||||
587 | APInt OffsetAI; | ||||||||||||
588 | if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL)) | ||||||||||||
589 | return nullptr; | ||||||||||||
590 | |||||||||||||
591 | auto *GV = dyn_cast<GlobalVariable>(GVal); | ||||||||||||
592 | if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() || | ||||||||||||
593 | !GV->getInitializer()->getType()->isSized()) | ||||||||||||
594 | return nullptr; | ||||||||||||
595 | |||||||||||||
596 | int64_t Offset = OffsetAI.getSExtValue(); | ||||||||||||
597 | int64_t InitializerSize = | ||||||||||||
598 | DL.getTypeAllocSize(GV->getInitializer()->getType()).getFixedSize(); | ||||||||||||
599 | |||||||||||||
600 | // If we're not accessing anything in this constant, the result is undefined. | ||||||||||||
601 | if (Offset <= -1 * static_cast<int64_t>(BytesLoaded)) | ||||||||||||
602 | return UndefValue::get(IntType); | ||||||||||||
603 | |||||||||||||
604 | // If we're not accessing anything in this constant, the result is undefined. | ||||||||||||
605 | if (Offset >= InitializerSize) | ||||||||||||
606 | return UndefValue::get(IntType); | ||||||||||||
607 | |||||||||||||
608 | unsigned char RawBytes[32] = {0}; | ||||||||||||
609 | unsigned char *CurPtr = RawBytes; | ||||||||||||
610 | unsigned BytesLeft = BytesLoaded; | ||||||||||||
611 | |||||||||||||
612 | // If we're loading off the beginning of the global, some bytes may be valid. | ||||||||||||
613 | if (Offset < 0) { | ||||||||||||
614 | CurPtr += -Offset; | ||||||||||||
615 | BytesLeft += Offset; | ||||||||||||
616 | Offset = 0; | ||||||||||||
617 | } | ||||||||||||
618 | |||||||||||||
619 | if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL)) | ||||||||||||
620 | return nullptr; | ||||||||||||
621 | |||||||||||||
622 | APInt ResultVal = APInt(IntType->getBitWidth(), 0); | ||||||||||||
623 | if (DL.isLittleEndian()) { | ||||||||||||
624 | ResultVal = RawBytes[BytesLoaded - 1]; | ||||||||||||
625 | for (unsigned i = 1; i != BytesLoaded; ++i) { | ||||||||||||
626 | ResultVal <<= 8; | ||||||||||||
627 | ResultVal |= RawBytes[BytesLoaded - 1 - i]; | ||||||||||||
628 | } | ||||||||||||
629 | } else { | ||||||||||||
630 | ResultVal = RawBytes[0]; | ||||||||||||
631 | for (unsigned i = 1; i != BytesLoaded; ++i) { | ||||||||||||
632 | ResultVal <<= 8; | ||||||||||||
633 | ResultVal |= RawBytes[i]; | ||||||||||||
634 | } | ||||||||||||
635 | } | ||||||||||||
636 | |||||||||||||
637 | return ConstantInt::get(IntType->getContext(), ResultVal); | ||||||||||||
638 | } | ||||||||||||
639 | |||||||||||||
640 | Constant *ConstantFoldLoadThroughBitcastExpr(ConstantExpr *CE, Type *DestTy, | ||||||||||||
641 | const DataLayout &DL) { | ||||||||||||
642 | auto *SrcPtr = CE->getOperand(0); | ||||||||||||
643 | auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType()); | ||||||||||||
644 | if (!SrcPtrTy) | ||||||||||||
645 | return nullptr; | ||||||||||||
646 | Type *SrcTy = SrcPtrTy->getPointerElementType(); | ||||||||||||
647 | |||||||||||||
648 | Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL); | ||||||||||||
649 | if (!C) | ||||||||||||
650 | return nullptr; | ||||||||||||
651 | |||||||||||||
652 | return llvm::ConstantFoldLoadThroughBitcast(C, DestTy, DL); | ||||||||||||
653 | } | ||||||||||||
654 | |||||||||||||
655 | } // end anonymous namespace | ||||||||||||
656 | |||||||||||||
657 | Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty, | ||||||||||||
658 | const DataLayout &DL) { | ||||||||||||
659 | // First, try the easy cases: | ||||||||||||
660 | if (auto *GV = dyn_cast<GlobalVariable>(C)) | ||||||||||||
661 | if (GV->isConstant() && GV->hasDefinitiveInitializer()) | ||||||||||||
662 | return GV->getInitializer(); | ||||||||||||
663 | |||||||||||||
664 | if (auto *GA = dyn_cast<GlobalAlias>(C)) | ||||||||||||
665 | if (GA->getAliasee() && !GA->isInterposable()) | ||||||||||||
666 | return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL); | ||||||||||||
667 | |||||||||||||
668 | // If the loaded value isn't a constant expr, we can't handle it. | ||||||||||||
669 | auto *CE = dyn_cast<ConstantExpr>(C); | ||||||||||||
670 | if (!CE) | ||||||||||||
671 | return nullptr; | ||||||||||||
672 | |||||||||||||
673 | if (CE->getOpcode() == Instruction::GetElementPtr) { | ||||||||||||
674 | if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) { | ||||||||||||
675 | if (GV->isConstant() && GV->hasDefinitiveInitializer()) { | ||||||||||||
676 | if (Constant *V = | ||||||||||||
677 | ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE)) | ||||||||||||
678 | return V; | ||||||||||||
679 | } | ||||||||||||
680 | } | ||||||||||||
681 | } | ||||||||||||
682 | |||||||||||||
683 | if (CE->getOpcode() == Instruction::BitCast) | ||||||||||||
684 | if (Constant *LoadedC = ConstantFoldLoadThroughBitcastExpr(CE, Ty, DL)) | ||||||||||||
685 | return LoadedC; | ||||||||||||
686 | |||||||||||||
687 | // Instead of loading constant c string, use corresponding integer value | ||||||||||||
688 | // directly if string length is small enough. | ||||||||||||
689 | StringRef Str; | ||||||||||||
690 | if (getConstantStringInfo(CE, Str) && !Str.empty()) { | ||||||||||||
691 | size_t StrLen = Str.size(); | ||||||||||||
692 | unsigned NumBits = Ty->getPrimitiveSizeInBits(); | ||||||||||||
693 | // Replace load with immediate integer if the result is an integer or fp | ||||||||||||
694 | // value. | ||||||||||||
695 | if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 && | ||||||||||||
696 | (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) { | ||||||||||||
697 | APInt StrVal(NumBits, 0); | ||||||||||||
698 | APInt SingleChar(NumBits, 0); | ||||||||||||
699 | if (DL.isLittleEndian()) { | ||||||||||||
700 | for (unsigned char C : reverse(Str.bytes())) { | ||||||||||||
701 | SingleChar = static_cast<uint64_t>(C); | ||||||||||||
702 | StrVal = (StrVal << 8) | SingleChar; | ||||||||||||
703 | } | ||||||||||||
704 | } else { | ||||||||||||
705 | for (unsigned char C : Str.bytes()) { | ||||||||||||
706 | SingleChar = static_cast<uint64_t>(C); | ||||||||||||
707 | StrVal = (StrVal << 8) | SingleChar; | ||||||||||||
708 | } | ||||||||||||
709 | // Append NULL at the end. | ||||||||||||
710 | SingleChar = 0; | ||||||||||||
711 | StrVal = (StrVal << 8) | SingleChar; | ||||||||||||
712 | } | ||||||||||||
713 | |||||||||||||
714 | Constant *Res = ConstantInt::get(CE->getContext(), StrVal); | ||||||||||||
715 | if (Ty->isFloatingPointTy()) | ||||||||||||
716 | Res = ConstantExpr::getBitCast(Res, Ty); | ||||||||||||
717 | return Res; | ||||||||||||
718 | } | ||||||||||||
719 | } | ||||||||||||
720 | |||||||||||||
721 | // If this load comes from anywhere in a constant global, and if the global | ||||||||||||
722 | // is all undef or zero, we know what it loads. | ||||||||||||
723 | if (auto *GV = dyn_cast<GlobalVariable>(getUnderlyingObject(CE))) { | ||||||||||||
724 | if (GV->isConstant() && GV->hasDefinitiveInitializer()) { | ||||||||||||
725 | if (GV->getInitializer()->isNullValue()) | ||||||||||||
726 | return Constant::getNullValue(Ty); | ||||||||||||
727 | if (isa<UndefValue>(GV->getInitializer())) | ||||||||||||
728 | return UndefValue::get(Ty); | ||||||||||||
729 | } | ||||||||||||
730 | } | ||||||||||||
731 | |||||||||||||
732 | // Try hard to fold loads from bitcasted strange and non-type-safe things. | ||||||||||||
733 | return FoldReinterpretLoadFromConstPtr(CE, Ty, DL); | ||||||||||||
734 | } | ||||||||||||
735 | |||||||||||||
736 | namespace { | ||||||||||||
737 | |||||||||||||
738 | Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) { | ||||||||||||
739 | if (LI->isVolatile()) return nullptr; | ||||||||||||
740 | |||||||||||||
741 | if (auto *C = dyn_cast<Constant>(LI->getOperand(0))) | ||||||||||||
742 | return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL); | ||||||||||||
743 | |||||||||||||
744 | return nullptr; | ||||||||||||
745 | } | ||||||||||||
746 | |||||||||||||
747 | /// One of Op0/Op1 is a constant expression. | ||||||||||||
748 | /// Attempt to symbolically evaluate the result of a binary operator merging | ||||||||||||
749 | /// these together. If target data info is available, it is provided as DL, | ||||||||||||
750 | /// otherwise DL is null. | ||||||||||||
751 | Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1, | ||||||||||||
752 | const DataLayout &DL) { | ||||||||||||
753 | // SROA | ||||||||||||
754 | |||||||||||||
755 | // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl. | ||||||||||||
756 | // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute | ||||||||||||
757 | // bits. | ||||||||||||
758 | |||||||||||||
759 | if (Opc == Instruction::And) { | ||||||||||||
760 | KnownBits Known0 = computeKnownBits(Op0, DL); | ||||||||||||
761 | KnownBits Known1 = computeKnownBits(Op1, DL); | ||||||||||||
762 | if ((Known1.One | Known0.Zero).isAllOnesValue()) { | ||||||||||||
763 | // All the bits of Op0 that the 'and' could be masking are already zero. | ||||||||||||
764 | return Op0; | ||||||||||||
765 | } | ||||||||||||
766 | if ((Known0.One | Known1.Zero).isAllOnesValue()) { | ||||||||||||
767 | // All the bits of Op1 that the 'and' could be masking are already zero. | ||||||||||||
768 | return Op1; | ||||||||||||
769 | } | ||||||||||||
770 | |||||||||||||
771 | Known0 &= Known1; | ||||||||||||
772 | if (Known0.isConstant()) | ||||||||||||
773 | return ConstantInt::get(Op0->getType(), Known0.getConstant()); | ||||||||||||
774 | } | ||||||||||||
775 | |||||||||||||
776 | // If the constant expr is something like &A[123] - &A[4].f, fold this into a | ||||||||||||
777 | // constant. This happens frequently when iterating over a global array. | ||||||||||||
778 | if (Opc == Instruction::Sub) { | ||||||||||||
779 | GlobalValue *GV1, *GV2; | ||||||||||||
780 | APInt Offs1, Offs2; | ||||||||||||
781 | |||||||||||||
782 | if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL)) | ||||||||||||
783 | if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) { | ||||||||||||
784 | unsigned OpSize = DL.getTypeSizeInBits(Op0->getType()); | ||||||||||||
785 | |||||||||||||
786 | // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow. | ||||||||||||
787 | // PtrToInt may change the bitwidth so we have convert to the right size | ||||||||||||
788 | // first. | ||||||||||||
789 | return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) - | ||||||||||||
790 | Offs2.zextOrTrunc(OpSize)); | ||||||||||||
791 | } | ||||||||||||
792 | } | ||||||||||||
793 | |||||||||||||
794 | return nullptr; | ||||||||||||
795 | } | ||||||||||||
796 | |||||||||||||
797 | /// If array indices are not pointer-sized integers, explicitly cast them so | ||||||||||||
798 | /// that they aren't implicitly casted by the getelementptr. | ||||||||||||
799 | Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops, | ||||||||||||
800 | Type *ResultTy, Optional<unsigned> InRangeIndex, | ||||||||||||
801 | const DataLayout &DL, const TargetLibraryInfo *TLI) { | ||||||||||||
802 | Type *IntIdxTy = DL.getIndexType(ResultTy); | ||||||||||||
803 | Type *IntIdxScalarTy = IntIdxTy->getScalarType(); | ||||||||||||
804 | |||||||||||||
805 | bool Any = false; | ||||||||||||
806 | SmallVector<Constant*, 32> NewIdxs; | ||||||||||||
807 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) { | ||||||||||||
808 | if ((i == 1 || | ||||||||||||
809 | !isa<StructType>(GetElementPtrInst::getIndexedType( | ||||||||||||
810 | SrcElemTy, Ops.slice(1, i - 1)))) && | ||||||||||||
811 | Ops[i]->getType()->getScalarType() != IntIdxScalarTy) { | ||||||||||||
812 | Any = true; | ||||||||||||
813 | Type *NewType = Ops[i]->getType()->isVectorTy() | ||||||||||||
814 | ? IntIdxTy | ||||||||||||
815 | : IntIdxScalarTy; | ||||||||||||
816 | NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i], | ||||||||||||
817 | true, | ||||||||||||
818 | NewType, | ||||||||||||
819 | true), | ||||||||||||
820 | Ops[i], NewType)); | ||||||||||||
821 | } else | ||||||||||||
822 | NewIdxs.push_back(Ops[i]); | ||||||||||||
823 | } | ||||||||||||
824 | |||||||||||||
825 | if (!Any) | ||||||||||||
826 | return nullptr; | ||||||||||||
827 | |||||||||||||
828 | Constant *C = ConstantExpr::getGetElementPtr( | ||||||||||||
829 | SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex); | ||||||||||||
830 | return ConstantFoldConstant(C, DL, TLI); | ||||||||||||
831 | } | ||||||||||||
832 | |||||||||||||
833 | /// Strip the pointer casts, but preserve the address space information. | ||||||||||||
834 | Constant *StripPtrCastKeepAS(Constant *Ptr, Type *&ElemTy) { | ||||||||||||
835 | assert(Ptr->getType()->isPointerTy() && "Not a pointer type")((Ptr->getType()->isPointerTy() && "Not a pointer type" ) ? static_cast<void> (0) : __assert_fail ("Ptr->getType()->isPointerTy() && \"Not a pointer type\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 835, __PRETTY_FUNCTION__)); | ||||||||||||
836 | auto *OldPtrTy = cast<PointerType>(Ptr->getType()); | ||||||||||||
837 | Ptr = cast<Constant>(Ptr->stripPointerCasts()); | ||||||||||||
838 | auto *NewPtrTy = cast<PointerType>(Ptr->getType()); | ||||||||||||
839 | |||||||||||||
840 | ElemTy = NewPtrTy->getPointerElementType(); | ||||||||||||
841 | |||||||||||||
842 | // Preserve the address space number of the pointer. | ||||||||||||
843 | if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) { | ||||||||||||
844 | NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace()); | ||||||||||||
845 | Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy); | ||||||||||||
846 | } | ||||||||||||
847 | return Ptr; | ||||||||||||
848 | } | ||||||||||||
849 | |||||||||||||
850 | /// If we can symbolically evaluate the GEP constant expression, do so. | ||||||||||||
851 | Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP, | ||||||||||||
852 | ArrayRef<Constant *> Ops, | ||||||||||||
853 | const DataLayout &DL, | ||||||||||||
854 | const TargetLibraryInfo *TLI) { | ||||||||||||
855 | const GEPOperator *InnermostGEP = GEP; | ||||||||||||
856 | bool InBounds = GEP->isInBounds(); | ||||||||||||
857 | |||||||||||||
858 | Type *SrcElemTy = GEP->getSourceElementType(); | ||||||||||||
859 | Type *ResElemTy = GEP->getResultElementType(); | ||||||||||||
860 | Type *ResTy = GEP->getType(); | ||||||||||||
861 | if (!SrcElemTy->isSized() || isa<ScalableVectorType>(SrcElemTy)) | ||||||||||||
862 | return nullptr; | ||||||||||||
863 | |||||||||||||
864 | if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, | ||||||||||||
865 | GEP->getInRangeIndex(), DL, TLI)) | ||||||||||||
866 | return C; | ||||||||||||
867 | |||||||||||||
868 | Constant *Ptr = Ops[0]; | ||||||||||||
869 | if (!Ptr->getType()->isPointerTy()) | ||||||||||||
870 | return nullptr; | ||||||||||||
871 | |||||||||||||
872 | Type *IntIdxTy = DL.getIndexType(Ptr->getType()); | ||||||||||||
873 | |||||||||||||
874 | // If this is a constant expr gep that is effectively computing an | ||||||||||||
875 | // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12' | ||||||||||||
876 | for (unsigned i = 1, e = Ops.size(); i != e; ++i) | ||||||||||||
877 | if (!isa<ConstantInt>(Ops[i])) { | ||||||||||||
878 | |||||||||||||
879 | // If this is "gep i8* Ptr, (sub 0, V)", fold this as: | ||||||||||||
880 | // "inttoptr (sub (ptrtoint Ptr), V)" | ||||||||||||
881 | if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) { | ||||||||||||
882 | auto *CE = dyn_cast<ConstantExpr>(Ops[1]); | ||||||||||||
883 | assert((!CE || CE->getType() == IntIdxTy) &&(((!CE || CE->getType() == IntIdxTy) && "CastGEPIndices didn't canonicalize index types!" ) ? static_cast<void> (0) : __assert_fail ("(!CE || CE->getType() == IntIdxTy) && \"CastGEPIndices didn't canonicalize index types!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 884, __PRETTY_FUNCTION__)) | ||||||||||||
884 | "CastGEPIndices didn't canonicalize index types!")(((!CE || CE->getType() == IntIdxTy) && "CastGEPIndices didn't canonicalize index types!" ) ? static_cast<void> (0) : __assert_fail ("(!CE || CE->getType() == IntIdxTy) && \"CastGEPIndices didn't canonicalize index types!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 884, __PRETTY_FUNCTION__)); | ||||||||||||
885 | if (CE && CE->getOpcode() == Instruction::Sub && | ||||||||||||
886 | CE->getOperand(0)->isNullValue()) { | ||||||||||||
887 | Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType()); | ||||||||||||
888 | Res = ConstantExpr::getSub(Res, CE->getOperand(1)); | ||||||||||||
889 | Res = ConstantExpr::getIntToPtr(Res, ResTy); | ||||||||||||
890 | return ConstantFoldConstant(Res, DL, TLI); | ||||||||||||
891 | } | ||||||||||||
892 | } | ||||||||||||
893 | return nullptr; | ||||||||||||
894 | } | ||||||||||||
895 | |||||||||||||
896 | unsigned BitWidth = DL.getTypeSizeInBits(IntIdxTy); | ||||||||||||
897 | APInt Offset = | ||||||||||||
898 | APInt(BitWidth, | ||||||||||||
899 | DL.getIndexedOffsetInType( | ||||||||||||
900 | SrcElemTy, | ||||||||||||
901 | makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1))); | ||||||||||||
902 | Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy); | ||||||||||||
903 | |||||||||||||
904 | // If this is a GEP of a GEP, fold it all into a single GEP. | ||||||||||||
905 | while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) { | ||||||||||||
906 | InnermostGEP = GEP; | ||||||||||||
907 | InBounds &= GEP->isInBounds(); | ||||||||||||
908 | |||||||||||||
909 | SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end()); | ||||||||||||
910 | |||||||||||||
911 | // Do not try the incorporate the sub-GEP if some index is not a number. | ||||||||||||
912 | bool AllConstantInt = true; | ||||||||||||
913 | for (Value *NestedOp : NestedOps) | ||||||||||||
914 | if (!isa<ConstantInt>(NestedOp)) { | ||||||||||||
915 | AllConstantInt = false; | ||||||||||||
916 | break; | ||||||||||||
917 | } | ||||||||||||
918 | if (!AllConstantInt) | ||||||||||||
919 | break; | ||||||||||||
920 | |||||||||||||
921 | Ptr = cast<Constant>(GEP->getOperand(0)); | ||||||||||||
922 | SrcElemTy = GEP->getSourceElementType(); | ||||||||||||
923 | Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps)); | ||||||||||||
924 | Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy); | ||||||||||||
925 | } | ||||||||||||
926 | |||||||||||||
927 | // If the base value for this address is a literal integer value, fold the | ||||||||||||
928 | // getelementptr to the resulting integer value casted to the pointer type. | ||||||||||||
929 | APInt BasePtr(BitWidth, 0); | ||||||||||||
930 | if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) { | ||||||||||||
931 | if (CE->getOpcode() == Instruction::IntToPtr) { | ||||||||||||
932 | if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0))) | ||||||||||||
933 | BasePtr = Base->getValue().zextOrTrunc(BitWidth); | ||||||||||||
934 | } | ||||||||||||
935 | } | ||||||||||||
936 | |||||||||||||
937 | auto *PTy = cast<PointerType>(Ptr->getType()); | ||||||||||||
938 | if ((Ptr->isNullValue() || BasePtr != 0) && | ||||||||||||
939 | !DL.isNonIntegralPointerType(PTy)) { | ||||||||||||
940 | Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr); | ||||||||||||
941 | return ConstantExpr::getIntToPtr(C, ResTy); | ||||||||||||
942 | } | ||||||||||||
943 | |||||||||||||
944 | // Otherwise form a regular getelementptr. Recompute the indices so that | ||||||||||||
945 | // we eliminate over-indexing of the notional static type array bounds. | ||||||||||||
946 | // This makes it easy to determine if the getelementptr is "inbounds". | ||||||||||||
947 | // Also, this helps GlobalOpt do SROA on GlobalVariables. | ||||||||||||
948 | Type *Ty = PTy; | ||||||||||||
949 | SmallVector<Constant *, 32> NewIdxs; | ||||||||||||
950 | |||||||||||||
951 | do { | ||||||||||||
952 | if (!Ty->isStructTy()) { | ||||||||||||
953 | if (Ty->isPointerTy()) { | ||||||||||||
954 | // The only pointer indexing we'll do is on the first index of the GEP. | ||||||||||||
955 | if (!NewIdxs.empty()) | ||||||||||||
956 | break; | ||||||||||||
957 | |||||||||||||
958 | Ty = SrcElemTy; | ||||||||||||
959 | |||||||||||||
960 | // Only handle pointers to sized types, not pointers to functions. | ||||||||||||
961 | if (!Ty->isSized()) | ||||||||||||
962 | return nullptr; | ||||||||||||
963 | } else { | ||||||||||||
964 | Type *NextTy = GetElementPtrInst::getTypeAtIndex(Ty, (uint64_t)0); | ||||||||||||
965 | if (!NextTy) | ||||||||||||
966 | break; | ||||||||||||
967 | Ty = NextTy; | ||||||||||||
968 | } | ||||||||||||
969 | |||||||||||||
970 | // Determine which element of the array the offset points into. | ||||||||||||
971 | APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty)); | ||||||||||||
972 | if (ElemSize == 0) { | ||||||||||||
973 | // The element size is 0. This may be [0 x Ty]*, so just use a zero | ||||||||||||
974 | // index for this level and proceed to the next level to see if it can | ||||||||||||
975 | // accommodate the offset. | ||||||||||||
976 | NewIdxs.push_back(ConstantInt::get(IntIdxTy, 0)); | ||||||||||||
977 | } else { | ||||||||||||
978 | // The element size is non-zero divide the offset by the element | ||||||||||||
979 | // size (rounding down), to compute the index at this level. | ||||||||||||
980 | bool Overflow; | ||||||||||||
981 | APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow); | ||||||||||||
982 | if (Overflow) | ||||||||||||
983 | break; | ||||||||||||
984 | Offset -= NewIdx * ElemSize; | ||||||||||||
985 | NewIdxs.push_back(ConstantInt::get(IntIdxTy, NewIdx)); | ||||||||||||
986 | } | ||||||||||||
987 | } else { | ||||||||||||
988 | auto *STy = cast<StructType>(Ty); | ||||||||||||
989 | // If we end up with an offset that isn't valid for this struct type, we | ||||||||||||
990 | // can't re-form this GEP in a regular form, so bail out. The pointer | ||||||||||||
991 | // operand likely went through casts that are necessary to make the GEP | ||||||||||||
992 | // sensible. | ||||||||||||
993 | const StructLayout &SL = *DL.getStructLayout(STy); | ||||||||||||
994 | if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes())) | ||||||||||||
995 | break; | ||||||||||||
996 | |||||||||||||
997 | // Determine which field of the struct the offset points into. The | ||||||||||||
998 | // getZExtValue is fine as we've already ensured that the offset is | ||||||||||||
999 | // within the range representable by the StructLayout API. | ||||||||||||
1000 | unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue()); | ||||||||||||
1001 | NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()), | ||||||||||||
1002 | ElIdx)); | ||||||||||||
1003 | Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx)); | ||||||||||||
1004 | Ty = STy->getTypeAtIndex(ElIdx); | ||||||||||||
1005 | } | ||||||||||||
1006 | } while (Ty != ResElemTy); | ||||||||||||
1007 | |||||||||||||
1008 | // If we haven't used up the entire offset by descending the static | ||||||||||||
1009 | // type, then the offset is pointing into the middle of an indivisible | ||||||||||||
1010 | // member, so we can't simplify it. | ||||||||||||
1011 | if (Offset != 0) | ||||||||||||
1012 | return nullptr; | ||||||||||||
1013 | |||||||||||||
1014 | // Preserve the inrange index from the innermost GEP if possible. We must | ||||||||||||
1015 | // have calculated the same indices up to and including the inrange index. | ||||||||||||
1016 | Optional<unsigned> InRangeIndex; | ||||||||||||
1017 | if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex()) | ||||||||||||
1018 | if (SrcElemTy == InnermostGEP->getSourceElementType() && | ||||||||||||
1019 | NewIdxs.size() > *LastIRIndex) { | ||||||||||||
1020 | InRangeIndex = LastIRIndex; | ||||||||||||
1021 | for (unsigned I = 0; I <= *LastIRIndex; ++I) | ||||||||||||
1022 | if (NewIdxs[I] != InnermostGEP->getOperand(I + 1)) | ||||||||||||
1023 | return nullptr; | ||||||||||||
1024 | } | ||||||||||||
1025 | |||||||||||||
1026 | // Create a GEP. | ||||||||||||
1027 | Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs, | ||||||||||||
1028 | InBounds, InRangeIndex); | ||||||||||||
1029 | assert(C->getType()->getPointerElementType() == Ty &&((C->getType()->getPointerElementType() == Ty && "Computed GetElementPtr has unexpected type!") ? static_cast <void> (0) : __assert_fail ("C->getType()->getPointerElementType() == Ty && \"Computed GetElementPtr has unexpected type!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1030, __PRETTY_FUNCTION__)) | ||||||||||||
1030 | "Computed GetElementPtr has unexpected type!")((C->getType()->getPointerElementType() == Ty && "Computed GetElementPtr has unexpected type!") ? static_cast <void> (0) : __assert_fail ("C->getType()->getPointerElementType() == Ty && \"Computed GetElementPtr has unexpected type!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1030, __PRETTY_FUNCTION__)); | ||||||||||||
1031 | |||||||||||||
1032 | // If we ended up indexing a member with a type that doesn't match | ||||||||||||
1033 | // the type of what the original indices indexed, add a cast. | ||||||||||||
1034 | if (Ty != ResElemTy) | ||||||||||||
1035 | C = FoldBitCast(C, ResTy, DL); | ||||||||||||
1036 | |||||||||||||
1037 | return C; | ||||||||||||
1038 | } | ||||||||||||
1039 | |||||||||||||
1040 | /// Attempt to constant fold an instruction with the | ||||||||||||
1041 | /// specified opcode and operands. If successful, the constant result is | ||||||||||||
1042 | /// returned, if not, null is returned. Note that this function can fail when | ||||||||||||
1043 | /// attempting to fold instructions like loads and stores, which have no | ||||||||||||
1044 | /// constant expression form. | ||||||||||||
1045 | Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode, | ||||||||||||
1046 | ArrayRef<Constant *> Ops, | ||||||||||||
1047 | const DataLayout &DL, | ||||||||||||
1048 | const TargetLibraryInfo *TLI) { | ||||||||||||
1049 | Type *DestTy = InstOrCE->getType(); | ||||||||||||
1050 | |||||||||||||
1051 | if (Instruction::isUnaryOp(Opcode)) | ||||||||||||
1052 | return ConstantFoldUnaryOpOperand(Opcode, Ops[0], DL); | ||||||||||||
1053 | |||||||||||||
1054 | if (Instruction::isBinaryOp(Opcode)) | ||||||||||||
1055 | return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL); | ||||||||||||
1056 | |||||||||||||
1057 | if (Instruction::isCast(Opcode)) | ||||||||||||
1058 | return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL); | ||||||||||||
1059 | |||||||||||||
1060 | if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) { | ||||||||||||
1061 | if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI)) | ||||||||||||
1062 | return C; | ||||||||||||
1063 | |||||||||||||
1064 | return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0], | ||||||||||||
1065 | Ops.slice(1), GEP->isInBounds(), | ||||||||||||
1066 | GEP->getInRangeIndex()); | ||||||||||||
1067 | } | ||||||||||||
1068 | |||||||||||||
1069 | if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE)) | ||||||||||||
1070 | return CE->getWithOperands(Ops); | ||||||||||||
1071 | |||||||||||||
1072 | switch (Opcode) { | ||||||||||||
1073 | default: return nullptr; | ||||||||||||
1074 | case Instruction::ICmp: | ||||||||||||
1075 | case Instruction::FCmp: llvm_unreachable("Invalid for compares")::llvm::llvm_unreachable_internal("Invalid for compares", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1075); | ||||||||||||
1076 | case Instruction::Freeze: | ||||||||||||
1077 | return isGuaranteedNotToBeUndefOrPoison(Ops[0]) ? Ops[0] : nullptr; | ||||||||||||
1078 | case Instruction::Call: | ||||||||||||
1079 | if (auto *F = dyn_cast<Function>(Ops.back())) { | ||||||||||||
1080 | const auto *Call = cast<CallBase>(InstOrCE); | ||||||||||||
1081 | if (canConstantFoldCallTo(Call, F)) | ||||||||||||
1082 | return ConstantFoldCall(Call, F, Ops.slice(0, Ops.size() - 1), TLI); | ||||||||||||
1083 | } | ||||||||||||
1084 | return nullptr; | ||||||||||||
1085 | case Instruction::Select: | ||||||||||||
1086 | return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]); | ||||||||||||
1087 | case Instruction::ExtractElement: | ||||||||||||
1088 | return ConstantExpr::getExtractElement(Ops[0], Ops[1]); | ||||||||||||
1089 | case Instruction::ExtractValue: | ||||||||||||
1090 | return ConstantExpr::getExtractValue( | ||||||||||||
1091 | Ops[0], cast<ExtractValueInst>(InstOrCE)->getIndices()); | ||||||||||||
1092 | case Instruction::InsertElement: | ||||||||||||
1093 | return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]); | ||||||||||||
1094 | case Instruction::ShuffleVector: | ||||||||||||
1095 | return ConstantExpr::getShuffleVector( | ||||||||||||
1096 | Ops[0], Ops[1], cast<ShuffleVectorInst>(InstOrCE)->getShuffleMask()); | ||||||||||||
1097 | } | ||||||||||||
1098 | } | ||||||||||||
1099 | |||||||||||||
1100 | } // end anonymous namespace | ||||||||||||
1101 | |||||||||||||
1102 | //===----------------------------------------------------------------------===// | ||||||||||||
1103 | // Constant Folding public APIs | ||||||||||||
1104 | //===----------------------------------------------------------------------===// | ||||||||||||
1105 | |||||||||||||
1106 | namespace { | ||||||||||||
1107 | |||||||||||||
1108 | Constant * | ||||||||||||
1109 | ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL, | ||||||||||||
1110 | const TargetLibraryInfo *TLI, | ||||||||||||
1111 | SmallDenseMap<Constant *, Constant *> &FoldedOps) { | ||||||||||||
1112 | if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C)) | ||||||||||||
1113 | return const_cast<Constant *>(C); | ||||||||||||
1114 | |||||||||||||
1115 | SmallVector<Constant *, 8> Ops; | ||||||||||||
1116 | for (const Use &OldU : C->operands()) { | ||||||||||||
1117 | Constant *OldC = cast<Constant>(&OldU); | ||||||||||||
1118 | Constant *NewC = OldC; | ||||||||||||
1119 | // Recursively fold the ConstantExpr's operands. If we have already folded | ||||||||||||
1120 | // a ConstantExpr, we don't have to process it again. | ||||||||||||
1121 | if (isa<ConstantVector>(OldC) || isa<ConstantExpr>(OldC)) { | ||||||||||||
1122 | auto It = FoldedOps.find(OldC); | ||||||||||||
1123 | if (It == FoldedOps.end()) { | ||||||||||||
1124 | NewC = ConstantFoldConstantImpl(OldC, DL, TLI, FoldedOps); | ||||||||||||
1125 | FoldedOps.insert({OldC, NewC}); | ||||||||||||
1126 | } else { | ||||||||||||
1127 | NewC = It->second; | ||||||||||||
1128 | } | ||||||||||||
1129 | } | ||||||||||||
1130 | Ops.push_back(NewC); | ||||||||||||
1131 | } | ||||||||||||
1132 | |||||||||||||
1133 | if (auto *CE = dyn_cast<ConstantExpr>(C)) { | ||||||||||||
1134 | if (CE->isCompare()) | ||||||||||||
1135 | return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1], | ||||||||||||
1136 | DL, TLI); | ||||||||||||
1137 | |||||||||||||
1138 | return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI); | ||||||||||||
1139 | } | ||||||||||||
1140 | |||||||||||||
1141 | assert(isa<ConstantVector>(C))((isa<ConstantVector>(C)) ? static_cast<void> (0) : __assert_fail ("isa<ConstantVector>(C)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1141, __PRETTY_FUNCTION__)); | ||||||||||||
1142 | return ConstantVector::get(Ops); | ||||||||||||
1143 | } | ||||||||||||
1144 | |||||||||||||
1145 | } // end anonymous namespace | ||||||||||||
1146 | |||||||||||||
1147 | Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL, | ||||||||||||
1148 | const TargetLibraryInfo *TLI) { | ||||||||||||
1149 | // Handle PHI nodes quickly here... | ||||||||||||
1150 | if (auto *PN = dyn_cast<PHINode>(I)) { | ||||||||||||
1151 | Constant *CommonValue = nullptr; | ||||||||||||
1152 | |||||||||||||
1153 | SmallDenseMap<Constant *, Constant *> FoldedOps; | ||||||||||||
1154 | for (Value *Incoming : PN->incoming_values()) { | ||||||||||||
1155 | // If the incoming value is undef then skip it. Note that while we could | ||||||||||||
1156 | // skip the value if it is equal to the phi node itself we choose not to | ||||||||||||
1157 | // because that would break the rule that constant folding only applies if | ||||||||||||
1158 | // all operands are constants. | ||||||||||||
1159 | if (isa<UndefValue>(Incoming)) | ||||||||||||
1160 | continue; | ||||||||||||
1161 | // If the incoming value is not a constant, then give up. | ||||||||||||
1162 | auto *C = dyn_cast<Constant>(Incoming); | ||||||||||||
1163 | if (!C) | ||||||||||||
1164 | return nullptr; | ||||||||||||
1165 | // Fold the PHI's operands. | ||||||||||||
1166 | C = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps); | ||||||||||||
1167 | // If the incoming value is a different constant to | ||||||||||||
1168 | // the one we saw previously, then give up. | ||||||||||||
1169 | if (CommonValue && C != CommonValue) | ||||||||||||
1170 | return nullptr; | ||||||||||||
1171 | CommonValue = C; | ||||||||||||
1172 | } | ||||||||||||
1173 | |||||||||||||
1174 | // If we reach here, all incoming values are the same constant or undef. | ||||||||||||
1175 | return CommonValue ? CommonValue : UndefValue::get(PN->getType()); | ||||||||||||
1176 | } | ||||||||||||
1177 | |||||||||||||
1178 | // Scan the operand list, checking to see if they are all constants, if so, | ||||||||||||
1179 | // hand off to ConstantFoldInstOperandsImpl. | ||||||||||||
1180 | if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); })) | ||||||||||||
1181 | return nullptr; | ||||||||||||
1182 | |||||||||||||
1183 | SmallDenseMap<Constant *, Constant *> FoldedOps; | ||||||||||||
1184 | SmallVector<Constant *, 8> Ops; | ||||||||||||
1185 | for (const Use &OpU : I->operands()) { | ||||||||||||
1186 | auto *Op = cast<Constant>(&OpU); | ||||||||||||
1187 | // Fold the Instruction's operands. | ||||||||||||
1188 | Op = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps); | ||||||||||||
1189 | Ops.push_back(Op); | ||||||||||||
1190 | } | ||||||||||||
1191 | |||||||||||||
1192 | if (const auto *CI = dyn_cast<CmpInst>(I)) | ||||||||||||
1193 | return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1], | ||||||||||||
1194 | DL, TLI); | ||||||||||||
1195 | |||||||||||||
1196 | if (const auto *LI = dyn_cast<LoadInst>(I)) | ||||||||||||
1197 | return ConstantFoldLoadInst(LI, DL); | ||||||||||||
1198 | |||||||||||||
1199 | if (auto *IVI = dyn_cast<InsertValueInst>(I)) { | ||||||||||||
1200 | return ConstantExpr::getInsertValue( | ||||||||||||
1201 | cast<Constant>(IVI->getAggregateOperand()), | ||||||||||||
1202 | cast<Constant>(IVI->getInsertedValueOperand()), | ||||||||||||
1203 | IVI->getIndices()); | ||||||||||||
1204 | } | ||||||||||||
1205 | |||||||||||||
1206 | if (auto *EVI = dyn_cast<ExtractValueInst>(I)) { | ||||||||||||
1207 | return ConstantExpr::getExtractValue( | ||||||||||||
1208 | cast<Constant>(EVI->getAggregateOperand()), | ||||||||||||
1209 | EVI->getIndices()); | ||||||||||||
1210 | } | ||||||||||||
1211 | |||||||||||||
1212 | return ConstantFoldInstOperands(I, Ops, DL, TLI); | ||||||||||||
1213 | } | ||||||||||||
1214 | |||||||||||||
1215 | Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL, | ||||||||||||
1216 | const TargetLibraryInfo *TLI) { | ||||||||||||
1217 | SmallDenseMap<Constant *, Constant *> FoldedOps; | ||||||||||||
1218 | return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps); | ||||||||||||
1219 | } | ||||||||||||
1220 | |||||||||||||
1221 | Constant *llvm::ConstantFoldInstOperands(Instruction *I, | ||||||||||||
1222 | ArrayRef<Constant *> Ops, | ||||||||||||
1223 | const DataLayout &DL, | ||||||||||||
1224 | const TargetLibraryInfo *TLI) { | ||||||||||||
1225 | return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI); | ||||||||||||
1226 | } | ||||||||||||
1227 | |||||||||||||
1228 | Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate, | ||||||||||||
1229 | Constant *Ops0, Constant *Ops1, | ||||||||||||
1230 | const DataLayout &DL, | ||||||||||||
1231 | const TargetLibraryInfo *TLI) { | ||||||||||||
1232 | // fold: icmp (inttoptr x), null -> icmp x, 0 | ||||||||||||
1233 | // fold: icmp null, (inttoptr x) -> icmp 0, x | ||||||||||||
1234 | // fold: icmp (ptrtoint x), 0 -> icmp x, null | ||||||||||||
1235 | // fold: icmp 0, (ptrtoint x) -> icmp null, x | ||||||||||||
1236 | // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y | ||||||||||||
1237 | // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y | ||||||||||||
1238 | // | ||||||||||||
1239 | // FIXME: The following comment is out of data and the DataLayout is here now. | ||||||||||||
1240 | // ConstantExpr::getCompare cannot do this, because it doesn't have DL | ||||||||||||
1241 | // around to know if bit truncation is happening. | ||||||||||||
1242 | if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) { | ||||||||||||
1243 | if (Ops1->isNullValue()) { | ||||||||||||
1244 | if (CE0->getOpcode() == Instruction::IntToPtr) { | ||||||||||||
1245 | Type *IntPtrTy = DL.getIntPtrType(CE0->getType()); | ||||||||||||
1246 | // Convert the integer value to the right size to ensure we get the | ||||||||||||
1247 | // proper extension or truncation. | ||||||||||||
1248 | Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0), | ||||||||||||
1249 | IntPtrTy, false); | ||||||||||||
1250 | Constant *Null = Constant::getNullValue(C->getType()); | ||||||||||||
1251 | return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI); | ||||||||||||
1252 | } | ||||||||||||
1253 | |||||||||||||
1254 | // Only do this transformation if the int is intptrty in size, otherwise | ||||||||||||
1255 | // there is a truncation or extension that we aren't modeling. | ||||||||||||
1256 | if (CE0->getOpcode() == Instruction::PtrToInt) { | ||||||||||||
1257 | Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType()); | ||||||||||||
1258 | if (CE0->getType() == IntPtrTy) { | ||||||||||||
1259 | Constant *C = CE0->getOperand(0); | ||||||||||||
1260 | Constant *Null = Constant::getNullValue(C->getType()); | ||||||||||||
1261 | return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI); | ||||||||||||
1262 | } | ||||||||||||
1263 | } | ||||||||||||
1264 | } | ||||||||||||
1265 | |||||||||||||
1266 | if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) { | ||||||||||||
1267 | if (CE0->getOpcode() == CE1->getOpcode()) { | ||||||||||||
1268 | if (CE0->getOpcode() == Instruction::IntToPtr) { | ||||||||||||
1269 | Type *IntPtrTy = DL.getIntPtrType(CE0->getType()); | ||||||||||||
1270 | |||||||||||||
1271 | // Convert the integer value to the right size to ensure we get the | ||||||||||||
1272 | // proper extension or truncation. | ||||||||||||
1273 | Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0), | ||||||||||||
1274 | IntPtrTy, false); | ||||||||||||
1275 | Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0), | ||||||||||||
1276 | IntPtrTy, false); | ||||||||||||
1277 | return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI); | ||||||||||||
1278 | } | ||||||||||||
1279 | |||||||||||||
1280 | // Only do this transformation if the int is intptrty in size, otherwise | ||||||||||||
1281 | // there is a truncation or extension that we aren't modeling. | ||||||||||||
1282 | if (CE0->getOpcode() == Instruction::PtrToInt) { | ||||||||||||
1283 | Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType()); | ||||||||||||
1284 | if (CE0->getType() == IntPtrTy && | ||||||||||||
1285 | CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) { | ||||||||||||
1286 | return ConstantFoldCompareInstOperands( | ||||||||||||
1287 | Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI); | ||||||||||||
1288 | } | ||||||||||||
1289 | } | ||||||||||||
1290 | } | ||||||||||||
1291 | } | ||||||||||||
1292 | |||||||||||||
1293 | // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0) | ||||||||||||
1294 | // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0) | ||||||||||||
1295 | if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) && | ||||||||||||
1296 | CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) { | ||||||||||||
1297 | Constant *LHS = ConstantFoldCompareInstOperands( | ||||||||||||
1298 | Predicate, CE0->getOperand(0), Ops1, DL, TLI); | ||||||||||||
1299 | Constant *RHS = ConstantFoldCompareInstOperands( | ||||||||||||
1300 | Predicate, CE0->getOperand(1), Ops1, DL, TLI); | ||||||||||||
1301 | unsigned OpC = | ||||||||||||
1302 | Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or; | ||||||||||||
1303 | return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL); | ||||||||||||
1304 | } | ||||||||||||
1305 | } else if (isa<ConstantExpr>(Ops1)) { | ||||||||||||
1306 | // If RHS is a constant expression, but the left side isn't, swap the | ||||||||||||
1307 | // operands and try again. | ||||||||||||
1308 | Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate); | ||||||||||||
1309 | return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI); | ||||||||||||
1310 | } | ||||||||||||
1311 | |||||||||||||
1312 | return ConstantExpr::getCompare(Predicate, Ops0, Ops1); | ||||||||||||
1313 | } | ||||||||||||
1314 | |||||||||||||
1315 | Constant *llvm::ConstantFoldUnaryOpOperand(unsigned Opcode, Constant *Op, | ||||||||||||
1316 | const DataLayout &DL) { | ||||||||||||
1317 | assert(Instruction::isUnaryOp(Opcode))((Instruction::isUnaryOp(Opcode)) ? static_cast<void> ( 0) : __assert_fail ("Instruction::isUnaryOp(Opcode)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1317, __PRETTY_FUNCTION__)); | ||||||||||||
1318 | |||||||||||||
1319 | return ConstantExpr::get(Opcode, Op); | ||||||||||||
1320 | } | ||||||||||||
1321 | |||||||||||||
1322 | Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, | ||||||||||||
1323 | Constant *RHS, | ||||||||||||
1324 | const DataLayout &DL) { | ||||||||||||
1325 | assert(Instruction::isBinaryOp(Opcode))((Instruction::isBinaryOp(Opcode)) ? static_cast<void> ( 0) : __assert_fail ("Instruction::isBinaryOp(Opcode)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1325, __PRETTY_FUNCTION__)); | ||||||||||||
1326 | if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS)) | ||||||||||||
1327 | if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL)) | ||||||||||||
1328 | return C; | ||||||||||||
1329 | |||||||||||||
1330 | return ConstantExpr::get(Opcode, LHS, RHS); | ||||||||||||
1331 | } | ||||||||||||
1332 | |||||||||||||
1333 | Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C, | ||||||||||||
1334 | Type *DestTy, const DataLayout &DL) { | ||||||||||||
1335 | assert(Instruction::isCast(Opcode))((Instruction::isCast(Opcode)) ? static_cast<void> (0) : __assert_fail ("Instruction::isCast(Opcode)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1335, __PRETTY_FUNCTION__)); | ||||||||||||
1336 | switch (Opcode) { | ||||||||||||
1337 | default: | ||||||||||||
1338 | llvm_unreachable("Missing case")::llvm::llvm_unreachable_internal("Missing case", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1338); | ||||||||||||
1339 | case Instruction::PtrToInt: | ||||||||||||
1340 | // If the input is a inttoptr, eliminate the pair. This requires knowing | ||||||||||||
1341 | // the width of a pointer, so it can't be done in ConstantExpr::getCast. | ||||||||||||
1342 | if (auto *CE = dyn_cast<ConstantExpr>(C)) { | ||||||||||||
1343 | if (CE->getOpcode() == Instruction::IntToPtr) { | ||||||||||||
1344 | Constant *Input = CE->getOperand(0); | ||||||||||||
1345 | unsigned InWidth = Input->getType()->getScalarSizeInBits(); | ||||||||||||
1346 | unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType()); | ||||||||||||
1347 | if (PtrWidth < InWidth) { | ||||||||||||
1348 | Constant *Mask = | ||||||||||||
1349 | ConstantInt::get(CE->getContext(), | ||||||||||||
1350 | APInt::getLowBitsSet(InWidth, PtrWidth)); | ||||||||||||
1351 | Input = ConstantExpr::getAnd(Input, Mask); | ||||||||||||
1352 | } | ||||||||||||
1353 | // Do a zext or trunc to get to the dest size. | ||||||||||||
1354 | return ConstantExpr::getIntegerCast(Input, DestTy, false); | ||||||||||||
1355 | } | ||||||||||||
1356 | } | ||||||||||||
1357 | return ConstantExpr::getCast(Opcode, C, DestTy); | ||||||||||||
1358 | case Instruction::IntToPtr: | ||||||||||||
1359 | // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if | ||||||||||||
1360 | // the int size is >= the ptr size and the address spaces are the same. | ||||||||||||
1361 | // This requires knowing the width of a pointer, so it can't be done in | ||||||||||||
1362 | // ConstantExpr::getCast. | ||||||||||||
1363 | if (auto *CE = dyn_cast<ConstantExpr>(C)) { | ||||||||||||
1364 | if (CE->getOpcode() == Instruction::PtrToInt) { | ||||||||||||
1365 | Constant *SrcPtr = CE->getOperand(0); | ||||||||||||
1366 | unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType()); | ||||||||||||
1367 | unsigned MidIntSize = CE->getType()->getScalarSizeInBits(); | ||||||||||||
1368 | |||||||||||||
1369 | if (MidIntSize >= SrcPtrSize) { | ||||||||||||
1370 | unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace(); | ||||||||||||
1371 | if (SrcAS == DestTy->getPointerAddressSpace()) | ||||||||||||
1372 | return FoldBitCast(CE->getOperand(0), DestTy, DL); | ||||||||||||
1373 | } | ||||||||||||
1374 | } | ||||||||||||
1375 | } | ||||||||||||
1376 | |||||||||||||
1377 | return ConstantExpr::getCast(Opcode, C, DestTy); | ||||||||||||
1378 | case Instruction::Trunc: | ||||||||||||
1379 | case Instruction::ZExt: | ||||||||||||
1380 | case Instruction::SExt: | ||||||||||||
1381 | case Instruction::FPTrunc: | ||||||||||||
1382 | case Instruction::FPExt: | ||||||||||||
1383 | case Instruction::UIToFP: | ||||||||||||
1384 | case Instruction::SIToFP: | ||||||||||||
1385 | case Instruction::FPToUI: | ||||||||||||
1386 | case Instruction::FPToSI: | ||||||||||||
1387 | case Instruction::AddrSpaceCast: | ||||||||||||
1388 | return ConstantExpr::getCast(Opcode, C, DestTy); | ||||||||||||
1389 | case Instruction::BitCast: | ||||||||||||
1390 | return FoldBitCast(C, DestTy, DL); | ||||||||||||
1391 | } | ||||||||||||
1392 | } | ||||||||||||
1393 | |||||||||||||
1394 | Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, | ||||||||||||
1395 | ConstantExpr *CE) { | ||||||||||||
1396 | if (!CE->getOperand(1)->isNullValue()) | ||||||||||||
1397 | return nullptr; // Do not allow stepping over the value! | ||||||||||||
1398 | |||||||||||||
1399 | // Loop over all of the operands, tracking down which value we are | ||||||||||||
1400 | // addressing. | ||||||||||||
1401 | for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) { | ||||||||||||
1402 | C = C->getAggregateElement(CE->getOperand(i)); | ||||||||||||
1403 | if (!C) | ||||||||||||
1404 | return nullptr; | ||||||||||||
1405 | } | ||||||||||||
1406 | return C; | ||||||||||||
1407 | } | ||||||||||||
1408 | |||||||||||||
1409 | Constant * | ||||||||||||
1410 | llvm::ConstantFoldLoadThroughGEPIndices(Constant *C, | ||||||||||||
1411 | ArrayRef<Constant *> Indices) { | ||||||||||||
1412 | // Loop over all of the operands, tracking down which value we are | ||||||||||||
1413 | // addressing. | ||||||||||||
1414 | for (Constant *Index : Indices) { | ||||||||||||
1415 | C = C->getAggregateElement(Index); | ||||||||||||
1416 | if (!C) | ||||||||||||
1417 | return nullptr; | ||||||||||||
1418 | } | ||||||||||||
1419 | return C; | ||||||||||||
1420 | } | ||||||||||||
1421 | |||||||||||||
1422 | //===----------------------------------------------------------------------===// | ||||||||||||
1423 | // Constant Folding for Calls | ||||||||||||
1424 | // | ||||||||||||
1425 | |||||||||||||
1426 | bool llvm::canConstantFoldCallTo(const CallBase *Call, const Function *F) { | ||||||||||||
1427 | if (Call->isNoBuiltin()) | ||||||||||||
1428 | return false; | ||||||||||||
1429 | switch (F->getIntrinsicID()) { | ||||||||||||
1430 | // Operations that do not operate floating-point numbers and do not depend on | ||||||||||||
1431 | // FP environment can be folded even in strictfp functions. | ||||||||||||
1432 | case Intrinsic::bswap: | ||||||||||||
1433 | case Intrinsic::ctpop: | ||||||||||||
1434 | case Intrinsic::ctlz: | ||||||||||||
1435 | case Intrinsic::cttz: | ||||||||||||
1436 | case Intrinsic::fshl: | ||||||||||||
1437 | case Intrinsic::fshr: | ||||||||||||
1438 | case Intrinsic::launder_invariant_group: | ||||||||||||
1439 | case Intrinsic::strip_invariant_group: | ||||||||||||
1440 | case Intrinsic::masked_load: | ||||||||||||
1441 | case Intrinsic::abs: | ||||||||||||
1442 | case Intrinsic::smax: | ||||||||||||
1443 | case Intrinsic::smin: | ||||||||||||
1444 | case Intrinsic::umax: | ||||||||||||
1445 | case Intrinsic::umin: | ||||||||||||
1446 | case Intrinsic::sadd_with_overflow: | ||||||||||||
1447 | case Intrinsic::uadd_with_overflow: | ||||||||||||
1448 | case Intrinsic::ssub_with_overflow: | ||||||||||||
1449 | case Intrinsic::usub_with_overflow: | ||||||||||||
1450 | case Intrinsic::smul_with_overflow: | ||||||||||||
1451 | case Intrinsic::umul_with_overflow: | ||||||||||||
1452 | case Intrinsic::sadd_sat: | ||||||||||||
1453 | case Intrinsic::uadd_sat: | ||||||||||||
1454 | case Intrinsic::ssub_sat: | ||||||||||||
1455 | case Intrinsic::usub_sat: | ||||||||||||
1456 | case Intrinsic::smul_fix: | ||||||||||||
1457 | case Intrinsic::smul_fix_sat: | ||||||||||||
1458 | case Intrinsic::bitreverse: | ||||||||||||
1459 | case Intrinsic::is_constant: | ||||||||||||
1460 | case Intrinsic::experimental_vector_reduce_add: | ||||||||||||
1461 | case Intrinsic::experimental_vector_reduce_mul: | ||||||||||||
1462 | case Intrinsic::experimental_vector_reduce_and: | ||||||||||||
1463 | case Intrinsic::experimental_vector_reduce_or: | ||||||||||||
1464 | case Intrinsic::experimental_vector_reduce_xor: | ||||||||||||
1465 | case Intrinsic::experimental_vector_reduce_smin: | ||||||||||||
1466 | case Intrinsic::experimental_vector_reduce_smax: | ||||||||||||
1467 | case Intrinsic::experimental_vector_reduce_umin: | ||||||||||||
1468 | case Intrinsic::experimental_vector_reduce_umax: | ||||||||||||
1469 | // Target intrinsics | ||||||||||||
1470 | case Intrinsic::arm_mve_vctp8: | ||||||||||||
1471 | case Intrinsic::arm_mve_vctp16: | ||||||||||||
1472 | case Intrinsic::arm_mve_vctp32: | ||||||||||||
1473 | case Intrinsic::arm_mve_vctp64: | ||||||||||||
1474 | // WebAssembly float semantics are always known | ||||||||||||
1475 | case Intrinsic::wasm_trunc_signed: | ||||||||||||
1476 | case Intrinsic::wasm_trunc_unsigned: | ||||||||||||
1477 | case Intrinsic::wasm_trunc_saturate_signed: | ||||||||||||
1478 | case Intrinsic::wasm_trunc_saturate_unsigned: | ||||||||||||
1479 | return true; | ||||||||||||
1480 | |||||||||||||
1481 | // Floating point operations cannot be folded in strictfp functions in | ||||||||||||
1482 | // general case. They can be folded if FP environment is known to compiler. | ||||||||||||
1483 | case Intrinsic::minnum: | ||||||||||||
1484 | case Intrinsic::maxnum: | ||||||||||||
1485 | case Intrinsic::minimum: | ||||||||||||
1486 | case Intrinsic::maximum: | ||||||||||||
1487 | case Intrinsic::log: | ||||||||||||
1488 | case Intrinsic::log2: | ||||||||||||
1489 | case Intrinsic::log10: | ||||||||||||
1490 | case Intrinsic::exp: | ||||||||||||
1491 | case Intrinsic::exp2: | ||||||||||||
1492 | case Intrinsic::sqrt: | ||||||||||||
1493 | case Intrinsic::sin: | ||||||||||||
1494 | case Intrinsic::cos: | ||||||||||||
1495 | case Intrinsic::pow: | ||||||||||||
1496 | case Intrinsic::powi: | ||||||||||||
1497 | case Intrinsic::fma: | ||||||||||||
1498 | case Intrinsic::fmuladd: | ||||||||||||
1499 | case Intrinsic::convert_from_fp16: | ||||||||||||
1500 | case Intrinsic::convert_to_fp16: | ||||||||||||
1501 | case Intrinsic::amdgcn_cos: | ||||||||||||
1502 | case Intrinsic::amdgcn_cubeid: | ||||||||||||
1503 | case Intrinsic::amdgcn_cubema: | ||||||||||||
1504 | case Intrinsic::amdgcn_cubesc: | ||||||||||||
1505 | case Intrinsic::amdgcn_cubetc: | ||||||||||||
1506 | case Intrinsic::amdgcn_fmul_legacy: | ||||||||||||
1507 | case Intrinsic::amdgcn_fract: | ||||||||||||
1508 | case Intrinsic::amdgcn_ldexp: | ||||||||||||
1509 | case Intrinsic::amdgcn_sin: | ||||||||||||
1510 | // The intrinsics below depend on rounding mode in MXCSR. | ||||||||||||
1511 | case Intrinsic::x86_sse_cvtss2si: | ||||||||||||
1512 | case Intrinsic::x86_sse_cvtss2si64: | ||||||||||||
1513 | case Intrinsic::x86_sse_cvttss2si: | ||||||||||||
1514 | case Intrinsic::x86_sse_cvttss2si64: | ||||||||||||
1515 | case Intrinsic::x86_sse2_cvtsd2si: | ||||||||||||
1516 | case Intrinsic::x86_sse2_cvtsd2si64: | ||||||||||||
1517 | case Intrinsic::x86_sse2_cvttsd2si: | ||||||||||||
1518 | case Intrinsic::x86_sse2_cvttsd2si64: | ||||||||||||
1519 | case Intrinsic::x86_avx512_vcvtss2si32: | ||||||||||||
1520 | case Intrinsic::x86_avx512_vcvtss2si64: | ||||||||||||
1521 | case Intrinsic::x86_avx512_cvttss2si: | ||||||||||||
1522 | case Intrinsic::x86_avx512_cvttss2si64: | ||||||||||||
1523 | case Intrinsic::x86_avx512_vcvtsd2si32: | ||||||||||||
1524 | case Intrinsic::x86_avx512_vcvtsd2si64: | ||||||||||||
1525 | case Intrinsic::x86_avx512_cvttsd2si: | ||||||||||||
1526 | case Intrinsic::x86_avx512_cvttsd2si64: | ||||||||||||
1527 | case Intrinsic::x86_avx512_vcvtss2usi32: | ||||||||||||
1528 | case Intrinsic::x86_avx512_vcvtss2usi64: | ||||||||||||
1529 | case Intrinsic::x86_avx512_cvttss2usi: | ||||||||||||
1530 | case Intrinsic::x86_avx512_cvttss2usi64: | ||||||||||||
1531 | case Intrinsic::x86_avx512_vcvtsd2usi32: | ||||||||||||
1532 | case Intrinsic::x86_avx512_vcvtsd2usi64: | ||||||||||||
1533 | case Intrinsic::x86_avx512_cvttsd2usi: | ||||||||||||
1534 | case Intrinsic::x86_avx512_cvttsd2usi64: | ||||||||||||
1535 | return !Call->isStrictFP(); | ||||||||||||
1536 | |||||||||||||
1537 | // Sign operations are actually bitwise operations, they do not raise | ||||||||||||
1538 | // exceptions even for SNANs. | ||||||||||||
1539 | case Intrinsic::fabs: | ||||||||||||
1540 | case Intrinsic::copysign: | ||||||||||||
1541 | // Non-constrained variants of rounding operations means default FP | ||||||||||||
1542 | // environment, they can be folded in any case. | ||||||||||||
1543 | case Intrinsic::ceil: | ||||||||||||
1544 | case Intrinsic::floor: | ||||||||||||
1545 | case Intrinsic::round: | ||||||||||||
1546 | case Intrinsic::roundeven: | ||||||||||||
1547 | case Intrinsic::trunc: | ||||||||||||
1548 | case Intrinsic::nearbyint: | ||||||||||||
1549 | case Intrinsic::rint: | ||||||||||||
1550 | // Constrained intrinsics can be folded if FP environment is known | ||||||||||||
1551 | // to compiler. | ||||||||||||
1552 | case Intrinsic::experimental_constrained_ceil: | ||||||||||||
1553 | case Intrinsic::experimental_constrained_floor: | ||||||||||||
1554 | case Intrinsic::experimental_constrained_round: | ||||||||||||
1555 | case Intrinsic::experimental_constrained_roundeven: | ||||||||||||
1556 | case Intrinsic::experimental_constrained_trunc: | ||||||||||||
1557 | case Intrinsic::experimental_constrained_nearbyint: | ||||||||||||
1558 | case Intrinsic::experimental_constrained_rint: | ||||||||||||
1559 | return true; | ||||||||||||
1560 | default: | ||||||||||||
1561 | return false; | ||||||||||||
1562 | case Intrinsic::not_intrinsic: break; | ||||||||||||
1563 | } | ||||||||||||
1564 | |||||||||||||
1565 | if (!F->hasName() || Call->isStrictFP()) | ||||||||||||
1566 | return false; | ||||||||||||
1567 | |||||||||||||
1568 | // In these cases, the check of the length is required. We don't want to | ||||||||||||
1569 | // return true for a name like "cos\0blah" which strcmp would return equal to | ||||||||||||
1570 | // "cos", but has length 8. | ||||||||||||
1571 | StringRef Name = F->getName(); | ||||||||||||
1572 | switch (Name[0]) { | ||||||||||||
1573 | default: | ||||||||||||
1574 | return false; | ||||||||||||
1575 | case 'a': | ||||||||||||
1576 | return Name == "acos" || Name == "acosf" || | ||||||||||||
1577 | Name == "asin" || Name == "asinf" || | ||||||||||||
1578 | Name == "atan" || Name == "atanf" || | ||||||||||||
1579 | Name == "atan2" || Name == "atan2f"; | ||||||||||||
1580 | case 'c': | ||||||||||||
1581 | return Name == "ceil" || Name == "ceilf" || | ||||||||||||
1582 | Name == "cos" || Name == "cosf" || | ||||||||||||
1583 | Name == "cosh" || Name == "coshf"; | ||||||||||||
1584 | case 'e': | ||||||||||||
1585 | return Name == "exp" || Name == "expf" || | ||||||||||||
1586 | Name == "exp2" || Name == "exp2f"; | ||||||||||||
1587 | case 'f': | ||||||||||||
1588 | return Name == "fabs" || Name == "fabsf" || | ||||||||||||
1589 | Name == "floor" || Name == "floorf" || | ||||||||||||
1590 | Name == "fmod" || Name == "fmodf"; | ||||||||||||
1591 | case 'l': | ||||||||||||
1592 | return Name == "log" || Name == "logf" || | ||||||||||||
1593 | Name == "log2" || Name == "log2f" || | ||||||||||||
1594 | Name == "log10" || Name == "log10f"; | ||||||||||||
1595 | case 'n': | ||||||||||||
1596 | return Name == "nearbyint" || Name == "nearbyintf"; | ||||||||||||
1597 | case 'p': | ||||||||||||
1598 | return Name == "pow" || Name == "powf"; | ||||||||||||
1599 | case 'r': | ||||||||||||
1600 | return Name == "remainder" || Name == "remainderf" || | ||||||||||||
1601 | Name == "rint" || Name == "rintf" || | ||||||||||||
1602 | Name == "round" || Name == "roundf"; | ||||||||||||
1603 | case 's': | ||||||||||||
1604 | return Name == "sin" || Name == "sinf" || | ||||||||||||
1605 | Name == "sinh" || Name == "sinhf" || | ||||||||||||
1606 | Name == "sqrt" || Name == "sqrtf"; | ||||||||||||
1607 | case 't': | ||||||||||||
1608 | return Name == "tan" || Name == "tanf" || | ||||||||||||
1609 | Name == "tanh" || Name == "tanhf" || | ||||||||||||
1610 | Name == "trunc" || Name == "truncf"; | ||||||||||||
1611 | case '_': | ||||||||||||
1612 | // Check for various function names that get used for the math functions | ||||||||||||
1613 | // when the header files are preprocessed with the macro | ||||||||||||
1614 | // __FINITE_MATH_ONLY__ enabled. | ||||||||||||
1615 | // The '12' here is the length of the shortest name that can match. | ||||||||||||
1616 | // We need to check the size before looking at Name[1] and Name[2] | ||||||||||||
1617 | // so we may as well check a limit that will eliminate mismatches. | ||||||||||||
1618 | if (Name.size() < 12 || Name[1] != '_') | ||||||||||||
1619 | return false; | ||||||||||||
1620 | switch (Name[2]) { | ||||||||||||
1621 | default: | ||||||||||||
1622 | return false; | ||||||||||||
1623 | case 'a': | ||||||||||||
1624 | return Name == "__acos_finite" || Name == "__acosf_finite" || | ||||||||||||
1625 | Name == "__asin_finite" || Name == "__asinf_finite" || | ||||||||||||
1626 | Name == "__atan2_finite" || Name == "__atan2f_finite"; | ||||||||||||
1627 | case 'c': | ||||||||||||
1628 | return Name == "__cosh_finite" || Name == "__coshf_finite"; | ||||||||||||
1629 | case 'e': | ||||||||||||
1630 | return Name == "__exp_finite" || Name == "__expf_finite" || | ||||||||||||
1631 | Name == "__exp2_finite" || Name == "__exp2f_finite"; | ||||||||||||
1632 | case 'l': | ||||||||||||
1633 | return Name == "__log_finite" || Name == "__logf_finite" || | ||||||||||||
1634 | Name == "__log10_finite" || Name == "__log10f_finite"; | ||||||||||||
1635 | case 'p': | ||||||||||||
1636 | return Name == "__pow_finite" || Name == "__powf_finite"; | ||||||||||||
1637 | case 's': | ||||||||||||
1638 | return Name == "__sinh_finite" || Name == "__sinhf_finite"; | ||||||||||||
1639 | } | ||||||||||||
1640 | } | ||||||||||||
1641 | } | ||||||||||||
1642 | |||||||||||||
1643 | namespace { | ||||||||||||
1644 | |||||||||||||
1645 | Constant *GetConstantFoldFPValue(double V, Type *Ty) { | ||||||||||||
1646 | if (Ty->isHalfTy() || Ty->isFloatTy()) { | ||||||||||||
1647 | APFloat APF(V); | ||||||||||||
1648 | bool unused; | ||||||||||||
1649 | APF.convert(Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &unused); | ||||||||||||
1650 | return ConstantFP::get(Ty->getContext(), APF); | ||||||||||||
1651 | } | ||||||||||||
1652 | if (Ty->isDoubleTy()) | ||||||||||||
1653 | return ConstantFP::get(Ty->getContext(), APFloat(V)); | ||||||||||||
1654 | llvm_unreachable("Can only constant fold half/float/double")::llvm::llvm_unreachable_internal("Can only constant fold half/float/double" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1654); | ||||||||||||
1655 | } | ||||||||||||
1656 | |||||||||||||
1657 | /// Clear the floating-point exception state. | ||||||||||||
1658 | inline void llvm_fenv_clearexcept() { | ||||||||||||
1659 | #if defined(HAVE_FENV_H1) && HAVE_DECL_FE_ALL_EXCEPT1 | ||||||||||||
1660 | feclearexcept(FE_ALL_EXCEPT(0x20 | 0x04 | 0x10 | 0x08 | 0x01)); | ||||||||||||
1661 | #endif | ||||||||||||
1662 | errno(*__errno_location ()) = 0; | ||||||||||||
1663 | } | ||||||||||||
1664 | |||||||||||||
1665 | /// Test if a floating-point exception was raised. | ||||||||||||
1666 | inline bool llvm_fenv_testexcept() { | ||||||||||||
1667 | int errno_val = errno(*__errno_location ()); | ||||||||||||
1668 | if (errno_val == ERANGE34 || errno_val == EDOM33) | ||||||||||||
1669 | return true; | ||||||||||||
1670 | #if defined(HAVE_FENV_H1) && HAVE_DECL_FE_ALL_EXCEPT1 && HAVE_DECL_FE_INEXACT1 | ||||||||||||
1671 | if (fetestexcept(FE_ALL_EXCEPT(0x20 | 0x04 | 0x10 | 0x08 | 0x01) & ~FE_INEXACT0x20)) | ||||||||||||
1672 | return true; | ||||||||||||
1673 | #endif | ||||||||||||
1674 | return false; | ||||||||||||
1675 | } | ||||||||||||
1676 | |||||||||||||
1677 | Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) { | ||||||||||||
1678 | llvm_fenv_clearexcept(); | ||||||||||||
1679 | V = NativeFP(V); | ||||||||||||
1680 | if (llvm_fenv_testexcept()) { | ||||||||||||
1681 | llvm_fenv_clearexcept(); | ||||||||||||
1682 | return nullptr; | ||||||||||||
1683 | } | ||||||||||||
1684 | |||||||||||||
1685 | return GetConstantFoldFPValue(V, Ty); | ||||||||||||
1686 | } | ||||||||||||
1687 | |||||||||||||
1688 | Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V, | ||||||||||||
1689 | double W, Type *Ty) { | ||||||||||||
1690 | llvm_fenv_clearexcept(); | ||||||||||||
1691 | V = NativeFP(V, W); | ||||||||||||
1692 | if (llvm_fenv_testexcept()) { | ||||||||||||
1693 | llvm_fenv_clearexcept(); | ||||||||||||
1694 | return nullptr; | ||||||||||||
1695 | } | ||||||||||||
1696 | |||||||||||||
1697 | return GetConstantFoldFPValue(V, Ty); | ||||||||||||
1698 | } | ||||||||||||
1699 | |||||||||||||
1700 | Constant *ConstantFoldVectorReduce(Intrinsic::ID IID, Constant *Op) { | ||||||||||||
1701 | FixedVectorType *VT = dyn_cast<FixedVectorType>(Op->getType()); | ||||||||||||
1702 | if (!VT) | ||||||||||||
1703 | return nullptr; | ||||||||||||
1704 | ConstantInt *CI = dyn_cast<ConstantInt>(Op->getAggregateElement(0U)); | ||||||||||||
1705 | if (!CI) | ||||||||||||
1706 | return nullptr; | ||||||||||||
1707 | APInt Acc = CI->getValue(); | ||||||||||||
1708 | |||||||||||||
1709 | for (unsigned I = 1; I < VT->getNumElements(); I++) { | ||||||||||||
1710 | if (!(CI = dyn_cast<ConstantInt>(Op->getAggregateElement(I)))) | ||||||||||||
1711 | return nullptr; | ||||||||||||
1712 | const APInt &X = CI->getValue(); | ||||||||||||
1713 | switch (IID) { | ||||||||||||
1714 | case Intrinsic::experimental_vector_reduce_add: | ||||||||||||
1715 | Acc = Acc + X; | ||||||||||||
1716 | break; | ||||||||||||
1717 | case Intrinsic::experimental_vector_reduce_mul: | ||||||||||||
1718 | Acc = Acc * X; | ||||||||||||
1719 | break; | ||||||||||||
1720 | case Intrinsic::experimental_vector_reduce_and: | ||||||||||||
1721 | Acc = Acc & X; | ||||||||||||
1722 | break; | ||||||||||||
1723 | case Intrinsic::experimental_vector_reduce_or: | ||||||||||||
1724 | Acc = Acc | X; | ||||||||||||
1725 | break; | ||||||||||||
1726 | case Intrinsic::experimental_vector_reduce_xor: | ||||||||||||
1727 | Acc = Acc ^ X; | ||||||||||||
1728 | break; | ||||||||||||
1729 | case Intrinsic::experimental_vector_reduce_smin: | ||||||||||||
1730 | Acc = APIntOps::smin(Acc, X); | ||||||||||||
1731 | break; | ||||||||||||
1732 | case Intrinsic::experimental_vector_reduce_smax: | ||||||||||||
1733 | Acc = APIntOps::smax(Acc, X); | ||||||||||||
1734 | break; | ||||||||||||
1735 | case Intrinsic::experimental_vector_reduce_umin: | ||||||||||||
1736 | Acc = APIntOps::umin(Acc, X); | ||||||||||||
1737 | break; | ||||||||||||
1738 | case Intrinsic::experimental_vector_reduce_umax: | ||||||||||||
1739 | Acc = APIntOps::umax(Acc, X); | ||||||||||||
1740 | break; | ||||||||||||
1741 | } | ||||||||||||
1742 | } | ||||||||||||
1743 | |||||||||||||
1744 | return ConstantInt::get(Op->getContext(), Acc); | ||||||||||||
1745 | } | ||||||||||||
1746 | |||||||||||||
1747 | /// Attempt to fold an SSE floating point to integer conversion of a constant | ||||||||||||
1748 | /// floating point. If roundTowardZero is false, the default IEEE rounding is | ||||||||||||
1749 | /// used (toward nearest, ties to even). This matches the behavior of the | ||||||||||||
1750 | /// non-truncating SSE instructions in the default rounding mode. The desired | ||||||||||||
1751 | /// integer type Ty is used to select how many bits are available for the | ||||||||||||
1752 | /// result. Returns null if the conversion cannot be performed, otherwise | ||||||||||||
1753 | /// returns the Constant value resulting from the conversion. | ||||||||||||
1754 | Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero, | ||||||||||||
1755 | Type *Ty, bool IsSigned) { | ||||||||||||
1756 | // All of these conversion intrinsics form an integer of at most 64bits. | ||||||||||||
1757 | unsigned ResultWidth = Ty->getIntegerBitWidth(); | ||||||||||||
1758 | assert(ResultWidth <= 64 &&((ResultWidth <= 64 && "Can only constant fold conversions to 64 and 32 bit ints" ) ? static_cast<void> (0) : __assert_fail ("ResultWidth <= 64 && \"Can only constant fold conversions to 64 and 32 bit ints\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1759, __PRETTY_FUNCTION__)) | ||||||||||||
1759 | "Can only constant fold conversions to 64 and 32 bit ints")((ResultWidth <= 64 && "Can only constant fold conversions to 64 and 32 bit ints" ) ? static_cast<void> (0) : __assert_fail ("ResultWidth <= 64 && \"Can only constant fold conversions to 64 and 32 bit ints\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1759, __PRETTY_FUNCTION__)); | ||||||||||||
1760 | |||||||||||||
1761 | uint64_t UIntVal; | ||||||||||||
1762 | bool isExact = false; | ||||||||||||
1763 | APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero | ||||||||||||
1764 | : APFloat::rmNearestTiesToEven; | ||||||||||||
1765 | APFloat::opStatus status = | ||||||||||||
1766 | Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth, | ||||||||||||
1767 | IsSigned, mode, &isExact); | ||||||||||||
1768 | if (status != APFloat::opOK && | ||||||||||||
1769 | (!roundTowardZero || status != APFloat::opInexact)) | ||||||||||||
1770 | return nullptr; | ||||||||||||
1771 | return ConstantInt::get(Ty, UIntVal, IsSigned); | ||||||||||||
1772 | } | ||||||||||||
1773 | |||||||||||||
1774 | double getValueAsDouble(ConstantFP *Op) { | ||||||||||||
1775 | Type *Ty = Op->getType(); | ||||||||||||
1776 | |||||||||||||
1777 | if (Ty->isFloatTy()) | ||||||||||||
1778 | return Op->getValueAPF().convertToFloat(); | ||||||||||||
1779 | |||||||||||||
1780 | if (Ty->isDoubleTy()) | ||||||||||||
1781 | return Op->getValueAPF().convertToDouble(); | ||||||||||||
1782 | |||||||||||||
1783 | bool unused; | ||||||||||||
1784 | APFloat APF = Op->getValueAPF(); | ||||||||||||
1785 | APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused); | ||||||||||||
1786 | return APF.convertToDouble(); | ||||||||||||
1787 | } | ||||||||||||
1788 | |||||||||||||
1789 | static bool isManifestConstant(const Constant *c) { | ||||||||||||
1790 | if (isa<ConstantData>(c)) { | ||||||||||||
1791 | return true; | ||||||||||||
1792 | } else if (isa<ConstantAggregate>(c) || isa<ConstantExpr>(c)) { | ||||||||||||
1793 | for (const Value *subc : c->operand_values()) { | ||||||||||||
1794 | if (!isManifestConstant(cast<Constant>(subc))) | ||||||||||||
1795 | return false; | ||||||||||||
1796 | } | ||||||||||||
1797 | return true; | ||||||||||||
1798 | } | ||||||||||||
1799 | return false; | ||||||||||||
1800 | } | ||||||||||||
1801 | |||||||||||||
1802 | static bool getConstIntOrUndef(Value *Op, const APInt *&C) { | ||||||||||||
1803 | if (auto *CI
| ||||||||||||
1804 | C = &CI->getValue(); | ||||||||||||
1805 | return true; | ||||||||||||
1806 | } | ||||||||||||
1807 | if (isa<UndefValue>(Op)) { | ||||||||||||
1808 | C = nullptr; | ||||||||||||
1809 | return true; | ||||||||||||
1810 | } | ||||||||||||
1811 | return false; | ||||||||||||
1812 | } | ||||||||||||
1813 | |||||||||||||
1814 | static Constant *ConstantFoldScalarCall1(StringRef Name, | ||||||||||||
1815 | Intrinsic::ID IntrinsicID, | ||||||||||||
1816 | Type *Ty, | ||||||||||||
1817 | ArrayRef<Constant *> Operands, | ||||||||||||
1818 | const TargetLibraryInfo *TLI, | ||||||||||||
1819 | const CallBase *Call) { | ||||||||||||
1820 | assert(Operands.size() == 1 && "Wrong number of operands.")((Operands.size() == 1 && "Wrong number of operands." ) ? static_cast<void> (0) : __assert_fail ("Operands.size() == 1 && \"Wrong number of operands.\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 1820, __PRETTY_FUNCTION__)); | ||||||||||||
1821 | |||||||||||||
1822 | if (IntrinsicID == Intrinsic::is_constant) { | ||||||||||||
1823 | // We know we have a "Constant" argument. But we want to only | ||||||||||||
1824 | // return true for manifest constants, not those that depend on | ||||||||||||
1825 | // constants with unknowable values, e.g. GlobalValue or BlockAddress. | ||||||||||||
1826 | if (isManifestConstant(Operands[0])) | ||||||||||||
1827 | return ConstantInt::getTrue(Ty->getContext()); | ||||||||||||
1828 | return nullptr; | ||||||||||||
1829 | } | ||||||||||||
1830 | if (isa<UndefValue>(Operands[0])) { | ||||||||||||
1831 | // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN. | ||||||||||||
1832 | // ctpop() is between 0 and bitwidth, pick 0 for undef. | ||||||||||||
1833 | if (IntrinsicID == Intrinsic::cos || | ||||||||||||
1834 | IntrinsicID == Intrinsic::ctpop) | ||||||||||||
1835 | return Constant::getNullValue(Ty); | ||||||||||||
1836 | if (IntrinsicID == Intrinsic::bswap || | ||||||||||||
1837 | IntrinsicID == Intrinsic::bitreverse || | ||||||||||||
1838 | IntrinsicID == Intrinsic::launder_invariant_group || | ||||||||||||
1839 | IntrinsicID == Intrinsic::strip_invariant_group) | ||||||||||||
1840 | return Operands[0]; | ||||||||||||
1841 | } | ||||||||||||
1842 | |||||||||||||
1843 | if (isa<ConstantPointerNull>(Operands[0])) { | ||||||||||||
1844 | // launder(null) == null == strip(null) iff in addrspace 0 | ||||||||||||
1845 | if (IntrinsicID == Intrinsic::launder_invariant_group || | ||||||||||||
1846 | IntrinsicID == Intrinsic::strip_invariant_group) { | ||||||||||||
1847 | // If instruction is not yet put in a basic block (e.g. when cloning | ||||||||||||
1848 | // a function during inlining), Call's caller may not be available. | ||||||||||||
1849 | // So check Call's BB first before querying Call->getCaller. | ||||||||||||
1850 | const Function *Caller = | ||||||||||||
1851 | Call->getParent() ? Call->getCaller() : nullptr; | ||||||||||||
1852 | if (Caller && | ||||||||||||
1853 | !NullPointerIsDefined( | ||||||||||||
1854 | Caller, Operands[0]->getType()->getPointerAddressSpace())) { | ||||||||||||
1855 | return Operands[0]; | ||||||||||||
1856 | } | ||||||||||||
1857 | return nullptr; | ||||||||||||
1858 | } | ||||||||||||
1859 | } | ||||||||||||
1860 | |||||||||||||
1861 | if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) { | ||||||||||||
1862 | if (IntrinsicID == Intrinsic::convert_to_fp16) { | ||||||||||||
1863 | APFloat Val(Op->getValueAPF()); | ||||||||||||
1864 | |||||||||||||
1865 | bool lost = false; | ||||||||||||
1866 | Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost); | ||||||||||||
1867 | |||||||||||||
1868 | return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt()); | ||||||||||||
1869 | } | ||||||||||||
1870 | |||||||||||||
1871 | APFloat U = Op->getValueAPF(); | ||||||||||||
1872 | |||||||||||||
1873 | if (IntrinsicID == Intrinsic::wasm_trunc_signed || | ||||||||||||
1874 | IntrinsicID == Intrinsic::wasm_trunc_unsigned || | ||||||||||||
1875 | IntrinsicID == Intrinsic::wasm_trunc_saturate_signed || | ||||||||||||
1876 | IntrinsicID == Intrinsic::wasm_trunc_saturate_unsigned) { | ||||||||||||
1877 | |||||||||||||
1878 | bool Saturating = IntrinsicID == Intrinsic::wasm_trunc_saturate_signed || | ||||||||||||
1879 | IntrinsicID == Intrinsic::wasm_trunc_saturate_unsigned; | ||||||||||||
1880 | bool Signed = IntrinsicID == Intrinsic::wasm_trunc_signed || | ||||||||||||
1881 | IntrinsicID == Intrinsic::wasm_trunc_saturate_signed; | ||||||||||||
1882 | |||||||||||||
1883 | if (U.isNaN()) | ||||||||||||
1884 | return Saturating ? ConstantInt::get(Ty, 0) : nullptr; | ||||||||||||
1885 | |||||||||||||
1886 | unsigned Width = Ty->getIntegerBitWidth(); | ||||||||||||
1887 | APSInt Int(Width, !Signed); | ||||||||||||
1888 | bool IsExact = false; | ||||||||||||
1889 | APFloat::opStatus Status = | ||||||||||||
1890 | U.convertToInteger(Int, APFloat::rmTowardZero, &IsExact); | ||||||||||||
1891 | |||||||||||||
1892 | if (Status == APFloat::opOK || Status == APFloat::opInexact) | ||||||||||||
1893 | return ConstantInt::get(Ty, Int); | ||||||||||||
1894 | |||||||||||||
1895 | if (!Saturating) | ||||||||||||
1896 | return nullptr; | ||||||||||||
1897 | |||||||||||||
1898 | if (U.isNegative()) | ||||||||||||
1899 | return Signed ? ConstantInt::get(Ty, APInt::getSignedMinValue(Width)) | ||||||||||||
1900 | : ConstantInt::get(Ty, APInt::getMinValue(Width)); | ||||||||||||
1901 | else | ||||||||||||
1902 | return Signed ? ConstantInt::get(Ty, APInt::getSignedMaxValue(Width)) | ||||||||||||
1903 | : ConstantInt::get(Ty, APInt::getMaxValue(Width)); | ||||||||||||
1904 | } | ||||||||||||
1905 | |||||||||||||
1906 | if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy()) | ||||||||||||
1907 | return nullptr; | ||||||||||||
1908 | |||||||||||||
1909 | // Use internal versions of these intrinsics. | ||||||||||||
1910 | |||||||||||||
1911 | if (IntrinsicID == Intrinsic::nearbyint || IntrinsicID == Intrinsic::rint) { | ||||||||||||
1912 | U.roundToIntegral(APFloat::rmNearestTiesToEven); | ||||||||||||
1913 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
1914 | } | ||||||||||||
1915 | |||||||||||||
1916 | if (IntrinsicID == Intrinsic::round) { | ||||||||||||
1917 | U.roundToIntegral(APFloat::rmNearestTiesToAway); | ||||||||||||
1918 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
1919 | } | ||||||||||||
1920 | |||||||||||||
1921 | if (IntrinsicID == Intrinsic::roundeven) { | ||||||||||||
1922 | U.roundToIntegral(APFloat::rmNearestTiesToEven); | ||||||||||||
1923 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
1924 | } | ||||||||||||
1925 | |||||||||||||
1926 | if (IntrinsicID == Intrinsic::ceil) { | ||||||||||||
1927 | U.roundToIntegral(APFloat::rmTowardPositive); | ||||||||||||
1928 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
1929 | } | ||||||||||||
1930 | |||||||||||||
1931 | if (IntrinsicID == Intrinsic::floor) { | ||||||||||||
1932 | U.roundToIntegral(APFloat::rmTowardNegative); | ||||||||||||
1933 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
1934 | } | ||||||||||||
1935 | |||||||||||||
1936 | if (IntrinsicID == Intrinsic::trunc) { | ||||||||||||
1937 | U.roundToIntegral(APFloat::rmTowardZero); | ||||||||||||
1938 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
1939 | } | ||||||||||||
1940 | |||||||||||||
1941 | if (IntrinsicID == Intrinsic::fabs) { | ||||||||||||
1942 | U.clearSign(); | ||||||||||||
1943 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
1944 | } | ||||||||||||
1945 | |||||||||||||
1946 | if (IntrinsicID == Intrinsic::amdgcn_fract) { | ||||||||||||
1947 | // The v_fract instruction behaves like the OpenCL spec, which defines | ||||||||||||
1948 | // fract(x) as fmin(x - floor(x), 0x1.fffffep-1f): "The min() operator is | ||||||||||||
1949 | // there to prevent fract(-small) from returning 1.0. It returns the | ||||||||||||
1950 | // largest positive floating-point number less than 1.0." | ||||||||||||
1951 | APFloat FloorU(U); | ||||||||||||
1952 | FloorU.roundToIntegral(APFloat::rmTowardNegative); | ||||||||||||
1953 | APFloat FractU(U - FloorU); | ||||||||||||
1954 | APFloat AlmostOne(U.getSemantics(), 1); | ||||||||||||
1955 | AlmostOne.next(/*nextDown*/ true); | ||||||||||||
1956 | return ConstantFP::get(Ty->getContext(), minimum(FractU, AlmostOne)); | ||||||||||||
1957 | } | ||||||||||||
1958 | |||||||||||||
1959 | // Rounding operations (floor, trunc, ceil, round and nearbyint) do not | ||||||||||||
1960 | // raise FP exceptions, unless the argument is signaling NaN. | ||||||||||||
1961 | |||||||||||||
1962 | Optional<APFloat::roundingMode> RM; | ||||||||||||
1963 | switch (IntrinsicID) { | ||||||||||||
1964 | default: | ||||||||||||
1965 | break; | ||||||||||||
1966 | case Intrinsic::experimental_constrained_nearbyint: | ||||||||||||
1967 | case Intrinsic::experimental_constrained_rint: { | ||||||||||||
1968 | auto CI = cast<ConstrainedFPIntrinsic>(Call); | ||||||||||||
1969 | RM = CI->getRoundingMode(); | ||||||||||||
1970 | if (!RM || RM.getValue() == RoundingMode::Dynamic) | ||||||||||||
1971 | return nullptr; | ||||||||||||
1972 | break; | ||||||||||||
1973 | } | ||||||||||||
1974 | case Intrinsic::experimental_constrained_round: | ||||||||||||
1975 | RM = APFloat::rmNearestTiesToAway; | ||||||||||||
1976 | break; | ||||||||||||
1977 | case Intrinsic::experimental_constrained_ceil: | ||||||||||||
1978 | RM = APFloat::rmTowardPositive; | ||||||||||||
1979 | break; | ||||||||||||
1980 | case Intrinsic::experimental_constrained_floor: | ||||||||||||
1981 | RM = APFloat::rmTowardNegative; | ||||||||||||
1982 | break; | ||||||||||||
1983 | case Intrinsic::experimental_constrained_trunc: | ||||||||||||
1984 | RM = APFloat::rmTowardZero; | ||||||||||||
1985 | break; | ||||||||||||
1986 | } | ||||||||||||
1987 | if (RM) { | ||||||||||||
1988 | auto CI = cast<ConstrainedFPIntrinsic>(Call); | ||||||||||||
1989 | if (U.isFinite()) { | ||||||||||||
1990 | APFloat::opStatus St = U.roundToIntegral(*RM); | ||||||||||||
1991 | if (IntrinsicID == Intrinsic::experimental_constrained_rint && | ||||||||||||
1992 | St == APFloat::opInexact) { | ||||||||||||
1993 | Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior(); | ||||||||||||
1994 | if (EB && *EB == fp::ebStrict) | ||||||||||||
1995 | return nullptr; | ||||||||||||
1996 | } | ||||||||||||
1997 | } else if (U.isSignaling()) { | ||||||||||||
1998 | Optional<fp::ExceptionBehavior> EB = CI->getExceptionBehavior(); | ||||||||||||
1999 | if (EB && *EB != fp::ebIgnore) | ||||||||||||
2000 | return nullptr; | ||||||||||||
2001 | U = APFloat::getQNaN(U.getSemantics()); | ||||||||||||
2002 | } | ||||||||||||
2003 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
2004 | } | ||||||||||||
2005 | |||||||||||||
2006 | /// We only fold functions with finite arguments. Folding NaN and inf is | ||||||||||||
2007 | /// likely to be aborted with an exception anyway, and some host libms | ||||||||||||
2008 | /// have known errors raising exceptions. | ||||||||||||
2009 | if (!U.isFinite()) | ||||||||||||
2010 | return nullptr; | ||||||||||||
2011 | |||||||||||||
2012 | /// Currently APFloat versions of these functions do not exist, so we use | ||||||||||||
2013 | /// the host native double versions. Float versions are not called | ||||||||||||
2014 | /// directly but for all these it is true (float)(f((double)arg)) == | ||||||||||||
2015 | /// f(arg). Long double not supported yet. | ||||||||||||
2016 | double V = getValueAsDouble(Op); | ||||||||||||
2017 | |||||||||||||
2018 | switch (IntrinsicID) { | ||||||||||||
2019 | default: break; | ||||||||||||
2020 | case Intrinsic::log: | ||||||||||||
2021 | return ConstantFoldFP(log, V, Ty); | ||||||||||||
2022 | case Intrinsic::log2: | ||||||||||||
2023 | // TODO: What about hosts that lack a C99 library? | ||||||||||||
2024 | return ConstantFoldFP(Log2, V, Ty); | ||||||||||||
2025 | case Intrinsic::log10: | ||||||||||||
2026 | // TODO: What about hosts that lack a C99 library? | ||||||||||||
2027 | return ConstantFoldFP(log10, V, Ty); | ||||||||||||
2028 | case Intrinsic::exp: | ||||||||||||
2029 | return ConstantFoldFP(exp, V, Ty); | ||||||||||||
2030 | case Intrinsic::exp2: | ||||||||||||
2031 | // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library. | ||||||||||||
2032 | return ConstantFoldBinaryFP(pow, 2.0, V, Ty); | ||||||||||||
2033 | case Intrinsic::sin: | ||||||||||||
2034 | return ConstantFoldFP(sin, V, Ty); | ||||||||||||
2035 | case Intrinsic::cos: | ||||||||||||
2036 | return ConstantFoldFP(cos, V, Ty); | ||||||||||||
2037 | case Intrinsic::sqrt: | ||||||||||||
2038 | return ConstantFoldFP(sqrt, V, Ty); | ||||||||||||
2039 | case Intrinsic::amdgcn_cos: | ||||||||||||
2040 | case Intrinsic::amdgcn_sin: | ||||||||||||
2041 | if (V < -256.0 || V > 256.0) | ||||||||||||
2042 | // The gfx8 and gfx9 architectures handle arguments outside the range | ||||||||||||
2043 | // [-256, 256] differently. This should be a rare case so bail out | ||||||||||||
2044 | // rather than trying to handle the difference. | ||||||||||||
2045 | return nullptr; | ||||||||||||
2046 | bool IsCos = IntrinsicID == Intrinsic::amdgcn_cos; | ||||||||||||
2047 | double V4 = V * 4.0; | ||||||||||||
2048 | if (V4 == floor(V4)) { | ||||||||||||
2049 | // Force exact results for quarter-integer inputs. | ||||||||||||
2050 | const double SinVals[4] = { 0.0, 1.0, 0.0, -1.0 }; | ||||||||||||
2051 | V = SinVals[((int)V4 + (IsCos ? 1 : 0)) & 3]; | ||||||||||||
2052 | } else { | ||||||||||||
2053 | if (IsCos) | ||||||||||||
2054 | V = cos(V * 2.0 * numbers::pi); | ||||||||||||
2055 | else | ||||||||||||
2056 | V = sin(V * 2.0 * numbers::pi); | ||||||||||||
2057 | } | ||||||||||||
2058 | return GetConstantFoldFPValue(V, Ty); | ||||||||||||
2059 | } | ||||||||||||
2060 | |||||||||||||
2061 | if (!TLI) | ||||||||||||
2062 | return nullptr; | ||||||||||||
2063 | |||||||||||||
2064 | LibFunc Func = NotLibFunc; | ||||||||||||
2065 | TLI->getLibFunc(Name, Func); | ||||||||||||
2066 | switch (Func) { | ||||||||||||
2067 | default: | ||||||||||||
2068 | break; | ||||||||||||
2069 | case LibFunc_acos: | ||||||||||||
2070 | case LibFunc_acosf: | ||||||||||||
2071 | case LibFunc_acos_finite: | ||||||||||||
2072 | case LibFunc_acosf_finite: | ||||||||||||
2073 | if (TLI->has(Func)) | ||||||||||||
2074 | return ConstantFoldFP(acos, V, Ty); | ||||||||||||
2075 | break; | ||||||||||||
2076 | case LibFunc_asin: | ||||||||||||
2077 | case LibFunc_asinf: | ||||||||||||
2078 | case LibFunc_asin_finite: | ||||||||||||
2079 | case LibFunc_asinf_finite: | ||||||||||||
2080 | if (TLI->has(Func)) | ||||||||||||
2081 | return ConstantFoldFP(asin, V, Ty); | ||||||||||||
2082 | break; | ||||||||||||
2083 | case LibFunc_atan: | ||||||||||||
2084 | case LibFunc_atanf: | ||||||||||||
2085 | if (TLI->has(Func)) | ||||||||||||
2086 | return ConstantFoldFP(atan, V, Ty); | ||||||||||||
2087 | break; | ||||||||||||
2088 | case LibFunc_ceil: | ||||||||||||
2089 | case LibFunc_ceilf: | ||||||||||||
2090 | if (TLI->has(Func)) { | ||||||||||||
2091 | U.roundToIntegral(APFloat::rmTowardPositive); | ||||||||||||
2092 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
2093 | } | ||||||||||||
2094 | break; | ||||||||||||
2095 | case LibFunc_cos: | ||||||||||||
2096 | case LibFunc_cosf: | ||||||||||||
2097 | if (TLI->has(Func)) | ||||||||||||
2098 | return ConstantFoldFP(cos, V, Ty); | ||||||||||||
2099 | break; | ||||||||||||
2100 | case LibFunc_cosh: | ||||||||||||
2101 | case LibFunc_coshf: | ||||||||||||
2102 | case LibFunc_cosh_finite: | ||||||||||||
2103 | case LibFunc_coshf_finite: | ||||||||||||
2104 | if (TLI->has(Func)) | ||||||||||||
2105 | return ConstantFoldFP(cosh, V, Ty); | ||||||||||||
2106 | break; | ||||||||||||
2107 | case LibFunc_exp: | ||||||||||||
2108 | case LibFunc_expf: | ||||||||||||
2109 | case LibFunc_exp_finite: | ||||||||||||
2110 | case LibFunc_expf_finite: | ||||||||||||
2111 | if (TLI->has(Func)) | ||||||||||||
2112 | return ConstantFoldFP(exp, V, Ty); | ||||||||||||
2113 | break; | ||||||||||||
2114 | case LibFunc_exp2: | ||||||||||||
2115 | case LibFunc_exp2f: | ||||||||||||
2116 | case LibFunc_exp2_finite: | ||||||||||||
2117 | case LibFunc_exp2f_finite: | ||||||||||||
2118 | if (TLI->has(Func)) | ||||||||||||
2119 | // Fold exp2(x) as pow(2, x), in case the host lacks a C99 library. | ||||||||||||
2120 | return ConstantFoldBinaryFP(pow, 2.0, V, Ty); | ||||||||||||
2121 | break; | ||||||||||||
2122 | case LibFunc_fabs: | ||||||||||||
2123 | case LibFunc_fabsf: | ||||||||||||
2124 | if (TLI->has(Func)) { | ||||||||||||
2125 | U.clearSign(); | ||||||||||||
2126 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
2127 | } | ||||||||||||
2128 | break; | ||||||||||||
2129 | case LibFunc_floor: | ||||||||||||
2130 | case LibFunc_floorf: | ||||||||||||
2131 | if (TLI->has(Func)) { | ||||||||||||
2132 | U.roundToIntegral(APFloat::rmTowardNegative); | ||||||||||||
2133 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
2134 | } | ||||||||||||
2135 | break; | ||||||||||||
2136 | case LibFunc_log: | ||||||||||||
2137 | case LibFunc_logf: | ||||||||||||
2138 | case LibFunc_log_finite: | ||||||||||||
2139 | case LibFunc_logf_finite: | ||||||||||||
2140 | if (V > 0.0 && TLI->has(Func)) | ||||||||||||
2141 | return ConstantFoldFP(log, V, Ty); | ||||||||||||
2142 | break; | ||||||||||||
2143 | case LibFunc_log2: | ||||||||||||
2144 | case LibFunc_log2f: | ||||||||||||
2145 | case LibFunc_log2_finite: | ||||||||||||
2146 | case LibFunc_log2f_finite: | ||||||||||||
2147 | if (V > 0.0 && TLI->has(Func)) | ||||||||||||
2148 | // TODO: What about hosts that lack a C99 library? | ||||||||||||
2149 | return ConstantFoldFP(Log2, V, Ty); | ||||||||||||
2150 | break; | ||||||||||||
2151 | case LibFunc_log10: | ||||||||||||
2152 | case LibFunc_log10f: | ||||||||||||
2153 | case LibFunc_log10_finite: | ||||||||||||
2154 | case LibFunc_log10f_finite: | ||||||||||||
2155 | if (V > 0.0 && TLI->has(Func)) | ||||||||||||
2156 | // TODO: What about hosts that lack a C99 library? | ||||||||||||
2157 | return ConstantFoldFP(log10, V, Ty); | ||||||||||||
2158 | break; | ||||||||||||
2159 | case LibFunc_nearbyint: | ||||||||||||
2160 | case LibFunc_nearbyintf: | ||||||||||||
2161 | case LibFunc_rint: | ||||||||||||
2162 | case LibFunc_rintf: | ||||||||||||
2163 | if (TLI->has(Func)) { | ||||||||||||
2164 | U.roundToIntegral(APFloat::rmNearestTiesToEven); | ||||||||||||
2165 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
2166 | } | ||||||||||||
2167 | break; | ||||||||||||
2168 | case LibFunc_round: | ||||||||||||
2169 | case LibFunc_roundf: | ||||||||||||
2170 | if (TLI->has(Func)) { | ||||||||||||
2171 | U.roundToIntegral(APFloat::rmNearestTiesToAway); | ||||||||||||
2172 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
2173 | } | ||||||||||||
2174 | break; | ||||||||||||
2175 | case LibFunc_sin: | ||||||||||||
2176 | case LibFunc_sinf: | ||||||||||||
2177 | if (TLI->has(Func)) | ||||||||||||
2178 | return ConstantFoldFP(sin, V, Ty); | ||||||||||||
2179 | break; | ||||||||||||
2180 | case LibFunc_sinh: | ||||||||||||
2181 | case LibFunc_sinhf: | ||||||||||||
2182 | case LibFunc_sinh_finite: | ||||||||||||
2183 | case LibFunc_sinhf_finite: | ||||||||||||
2184 | if (TLI->has(Func)) | ||||||||||||
2185 | return ConstantFoldFP(sinh, V, Ty); | ||||||||||||
2186 | break; | ||||||||||||
2187 | case LibFunc_sqrt: | ||||||||||||
2188 | case LibFunc_sqrtf: | ||||||||||||
2189 | if (V >= 0.0 && TLI->has(Func)) | ||||||||||||
2190 | return ConstantFoldFP(sqrt, V, Ty); | ||||||||||||
2191 | break; | ||||||||||||
2192 | case LibFunc_tan: | ||||||||||||
2193 | case LibFunc_tanf: | ||||||||||||
2194 | if (TLI->has(Func)) | ||||||||||||
2195 | return ConstantFoldFP(tan, V, Ty); | ||||||||||||
2196 | break; | ||||||||||||
2197 | case LibFunc_tanh: | ||||||||||||
2198 | case LibFunc_tanhf: | ||||||||||||
2199 | if (TLI->has(Func)) | ||||||||||||
2200 | return ConstantFoldFP(tanh, V, Ty); | ||||||||||||
2201 | break; | ||||||||||||
2202 | case LibFunc_trunc: | ||||||||||||
2203 | case LibFunc_truncf: | ||||||||||||
2204 | if (TLI->has(Func)) { | ||||||||||||
2205 | U.roundToIntegral(APFloat::rmTowardZero); | ||||||||||||
2206 | return ConstantFP::get(Ty->getContext(), U); | ||||||||||||
2207 | } | ||||||||||||
2208 | break; | ||||||||||||
2209 | } | ||||||||||||
2210 | return nullptr; | ||||||||||||
2211 | } | ||||||||||||
2212 | |||||||||||||
2213 | if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) { | ||||||||||||
2214 | switch (IntrinsicID) { | ||||||||||||
2215 | case Intrinsic::bswap: | ||||||||||||
2216 | return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap()); | ||||||||||||
2217 | case Intrinsic::ctpop: | ||||||||||||
2218 | return ConstantInt::get(Ty, Op->getValue().countPopulation()); | ||||||||||||
2219 | case Intrinsic::bitreverse: | ||||||||||||
2220 | return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits()); | ||||||||||||
2221 | case Intrinsic::convert_from_fp16: { | ||||||||||||
2222 | APFloat Val(APFloat::IEEEhalf(), Op->getValue()); | ||||||||||||
2223 | |||||||||||||
2224 | bool lost = false; | ||||||||||||
2225 | APFloat::opStatus status = Val.convert( | ||||||||||||
2226 | Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost); | ||||||||||||
2227 | |||||||||||||
2228 | // Conversion is always precise. | ||||||||||||
2229 | (void)status; | ||||||||||||
2230 | assert(status == APFloat::opOK && !lost &&((status == APFloat::opOK && !lost && "Precision lost during fp16 constfolding" ) ? static_cast<void> (0) : __assert_fail ("status == APFloat::opOK && !lost && \"Precision lost during fp16 constfolding\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 2231, __PRETTY_FUNCTION__)) | ||||||||||||
2231 | "Precision lost during fp16 constfolding")((status == APFloat::opOK && !lost && "Precision lost during fp16 constfolding" ) ? static_cast<void> (0) : __assert_fail ("status == APFloat::opOK && !lost && \"Precision lost during fp16 constfolding\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 2231, __PRETTY_FUNCTION__)); | ||||||||||||
2232 | |||||||||||||
2233 | return ConstantFP::get(Ty->getContext(), Val); | ||||||||||||
2234 | } | ||||||||||||
2235 | default: | ||||||||||||
2236 | return nullptr; | ||||||||||||
2237 | } | ||||||||||||
2238 | } | ||||||||||||
2239 | |||||||||||||
2240 | if (isa<ConstantAggregateZero>(Operands[0])) { | ||||||||||||
2241 | switch (IntrinsicID) { | ||||||||||||
2242 | default: break; | ||||||||||||
2243 | case Intrinsic::experimental_vector_reduce_add: | ||||||||||||
2244 | case Intrinsic::experimental_vector_reduce_mul: | ||||||||||||
2245 | case Intrinsic::experimental_vector_reduce_and: | ||||||||||||
2246 | case Intrinsic::experimental_vector_reduce_or: | ||||||||||||
2247 | case Intrinsic::experimental_vector_reduce_xor: | ||||||||||||
2248 | case Intrinsic::experimental_vector_reduce_smin: | ||||||||||||
2249 | case Intrinsic::experimental_vector_reduce_smax: | ||||||||||||
2250 | case Intrinsic::experimental_vector_reduce_umin: | ||||||||||||
2251 | case Intrinsic::experimental_vector_reduce_umax: | ||||||||||||
2252 | return ConstantInt::get(Ty, 0); | ||||||||||||
2253 | } | ||||||||||||
2254 | } | ||||||||||||
2255 | |||||||||||||
2256 | // Support ConstantVector in case we have an Undef in the top. | ||||||||||||
2257 | if (isa<ConstantVector>(Operands[0]) || | ||||||||||||
2258 | isa<ConstantDataVector>(Operands[0])) { | ||||||||||||
2259 | auto *Op = cast<Constant>(Operands[0]); | ||||||||||||
2260 | switch (IntrinsicID) { | ||||||||||||
2261 | default: break; | ||||||||||||
2262 | case Intrinsic::experimental_vector_reduce_add: | ||||||||||||
2263 | case Intrinsic::experimental_vector_reduce_mul: | ||||||||||||
2264 | case Intrinsic::experimental_vector_reduce_and: | ||||||||||||
2265 | case Intrinsic::experimental_vector_reduce_or: | ||||||||||||
2266 | case Intrinsic::experimental_vector_reduce_xor: | ||||||||||||
2267 | case Intrinsic::experimental_vector_reduce_smin: | ||||||||||||
2268 | case Intrinsic::experimental_vector_reduce_smax: | ||||||||||||
2269 | case Intrinsic::experimental_vector_reduce_umin: | ||||||||||||
2270 | case Intrinsic::experimental_vector_reduce_umax: | ||||||||||||
2271 | if (Constant *C = ConstantFoldVectorReduce(IntrinsicID, Op)) | ||||||||||||
2272 | return C; | ||||||||||||
2273 | break; | ||||||||||||
2274 | case Intrinsic::x86_sse_cvtss2si: | ||||||||||||
2275 | case Intrinsic::x86_sse_cvtss2si64: | ||||||||||||
2276 | case Intrinsic::x86_sse2_cvtsd2si: | ||||||||||||
2277 | case Intrinsic::x86_sse2_cvtsd2si64: | ||||||||||||
2278 | if (ConstantFP *FPOp = | ||||||||||||
2279 | dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) | ||||||||||||
2280 | return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), | ||||||||||||
2281 | /*roundTowardZero=*/false, Ty, | ||||||||||||
2282 | /*IsSigned*/true); | ||||||||||||
2283 | break; | ||||||||||||
2284 | case Intrinsic::x86_sse_cvttss2si: | ||||||||||||
2285 | case Intrinsic::x86_sse_cvttss2si64: | ||||||||||||
2286 | case Intrinsic::x86_sse2_cvttsd2si: | ||||||||||||
2287 | case Intrinsic::x86_sse2_cvttsd2si64: | ||||||||||||
2288 | if (ConstantFP *FPOp = | ||||||||||||
2289 | dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) | ||||||||||||
2290 | return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), | ||||||||||||
2291 | /*roundTowardZero=*/true, Ty, | ||||||||||||
2292 | /*IsSigned*/true); | ||||||||||||
2293 | break; | ||||||||||||
2294 | } | ||||||||||||
2295 | } | ||||||||||||
2296 | |||||||||||||
2297 | return nullptr; | ||||||||||||
2298 | } | ||||||||||||
2299 | |||||||||||||
2300 | static Constant *ConstantFoldScalarCall2(StringRef Name, | ||||||||||||
2301 | Intrinsic::ID IntrinsicID, | ||||||||||||
2302 | Type *Ty, | ||||||||||||
2303 | ArrayRef<Constant *> Operands, | ||||||||||||
2304 | const TargetLibraryInfo *TLI, | ||||||||||||
2305 | const CallBase *Call) { | ||||||||||||
2306 | assert(Operands.size() == 2 && "Wrong number of operands.")((Operands.size() == 2 && "Wrong number of operands." ) ? static_cast<void> (0) : __assert_fail ("Operands.size() == 2 && \"Wrong number of operands.\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 2306, __PRETTY_FUNCTION__)); | ||||||||||||
| |||||||||||||
2307 | |||||||||||||
2308 | if (auto *Op1
| ||||||||||||
2309 | if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy()) | ||||||||||||
2310 | return nullptr; | ||||||||||||
2311 | double Op1V = getValueAsDouble(Op1); | ||||||||||||
2312 | |||||||||||||
2313 | if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) { | ||||||||||||
2314 | if (Op2->getType() != Op1->getType()) | ||||||||||||
2315 | return nullptr; | ||||||||||||
2316 | |||||||||||||
2317 | double Op2V = getValueAsDouble(Op2); | ||||||||||||
2318 | if (IntrinsicID == Intrinsic::pow) { | ||||||||||||
2319 | return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty); | ||||||||||||
2320 | } | ||||||||||||
2321 | if (IntrinsicID == Intrinsic::copysign) { | ||||||||||||
2322 | APFloat V1 = Op1->getValueAPF(); | ||||||||||||
2323 | const APFloat &V2 = Op2->getValueAPF(); | ||||||||||||
2324 | V1.copySign(V2); | ||||||||||||
2325 | return ConstantFP::get(Ty->getContext(), V1); | ||||||||||||
2326 | } | ||||||||||||
2327 | |||||||||||||
2328 | if (IntrinsicID == Intrinsic::minnum) { | ||||||||||||
2329 | const APFloat &C1 = Op1->getValueAPF(); | ||||||||||||
2330 | const APFloat &C2 = Op2->getValueAPF(); | ||||||||||||
2331 | return ConstantFP::get(Ty->getContext(), minnum(C1, C2)); | ||||||||||||
2332 | } | ||||||||||||
2333 | |||||||||||||
2334 | if (IntrinsicID == Intrinsic::maxnum) { | ||||||||||||
2335 | const APFloat &C1 = Op1->getValueAPF(); | ||||||||||||
2336 | const APFloat &C2 = Op2->getValueAPF(); | ||||||||||||
2337 | return ConstantFP::get(Ty->getContext(), maxnum(C1, C2)); | ||||||||||||
2338 | } | ||||||||||||
2339 | |||||||||||||
2340 | if (IntrinsicID == Intrinsic::minimum) { | ||||||||||||
2341 | const APFloat &C1 = Op1->getValueAPF(); | ||||||||||||
2342 | const APFloat &C2 = Op2->getValueAPF(); | ||||||||||||
2343 | return ConstantFP::get(Ty->getContext(), minimum(C1, C2)); | ||||||||||||
2344 | } | ||||||||||||
2345 | |||||||||||||
2346 | if (IntrinsicID == Intrinsic::maximum) { | ||||||||||||
2347 | const APFloat &C1 = Op1->getValueAPF(); | ||||||||||||
2348 | const APFloat &C2 = Op2->getValueAPF(); | ||||||||||||
2349 | return ConstantFP::get(Ty->getContext(), maximum(C1, C2)); | ||||||||||||
2350 | } | ||||||||||||
2351 | |||||||||||||
2352 | if (IntrinsicID == Intrinsic::amdgcn_fmul_legacy) { | ||||||||||||
2353 | const APFloat &C1 = Op1->getValueAPF(); | ||||||||||||
2354 | const APFloat &C2 = Op2->getValueAPF(); | ||||||||||||
2355 | // The legacy behaviour is that multiplying zero by anything, even NaN | ||||||||||||
2356 | // or infinity, gives +0.0. | ||||||||||||
2357 | if (C1.isZero() || C2.isZero()) | ||||||||||||
2358 | return ConstantFP::getNullValue(Ty); | ||||||||||||
2359 | return ConstantFP::get(Ty->getContext(), C1 * C2); | ||||||||||||
2360 | } | ||||||||||||
2361 | |||||||||||||
2362 | if (!TLI) | ||||||||||||
2363 | return nullptr; | ||||||||||||
2364 | |||||||||||||
2365 | LibFunc Func = NotLibFunc; | ||||||||||||
2366 | TLI->getLibFunc(Name, Func); | ||||||||||||
2367 | switch (Func) { | ||||||||||||
2368 | default: | ||||||||||||
2369 | break; | ||||||||||||
2370 | case LibFunc_pow: | ||||||||||||
2371 | case LibFunc_powf: | ||||||||||||
2372 | case LibFunc_pow_finite: | ||||||||||||
2373 | case LibFunc_powf_finite: | ||||||||||||
2374 | if (TLI->has(Func)) | ||||||||||||
2375 | return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty); | ||||||||||||
2376 | break; | ||||||||||||
2377 | case LibFunc_fmod: | ||||||||||||
2378 | case LibFunc_fmodf: | ||||||||||||
2379 | if (TLI->has(Func)) { | ||||||||||||
2380 | APFloat V = Op1->getValueAPF(); | ||||||||||||
2381 | if (APFloat::opStatus::opOK == V.mod(Op2->getValueAPF())) | ||||||||||||
2382 | return ConstantFP::get(Ty->getContext(), V); | ||||||||||||
2383 | } | ||||||||||||
2384 | break; | ||||||||||||
2385 | case LibFunc_remainder: | ||||||||||||
2386 | case LibFunc_remainderf: | ||||||||||||
2387 | if (TLI->has(Func)) { | ||||||||||||
2388 | APFloat V = Op1->getValueAPF(); | ||||||||||||
2389 | if (APFloat::opStatus::opOK == V.remainder(Op2->getValueAPF())) | ||||||||||||
2390 | return ConstantFP::get(Ty->getContext(), V); | ||||||||||||
2391 | } | ||||||||||||
2392 | break; | ||||||||||||
2393 | case LibFunc_atan2: | ||||||||||||
2394 | case LibFunc_atan2f: | ||||||||||||
2395 | case LibFunc_atan2_finite: | ||||||||||||
2396 | case LibFunc_atan2f_finite: | ||||||||||||
2397 | if (TLI->has(Func)) | ||||||||||||
2398 | return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty); | ||||||||||||
2399 | break; | ||||||||||||
2400 | } | ||||||||||||
2401 | } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) { | ||||||||||||
2402 | if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy()) | ||||||||||||
2403 | return ConstantFP::get(Ty->getContext(), | ||||||||||||
2404 | APFloat((float)std::pow((float)Op1V, | ||||||||||||
2405 | (int)Op2C->getZExtValue()))); | ||||||||||||
2406 | if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy()) | ||||||||||||
2407 | return ConstantFP::get(Ty->getContext(), | ||||||||||||
2408 | APFloat((float)std::pow((float)Op1V, | ||||||||||||
2409 | (int)Op2C->getZExtValue()))); | ||||||||||||
2410 | if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy()) | ||||||||||||
2411 | return ConstantFP::get(Ty->getContext(), | ||||||||||||
2412 | APFloat((double)std::pow((double)Op1V, | ||||||||||||
2413 | (int)Op2C->getZExtValue()))); | ||||||||||||
2414 | |||||||||||||
2415 | if (IntrinsicID == Intrinsic::amdgcn_ldexp) { | ||||||||||||
2416 | // FIXME: Should flush denorms depending on FP mode, but that's ignored | ||||||||||||
2417 | // everywhere else. | ||||||||||||
2418 | |||||||||||||
2419 | // scalbn is equivalent to ldexp with float radix 2 | ||||||||||||
2420 | APFloat Result = scalbn(Op1->getValueAPF(), Op2C->getSExtValue(), | ||||||||||||
2421 | APFloat::rmNearestTiesToEven); | ||||||||||||
2422 | return ConstantFP::get(Ty->getContext(), Result); | ||||||||||||
2423 | } | ||||||||||||
2424 | } | ||||||||||||
2425 | return nullptr; | ||||||||||||
2426 | } | ||||||||||||
2427 | |||||||||||||
2428 | if (Operands[0]->getType()->isIntegerTy() && | ||||||||||||
2429 | Operands[1]->getType()->isIntegerTy()) { | ||||||||||||
2430 | const APInt *C0, *C1; | ||||||||||||
2431 | if (!getConstIntOrUndef(Operands[0], C0) || | ||||||||||||
2432 | !getConstIntOrUndef(Operands[1], C1)) | ||||||||||||
2433 | return nullptr; | ||||||||||||
2434 | |||||||||||||
2435 | unsigned BitWidth = Ty->getScalarSizeInBits(); | ||||||||||||
2436 | switch (IntrinsicID) { | ||||||||||||
2437 | default: break; | ||||||||||||
2438 | case Intrinsic::smax: | ||||||||||||
2439 | if (!C0 && !C1) | ||||||||||||
2440 | return UndefValue::get(Ty); | ||||||||||||
2441 | if (!C0 || !C1) | ||||||||||||
2442 | return ConstantInt::get(Ty, APInt::getSignedMaxValue(BitWidth)); | ||||||||||||
2443 | return ConstantInt::get(Ty, C0->sgt(*C1) ? *C0 : *C1); | ||||||||||||
2444 | |||||||||||||
2445 | case Intrinsic::smin: | ||||||||||||
2446 | if (!C0 && !C1) | ||||||||||||
2447 | return UndefValue::get(Ty); | ||||||||||||
2448 | if (!C0 || !C1) | ||||||||||||
2449 | return ConstantInt::get(Ty, APInt::getSignedMinValue(BitWidth)); | ||||||||||||
2450 | return ConstantInt::get(Ty, C0->slt(*C1) ? *C0 : *C1); | ||||||||||||
2451 | |||||||||||||
2452 | case Intrinsic::umax: | ||||||||||||
2453 | if (!C0 && !C1) | ||||||||||||
2454 | return UndefValue::get(Ty); | ||||||||||||
2455 | if (!C0 || !C1) | ||||||||||||
2456 | return ConstantInt::get(Ty, APInt::getMaxValue(BitWidth)); | ||||||||||||
2457 | return ConstantInt::get(Ty, C0->ugt(*C1) ? *C0 : *C1); | ||||||||||||
2458 | |||||||||||||
2459 | case Intrinsic::umin: | ||||||||||||
2460 | if (!C0 && !C1) | ||||||||||||
2461 | return UndefValue::get(Ty); | ||||||||||||
2462 | if (!C0 || !C1) | ||||||||||||
2463 | return ConstantInt::get(Ty, APInt::getMinValue(BitWidth)); | ||||||||||||
2464 | return ConstantInt::get(Ty, C0->ult(*C1) ? *C0 : *C1); | ||||||||||||
2465 | |||||||||||||
2466 | case Intrinsic::usub_with_overflow: | ||||||||||||
2467 | case Intrinsic::ssub_with_overflow: | ||||||||||||
2468 | case Intrinsic::uadd_with_overflow: | ||||||||||||
2469 | case Intrinsic::sadd_with_overflow: | ||||||||||||
2470 | // X - undef -> { undef, false } | ||||||||||||
2471 | // undef - X -> { undef, false } | ||||||||||||
2472 | // X + undef -> { undef, false } | ||||||||||||
2473 | // undef + x -> { undef, false } | ||||||||||||
2474 | if (!C0 || !C1) { | ||||||||||||
2475 | return ConstantStruct::get( | ||||||||||||
2476 | cast<StructType>(Ty), | ||||||||||||
2477 | {UndefValue::get(Ty->getStructElementType(0)), | ||||||||||||
2478 | Constant::getNullValue(Ty->getStructElementType(1))}); | ||||||||||||
2479 | } | ||||||||||||
2480 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||||||||
2481 | case Intrinsic::smul_with_overflow: | ||||||||||||
2482 | case Intrinsic::umul_with_overflow: { | ||||||||||||
2483 | // undef * X -> { 0, false } | ||||||||||||
2484 | // X * undef -> { 0, false } | ||||||||||||
2485 | if (!C0 || !C1) | ||||||||||||
2486 | return Constant::getNullValue(Ty); | ||||||||||||
2487 | |||||||||||||
2488 | APInt Res; | ||||||||||||
2489 | bool Overflow; | ||||||||||||
2490 | switch (IntrinsicID) { | ||||||||||||
2491 | default: llvm_unreachable("Invalid case")::llvm::llvm_unreachable_internal("Invalid case", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 2491); | ||||||||||||
2492 | case Intrinsic::sadd_with_overflow: | ||||||||||||
2493 | Res = C0->sadd_ov(*C1, Overflow); | ||||||||||||
2494 | break; | ||||||||||||
2495 | case Intrinsic::uadd_with_overflow: | ||||||||||||
2496 | Res = C0->uadd_ov(*C1, Overflow); | ||||||||||||
2497 | break; | ||||||||||||
2498 | case Intrinsic::ssub_with_overflow: | ||||||||||||
2499 | Res = C0->ssub_ov(*C1, Overflow); | ||||||||||||
2500 | break; | ||||||||||||
2501 | case Intrinsic::usub_with_overflow: | ||||||||||||
2502 | Res = C0->usub_ov(*C1, Overflow); | ||||||||||||
2503 | break; | ||||||||||||
2504 | case Intrinsic::smul_with_overflow: | ||||||||||||
2505 | Res = C0->smul_ov(*C1, Overflow); | ||||||||||||
2506 | break; | ||||||||||||
2507 | case Intrinsic::umul_with_overflow: | ||||||||||||
2508 | Res = C0->umul_ov(*C1, Overflow); | ||||||||||||
2509 | break; | ||||||||||||
2510 | } | ||||||||||||
2511 | Constant *Ops[] = { | ||||||||||||
2512 | ConstantInt::get(Ty->getContext(), Res), | ||||||||||||
2513 | ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow) | ||||||||||||
2514 | }; | ||||||||||||
2515 | return ConstantStruct::get(cast<StructType>(Ty), Ops); | ||||||||||||
2516 | } | ||||||||||||
2517 | case Intrinsic::uadd_sat: | ||||||||||||
2518 | case Intrinsic::sadd_sat: | ||||||||||||
2519 | if (!C0 && !C1) | ||||||||||||
2520 | return UndefValue::get(Ty); | ||||||||||||
2521 | if (!C0 || !C1) | ||||||||||||
2522 | return Constant::getAllOnesValue(Ty); | ||||||||||||
2523 | if (IntrinsicID == Intrinsic::uadd_sat) | ||||||||||||
2524 | return ConstantInt::get(Ty, C0->uadd_sat(*C1)); | ||||||||||||
2525 | else | ||||||||||||
2526 | return ConstantInt::get(Ty, C0->sadd_sat(*C1)); | ||||||||||||
2527 | case Intrinsic::usub_sat: | ||||||||||||
2528 | case Intrinsic::ssub_sat: | ||||||||||||
2529 | if (!C0 && !C1) | ||||||||||||
2530 | return UndefValue::get(Ty); | ||||||||||||
2531 | if (!C0 || !C1) | ||||||||||||
2532 | return Constant::getNullValue(Ty); | ||||||||||||
2533 | if (IntrinsicID == Intrinsic::usub_sat) | ||||||||||||
2534 | return ConstantInt::get(Ty, C0->usub_sat(*C1)); | ||||||||||||
2535 | else | ||||||||||||
2536 | return ConstantInt::get(Ty, C0->ssub_sat(*C1)); | ||||||||||||
2537 | case Intrinsic::cttz: | ||||||||||||
2538 | case Intrinsic::ctlz: | ||||||||||||
2539 | assert(C1 && "Must be constant int")((C1 && "Must be constant int") ? static_cast<void > (0) : __assert_fail ("C1 && \"Must be constant int\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 2539, __PRETTY_FUNCTION__)); | ||||||||||||
2540 | |||||||||||||
2541 | // cttz(0, 1) and ctlz(0, 1) are undef. | ||||||||||||
2542 | if (C1->isOneValue() && (!C0 || C0->isNullValue())) | ||||||||||||
2543 | return UndefValue::get(Ty); | ||||||||||||
2544 | if (!C0) | ||||||||||||
2545 | return Constant::getNullValue(Ty); | ||||||||||||
2546 | if (IntrinsicID == Intrinsic::cttz) | ||||||||||||
2547 | return ConstantInt::get(Ty, C0->countTrailingZeros()); | ||||||||||||
2548 | else | ||||||||||||
2549 | return ConstantInt::get(Ty, C0->countLeadingZeros()); | ||||||||||||
2550 | |||||||||||||
2551 | case Intrinsic::abs: | ||||||||||||
2552 | // Undef or minimum val operand with poison min --> undef | ||||||||||||
2553 | assert(C1 && "Must be constant int")((C1 && "Must be constant int") ? static_cast<void > (0) : __assert_fail ("C1 && \"Must be constant int\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 2553, __PRETTY_FUNCTION__)); | ||||||||||||
2554 | if (C1->isOneValue() && (!C0 || C0->isMinSignedValue())) | ||||||||||||
2555 | return UndefValue::get(Ty); | ||||||||||||
2556 | |||||||||||||
2557 | // Undef operand with no poison min --> 0 (sign bit must be clear) | ||||||||||||
2558 | if (C1->isNullValue() && !C0) | ||||||||||||
2559 | return Constant::getNullValue(Ty); | ||||||||||||
2560 | |||||||||||||
2561 | return ConstantInt::get(Ty, C0->abs()); | ||||||||||||
| |||||||||||||
2562 | } | ||||||||||||
2563 | |||||||||||||
2564 | return nullptr; | ||||||||||||
2565 | } | ||||||||||||
2566 | |||||||||||||
2567 | // Support ConstantVector in case we have an Undef in the top. | ||||||||||||
2568 | if ((isa<ConstantVector>(Operands[0]) || | ||||||||||||
2569 | isa<ConstantDataVector>(Operands[0])) && | ||||||||||||
2570 | // Check for default rounding mode. | ||||||||||||
2571 | // FIXME: Support other rounding modes? | ||||||||||||
2572 | isa<ConstantInt>(Operands[1]) && | ||||||||||||
2573 | cast<ConstantInt>(Operands[1])->getValue() == 4) { | ||||||||||||
2574 | auto *Op = cast<Constant>(Operands[0]); | ||||||||||||
2575 | switch (IntrinsicID) { | ||||||||||||
2576 | default: break; | ||||||||||||
2577 | case Intrinsic::x86_avx512_vcvtss2si32: | ||||||||||||
2578 | case Intrinsic::x86_avx512_vcvtss2si64: | ||||||||||||
2579 | case Intrinsic::x86_avx512_vcvtsd2si32: | ||||||||||||
2580 | case Intrinsic::x86_avx512_vcvtsd2si64: | ||||||||||||
2581 | if (ConstantFP *FPOp = | ||||||||||||
2582 | dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) | ||||||||||||
2583 | return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), | ||||||||||||
2584 | /*roundTowardZero=*/false, Ty, | ||||||||||||
2585 | /*IsSigned*/true); | ||||||||||||
2586 | break; | ||||||||||||
2587 | case Intrinsic::x86_avx512_vcvtss2usi32: | ||||||||||||
2588 | case Intrinsic::x86_avx512_vcvtss2usi64: | ||||||||||||
2589 | case Intrinsic::x86_avx512_vcvtsd2usi32: | ||||||||||||
2590 | case Intrinsic::x86_avx512_vcvtsd2usi64: | ||||||||||||
2591 | if (ConstantFP *FPOp = | ||||||||||||
2592 | dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) | ||||||||||||
2593 | return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), | ||||||||||||
2594 | /*roundTowardZero=*/false, Ty, | ||||||||||||
2595 | /*IsSigned*/false); | ||||||||||||
2596 | break; | ||||||||||||
2597 | case Intrinsic::x86_avx512_cvttss2si: | ||||||||||||
2598 | case Intrinsic::x86_avx512_cvttss2si64: | ||||||||||||
2599 | case Intrinsic::x86_avx512_cvttsd2si: | ||||||||||||
2600 | case Intrinsic::x86_avx512_cvttsd2si64: | ||||||||||||
2601 | if (ConstantFP *FPOp = | ||||||||||||
2602 | dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) | ||||||||||||
2603 | return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), | ||||||||||||
2604 | /*roundTowardZero=*/true, Ty, | ||||||||||||
2605 | /*IsSigned*/true); | ||||||||||||
2606 | break; | ||||||||||||
2607 | case Intrinsic::x86_avx512_cvttss2usi: | ||||||||||||
2608 | case Intrinsic::x86_avx512_cvttss2usi64: | ||||||||||||
2609 | case Intrinsic::x86_avx512_cvttsd2usi: | ||||||||||||
2610 | case Intrinsic::x86_avx512_cvttsd2usi64: | ||||||||||||
2611 | if (ConstantFP *FPOp = | ||||||||||||
2612 | dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U))) | ||||||||||||
2613 | return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(), | ||||||||||||
2614 | /*roundTowardZero=*/true, Ty, | ||||||||||||
2615 | /*IsSigned*/false); | ||||||||||||
2616 | break; | ||||||||||||
2617 | } | ||||||||||||
2618 | } | ||||||||||||
2619 | return nullptr; | ||||||||||||
2620 | } | ||||||||||||
2621 | |||||||||||||
2622 | static APFloat ConstantFoldAMDGCNCubeIntrinsic(Intrinsic::ID IntrinsicID, | ||||||||||||
2623 | const APFloat &S0, | ||||||||||||
2624 | const APFloat &S1, | ||||||||||||
2625 | const APFloat &S2) { | ||||||||||||
2626 | unsigned ID; | ||||||||||||
2627 | const fltSemantics &Sem = S0.getSemantics(); | ||||||||||||
2628 | APFloat MA(Sem), SC(Sem), TC(Sem); | ||||||||||||
2629 | if (abs(S2) >= abs(S0) && abs(S2) >= abs(S1)) { | ||||||||||||
2630 | if (S2.isNegative() && S2.isNonZero() && !S2.isNaN()) { | ||||||||||||
2631 | // S2 < 0 | ||||||||||||
2632 | ID = 5; | ||||||||||||
2633 | SC = -S0; | ||||||||||||
2634 | } else { | ||||||||||||
2635 | ID = 4; | ||||||||||||
2636 | SC = S0; | ||||||||||||
2637 | } | ||||||||||||
2638 | MA = S2; | ||||||||||||
2639 | TC = -S1; | ||||||||||||
2640 | } else if (abs(S1) >= abs(S0)) { | ||||||||||||
2641 | if (S1.isNegative() && S1.isNonZero() && !S1.isNaN()) { | ||||||||||||
2642 | // S1 < 0 | ||||||||||||
2643 | ID = 3; | ||||||||||||
2644 | TC = -S2; | ||||||||||||
2645 | } else { | ||||||||||||
2646 | ID = 2; | ||||||||||||
2647 | TC = S2; | ||||||||||||
2648 | } | ||||||||||||
2649 | MA = S1; | ||||||||||||
2650 | SC = S0; | ||||||||||||
2651 | } else { | ||||||||||||
2652 | if (S0.isNegative() && S0.isNonZero() && !S0.isNaN()) { | ||||||||||||
2653 | // S0 < 0 | ||||||||||||
2654 | ID = 1; | ||||||||||||
2655 | SC = S2; | ||||||||||||
2656 | } else { | ||||||||||||
2657 | ID = 0; | ||||||||||||
2658 | SC = -S2; | ||||||||||||
2659 | } | ||||||||||||
2660 | MA = S0; | ||||||||||||
2661 | TC = -S1; | ||||||||||||
2662 | } | ||||||||||||
2663 | switch (IntrinsicID) { | ||||||||||||
2664 | default: | ||||||||||||
2665 | llvm_unreachable("unhandled amdgcn cube intrinsic")::llvm::llvm_unreachable_internal("unhandled amdgcn cube intrinsic" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 2665); | ||||||||||||
2666 | case Intrinsic::amdgcn_cubeid: | ||||||||||||
2667 | return APFloat(Sem, ID); | ||||||||||||
2668 | case Intrinsic::amdgcn_cubema: | ||||||||||||
2669 | return MA + MA; | ||||||||||||
2670 | case Intrinsic::amdgcn_cubesc: | ||||||||||||
2671 | return SC; | ||||||||||||
2672 | case Intrinsic::amdgcn_cubetc: | ||||||||||||
2673 | return TC; | ||||||||||||
2674 | } | ||||||||||||
2675 | } | ||||||||||||
2676 | |||||||||||||
2677 | static Constant *ConstantFoldScalarCall3(StringRef Name, | ||||||||||||
2678 | Intrinsic::ID IntrinsicID, | ||||||||||||
2679 | Type *Ty, | ||||||||||||
2680 | ArrayRef<Constant *> Operands, | ||||||||||||
2681 | const TargetLibraryInfo *TLI, | ||||||||||||
2682 | const CallBase *Call) { | ||||||||||||
2683 | assert(Operands.size() == 3 && "Wrong number of operands.")((Operands.size() == 3 && "Wrong number of operands." ) ? static_cast<void> (0) : __assert_fail ("Operands.size() == 3 && \"Wrong number of operands.\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 2683, __PRETTY_FUNCTION__)); | ||||||||||||
2684 | |||||||||||||
2685 | if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) { | ||||||||||||
2686 | if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) { | ||||||||||||
2687 | if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) { | ||||||||||||
2688 | switch (IntrinsicID) { | ||||||||||||
2689 | default: break; | ||||||||||||
2690 | case Intrinsic::fma: | ||||||||||||
2691 | case Intrinsic::fmuladd: { | ||||||||||||
2692 | APFloat V = Op1->getValueAPF(); | ||||||||||||
2693 | V.fusedMultiplyAdd(Op2->getValueAPF(), Op3->getValueAPF(), | ||||||||||||
2694 | APFloat::rmNearestTiesToEven); | ||||||||||||
2695 | return ConstantFP::get(Ty->getContext(), V); | ||||||||||||
2696 | } | ||||||||||||
2697 | case Intrinsic::amdgcn_cubeid: | ||||||||||||
2698 | case Intrinsic::amdgcn_cubema: | ||||||||||||
2699 | case Intrinsic::amdgcn_cubesc: | ||||||||||||
2700 | case Intrinsic::amdgcn_cubetc: { | ||||||||||||
2701 | APFloat V = ConstantFoldAMDGCNCubeIntrinsic( | ||||||||||||
2702 | IntrinsicID, Op1->getValueAPF(), Op2->getValueAPF(), | ||||||||||||
2703 | Op3->getValueAPF()); | ||||||||||||
2704 | return ConstantFP::get(Ty->getContext(), V); | ||||||||||||
2705 | } | ||||||||||||
2706 | } | ||||||||||||
2707 | } | ||||||||||||
2708 | } | ||||||||||||
2709 | } | ||||||||||||
2710 | |||||||||||||
2711 | if (const auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) { | ||||||||||||
2712 | if (const auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) { | ||||||||||||
2713 | if (const auto *Op3 = dyn_cast<ConstantInt>(Operands[2])) { | ||||||||||||
2714 | switch (IntrinsicID) { | ||||||||||||
2715 | default: break; | ||||||||||||
2716 | case Intrinsic::smul_fix: | ||||||||||||
2717 | case Intrinsic::smul_fix_sat: { | ||||||||||||
2718 | // This code performs rounding towards negative infinity in case the | ||||||||||||
2719 | // result cannot be represented exactly for the given scale. Targets | ||||||||||||
2720 | // that do care about rounding should use a target hook for specifying | ||||||||||||
2721 | // how rounding should be done, and provide their own folding to be | ||||||||||||
2722 | // consistent with rounding. This is the same approach as used by | ||||||||||||
2723 | // DAGTypeLegalizer::ExpandIntRes_MULFIX. | ||||||||||||
2724 | const APInt &Lhs = Op1->getValue(); | ||||||||||||
2725 | const APInt &Rhs = Op2->getValue(); | ||||||||||||
2726 | unsigned Scale = Op3->getValue().getZExtValue(); | ||||||||||||
2727 | unsigned Width = Lhs.getBitWidth(); | ||||||||||||
2728 | assert(Scale < Width && "Illegal scale.")((Scale < Width && "Illegal scale.") ? static_cast <void> (0) : __assert_fail ("Scale < Width && \"Illegal scale.\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/lib/Analysis/ConstantFolding.cpp" , 2728, __PRETTY_FUNCTION__)); | ||||||||||||
2729 | unsigned ExtendedWidth = Width * 2; | ||||||||||||
2730 | APInt Product = (Lhs.sextOrSelf(ExtendedWidth) * | ||||||||||||
2731 | Rhs.sextOrSelf(ExtendedWidth)).ashr(Scale); | ||||||||||||
2732 | if (IntrinsicID == Intrinsic::smul_fix_sat) { | ||||||||||||
2733 | APInt MaxValue = | ||||||||||||
2734 | APInt::getSignedMaxValue(Width).sextOrSelf(ExtendedWidth); | ||||||||||||
2735 | APInt MinValue = | ||||||||||||
2736 | APInt::getSignedMinValue(Width).sextOrSelf(ExtendedWidth); | ||||||||||||
2737 | Product = APIntOps::smin(Product, MaxValue); | ||||||||||||
2738 | Product = APIntOps::smax(Product, MinValue); | ||||||||||||
2739 | } | ||||||||||||
2740 | return ConstantInt::get(Ty->getContext(), | ||||||||||||
2741 | Product.sextOrTrunc(Width)); | ||||||||||||
2742 | } | ||||||||||||
2743 | } | ||||||||||||
2744 | } | ||||||||||||
2745 | } | ||||||||||||
2746 | } | ||||||||||||
2747 | |||||||||||||
2748 | if (IntrinsicID == Intrinsic::fshl || IntrinsicID == Intrinsic::fshr) { | ||||||||||||
2749 | const APInt *C0, *C1, *C2; | ||||||||||||
2750 | if (!getConstIntOrUndef(Operands[0], C0) || | ||||||||||||
2751 | !getConstIntOrUndef(Operands[1], C1) || | ||||||||||||
2752 | !getConstIntOrUndef(Operands[2], C2)) | ||||||||||||
2753 | return nullptr; | ||||||||||||
2754 | |||||||||||||
2755 | bool IsRight = IntrinsicID == Intrinsic::fshr; | ||||||||||||
2756 | if (!C2) | ||||||||||||
2757 | return Operands[IsRight ? 1 : 0]; | ||||||||||||
2758 | if (!C0 && !C1) | ||||||||||||
2759 | return UndefValue::get(Ty); | ||||||||||||
2760 | |||||||||||||
2761 | // The shift amount is interpreted as modulo the bitwidth. If the shift | ||||||||||||
2762 | // amount is effectively 0, avoid UB due to oversized inverse shift below. | ||||||||||||
2763 | unsigned BitWidth = C2->getBitWidth(); | ||||||||||||
2764 | unsigned ShAmt = C2->urem(BitWidth); | ||||||||||||
2765 | if (!ShAmt) | ||||||||||||
2766 | return Operands[IsRight ? 1 : 0]; | ||||||||||||
2767 | |||||||||||||
2768 | // (C0 << ShlAmt) | (C1 >> LshrAmt) | ||||||||||||
2769 | unsigned LshrAmt = IsRight ? ShAmt : BitWidth - ShAmt; | ||||||||||||
2770 | unsigned ShlAmt = !IsRight ? ShAmt : BitWidth - ShAmt; | ||||||||||||
2771 | if (!C0) | ||||||||||||
2772 | return ConstantInt::get(Ty, C1->lshr(LshrAmt)); | ||||||||||||
2773 | if (!C1) | ||||||||||||
2774 | return ConstantInt::get(Ty, C0->shl(ShlAmt)); | ||||||||||||
2775 | return ConstantInt::get(Ty, C0->shl(ShlAmt) | C1->lshr(LshrAmt)); | ||||||||||||
2776 | } | ||||||||||||
2777 | |||||||||||||
2778 | return nullptr; | ||||||||||||
2779 | } | ||||||||||||
2780 | |||||||||||||
2781 | static Constant *ConstantFoldScalarCall(StringRef Name, | ||||||||||||
2782 | Intrinsic::ID IntrinsicID, | ||||||||||||
2783 | Type *Ty, | ||||||||||||
2784 | ArrayRef<Constant *> Operands, | ||||||||||||
2785 | const TargetLibraryInfo *TLI, | ||||||||||||
2786 | const CallBase *Call) { | ||||||||||||
2787 | if (Operands.size() == 1) | ||||||||||||
2788 | return ConstantFoldScalarCall1(Name, IntrinsicID, Ty, Operands, TLI, Call); | ||||||||||||
2789 | |||||||||||||
2790 | if (Operands.size() == 2) | ||||||||||||
2791 | return ConstantFoldScalarCall2(Name, IntrinsicID, Ty, Operands, TLI, Call); | ||||||||||||
2792 | |||||||||||||
2793 | if (Operands.size() == 3) | ||||||||||||
2794 | return ConstantFoldScalarCall3(Name, IntrinsicID, Ty, Operands, TLI, Call); | ||||||||||||
2795 | |||||||||||||
2796 | return nullptr; | ||||||||||||
2797 | } | ||||||||||||
2798 | |||||||||||||
2799 | static Constant *ConstantFoldVectorCall(StringRef Name, | ||||||||||||
2800 | Intrinsic::ID IntrinsicID, | ||||||||||||
2801 | VectorType *VTy, | ||||||||||||
2802 | ArrayRef<Constant *> Operands, | ||||||||||||
2803 | const DataLayout &DL, | ||||||||||||
2804 | const TargetLibraryInfo *TLI, | ||||||||||||
2805 | const CallBase *Call) { | ||||||||||||
2806 | // Do not iterate on scalable vector. The number of elements is unknown at | ||||||||||||
2807 | // compile-time. | ||||||||||||
2808 | if (isa<ScalableVectorType>(VTy)) | ||||||||||||
2809 | return nullptr; | ||||||||||||
2810 | |||||||||||||
2811 | auto *FVTy = cast<FixedVectorType>(VTy); | ||||||||||||
2812 | |||||||||||||
2813 | SmallVector<Constant *, 4> Result(FVTy->getNumElements()); | ||||||||||||
2814 | SmallVector<Constant *, 4> Lane(Operands.size()); | ||||||||||||
2815 | Type *Ty = FVTy->getElementType(); | ||||||||||||
2816 | |||||||||||||
2817 | switch (IntrinsicID) { | ||||||||||||
2818 | case Intrinsic::masked_load: { | ||||||||||||
2819 | auto *SrcPtr = Operands[0]; | ||||||||||||
2820 | auto *Mask = Operands[2]; | ||||||||||||
2821 | auto *Passthru = Operands[3]; | ||||||||||||
2822 | |||||||||||||
2823 | Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, FVTy, DL); | ||||||||||||
2824 | |||||||||||||
2825 | SmallVector<Constant *, 32> NewElements; | ||||||||||||
2826 | for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) { | ||||||||||||
2827 | auto *MaskElt = Mask->getAggregateElement(I); | ||||||||||||
2828 | if (!MaskElt) | ||||||||||||
2829 | break; | ||||||||||||
2830 | auto *PassthruElt = Passthru->getAggregateElement(I); | ||||||||||||
2831 | auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr; | ||||||||||||
2832 | if (isa<UndefValue>(MaskElt)) { | ||||||||||||
2833 | if (PassthruElt) | ||||||||||||
2834 | NewElements.push_back(PassthruElt); | ||||||||||||
2835 | else if (VecElt) | ||||||||||||
2836 | NewElements.push_back(VecElt); | ||||||||||||
2837 | else | ||||||||||||
2838 | return nullptr; | ||||||||||||
2839 | } | ||||||||||||
2840 | if (MaskElt->isNullValue()) { | ||||||||||||
2841 | if (!PassthruElt) | ||||||||||||
2842 | return nullptr; | ||||||||||||
2843 | NewElements.push_back(PassthruElt); | ||||||||||||
2844 | } else if (MaskElt->isOneValue()) { | ||||||||||||
2845 | if (!VecElt) | ||||||||||||
2846 | return nullptr; | ||||||||||||
2847 | NewElements.push_back(VecElt); | ||||||||||||
2848 | } else { | ||||||||||||
2849 | return nullptr; | ||||||||||||
2850 | } | ||||||||||||
2851 | } | ||||||||||||
2852 | if (NewElements.size() != FVTy->getNumElements()) | ||||||||||||
2853 | return nullptr; | ||||||||||||
2854 | return ConstantVector::get(NewElements); | ||||||||||||
2855 | } | ||||||||||||
2856 | case Intrinsic::arm_mve_vctp8: | ||||||||||||
2857 | case Intrinsic::arm_mve_vctp16: | ||||||||||||
2858 | case Intrinsic::arm_mve_vctp32: | ||||||||||||
2859 | case Intrinsic::arm_mve_vctp64: { | ||||||||||||
2860 | if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) { | ||||||||||||
2861 | unsigned Lanes = FVTy->getNumElements(); | ||||||||||||
2862 | uint64_t Limit = Op->getZExtValue(); | ||||||||||||
2863 | // vctp64 are currently modelled as returning a v4i1, not a v2i1. Make | ||||||||||||
2864 | // sure we get the limit right in that case and set all relevant lanes. | ||||||||||||
2865 | if (IntrinsicID == Intrinsic::arm_mve_vctp64) | ||||||||||||
2866 | Limit *= 2; | ||||||||||||
2867 | |||||||||||||
2868 | SmallVector<Constant *, 16> NCs; | ||||||||||||
2869 | for (unsigned i = 0; i < Lanes; i++) { | ||||||||||||
2870 | if (i < Limit) | ||||||||||||
2871 | NCs.push_back(ConstantInt::getTrue(Ty)); | ||||||||||||
2872 | else | ||||||||||||
2873 | NCs.push_back(ConstantInt::getFalse(Ty)); | ||||||||||||
2874 | } | ||||||||||||
2875 | return ConstantVector::get(NCs); | ||||||||||||
2876 | } | ||||||||||||
2877 | break; | ||||||||||||
2878 | } | ||||||||||||
2879 | default: | ||||||||||||
2880 | break; | ||||||||||||
2881 | } | ||||||||||||
2882 | |||||||||||||
2883 | for (unsigned I = 0, E = FVTy->getNumElements(); I != E; ++I) { | ||||||||||||
2884 | // Gather a column of constants. | ||||||||||||
2885 | for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) { | ||||||||||||
2886 | // Some intrinsics use a scalar type for certain arguments. | ||||||||||||
2887 | if (hasVectorInstrinsicScalarOpd(IntrinsicID, J)) { | ||||||||||||
2888 | Lane[J] = Operands[J]; | ||||||||||||
2889 | continue; | ||||||||||||
2890 | } | ||||||||||||
2891 | |||||||||||||
2892 | Constant *Agg = Operands[J]->getAggregateElement(I); | ||||||||||||
2893 | if (!Agg) | ||||||||||||
2894 | return nullptr; | ||||||||||||
2895 | |||||||||||||
2896 | Lane[J] = Agg; | ||||||||||||
2897 | } | ||||||||||||
2898 | |||||||||||||
2899 | // Use the regular scalar folding to simplify this column. | ||||||||||||
2900 | Constant *Folded = | ||||||||||||
2901 | ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI, Call); | ||||||||||||
2902 | if (!Folded) | ||||||||||||
2903 | return nullptr; | ||||||||||||
2904 | Result[I] = Folded; | ||||||||||||
2905 | } | ||||||||||||
2906 | |||||||||||||
2907 | return ConstantVector::get(Result); | ||||||||||||
2908 | } | ||||||||||||
2909 | |||||||||||||
2910 | } // end anonymous namespace | ||||||||||||
2911 | |||||||||||||
2912 | Constant *llvm::ConstantFoldCall(const CallBase *Call, Function *F, | ||||||||||||
2913 | ArrayRef<Constant *> Operands, | ||||||||||||
2914 | const TargetLibraryInfo *TLI) { | ||||||||||||
2915 | if (Call->isNoBuiltin()) | ||||||||||||
2916 | return nullptr; | ||||||||||||
2917 | if (!F->hasName()) | ||||||||||||
2918 | return nullptr; | ||||||||||||
2919 | StringRef Name = F->getName(); | ||||||||||||
2920 | |||||||||||||
2921 | Type *Ty = F->getReturnType(); | ||||||||||||
2922 | |||||||||||||
2923 | if (auto *VTy = dyn_cast<VectorType>(Ty)) | ||||||||||||
2924 | return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, | ||||||||||||
2925 | F->getParent()->getDataLayout(), TLI, Call); | ||||||||||||
2926 | |||||||||||||
2927 | return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI, | ||||||||||||
2928 | Call); | ||||||||||||
2929 | } | ||||||||||||
2930 | |||||||||||||
2931 | bool llvm::isMathLibCallNoop(const CallBase *Call, | ||||||||||||
2932 | const TargetLibraryInfo *TLI) { | ||||||||||||
2933 | // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap | ||||||||||||
2934 | // (and to some extent ConstantFoldScalarCall). | ||||||||||||
2935 | if (Call->isNoBuiltin() || Call->isStrictFP()) | ||||||||||||
2936 | return false; | ||||||||||||
2937 | Function *F = Call->getCalledFunction(); | ||||||||||||
2938 | if (!F) | ||||||||||||
2939 | return false; | ||||||||||||
2940 | |||||||||||||
2941 | LibFunc Func; | ||||||||||||
2942 | if (!TLI || !TLI->getLibFunc(*F, Func)) | ||||||||||||
2943 | return false; | ||||||||||||
2944 | |||||||||||||
2945 | if (Call->getNumArgOperands() == 1) { | ||||||||||||
2946 | if (ConstantFP *OpC = dyn_cast<ConstantFP>(Call->getArgOperand(0))) { | ||||||||||||
2947 | const APFloat &Op = OpC->getValueAPF(); | ||||||||||||
2948 | switch (Func) { | ||||||||||||
2949 | case LibFunc_logl: | ||||||||||||
2950 | case LibFunc_log: | ||||||||||||
2951 | case LibFunc_logf: | ||||||||||||
2952 | case LibFunc_log2l: | ||||||||||||
2953 | case LibFunc_log2: | ||||||||||||
2954 | case LibFunc_log2f: | ||||||||||||
2955 | case LibFunc_log10l: | ||||||||||||
2956 | case LibFunc_log10: | ||||||||||||
2957 | case LibFunc_log10f: | ||||||||||||
2958 | return Op.isNaN() || (!Op.isZero() && !Op.isNegative()); | ||||||||||||
2959 | |||||||||||||
2960 | case LibFunc_expl: | ||||||||||||
2961 | case LibFunc_exp: | ||||||||||||
2962 | case LibFunc_expf: | ||||||||||||
2963 | // FIXME: These boundaries are slightly conservative. | ||||||||||||
2964 | if (OpC->getType()->isDoubleTy()) | ||||||||||||
2965 | return !(Op < APFloat(-745.0) || Op > APFloat(709.0)); | ||||||||||||
2966 | if (OpC->getType()->isFloatTy()) | ||||||||||||
2967 | return !(Op < APFloat(-103.0f) || Op > APFloat(88.0f)); | ||||||||||||
2968 | break; | ||||||||||||
2969 | |||||||||||||
2970 | case LibFunc_exp2l: | ||||||||||||
2971 | case LibFunc_exp2: | ||||||||||||
2972 | case LibFunc_exp2f: | ||||||||||||
2973 | // FIXME: These boundaries are slightly conservative. | ||||||||||||
2974 | if (OpC->getType()->isDoubleTy()) | ||||||||||||
2975 | return !(Op < APFloat(-1074.0) || Op > APFloat(1023.0)); | ||||||||||||
2976 | if (OpC->getType()->isFloatTy()) | ||||||||||||
2977 | return !(Op < APFloat(-149.0f) || Op > APFloat(127.0f)); | ||||||||||||
2978 | break; | ||||||||||||
2979 | |||||||||||||
2980 | case LibFunc_sinl: | ||||||||||||
2981 | case LibFunc_sin: | ||||||||||||
2982 | case LibFunc_sinf: | ||||||||||||
2983 | case LibFunc_cosl: | ||||||||||||
2984 | case LibFunc_cos: | ||||||||||||
2985 | case LibFunc_cosf: | ||||||||||||
2986 | return !Op.isInfinity(); | ||||||||||||
2987 | |||||||||||||
2988 | case LibFunc_tanl: | ||||||||||||
2989 | case LibFunc_tan: | ||||||||||||
2990 | case LibFunc_tanf: { | ||||||||||||
2991 | // FIXME: Stop using the host math library. | ||||||||||||
2992 | // FIXME: The computation isn't done in the right precision. | ||||||||||||
2993 | Type *Ty = OpC->getType(); | ||||||||||||
2994 | if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) { | ||||||||||||
2995 | double OpV = getValueAsDouble(OpC); | ||||||||||||
2996 | return ConstantFoldFP(tan, OpV, Ty) != nullptr; | ||||||||||||
2997 | } | ||||||||||||
2998 | break; | ||||||||||||
2999 | } | ||||||||||||
3000 | |||||||||||||
3001 | case LibFunc_asinl: | ||||||||||||
3002 | case LibFunc_asin: | ||||||||||||
3003 | case LibFunc_asinf: | ||||||||||||
3004 | case LibFunc_acosl: | ||||||||||||
3005 | case LibFunc_acos: | ||||||||||||
3006 | case LibFunc_acosf: | ||||||||||||
3007 | return !(Op < APFloat(Op.getSemantics(), "-1") || | ||||||||||||
3008 | Op > APFloat(Op.getSemantics(), "1")); | ||||||||||||
3009 | |||||||||||||
3010 | case LibFunc_sinh: | ||||||||||||
3011 | case LibFunc_cosh: | ||||||||||||
3012 | case LibFunc_sinhf: | ||||||||||||
3013 | case LibFunc_coshf: | ||||||||||||
3014 | case LibFunc_sinhl: | ||||||||||||
3015 | case LibFunc_coshl: | ||||||||||||
3016 | // FIXME: These boundaries are slightly conservative. | ||||||||||||
3017 | if (OpC->getType()->isDoubleTy()) | ||||||||||||
3018 | return !(Op < APFloat(-710.0) || Op > APFloat(710.0)); | ||||||||||||
3019 | if (OpC->getType()->isFloatTy()) | ||||||||||||
3020 | return !(Op < APFloat(-89.0f) || Op > APFloat(89.0f)); | ||||||||||||
3021 | break; | ||||||||||||
3022 | |||||||||||||
3023 | case LibFunc_sqrtl: | ||||||||||||
3024 | case LibFunc_sqrt: | ||||||||||||
3025 | case LibFunc_sqrtf: | ||||||||||||
3026 | return Op.isNaN() || Op.isZero() || !Op.isNegative(); | ||||||||||||
3027 | |||||||||||||
3028 | // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p, | ||||||||||||
3029 | // maybe others? | ||||||||||||
3030 | default: | ||||||||||||
3031 | break; | ||||||||||||
3032 | } | ||||||||||||
3033 | } | ||||||||||||
3034 | } | ||||||||||||
3035 | |||||||||||||
3036 | if (Call->getNumArgOperands() == 2) { | ||||||||||||
3037 | ConstantFP *Op0C = dyn_cast<ConstantFP>(Call->getArgOperand(0)); | ||||||||||||
3038 | ConstantFP *Op1C = dyn_cast<ConstantFP>(Call->getArgOperand(1)); | ||||||||||||
3039 | if (Op0C && Op1C) { | ||||||||||||
3040 | const APFloat &Op0 = Op0C->getValueAPF(); | ||||||||||||
3041 | const APFloat &Op1 = Op1C->getValueAPF(); | ||||||||||||
3042 | |||||||||||||
3043 | switch (Func) { | ||||||||||||
3044 | case LibFunc_powl: | ||||||||||||
3045 | case LibFunc_pow: | ||||||||||||
3046 | case LibFunc_powf: { | ||||||||||||
3047 | // FIXME: Stop using the host math library. | ||||||||||||
3048 | // FIXME: The computation isn't done in the right precision. | ||||||||||||
3049 | Type *Ty = Op0C->getType(); | ||||||||||||
3050 | if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) { | ||||||||||||
3051 | if (Ty == Op1C->getType()) { | ||||||||||||
3052 | double Op0V = getValueAsDouble(Op0C); | ||||||||||||
3053 | double Op1V = getValueAsDouble(Op1C); | ||||||||||||
3054 | return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr; | ||||||||||||
3055 | } | ||||||||||||
3056 | } | ||||||||||||
3057 | break; | ||||||||||||
3058 | } | ||||||||||||
3059 | |||||||||||||
3060 | case LibFunc_fmodl: | ||||||||||||
3061 | case LibFunc_fmod: | ||||||||||||
3062 | case LibFunc_fmodf: | ||||||||||||
3063 | case LibFunc_remainderl: | ||||||||||||
3064 | case LibFunc_remainder: | ||||||||||||
3065 | case LibFunc_remainderf: | ||||||||||||
3066 | return Op0.isNaN() || Op1.isNaN() || | ||||||||||||
3067 | (!Op0.isInfinity() && !Op1.isZero()); | ||||||||||||
3068 | |||||||||||||
3069 | default: | ||||||||||||
3070 | break; | ||||||||||||
3071 | } | ||||||||||||
3072 | } | ||||||||||||
3073 | } | ||||||||||||
3074 | |||||||||||||
3075 | return false; | ||||||||||||
3076 | } | ||||||||||||
3077 | |||||||||||||
3078 | void TargetFolder::anchor() {} |
1 | //===- llvm/Type.h - Classes for handling data types ------------*- C++ -*-===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This file contains the declaration of the Type class. For more "Type" |
10 | // stuff, look in DerivedTypes.h. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | |
14 | #ifndef LLVM_IR_TYPE_H |
15 | #define LLVM_IR_TYPE_H |
16 | |
17 | #include "llvm/ADT/APFloat.h" |
18 | #include "llvm/ADT/ArrayRef.h" |
19 | #include "llvm/ADT/SmallPtrSet.h" |
20 | #include "llvm/Support/CBindingWrapping.h" |
21 | #include "llvm/Support/Casting.h" |
22 | #include "llvm/Support/Compiler.h" |
23 | #include "llvm/Support/ErrorHandling.h" |
24 | #include "llvm/Support/TypeSize.h" |
25 | #include <cassert> |
26 | #include <cstdint> |
27 | #include <iterator> |
28 | |
29 | namespace llvm { |
30 | |
31 | template<class GraphType> struct GraphTraits; |
32 | class IntegerType; |
33 | class LLVMContext; |
34 | class PointerType; |
35 | class raw_ostream; |
36 | class StringRef; |
37 | |
38 | /// The instances of the Type class are immutable: once they are created, |
39 | /// they are never changed. Also note that only one instance of a particular |
40 | /// type is ever created. Thus seeing if two types are equal is a matter of |
41 | /// doing a trivial pointer comparison. To enforce that no two equal instances |
42 | /// are created, Type instances can only be created via static factory methods |
43 | /// in class Type and in derived classes. Once allocated, Types are never |
44 | /// free'd. |
45 | /// |
46 | class Type { |
47 | public: |
48 | //===--------------------------------------------------------------------===// |
49 | /// Definitions of all of the base types for the Type system. Based on this |
50 | /// value, you can cast to a class defined in DerivedTypes.h. |
51 | /// Note: If you add an element to this, you need to add an element to the |
52 | /// Type::getPrimitiveType function, or else things will break! |
53 | /// Also update LLVMTypeKind and LLVMGetTypeKind () in the C binding. |
54 | /// |
55 | enum TypeID { |
56 | // PrimitiveTypes |
57 | HalfTyID = 0, ///< 16-bit floating point type |
58 | BFloatTyID, ///< 16-bit floating point type (7-bit significand) |
59 | FloatTyID, ///< 32-bit floating point type |
60 | DoubleTyID, ///< 64-bit floating point type |
61 | X86_FP80TyID, ///< 80-bit floating point type (X87) |
62 | FP128TyID, ///< 128-bit floating point type (112-bit significand) |
63 | PPC_FP128TyID, ///< 128-bit floating point type (two 64-bits, PowerPC) |
64 | VoidTyID, ///< type with no size |
65 | LabelTyID, ///< Labels |
66 | MetadataTyID, ///< Metadata |
67 | X86_MMXTyID, ///< MMX vectors (64 bits, X86 specific) |
68 | TokenTyID, ///< Tokens |
69 | |
70 | // Derived types... see DerivedTypes.h file. |
71 | IntegerTyID, ///< Arbitrary bit width integers |
72 | FunctionTyID, ///< Functions |
73 | PointerTyID, ///< Pointers |
74 | StructTyID, ///< Structures |
75 | ArrayTyID, ///< Arrays |
76 | FixedVectorTyID, ///< Fixed width SIMD vector type |
77 | ScalableVectorTyID ///< Scalable SIMD vector type |
78 | }; |
79 | |
80 | private: |
81 | /// This refers to the LLVMContext in which this type was uniqued. |
82 | LLVMContext &Context; |
83 | |
84 | TypeID ID : 8; // The current base type of this type. |
85 | unsigned SubclassData : 24; // Space for subclasses to store data. |
86 | // Note that this should be synchronized with |
87 | // MAX_INT_BITS value in IntegerType class. |
88 | |
89 | protected: |
90 | friend class LLVMContextImpl; |
91 | |
92 | explicit Type(LLVMContext &C, TypeID tid) |
93 | : Context(C), ID(tid), SubclassData(0) {} |
94 | ~Type() = default; |
95 | |
96 | unsigned getSubclassData() const { return SubclassData; } |
97 | |
98 | void setSubclassData(unsigned val) { |
99 | SubclassData = val; |
100 | // Ensure we don't have any accidental truncation. |
101 | assert(getSubclassData() == val && "Subclass data too large for field")((getSubclassData() == val && "Subclass data too large for field" ) ? static_cast<void> (0) : __assert_fail ("getSubclassData() == val && \"Subclass data too large for field\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 101, __PRETTY_FUNCTION__)); |
102 | } |
103 | |
104 | /// Keeps track of how many Type*'s there are in the ContainedTys list. |
105 | unsigned NumContainedTys = 0; |
106 | |
107 | /// A pointer to the array of Types contained by this Type. For example, this |
108 | /// includes the arguments of a function type, the elements of a structure, |
109 | /// the pointee of a pointer, the element type of an array, etc. This pointer |
110 | /// may be 0 for types that don't contain other types (Integer, Double, |
111 | /// Float). |
112 | Type * const *ContainedTys = nullptr; |
113 | |
114 | public: |
115 | /// Print the current type. |
116 | /// Omit the type details if \p NoDetails == true. |
117 | /// E.g., let %st = type { i32, i16 } |
118 | /// When \p NoDetails is true, we only print %st. |
119 | /// Put differently, \p NoDetails prints the type as if |
120 | /// inlined with the operands when printing an instruction. |
121 | void print(raw_ostream &O, bool IsForDebug = false, |
122 | bool NoDetails = false) const; |
123 | |
124 | void dump() const; |
125 | |
126 | /// Return the LLVMContext in which this type was uniqued. |
127 | LLVMContext &getContext() const { return Context; } |
128 | |
129 | //===--------------------------------------------------------------------===// |
130 | // Accessors for working with types. |
131 | // |
132 | |
133 | /// Return the type id for the type. This will return one of the TypeID enum |
134 | /// elements defined above. |
135 | TypeID getTypeID() const { return ID; } |
136 | |
137 | /// Return true if this is 'void'. |
138 | bool isVoidTy() const { return getTypeID() == VoidTyID; } |
139 | |
140 | /// Return true if this is 'half', a 16-bit IEEE fp type. |
141 | bool isHalfTy() const { return getTypeID() == HalfTyID; } |
142 | |
143 | /// Return true if this is 'bfloat', a 16-bit bfloat type. |
144 | bool isBFloatTy() const { return getTypeID() == BFloatTyID; } |
145 | |
146 | /// Return true if this is 'float', a 32-bit IEEE fp type. |
147 | bool isFloatTy() const { return getTypeID() == FloatTyID; } |
148 | |
149 | /// Return true if this is 'double', a 64-bit IEEE fp type. |
150 | bool isDoubleTy() const { return getTypeID() == DoubleTyID; } |
151 | |
152 | /// Return true if this is x86 long double. |
153 | bool isX86_FP80Ty() const { return getTypeID() == X86_FP80TyID; } |
154 | |
155 | /// Return true if this is 'fp128'. |
156 | bool isFP128Ty() const { return getTypeID() == FP128TyID; } |
157 | |
158 | /// Return true if this is powerpc long double. |
159 | bool isPPC_FP128Ty() const { return getTypeID() == PPC_FP128TyID; } |
160 | |
161 | /// Return true if this is one of the six floating-point types |
162 | bool isFloatingPointTy() const { |
163 | return getTypeID() == HalfTyID || getTypeID() == BFloatTyID || |
164 | getTypeID() == FloatTyID || getTypeID() == DoubleTyID || |
165 | getTypeID() == X86_FP80TyID || getTypeID() == FP128TyID || |
166 | getTypeID() == PPC_FP128TyID; |
167 | } |
168 | |
169 | const fltSemantics &getFltSemantics() const { |
170 | switch (getTypeID()) { |
171 | case HalfTyID: return APFloat::IEEEhalf(); |
172 | case BFloatTyID: return APFloat::BFloat(); |
173 | case FloatTyID: return APFloat::IEEEsingle(); |
174 | case DoubleTyID: return APFloat::IEEEdouble(); |
175 | case X86_FP80TyID: return APFloat::x87DoubleExtended(); |
176 | case FP128TyID: return APFloat::IEEEquad(); |
177 | case PPC_FP128TyID: return APFloat::PPCDoubleDouble(); |
178 | default: llvm_unreachable("Invalid floating type")::llvm::llvm_unreachable_internal("Invalid floating type", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 178); |
179 | } |
180 | } |
181 | |
182 | /// Return true if this is X86 MMX. |
183 | bool isX86_MMXTy() const { return getTypeID() == X86_MMXTyID; } |
184 | |
185 | /// Return true if this is a FP type or a vector of FP. |
186 | bool isFPOrFPVectorTy() const { return getScalarType()->isFloatingPointTy(); } |
187 | |
188 | /// Return true if this is 'label'. |
189 | bool isLabelTy() const { return getTypeID() == LabelTyID; } |
190 | |
191 | /// Return true if this is 'metadata'. |
192 | bool isMetadataTy() const { return getTypeID() == MetadataTyID; } |
193 | |
194 | /// Return true if this is 'token'. |
195 | bool isTokenTy() const { return getTypeID() == TokenTyID; } |
196 | |
197 | /// True if this is an instance of IntegerType. |
198 | bool isIntegerTy() const { return getTypeID() == IntegerTyID; } |
199 | |
200 | /// Return true if this is an IntegerType of the given width. |
201 | bool isIntegerTy(unsigned Bitwidth) const; |
202 | |
203 | /// Return true if this is an integer type or a vector of integer types. |
204 | bool isIntOrIntVectorTy() const { return getScalarType()->isIntegerTy(); } |
205 | |
206 | /// Return true if this is an integer type or a vector of integer types of |
207 | /// the given width. |
208 | bool isIntOrIntVectorTy(unsigned BitWidth) const { |
209 | return getScalarType()->isIntegerTy(BitWidth); |
210 | } |
211 | |
212 | /// Return true if this is an integer type or a pointer type. |
213 | bool isIntOrPtrTy() const { return isIntegerTy() || isPointerTy(); } |
214 | |
215 | /// True if this is an instance of FunctionType. |
216 | bool isFunctionTy() const { return getTypeID() == FunctionTyID; } |
217 | |
218 | /// True if this is an instance of StructType. |
219 | bool isStructTy() const { return getTypeID() == StructTyID; } |
220 | |
221 | /// True if this is an instance of ArrayType. |
222 | bool isArrayTy() const { return getTypeID() == ArrayTyID; } |
223 | |
224 | /// True if this is an instance of PointerType. |
225 | bool isPointerTy() const { return getTypeID() == PointerTyID; } |
226 | |
227 | /// Return true if this is a pointer type or a vector of pointer types. |
228 | bool isPtrOrPtrVectorTy() const { return getScalarType()->isPointerTy(); } |
229 | |
230 | /// True if this is an instance of VectorType. |
231 | inline bool isVectorTy() const { |
232 | return getTypeID() == ScalableVectorTyID || getTypeID() == FixedVectorTyID; |
233 | } |
234 | |
235 | /// Return true if this type could be converted with a lossless BitCast to |
236 | /// type 'Ty'. For example, i8* to i32*. BitCasts are valid for types of the |
237 | /// same size only where no re-interpretation of the bits is done. |
238 | /// Determine if this type could be losslessly bitcast to Ty |
239 | bool canLosslesslyBitCastTo(Type *Ty) const; |
240 | |
241 | /// Return true if this type is empty, that is, it has no elements or all of |
242 | /// its elements are empty. |
243 | bool isEmptyTy() const; |
244 | |
245 | /// Return true if the type is "first class", meaning it is a valid type for a |
246 | /// Value. |
247 | bool isFirstClassType() const { |
248 | return getTypeID() != FunctionTyID && getTypeID() != VoidTyID; |
249 | } |
250 | |
251 | /// Return true if the type is a valid type for a register in codegen. This |
252 | /// includes all first-class types except struct and array types. |
253 | bool isSingleValueType() const { |
254 | return isFloatingPointTy() || isX86_MMXTy() || isIntegerTy() || |
255 | isPointerTy() || isVectorTy(); |
256 | } |
257 | |
258 | /// Return true if the type is an aggregate type. This means it is valid as |
259 | /// the first operand of an insertvalue or extractvalue instruction. This |
260 | /// includes struct and array types, but does not include vector types. |
261 | bool isAggregateType() const { |
262 | return getTypeID() == StructTyID || getTypeID() == ArrayTyID; |
263 | } |
264 | |
265 | /// Return true if it makes sense to take the size of this type. To get the |
266 | /// actual size for a particular target, it is reasonable to use the |
267 | /// DataLayout subsystem to do this. |
268 | bool isSized(SmallPtrSetImpl<Type*> *Visited = nullptr) const { |
269 | // If it's a primitive, it is always sized. |
270 | if (getTypeID() == IntegerTyID || isFloatingPointTy() || |
271 | getTypeID() == PointerTyID || |
272 | getTypeID() == X86_MMXTyID) |
273 | return true; |
274 | // If it is not something that can have a size (e.g. a function or label), |
275 | // it doesn't have a size. |
276 | if (getTypeID() != StructTyID && getTypeID() != ArrayTyID && !isVectorTy()) |
277 | return false; |
278 | // Otherwise we have to try harder to decide. |
279 | return isSizedDerivedType(Visited); |
280 | } |
281 | |
282 | /// Return the basic size of this type if it is a primitive type. These are |
283 | /// fixed by LLVM and are not target-dependent. |
284 | /// This will return zero if the type does not have a size or is not a |
285 | /// primitive type. |
286 | /// |
287 | /// If this is a scalable vector type, the scalable property will be set and |
288 | /// the runtime size will be a positive integer multiple of the base size. |
289 | /// |
290 | /// Note that this may not reflect the size of memory allocated for an |
291 | /// instance of the type or the number of bytes that are written when an |
292 | /// instance of the type is stored to memory. The DataLayout class provides |
293 | /// additional query functions to provide this information. |
294 | /// |
295 | TypeSize getPrimitiveSizeInBits() const LLVM_READONLY__attribute__((__pure__)); |
296 | |
297 | /// If this is a vector type, return the getPrimitiveSizeInBits value for the |
298 | /// element type. Otherwise return the getPrimitiveSizeInBits value for this |
299 | /// type. |
300 | unsigned getScalarSizeInBits() const LLVM_READONLY__attribute__((__pure__)); |
301 | |
302 | /// Return the width of the mantissa of this type. This is only valid on |
303 | /// floating-point types. If the FP type does not have a stable mantissa (e.g. |
304 | /// ppc long double), this method returns -1. |
305 | int getFPMantissaWidth() const; |
306 | |
307 | /// If this is a vector type, return the element type, otherwise return |
308 | /// 'this'. |
309 | inline Type *getScalarType() const { |
310 | if (isVectorTy()) |
311 | return getContainedType(0); |
312 | return const_cast<Type *>(this); |
313 | } |
314 | |
315 | //===--------------------------------------------------------------------===// |
316 | // Type Iteration support. |
317 | // |
318 | using subtype_iterator = Type * const *; |
319 | |
320 | subtype_iterator subtype_begin() const { return ContainedTys; } |
321 | subtype_iterator subtype_end() const { return &ContainedTys[NumContainedTys];} |
322 | ArrayRef<Type*> subtypes() const { |
323 | return makeArrayRef(subtype_begin(), subtype_end()); |
324 | } |
325 | |
326 | using subtype_reverse_iterator = std::reverse_iterator<subtype_iterator>; |
327 | |
328 | subtype_reverse_iterator subtype_rbegin() const { |
329 | return subtype_reverse_iterator(subtype_end()); |
330 | } |
331 | subtype_reverse_iterator subtype_rend() const { |
332 | return subtype_reverse_iterator(subtype_begin()); |
333 | } |
334 | |
335 | /// This method is used to implement the type iterator (defined at the end of |
336 | /// the file). For derived types, this returns the types 'contained' in the |
337 | /// derived type. |
338 | Type *getContainedType(unsigned i) const { |
339 | assert(i < NumContainedTys && "Index out of range!")((i < NumContainedTys && "Index out of range!") ? static_cast <void> (0) : __assert_fail ("i < NumContainedTys && \"Index out of range!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 339, __PRETTY_FUNCTION__)); |
340 | return ContainedTys[i]; |
341 | } |
342 | |
343 | /// Return the number of types in the derived type. |
344 | unsigned getNumContainedTypes() const { return NumContainedTys; } |
345 | |
346 | //===--------------------------------------------------------------------===// |
347 | // Helper methods corresponding to subclass methods. This forces a cast to |
348 | // the specified subclass and calls its accessor. "getArrayNumElements" (for |
349 | // example) is shorthand for cast<ArrayType>(Ty)->getNumElements(). This is |
350 | // only intended to cover the core methods that are frequently used, helper |
351 | // methods should not be added here. |
352 | |
353 | inline unsigned getIntegerBitWidth() const; |
354 | |
355 | inline Type *getFunctionParamType(unsigned i) const; |
356 | inline unsigned getFunctionNumParams() const; |
357 | inline bool isFunctionVarArg() const; |
358 | |
359 | inline StringRef getStructName() const; |
360 | inline unsigned getStructNumElements() const; |
361 | inline Type *getStructElementType(unsigned N) const; |
362 | |
363 | inline uint64_t getArrayNumElements() const; |
364 | |
365 | Type *getArrayElementType() const { |
366 | assert(getTypeID() == ArrayTyID)((getTypeID() == ArrayTyID) ? static_cast<void> (0) : __assert_fail ("getTypeID() == ArrayTyID", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 366, __PRETTY_FUNCTION__)); |
367 | return ContainedTys[0]; |
368 | } |
369 | |
370 | Type *getPointerElementType() const { |
371 | assert(getTypeID() == PointerTyID)((getTypeID() == PointerTyID) ? static_cast<void> (0) : __assert_fail ("getTypeID() == PointerTyID", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 371, __PRETTY_FUNCTION__)); |
372 | return ContainedTys[0]; |
373 | } |
374 | |
375 | /// Given an integer or vector type, change the lane bitwidth to NewBitwidth, |
376 | /// whilst keeping the old number of lanes. |
377 | inline Type *getWithNewBitWidth(unsigned NewBitWidth) const; |
378 | |
379 | /// Given scalar/vector integer type, returns a type with elements twice as |
380 | /// wide as in the original type. For vectors, preserves element count. |
381 | inline Type *getExtendedType() const; |
382 | |
383 | /// Get the address space of this pointer or pointer vector type. |
384 | inline unsigned getPointerAddressSpace() const; |
385 | |
386 | //===--------------------------------------------------------------------===// |
387 | // Static members exported by the Type class itself. Useful for getting |
388 | // instances of Type. |
389 | // |
390 | |
391 | /// Return a type based on an identifier. |
392 | static Type *getPrimitiveType(LLVMContext &C, TypeID IDNumber); |
393 | |
394 | //===--------------------------------------------------------------------===// |
395 | // These are the builtin types that are always available. |
396 | // |
397 | static Type *getVoidTy(LLVMContext &C); |
398 | static Type *getLabelTy(LLVMContext &C); |
399 | static Type *getHalfTy(LLVMContext &C); |
400 | static Type *getBFloatTy(LLVMContext &C); |
401 | static Type *getFloatTy(LLVMContext &C); |
402 | static Type *getDoubleTy(LLVMContext &C); |
403 | static Type *getMetadataTy(LLVMContext &C); |
404 | static Type *getX86_FP80Ty(LLVMContext &C); |
405 | static Type *getFP128Ty(LLVMContext &C); |
406 | static Type *getPPC_FP128Ty(LLVMContext &C); |
407 | static Type *getX86_MMXTy(LLVMContext &C); |
408 | static Type *getTokenTy(LLVMContext &C); |
409 | static IntegerType *getIntNTy(LLVMContext &C, unsigned N); |
410 | static IntegerType *getInt1Ty(LLVMContext &C); |
411 | static IntegerType *getInt8Ty(LLVMContext &C); |
412 | static IntegerType *getInt16Ty(LLVMContext &C); |
413 | static IntegerType *getInt32Ty(LLVMContext &C); |
414 | static IntegerType *getInt64Ty(LLVMContext &C); |
415 | static IntegerType *getInt128Ty(LLVMContext &C); |
416 | template <typename ScalarTy> static Type *getScalarTy(LLVMContext &C) { |
417 | int noOfBits = sizeof(ScalarTy) * CHAR_BIT8; |
418 | if (std::is_integral<ScalarTy>::value) { |
419 | return (Type*) Type::getIntNTy(C, noOfBits); |
420 | } else if (std::is_floating_point<ScalarTy>::value) { |
421 | switch (noOfBits) { |
422 | case 32: |
423 | return Type::getFloatTy(C); |
424 | case 64: |
425 | return Type::getDoubleTy(C); |
426 | } |
427 | } |
428 | llvm_unreachable("Unsupported type in Type::getScalarTy")::llvm::llvm_unreachable_internal("Unsupported type in Type::getScalarTy" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/IR/Type.h" , 428); |
429 | } |
430 | |
431 | //===--------------------------------------------------------------------===// |
432 | // Convenience methods for getting pointer types with one of the above builtin |
433 | // types as pointee. |
434 | // |
435 | static PointerType *getHalfPtrTy(LLVMContext &C, unsigned AS = 0); |
436 | static PointerType *getBFloatPtrTy(LLVMContext &C, unsigned AS = 0); |
437 | static PointerType *getFloatPtrTy(LLVMContext &C, unsigned AS = 0); |
438 | static PointerType *getDoublePtrTy(LLVMContext &C, unsigned AS = 0); |
439 | static PointerType *getX86_FP80PtrTy(LLVMContext &C, unsigned AS = 0); |
440 | static PointerType *getFP128PtrTy(LLVMContext &C, unsigned AS = 0); |
441 | static PointerType *getPPC_FP128PtrTy(LLVMContext &C, unsigned AS = 0); |
442 | static PointerType *getX86_MMXPtrTy(LLVMContext &C, unsigned AS = 0); |
443 | static PointerType *getIntNPtrTy(LLVMContext &C, unsigned N, unsigned AS = 0); |
444 | static PointerType *getInt1PtrTy(LLVMContext &C, unsigned AS = 0); |
445 | static PointerType *getInt8PtrTy(LLVMContext &C, unsigned AS = 0); |
446 | static PointerType *getInt16PtrTy(LLVMContext &C, unsigned AS = 0); |
447 | static PointerType *getInt32PtrTy(LLVMContext &C, unsigned AS = 0); |
448 | static PointerType *getInt64PtrTy(LLVMContext &C, unsigned AS = 0); |
449 | |
450 | /// Return a pointer to the current type. This is equivalent to |
451 | /// PointerType::get(Foo, AddrSpace). |
452 | PointerType *getPointerTo(unsigned AddrSpace = 0) const; |
453 | |
454 | private: |
455 | /// Derived types like structures and arrays are sized iff all of the members |
456 | /// of the type are sized as well. Since asking for their size is relatively |
457 | /// uncommon, move this operation out-of-line. |
458 | bool isSizedDerivedType(SmallPtrSetImpl<Type*> *Visited = nullptr) const; |
459 | }; |
460 | |
461 | // Printing of types. |
462 | inline raw_ostream &operator<<(raw_ostream &OS, const Type &T) { |
463 | T.print(OS); |
464 | return OS; |
465 | } |
466 | |
467 | // allow isa<PointerType>(x) to work without DerivedTypes.h included. |
468 | template <> struct isa_impl<PointerType, Type> { |
469 | static inline bool doit(const Type &Ty) { |
470 | return Ty.getTypeID() == Type::PointerTyID; |
471 | } |
472 | }; |
473 | |
474 | // Create wrappers for C Binding types (see CBindingWrapping.h). |
475 | DEFINE_ISA_CONVERSION_FUNCTIONS(Type, LLVMTypeRef)inline Type *unwrap(LLVMTypeRef P) { return reinterpret_cast< Type*>(P); } inline LLVMTypeRef wrap(const Type *P) { return reinterpret_cast<LLVMTypeRef>(const_cast<Type*>( P)); } template<typename T> inline T *unwrap(LLVMTypeRef P) { return cast<T>(unwrap(P)); } |
476 | |
477 | /* Specialized opaque type conversions. |
478 | */ |
479 | inline Type **unwrap(LLVMTypeRef* Tys) { |
480 | return reinterpret_cast<Type**>(Tys); |
481 | } |
482 | |
483 | inline LLVMTypeRef *wrap(Type **Tys) { |
484 | return reinterpret_cast<LLVMTypeRef*>(const_cast<Type**>(Tys)); |
485 | } |
486 | |
487 | } // end namespace llvm |
488 | |
489 | #endif // LLVM_IR_TYPE_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 <string> | ||||||
24 | |||||||
25 | namespace llvm { | ||||||
26 | class FoldingSetNodeID; | ||||||
27 | class StringRef; | ||||||
28 | class hash_code; | ||||||
29 | class raw_ostream; | ||||||
30 | |||||||
31 | template <typename T> class SmallVectorImpl; | ||||||
32 | template <typename T> class ArrayRef; | ||||||
33 | template <typename T> class Optional; | ||||||
34 | template <typename T> struct DenseMapInfo; | ||||||
35 | |||||||
36 | class APInt; | ||||||
37 | |||||||
38 | inline 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 | /// | ||||||
70 | class LLVM_NODISCARD[[clang::warn_unused_result]] APInt { | ||||||
71 | public: | ||||||
72 | typedef uint64_t WordType; | ||||||
73 | |||||||
74 | /// This enum is used to hold the constants we needed for APInt. | ||||||
75 | enum : unsigned { | ||||||
76 | /// Byte size of a word. | ||||||
77 | APINT_WORD_SIZE = sizeof(WordType), | ||||||
78 | /// Bits in a word. | ||||||
79 | APINT_BITS_PER_WORD = APINT_WORD_SIZE * CHAR_BIT8 | ||||||
80 | }; | ||||||
81 | |||||||
82 | enum class Rounding { | ||||||
83 | DOWN, | ||||||
84 | TOWARD_ZERO, | ||||||
85 | UP, | ||||||
86 | }; | ||||||
87 | |||||||
88 | static constexpr WordType WORDTYPE_MAX = ~WordType(0); | ||||||
89 | |||||||
90 | private: | ||||||
91 | /// This union is used to store the integer value. When the | ||||||
92 | /// integer bit-width <= 64, it uses VAL, otherwise it uses pVal. | ||||||
93 | union { | ||||||
94 | uint64_t VAL; ///< Used to store the <= 64 bits integer value. | ||||||
95 | uint64_t *pVal; ///< Used to store the >64 bits integer value. | ||||||
96 | } U; | ||||||
97 | |||||||
98 | unsigned BitWidth; ///< The number of bits in this APInt. | ||||||
99 | |||||||
100 | friend struct DenseMapInfo<APInt>; | ||||||
101 | |||||||
102 | friend class APSInt; | ||||||
103 | |||||||
104 | /// Fast internal constructor | ||||||
105 | /// | ||||||
106 | /// This constructor is used only internally for speed of construction of | ||||||
107 | /// temporaries. It is unsafe for general use so it is not public. | ||||||
108 | APInt(uint64_t *val, unsigned bits) : BitWidth(bits) { | ||||||
109 | U.pVal = val; | ||||||
110 | } | ||||||
111 | |||||||
112 | /// Determine if this APInt just has one word to store value. | ||||||
113 | /// | ||||||
114 | /// \returns true if the number of bits <= 64, false otherwise. | ||||||
115 | bool isSingleWord() const { return BitWidth
| ||||||
116 | |||||||
117 | /// Determine which word a bit is in. | ||||||
118 | /// | ||||||
119 | /// \returns the word position for the specified bit position. | ||||||
120 | static unsigned whichWord(unsigned bitPosition) { | ||||||
121 | return bitPosition / APINT_BITS_PER_WORD; | ||||||
122 | } | ||||||
123 | |||||||
124 | /// Determine which bit in a word a bit is in. | ||||||
125 | /// | ||||||
126 | /// \returns the bit position in a word for the specified bit position | ||||||
127 | /// in the APInt. | ||||||
128 | static unsigned whichBit(unsigned bitPosition) { | ||||||
129 | return bitPosition % APINT_BITS_PER_WORD; | ||||||
130 | } | ||||||
131 | |||||||
132 | /// Get a single bit mask. | ||||||
133 | /// | ||||||
134 | /// \returns a uint64_t with only bit at "whichBit(bitPosition)" set | ||||||
135 | /// This method generates and returns a uint64_t (word) mask for a single | ||||||
136 | /// bit at a specific bit position. This is used to mask the bit in the | ||||||
137 | /// corresponding word. | ||||||
138 | static uint64_t maskBit(unsigned bitPosition) { | ||||||
139 | return 1ULL << whichBit(bitPosition); | ||||||
140 | } | ||||||
141 | |||||||
142 | /// Clear unused high order bits | ||||||
143 | /// | ||||||
144 | /// This method is used internally to clear the top "N" bits in the high order | ||||||
145 | /// word that are not used by the APInt. This is needed after the most | ||||||
146 | /// significant word is assigned a value to ensure that those bits are | ||||||
147 | /// zero'd out. | ||||||
148 | APInt &clearUnusedBits() { | ||||||
149 | // Compute how many bits are used in the final word | ||||||
150 | unsigned WordBits = ((BitWidth-1) % APINT_BITS_PER_WORD) + 1; | ||||||
151 | |||||||
152 | // Mask out the high bits. | ||||||
153 | uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - WordBits); | ||||||
154 | if (isSingleWord()) | ||||||
155 | U.VAL &= mask; | ||||||
156 | else | ||||||
157 | U.pVal[getNumWords() - 1] &= mask; | ||||||
158 | return *this; | ||||||
159 | } | ||||||
160 | |||||||
161 | /// Get the word corresponding to a bit position | ||||||
162 | /// \returns the corresponding word for the specified bit position. | ||||||
163 | uint64_t getWord(unsigned bitPosition) const { | ||||||
164 | return isSingleWord() ? U.VAL : U.pVal[whichWord(bitPosition)]; | ||||||
165 | } | ||||||
166 | |||||||
167 | /// Utility method to change the bit width of this APInt to new bit width, | ||||||
168 | /// allocating and/or deallocating as necessary. There is no guarantee on the | ||||||
169 | /// value of any bits upon return. Caller should populate the bits after. | ||||||
170 | void reallocate(unsigned NewBitWidth); | ||||||
171 | |||||||
172 | /// Convert a char array into an APInt | ||||||
173 | /// | ||||||
174 | /// \param radix 2, 8, 10, 16, or 36 | ||||||
175 | /// Converts a string into a number. The string must be non-empty | ||||||
176 | /// and well-formed as a number of the given base. The bit-width | ||||||
177 | /// must be sufficient to hold the result. | ||||||
178 | /// | ||||||
179 | /// This is used by the constructors that take string arguments. | ||||||
180 | /// | ||||||
181 | /// StringRef::getAsInteger is superficially similar but (1) does | ||||||
182 | /// not assume that the string is well-formed and (2) grows the | ||||||
183 | /// result to hold the input. | ||||||
184 | void fromString(unsigned numBits, StringRef str, uint8_t radix); | ||||||
185 | |||||||
186 | /// An internal division function for dividing APInts. | ||||||
187 | /// | ||||||
188 | /// This is used by the toString method to divide by the radix. It simply | ||||||
189 | /// provides a more convenient form of divide for internal use since KnuthDiv | ||||||
190 | /// has specific constraints on its inputs. If those constraints are not met | ||||||
191 | /// then it provides a simpler form of divide. | ||||||
192 | static void divide(const WordType *LHS, unsigned lhsWords, | ||||||
193 | const WordType *RHS, unsigned rhsWords, WordType *Quotient, | ||||||
194 | WordType *Remainder); | ||||||
195 | |||||||
196 | /// out-of-line slow case for inline constructor | ||||||
197 | void initSlowCase(uint64_t val, bool isSigned); | ||||||
198 | |||||||
199 | /// shared code between two array constructors | ||||||
200 | void initFromArray(ArrayRef<uint64_t> array); | ||||||
201 | |||||||
202 | /// out-of-line slow case for inline copy constructor | ||||||
203 | void initSlowCase(const APInt &that); | ||||||
204 | |||||||
205 | /// out-of-line slow case for shl | ||||||
206 | void shlSlowCase(unsigned ShiftAmt); | ||||||
207 | |||||||
208 | /// out-of-line slow case for lshr. | ||||||
209 | void lshrSlowCase(unsigned ShiftAmt); | ||||||
210 | |||||||
211 | /// out-of-line slow case for ashr. | ||||||
212 | void ashrSlowCase(unsigned ShiftAmt); | ||||||
213 | |||||||
214 | /// out-of-line slow case for operator= | ||||||
215 | void AssignSlowCase(const APInt &RHS); | ||||||
216 | |||||||
217 | /// out-of-line slow case for operator== | ||||||
218 | bool EqualSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||
219 | |||||||
220 | /// out-of-line slow case for countLeadingZeros | ||||||
221 | unsigned countLeadingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||
222 | |||||||
223 | /// out-of-line slow case for countLeadingOnes. | ||||||
224 | unsigned countLeadingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||
225 | |||||||
226 | /// out-of-line slow case for countTrailingZeros. | ||||||
227 | unsigned countTrailingZerosSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||
228 | |||||||
229 | /// out-of-line slow case for countTrailingOnes | ||||||
230 | unsigned countTrailingOnesSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||
231 | |||||||
232 | /// out-of-line slow case for countPopulation | ||||||
233 | unsigned countPopulationSlowCase() const LLVM_READONLY__attribute__((__pure__)); | ||||||
234 | |||||||
235 | /// out-of-line slow case for intersects. | ||||||
236 | bool intersectsSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||
237 | |||||||
238 | /// out-of-line slow case for isSubsetOf. | ||||||
239 | bool isSubsetOfSlowCase(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||
240 | |||||||
241 | /// out-of-line slow case for setBits. | ||||||
242 | void setBitsSlowCase(unsigned loBit, unsigned hiBit); | ||||||
243 | |||||||
244 | /// out-of-line slow case for flipAllBits. | ||||||
245 | void flipAllBitsSlowCase(); | ||||||
246 | |||||||
247 | /// out-of-line slow case for operator&=. | ||||||
248 | void AndAssignSlowCase(const APInt& RHS); | ||||||
249 | |||||||
250 | /// out-of-line slow case for operator|=. | ||||||
251 | void OrAssignSlowCase(const APInt& RHS); | ||||||
252 | |||||||
253 | /// out-of-line slow case for operator^=. | ||||||
254 | void XorAssignSlowCase(const APInt& RHS); | ||||||
255 | |||||||
256 | /// Unsigned comparison. Returns -1, 0, or 1 if this APInt is less than, equal | ||||||
257 | /// to, or greater than RHS. | ||||||
258 | int compare(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||
259 | |||||||
260 | /// Signed comparison. Returns -1, 0, or 1 if this APInt is less than, equal | ||||||
261 | /// to, or greater than RHS. | ||||||
262 | int compareSigned(const APInt &RHS) const LLVM_READONLY__attribute__((__pure__)); | ||||||
263 | |||||||
264 | public: | ||||||
265 | /// \name Constructors | ||||||
266 | /// @{ | ||||||
267 | |||||||
268 | /// Create a new APInt of numBits width, initialized as val. | ||||||
269 | /// | ||||||
270 | /// If isSigned is true then val is treated as if it were a signed value | ||||||
271 | /// (i.e. as an int64_t) and the appropriate sign extension to the bit width | ||||||
272 | /// will be done. Otherwise, no sign extension occurs (high order bits beyond | ||||||
273 | /// the range of val are zero filled). | ||||||
274 | /// | ||||||
275 | /// \param numBits the bit width of the constructed APInt | ||||||
276 | /// \param val the initial value of the APInt | ||||||
277 | /// \param isSigned how to treat signedness of val | ||||||
278 | APInt(unsigned numBits, uint64_t val, bool isSigned = false) | ||||||
279 | : BitWidth(numBits) { | ||||||
280 | assert(BitWidth && "bitwidth too small")((BitWidth && "bitwidth too small") ? static_cast< void> (0) : __assert_fail ("BitWidth && \"bitwidth too small\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 280, __PRETTY_FUNCTION__)); | ||||||
281 | if (isSingleWord()) { | ||||||
282 | U.VAL = val; | ||||||
283 | clearUnusedBits(); | ||||||
284 | } else { | ||||||
285 | initSlowCase(val, isSigned); | ||||||
286 | } | ||||||
287 | } | ||||||
288 | |||||||
289 | /// Construct an APInt of numBits width, initialized as bigVal[]. | ||||||
290 | /// | ||||||
291 | /// Note that bigVal.size() can be smaller or larger than the corresponding | ||||||
292 | /// bit width but any extraneous bits will be dropped. | ||||||
293 | /// | ||||||
294 | /// \param numBits the bit width of the constructed APInt | ||||||
295 | /// \param bigVal a sequence of words to form the initial value of the APInt | ||||||
296 | APInt(unsigned numBits, ArrayRef<uint64_t> bigVal); | ||||||
297 | |||||||
298 | /// Equivalent to APInt(numBits, ArrayRef<uint64_t>(bigVal, numWords)), but | ||||||
299 | /// deprecated because this constructor is prone to ambiguity with the | ||||||
300 | /// APInt(unsigned, uint64_t, bool) constructor. | ||||||
301 | /// | ||||||
302 | /// If this overload is ever deleted, care should be taken to prevent calls | ||||||
303 | /// from being incorrectly captured by the APInt(unsigned, uint64_t, bool) | ||||||
304 | /// constructor. | ||||||
305 | APInt(unsigned numBits, unsigned numWords, const uint64_t bigVal[]); | ||||||
306 | |||||||
307 | /// Construct an APInt from a string representation. | ||||||
308 | /// | ||||||
309 | /// This constructor interprets the string \p str in the given radix. The | ||||||
310 | /// interpretation stops when the first character that is not suitable for the | ||||||
311 | /// radix is encountered, or the end of the string. Acceptable radix values | ||||||
312 | /// are 2, 8, 10, 16, and 36. It is an error for the value implied by the | ||||||
313 | /// string to require more bits than numBits. | ||||||
314 | /// | ||||||
315 | /// \param numBits the bit width of the constructed APInt | ||||||
316 | /// \param str the string to be interpreted | ||||||
317 | /// \param radix the radix to use for the conversion | ||||||
318 | APInt(unsigned numBits, StringRef str, uint8_t radix); | ||||||
319 | |||||||
320 | /// Simply makes *this a copy of that. | ||||||
321 | /// Copy Constructor. | ||||||
322 | APInt(const APInt &that) : BitWidth(that.BitWidth) { | ||||||
323 | if (isSingleWord()) | ||||||
324 | U.VAL = that.U.VAL; | ||||||
325 | else | ||||||
326 | initSlowCase(that); | ||||||
327 | } | ||||||
328 | |||||||
329 | /// Move Constructor. | ||||||
330 | APInt(APInt &&that) : BitWidth(that.BitWidth) { | ||||||
331 | memcpy(&U, &that.U, sizeof(U)); | ||||||
332 | that.BitWidth = 0; | ||||||
333 | } | ||||||
334 | |||||||
335 | /// Destructor. | ||||||
336 | ~APInt() { | ||||||
337 | if (needsCleanup()) | ||||||
338 | delete[] U.pVal; | ||||||
339 | } | ||||||
340 | |||||||
341 | /// Default constructor that creates an uninteresting APInt | ||||||
342 | /// representing a 1-bit zero value. | ||||||
343 | /// | ||||||
344 | /// This is useful for object deserialization (pair this with the static | ||||||
345 | /// method Read). | ||||||
346 | explicit APInt() : BitWidth(1) { U.VAL = 0; } | ||||||
347 | |||||||
348 | /// Returns whether this instance allocated memory. | ||||||
349 | bool needsCleanup() const { return !isSingleWord(); } | ||||||
350 | |||||||
351 | /// Used to insert APInt objects, or objects that contain APInt objects, into | ||||||
352 | /// FoldingSets. | ||||||
353 | void Profile(FoldingSetNodeID &id) const; | ||||||
354 | |||||||
355 | /// @} | ||||||
356 | /// \name Value Tests | ||||||
357 | /// @{ | ||||||
358 | |||||||
359 | /// Determine sign of this APInt. | ||||||
360 | /// | ||||||
361 | /// This tests the high bit of this APInt to determine if it is set. | ||||||
362 | /// | ||||||
363 | /// \returns true if this APInt is negative, false otherwise | ||||||
364 | bool isNegative() const { return (*this)[BitWidth - 1]; } | ||||||
365 | |||||||
366 | /// Determine if this APInt Value is non-negative (>= 0) | ||||||
367 | /// | ||||||
368 | /// This tests the high bit of the APInt to determine if it is unset. | ||||||
369 | bool isNonNegative() const { return !isNegative(); } | ||||||
370 | |||||||
371 | /// Determine if sign bit of this APInt is set. | ||||||
372 | /// | ||||||
373 | /// This tests the high bit of this APInt to determine if it is set. | ||||||
374 | /// | ||||||
375 | /// \returns true if this APInt has its sign bit set, false otherwise. | ||||||
376 | bool isSignBitSet() const { return (*this)[BitWidth-1]; } | ||||||
377 | |||||||
378 | /// Determine if sign bit of this APInt is clear. | ||||||
379 | /// | ||||||
380 | /// This tests the high bit of this APInt to determine if it is clear. | ||||||
381 | /// | ||||||
382 | /// \returns true if this APInt has its sign bit clear, false otherwise. | ||||||
383 | bool isSignBitClear() const { return !isSignBitSet(); } | ||||||
384 | |||||||
385 | /// Determine if this APInt Value is positive. | ||||||
386 | /// | ||||||
387 | /// This tests if the value of this APInt is positive (> 0). Note | ||||||
388 | /// that 0 is not a positive value. | ||||||
389 | /// | ||||||
390 | /// \returns true if this APInt is positive. | ||||||
391 | bool isStrictlyPositive() const { return isNonNegative() && !isNullValue(); } | ||||||
392 | |||||||
393 | /// Determine if this APInt Value is non-positive (<= 0). | ||||||
394 | /// | ||||||
395 | /// \returns true if this APInt is non-positive. | ||||||
396 | bool isNonPositive() const { return !isStrictlyPositive(); } | ||||||
397 | |||||||
398 | /// Determine if all bits are set | ||||||
399 | /// | ||||||
400 | /// This checks to see if the value has all bits of the APInt are set or not. | ||||||
401 | bool isAllOnesValue() const { | ||||||
402 | if (isSingleWord()) | ||||||
403 | return U.VAL == WORDTYPE_MAX >> (APINT_BITS_PER_WORD - BitWidth); | ||||||
404 | return countTrailingOnesSlowCase() == BitWidth; | ||||||
405 | } | ||||||
406 | |||||||
407 | /// Determine if all bits are clear | ||||||
408 | /// | ||||||
409 | /// This checks to see if the value has all bits of the APInt are clear or | ||||||
410 | /// not. | ||||||
411 | bool isNullValue() const { return !*this; } | ||||||
412 | |||||||
413 | /// Determine if this is a value of 1. | ||||||
414 | /// | ||||||
415 | /// This checks to see if the value of this APInt is one. | ||||||
416 | bool isOneValue() const { | ||||||
417 | if (isSingleWord()) | ||||||
418 | return U.VAL == 1; | ||||||
419 | return countLeadingZerosSlowCase() == BitWidth - 1; | ||||||
420 | } | ||||||
421 | |||||||
422 | /// Determine if this is the largest unsigned value. | ||||||
423 | /// | ||||||
424 | /// This checks to see if the value of this APInt is the maximum unsigned | ||||||
425 | /// value for the APInt's bit width. | ||||||
426 | bool isMaxValue() const { return isAllOnesValue(); } | ||||||
427 | |||||||
428 | /// Determine if this is the largest signed value. | ||||||
429 | /// | ||||||
430 | /// This checks to see if the value of this APInt is the maximum signed | ||||||
431 | /// value for the APInt's bit width. | ||||||
432 | bool isMaxSignedValue() const { | ||||||
433 | if (isSingleWord()) | ||||||
434 | return U.VAL == ((WordType(1) << (BitWidth - 1)) - 1); | ||||||
435 | return !isNegative() && countTrailingOnesSlowCase() == BitWidth - 1; | ||||||
436 | } | ||||||
437 | |||||||
438 | /// Determine if this is the smallest unsigned value. | ||||||
439 | /// | ||||||
440 | /// This checks to see if the value of this APInt is the minimum unsigned | ||||||
441 | /// value for the APInt's bit width. | ||||||
442 | bool isMinValue() const { return isNullValue(); } | ||||||
443 | |||||||
444 | /// Determine if this is the smallest signed value. | ||||||
445 | /// | ||||||
446 | /// This checks to see if the value of this APInt is the minimum signed | ||||||
447 | /// value for the APInt's bit width. | ||||||
448 | bool isMinSignedValue() const { | ||||||
449 | if (isSingleWord()) | ||||||
450 | return U.VAL == (WordType(1) << (BitWidth - 1)); | ||||||
451 | return isNegative() && countTrailingZerosSlowCase() == BitWidth - 1; | ||||||
452 | } | ||||||
453 | |||||||
454 | /// Check if this APInt has an N-bits unsigned integer value. | ||||||
455 | bool isIntN(unsigned N) const { | ||||||
456 | assert(N && "N == 0 ???")((N && "N == 0 ???") ? static_cast<void> (0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 456, __PRETTY_FUNCTION__)); | ||||||
457 | return getActiveBits() <= N; | ||||||
458 | } | ||||||
459 | |||||||
460 | /// Check if this APInt has an N-bits signed integer value. | ||||||
461 | bool isSignedIntN(unsigned N) const { | ||||||
462 | assert(N && "N == 0 ???")((N && "N == 0 ???") ? static_cast<void> (0) : __assert_fail ("N && \"N == 0 ???\"", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 462, __PRETTY_FUNCTION__)); | ||||||
463 | return getMinSignedBits() <= N; | ||||||
464 | } | ||||||
465 | |||||||
466 | /// Check if this APInt's value is a power of two greater than zero. | ||||||
467 | /// | ||||||
468 | /// \returns true if the argument APInt value is a power of two > 0. | ||||||
469 | bool isPowerOf2() const { | ||||||
470 | if (isSingleWord()) | ||||||
471 | return isPowerOf2_64(U.VAL); | ||||||
472 | return countPopulationSlowCase() == 1; | ||||||
473 | } | ||||||
474 | |||||||
475 | /// Check if the APInt's value is returned by getSignMask. | ||||||
476 | /// | ||||||
477 | /// \returns true if this is the value returned by getSignMask. | ||||||
478 | bool isSignMask() const { return isMinSignedValue(); } | ||||||
479 | |||||||
480 | /// Convert APInt to a boolean value. | ||||||
481 | /// | ||||||
482 | /// This converts the APInt to a boolean value as a test against zero. | ||||||
483 | bool getBoolValue() const { return !!*this; } | ||||||
484 | |||||||
485 | /// If this value is smaller than the specified limit, return it, otherwise | ||||||
486 | /// return the limit value. This causes the value to saturate to the limit. | ||||||
487 | uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) const { | ||||||
488 | return ugt(Limit) ? Limit : getZExtValue(); | ||||||
489 | } | ||||||
490 | |||||||
491 | /// Check if the APInt consists of a repeated bit pattern. | ||||||
492 | /// | ||||||
493 | /// e.g. 0x01010101 satisfies isSplat(8). | ||||||
494 | /// \param SplatSizeInBits The size of the pattern in bits. Must divide bit | ||||||
495 | /// width without remainder. | ||||||
496 | bool isSplat(unsigned SplatSizeInBits) const; | ||||||
497 | |||||||
498 | /// \returns true if this APInt value is a sequence of \param numBits ones | ||||||
499 | /// starting at the least significant bit with the remainder zero. | ||||||
500 | bool isMask(unsigned numBits) const { | ||||||
501 | assert(numBits != 0 && "numBits must be non-zero")((numBits != 0 && "numBits must be non-zero") ? static_cast <void> (0) : __assert_fail ("numBits != 0 && \"numBits must be non-zero\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 501, __PRETTY_FUNCTION__)); | ||||||
502 | assert(numBits <= BitWidth && "numBits out of range")((numBits <= BitWidth && "numBits out of range") ? static_cast<void> (0) : __assert_fail ("numBits <= BitWidth && \"numBits out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 502, __PRETTY_FUNCTION__)); | ||||||
503 | if (isSingleWord()) | ||||||
504 | return U.VAL == (WORDTYPE_MAX >> (APINT_BITS_PER_WORD - numBits)); | ||||||
505 | unsigned Ones = countTrailingOnesSlowCase(); | ||||||
506 | return (numBits == Ones) && | ||||||
507 | ((Ones + countLeadingZerosSlowCase()) == BitWidth); | ||||||
508 | } | ||||||
509 | |||||||
510 | /// \returns true if this APInt is a non-empty sequence of ones starting at | ||||||
511 | /// the least significant bit with the remainder zero. | ||||||
512 | /// Ex. isMask(0x0000FFFFU) == true. | ||||||
513 | bool isMask() const { | ||||||
514 | if (isSingleWord()) | ||||||
515 | return isMask_64(U.VAL); | ||||||
516 | unsigned Ones = countTrailingOnesSlowCase(); | ||||||
517 | return (Ones > 0) && ((Ones + countLeadingZerosSlowCase()) == BitWidth); | ||||||
518 | } | ||||||
519 | |||||||
520 | /// Return true if this APInt value contains a sequence of ones with | ||||||
521 | /// the remainder zero. | ||||||
522 | bool isShiftedMask() const { | ||||||
523 | if (isSingleWord()) | ||||||
524 | return isShiftedMask_64(U.VAL); | ||||||
525 | unsigned Ones = countPopulationSlowCase(); | ||||||
526 | unsigned LeadZ = countLeadingZerosSlowCase(); | ||||||
527 | return (Ones + LeadZ + countTrailingZeros()) == BitWidth; | ||||||
528 | } | ||||||
529 | |||||||
530 | /// @} | ||||||
531 | /// \name Value Generators | ||||||
532 | /// @{ | ||||||
533 | |||||||
534 | /// Gets maximum unsigned value of APInt for specific bit width. | ||||||
535 | static APInt getMaxValue(unsigned numBits) { | ||||||
536 | return getAllOnesValue(numBits); | ||||||
537 | } | ||||||
538 | |||||||
539 | /// Gets maximum signed value of APInt for a specific bit width. | ||||||
540 | static APInt getSignedMaxValue(unsigned numBits) { | ||||||
541 | APInt API = getAllOnesValue(numBits); | ||||||
542 | API.clearBit(numBits - 1); | ||||||
543 | return API; | ||||||
544 | } | ||||||
545 | |||||||
546 | /// Gets minimum unsigned value of APInt for a specific bit width. | ||||||
547 | static APInt getMinValue(unsigned numBits) { return APInt(numBits, 0); } | ||||||
548 | |||||||
549 | /// Gets minimum signed value of APInt for a specific bit width. | ||||||
550 | static APInt getSignedMinValue(unsigned numBits) { | ||||||
551 | APInt API(numBits, 0); | ||||||
552 | API.setBit(numBits - 1); | ||||||
553 | return API; | ||||||
554 | } | ||||||
555 | |||||||
556 | /// Get the SignMask for a specific bit width. | ||||||
557 | /// | ||||||
558 | /// This is just a wrapper function of getSignedMinValue(), and it helps code | ||||||
559 | /// readability when we want to get a SignMask. | ||||||
560 | static APInt getSignMask(unsigned BitWidth) { | ||||||
561 | return getSignedMinValue(BitWidth); | ||||||
562 | } | ||||||
563 | |||||||
564 | /// Get the all-ones value. | ||||||
565 | /// | ||||||
566 | /// \returns the all-ones value for an APInt of the specified bit-width. | ||||||
567 | static APInt getAllOnesValue(unsigned numBits) { | ||||||
568 | return APInt(numBits, WORDTYPE_MAX, true); | ||||||
569 | } | ||||||
570 | |||||||
571 | /// Get the '0' value. | ||||||
572 | /// | ||||||
573 | /// \returns the '0' value for an APInt of the specified bit-width. | ||||||
574 | static APInt getNullValue(unsigned numBits) { return APInt(numBits, 0); } | ||||||
575 | |||||||
576 | /// Compute an APInt containing numBits highbits from this APInt. | ||||||
577 | /// | ||||||
578 | /// Get an APInt with the same BitWidth as this APInt, just zero mask | ||||||
579 | /// the low bits and right shift to the least significant bit. | ||||||
580 | /// | ||||||
581 | /// \returns the high "numBits" bits of this APInt. | ||||||
582 | APInt getHiBits(unsigned numBits) const; | ||||||
583 | |||||||
584 | /// Compute an APInt containing numBits lowbits from this APInt. | ||||||
585 | /// | ||||||
586 | /// Get an APInt with the same BitWidth as this APInt, just zero mask | ||||||
587 | /// the high bits. | ||||||
588 | /// | ||||||
589 | /// \returns the low "numBits" bits of this APInt. | ||||||
590 | APInt getLoBits(unsigned numBits) const; | ||||||
591 | |||||||
592 | /// Return an APInt with exactly one bit set in the result. | ||||||
593 | static APInt getOneBitSet(unsigned numBits, unsigned BitNo) { | ||||||
594 | APInt Res(numBits, 0); | ||||||
595 | Res.setBit(BitNo); | ||||||
596 | return Res; | ||||||
597 | } | ||||||
598 | |||||||
599 | /// Get a value with a block of bits set. | ||||||
600 | /// | ||||||
601 | /// Constructs an APInt value that has a contiguous range of bits set. The | ||||||
602 | /// bits from loBit (inclusive) to hiBit (exclusive) will be set. All other | ||||||
603 | /// bits will be zero. For example, with parameters(32, 0, 16) you would get | ||||||
604 | /// 0x0000FFFF. Please call getBitsSetWithWrap if \p loBit may be greater than | ||||||
605 | /// \p hiBit. | ||||||
606 | /// | ||||||
607 | /// \param numBits the intended bit width of the result | ||||||
608 | /// \param loBit the index of the lowest bit set. | ||||||
609 | /// \param hiBit the index of the highest bit set. | ||||||
610 | /// | ||||||
611 | /// \returns An APInt value with the requested bits set. | ||||||
612 | static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit) { | ||||||
613 | assert(loBit <= hiBit && "loBit greater than hiBit")((loBit <= hiBit && "loBit greater than hiBit") ? static_cast <void> (0) : __assert_fail ("loBit <= hiBit && \"loBit greater than hiBit\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 613, __PRETTY_FUNCTION__)); | ||||||
614 | APInt Res(numBits, 0); | ||||||
615 | Res.setBits(loBit, hiBit); | ||||||
616 | return Res; | ||||||
617 | } | ||||||
618 | |||||||
619 | /// Wrap version of getBitsSet. | ||||||
620 | /// If \p hiBit is bigger than \p loBit, this is same with getBitsSet. | ||||||
621 | /// If \p hiBit is not bigger than \p loBit, the set bits "wrap". For example, | ||||||
622 | /// with parameters (32, 28, 4), you would get 0xF000000F. | ||||||
623 | /// If \p hiBit is equal to \p loBit, you would get a result with all bits | ||||||
624 | /// set. | ||||||
625 | static APInt getBitsSetWithWrap(unsigned numBits, unsigned loBit, | ||||||
626 | unsigned hiBit) { | ||||||
627 | APInt Res(numBits, 0); | ||||||
628 | Res.setBitsWithWrap(loBit, hiBit); | ||||||
629 | return Res; | ||||||
630 | } | ||||||
631 | |||||||
632 | /// Get a value with upper bits starting at loBit set. | ||||||
633 | /// | ||||||
634 | /// Constructs an APInt value that has a contiguous range of bits set. The | ||||||
635 | /// bits from loBit (inclusive) to numBits (exclusive) will be set. All other | ||||||
636 | /// bits will be zero. For example, with parameters(32, 12) you would get | ||||||
637 | /// 0xFFFFF000. | ||||||
638 | /// | ||||||
639 | /// \param numBits the intended bit width of the result | ||||||
640 | /// \param loBit the index of the lowest bit to set. | ||||||
641 | /// | ||||||
642 | /// \returns An APInt value with the requested bits set. | ||||||
643 | static APInt getBitsSetFrom(unsigned numBits, unsigned loBit) { | ||||||
644 | APInt Res(numBits, 0); | ||||||
645 | Res.setBitsFrom(loBit); | ||||||
646 | return Res; | ||||||
647 | } | ||||||
648 | |||||||
649 | /// Get a value with high bits set | ||||||
650 | /// | ||||||
651 | /// Constructs an APInt value that has the top hiBitsSet bits set. | ||||||
652 | /// | ||||||
653 | /// \param numBits the bitwidth of the result | ||||||
654 | /// \param hiBitsSet the number of high-order bits set in the result. | ||||||
655 | static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet) { | ||||||
656 | APInt Res(numBits, 0); | ||||||
657 | Res.setHighBits(hiBitsSet); | ||||||
658 | return Res; | ||||||
659 | } | ||||||
660 | |||||||
661 | /// Get a value with low bits set | ||||||
662 | /// | ||||||
663 | /// Constructs an APInt value that has the bottom loBitsSet bits set. | ||||||
664 | /// | ||||||
665 | /// \param numBits the bitwidth of the result | ||||||
666 | /// \param loBitsSet the number of low-order bits set in the result. | ||||||
667 | static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet) { | ||||||
668 | APInt Res(numBits, 0); | ||||||
669 | Res.setLowBits(loBitsSet); | ||||||
670 | return Res; | ||||||
671 | } | ||||||
672 | |||||||
673 | /// Return a value containing V broadcasted over NewLen bits. | ||||||
674 | static APInt getSplat(unsigned NewLen, const APInt &V); | ||||||
675 | |||||||
676 | /// Determine if two APInts have the same value, after zero-extending | ||||||
677 | /// one of them (if needed!) to ensure that the bit-widths match. | ||||||
678 | static bool isSameValue(const APInt &I1, const APInt &I2) { | ||||||
679 | if (I1.getBitWidth() == I2.getBitWidth()) | ||||||
680 | return I1 == I2; | ||||||
681 | |||||||
682 | if (I1.getBitWidth() > I2.getBitWidth()) | ||||||
683 | return I1 == I2.zext(I1.getBitWidth()); | ||||||
684 | |||||||
685 | return I1.zext(I2.getBitWidth()) == I2; | ||||||
686 | } | ||||||
687 | |||||||
688 | /// Overload to compute a hash_code for an APInt value. | ||||||
689 | friend hash_code hash_value(const APInt &Arg); | ||||||
690 | |||||||
691 | /// This function returns a pointer to the internal storage of the APInt. | ||||||
692 | /// This is useful for writing out the APInt in binary form without any | ||||||
693 | /// conversions. | ||||||
694 | const uint64_t *getRawData() const { | ||||||
695 | if (isSingleWord()) | ||||||
696 | return &U.VAL; | ||||||
697 | return &U.pVal[0]; | ||||||
698 | } | ||||||
699 | |||||||
700 | /// @} | ||||||
701 | /// \name Unary Operators | ||||||
702 | /// @{ | ||||||
703 | |||||||
704 | /// Postfix increment operator. | ||||||
705 | /// | ||||||
706 | /// Increments *this by 1. | ||||||
707 | /// | ||||||
708 | /// \returns a new APInt value representing the original value of *this. | ||||||
709 | const APInt operator++(int) { | ||||||
710 | APInt API(*this); | ||||||
711 | ++(*this); | ||||||
712 | return API; | ||||||
713 | } | ||||||
714 | |||||||
715 | /// Prefix increment operator. | ||||||
716 | /// | ||||||
717 | /// \returns *this incremented by one | ||||||
718 | APInt &operator++(); | ||||||
719 | |||||||
720 | /// Postfix decrement operator. | ||||||
721 | /// | ||||||
722 | /// Decrements *this by 1. | ||||||
723 | /// | ||||||
724 | /// \returns a new APInt value representing the original value of *this. | ||||||
725 | const APInt operator--(int) { | ||||||
726 | APInt API(*this); | ||||||
727 | --(*this); | ||||||
728 | return API; | ||||||
729 | } | ||||||
730 | |||||||
731 | /// Prefix decrement operator. | ||||||
732 | /// | ||||||
733 | /// \returns *this decremented by one. | ||||||
734 | APInt &operator--(); | ||||||
735 | |||||||
736 | /// Logical negation operator. | ||||||
737 | /// | ||||||
738 | /// Performs logical negation operation on this APInt. | ||||||
739 | /// | ||||||
740 | /// \returns true if *this is zero, false otherwise. | ||||||
741 | bool operator!() const { | ||||||
742 | if (isSingleWord()) | ||||||
743 | return U.VAL == 0; | ||||||
744 | return countLeadingZerosSlowCase() == BitWidth; | ||||||
745 | } | ||||||
746 | |||||||
747 | /// @} | ||||||
748 | /// \name Assignment Operators | ||||||
749 | /// @{ | ||||||
750 | |||||||
751 | /// Copy assignment operator. | ||||||
752 | /// | ||||||
753 | /// \returns *this after assignment of RHS. | ||||||
754 | APInt &operator=(const APInt &RHS) { | ||||||
755 | // If the bitwidths are the same, we can avoid mucking with memory | ||||||
756 | if (isSingleWord() && RHS.isSingleWord()) { | ||||||
757 | U.VAL = RHS.U.VAL; | ||||||
758 | BitWidth = RHS.BitWidth; | ||||||
759 | return clearUnusedBits(); | ||||||
760 | } | ||||||
761 | |||||||
762 | AssignSlowCase(RHS); | ||||||
763 | return *this; | ||||||
764 | } | ||||||
765 | |||||||
766 | /// Move assignment operator. | ||||||
767 | APInt &operator=(APInt &&that) { | ||||||
768 | #ifdef EXPENSIVE_CHECKS | ||||||
769 | // Some std::shuffle implementations still do self-assignment. | ||||||
770 | if (this == &that) | ||||||
771 | return *this; | ||||||
772 | #endif | ||||||
773 | assert(this != &that && "Self-move not supported")((this != &that && "Self-move not supported") ? static_cast <void> (0) : __assert_fail ("this != &that && \"Self-move not supported\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 773, __PRETTY_FUNCTION__)); | ||||||
774 | if (!isSingleWord()) | ||||||
775 | delete[] U.pVal; | ||||||
776 | |||||||
777 | // Use memcpy so that type based alias analysis sees both VAL and pVal | ||||||
778 | // as modified. | ||||||
779 | memcpy(&U, &that.U, sizeof(U)); | ||||||
780 | |||||||
781 | BitWidth = that.BitWidth; | ||||||
782 | that.BitWidth = 0; | ||||||
783 | |||||||
784 | return *this; | ||||||
785 | } | ||||||
786 | |||||||
787 | /// Assignment operator. | ||||||
788 | /// | ||||||
789 | /// The RHS value is assigned to *this. If the significant bits in RHS exceed | ||||||
790 | /// the bit width, the excess bits are truncated. If the bit width is larger | ||||||
791 | /// than 64, the value is zero filled in the unspecified high order bits. | ||||||
792 | /// | ||||||
793 | /// \returns *this after assignment of RHS value. | ||||||
794 | APInt &operator=(uint64_t RHS) { | ||||||
795 | if (isSingleWord()) { | ||||||
796 | U.VAL = RHS; | ||||||
797 | return clearUnusedBits(); | ||||||
798 | } | ||||||
799 | U.pVal[0] = RHS; | ||||||
800 | memset(U.pVal + 1, 0, (getNumWords() - 1) * APINT_WORD_SIZE); | ||||||
801 | return *this; | ||||||
802 | } | ||||||
803 | |||||||
804 | /// Bitwise AND assignment operator. | ||||||
805 | /// | ||||||
806 | /// Performs a bitwise AND operation on this APInt and RHS. The result is | ||||||
807 | /// assigned to *this. | ||||||
808 | /// | ||||||
809 | /// \returns *this after ANDing with RHS. | ||||||
810 | APInt &operator&=(const APInt &RHS) { | ||||||
811 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 811, __PRETTY_FUNCTION__)); | ||||||
812 | if (isSingleWord()) | ||||||
813 | U.VAL &= RHS.U.VAL; | ||||||
814 | else | ||||||
815 | AndAssignSlowCase(RHS); | ||||||
816 | return *this; | ||||||
817 | } | ||||||
818 | |||||||
819 | /// Bitwise AND assignment operator. | ||||||
820 | /// | ||||||
821 | /// Performs a bitwise AND operation on this APInt and RHS. RHS is | ||||||
822 | /// logically zero-extended or truncated to match the bit-width of | ||||||
823 | /// the LHS. | ||||||
824 | APInt &operator&=(uint64_t RHS) { | ||||||
825 | if (isSingleWord()) { | ||||||
826 | U.VAL &= RHS; | ||||||
827 | return *this; | ||||||
828 | } | ||||||
829 | U.pVal[0] &= RHS; | ||||||
830 | memset(U.pVal+1, 0, (getNumWords() - 1) * APINT_WORD_SIZE); | ||||||
831 | return *this; | ||||||
832 | } | ||||||
833 | |||||||
834 | /// Bitwise OR assignment operator. | ||||||
835 | /// | ||||||
836 | /// Performs a bitwise OR operation on this APInt and RHS. The result is | ||||||
837 | /// assigned *this; | ||||||
838 | /// | ||||||
839 | /// \returns *this after ORing with RHS. | ||||||
840 | APInt &operator|=(const APInt &RHS) { | ||||||
841 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 841, __PRETTY_FUNCTION__)); | ||||||
842 | if (isSingleWord()) | ||||||
843 | U.VAL |= RHS.U.VAL; | ||||||
844 | else | ||||||
845 | OrAssignSlowCase(RHS); | ||||||
846 | return *this; | ||||||
847 | } | ||||||
848 | |||||||
849 | /// Bitwise OR assignment operator. | ||||||
850 | /// | ||||||
851 | /// Performs a bitwise OR operation on this APInt and RHS. RHS is | ||||||
852 | /// logically zero-extended or truncated to match the bit-width of | ||||||
853 | /// the LHS. | ||||||
854 | APInt &operator|=(uint64_t RHS) { | ||||||
855 | if (isSingleWord()) { | ||||||
856 | U.VAL |= RHS; | ||||||
857 | return clearUnusedBits(); | ||||||
858 | } | ||||||
859 | U.pVal[0] |= RHS; | ||||||
860 | return *this; | ||||||
861 | } | ||||||
862 | |||||||
863 | /// Bitwise XOR assignment operator. | ||||||
864 | /// | ||||||
865 | /// Performs a bitwise XOR operation on this APInt and RHS. The result is | ||||||
866 | /// assigned to *this. | ||||||
867 | /// | ||||||
868 | /// \returns *this after XORing with RHS. | ||||||
869 | APInt &operator^=(const APInt &RHS) { | ||||||
870 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 870, __PRETTY_FUNCTION__)); | ||||||
871 | if (isSingleWord()) | ||||||
872 | U.VAL ^= RHS.U.VAL; | ||||||
873 | else | ||||||
874 | XorAssignSlowCase(RHS); | ||||||
875 | return *this; | ||||||
876 | } | ||||||
877 | |||||||
878 | /// Bitwise XOR assignment operator. | ||||||
879 | /// | ||||||
880 | /// Performs a bitwise XOR operation on this APInt and RHS. RHS is | ||||||
881 | /// logically zero-extended or truncated to match the bit-width of | ||||||
882 | /// the LHS. | ||||||
883 | APInt &operator^=(uint64_t RHS) { | ||||||
884 | if (isSingleWord()) { | ||||||
885 | U.VAL ^= RHS; | ||||||
886 | return clearUnusedBits(); | ||||||
887 | } | ||||||
888 | U.pVal[0] ^= RHS; | ||||||
889 | return *this; | ||||||
890 | } | ||||||
891 | |||||||
892 | /// Multiplication assignment operator. | ||||||
893 | /// | ||||||
894 | /// Multiplies this APInt by RHS and assigns the result to *this. | ||||||
895 | /// | ||||||
896 | /// \returns *this | ||||||
897 | APInt &operator*=(const APInt &RHS); | ||||||
898 | APInt &operator*=(uint64_t RHS); | ||||||
899 | |||||||
900 | /// Addition assignment operator. | ||||||
901 | /// | ||||||
902 | /// Adds RHS to *this and assigns the result to *this. | ||||||
903 | /// | ||||||
904 | /// \returns *this | ||||||
905 | APInt &operator+=(const APInt &RHS); | ||||||
906 | APInt &operator+=(uint64_t RHS); | ||||||
907 | |||||||
908 | /// Subtraction assignment operator. | ||||||
909 | /// | ||||||
910 | /// Subtracts RHS from *this and assigns the result to *this. | ||||||
911 | /// | ||||||
912 | /// \returns *this | ||||||
913 | APInt &operator-=(const APInt &RHS); | ||||||
914 | APInt &operator-=(uint64_t RHS); | ||||||
915 | |||||||
916 | /// Left-shift assignment function. | ||||||
917 | /// | ||||||
918 | /// Shifts *this left by shiftAmt and assigns the result to *this. | ||||||
919 | /// | ||||||
920 | /// \returns *this after shifting left by ShiftAmt | ||||||
921 | APInt &operator<<=(unsigned ShiftAmt) { | ||||||
922 | assert(ShiftAmt <= BitWidth && "Invalid shift amount")((ShiftAmt <= BitWidth && "Invalid shift amount") ? static_cast<void> (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 922, __PRETTY_FUNCTION__)); | ||||||
923 | if (isSingleWord()) { | ||||||
924 | if (ShiftAmt == BitWidth) | ||||||
925 | U.VAL = 0; | ||||||
926 | else | ||||||
927 | U.VAL <<= ShiftAmt; | ||||||
928 | return clearUnusedBits(); | ||||||
929 | } | ||||||
930 | shlSlowCase(ShiftAmt); | ||||||
931 | return *this; | ||||||
932 | } | ||||||
933 | |||||||
934 | /// Left-shift assignment function. | ||||||
935 | /// | ||||||
936 | /// Shifts *this left by shiftAmt and assigns the result to *this. | ||||||
937 | /// | ||||||
938 | /// \returns *this after shifting left by ShiftAmt | ||||||
939 | APInt &operator<<=(const APInt &ShiftAmt); | ||||||
940 | |||||||
941 | /// @} | ||||||
942 | /// \name Binary Operators | ||||||
943 | /// @{ | ||||||
944 | |||||||
945 | /// Multiplication operator. | ||||||
946 | /// | ||||||
947 | /// Multiplies this APInt by RHS and returns the result. | ||||||
948 | APInt operator*(const APInt &RHS) const; | ||||||
949 | |||||||
950 | /// Left logical shift operator. | ||||||
951 | /// | ||||||
952 | /// Shifts this APInt left by \p Bits and returns the result. | ||||||
953 | APInt operator<<(unsigned Bits) const { return shl(Bits); } | ||||||
954 | |||||||
955 | /// Left logical shift operator. | ||||||
956 | /// | ||||||
957 | /// Shifts this APInt left by \p Bits and returns the result. | ||||||
958 | APInt operator<<(const APInt &Bits) const { return shl(Bits); } | ||||||
959 | |||||||
960 | /// Arithmetic right-shift function. | ||||||
961 | /// | ||||||
962 | /// Arithmetic right-shift this APInt by shiftAmt. | ||||||
963 | APInt ashr(unsigned ShiftAmt) const { | ||||||
964 | APInt R(*this); | ||||||
965 | R.ashrInPlace(ShiftAmt); | ||||||
966 | return R; | ||||||
967 | } | ||||||
968 | |||||||
969 | /// Arithmetic right-shift this APInt by ShiftAmt in place. | ||||||
970 | void ashrInPlace(unsigned ShiftAmt) { | ||||||
971 | assert(ShiftAmt <= BitWidth && "Invalid shift amount")((ShiftAmt <= BitWidth && "Invalid shift amount") ? static_cast<void> (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 971, __PRETTY_FUNCTION__)); | ||||||
972 | if (isSingleWord()) { | ||||||
973 | int64_t SExtVAL = SignExtend64(U.VAL, BitWidth); | ||||||
974 | if (ShiftAmt == BitWidth) | ||||||
975 | U.VAL = SExtVAL >> (APINT_BITS_PER_WORD - 1); // Fill with sign bit. | ||||||
976 | else | ||||||
977 | U.VAL = SExtVAL >> ShiftAmt; | ||||||
978 | clearUnusedBits(); | ||||||
979 | return; | ||||||
980 | } | ||||||
981 | ashrSlowCase(ShiftAmt); | ||||||
982 | } | ||||||
983 | |||||||
984 | /// Logical right-shift function. | ||||||
985 | /// | ||||||
986 | /// Logical right-shift this APInt by shiftAmt. | ||||||
987 | APInt lshr(unsigned shiftAmt) const { | ||||||
988 | APInt R(*this); | ||||||
989 | R.lshrInPlace(shiftAmt); | ||||||
990 | return R; | ||||||
991 | } | ||||||
992 | |||||||
993 | /// Logical right-shift this APInt by ShiftAmt in place. | ||||||
994 | void lshrInPlace(unsigned ShiftAmt) { | ||||||
995 | assert(ShiftAmt <= BitWidth && "Invalid shift amount")((ShiftAmt <= BitWidth && "Invalid shift amount") ? static_cast<void> (0) : __assert_fail ("ShiftAmt <= BitWidth && \"Invalid shift amount\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 995, __PRETTY_FUNCTION__)); | ||||||
996 | if (isSingleWord()) { | ||||||
997 | if (ShiftAmt == BitWidth) | ||||||
998 | U.VAL = 0; | ||||||
999 | else | ||||||
1000 | U.VAL >>= ShiftAmt; | ||||||
1001 | return; | ||||||
1002 | } | ||||||
1003 | lshrSlowCase(ShiftAmt); | ||||||
1004 | } | ||||||
1005 | |||||||
1006 | /// Left-shift function. | ||||||
1007 | /// | ||||||
1008 | /// Left-shift this APInt by shiftAmt. | ||||||
1009 | APInt shl(unsigned shiftAmt) const { | ||||||
1010 | APInt R(*this); | ||||||
1011 | R <<= shiftAmt; | ||||||
1012 | return R; | ||||||
1013 | } | ||||||
1014 | |||||||
1015 | /// Rotate left by rotateAmt. | ||||||
1016 | APInt rotl(unsigned rotateAmt) const; | ||||||
1017 | |||||||
1018 | /// Rotate right by rotateAmt. | ||||||
1019 | APInt rotr(unsigned rotateAmt) const; | ||||||
1020 | |||||||
1021 | /// Arithmetic right-shift function. | ||||||
1022 | /// | ||||||
1023 | /// Arithmetic right-shift this APInt by shiftAmt. | ||||||
1024 | APInt ashr(const APInt &ShiftAmt) const { | ||||||
1025 | APInt R(*this); | ||||||
1026 | R.ashrInPlace(ShiftAmt); | ||||||
1027 | return R; | ||||||
1028 | } | ||||||
1029 | |||||||
1030 | /// Arithmetic right-shift this APInt by shiftAmt in place. | ||||||
1031 | void ashrInPlace(const APInt &shiftAmt); | ||||||
1032 | |||||||
1033 | /// Logical right-shift function. | ||||||
1034 | /// | ||||||
1035 | /// Logical right-shift this APInt by shiftAmt. | ||||||
1036 | APInt lshr(const APInt &ShiftAmt) const { | ||||||
1037 | APInt R(*this); | ||||||
1038 | R.lshrInPlace(ShiftAmt); | ||||||
1039 | return R; | ||||||
1040 | } | ||||||
1041 | |||||||
1042 | /// Logical right-shift this APInt by ShiftAmt in place. | ||||||
1043 | void lshrInPlace(const APInt &ShiftAmt); | ||||||
1044 | |||||||
1045 | /// Left-shift function. | ||||||
1046 | /// | ||||||
1047 | /// Left-shift this APInt by shiftAmt. | ||||||
1048 | APInt shl(const APInt &ShiftAmt) const { | ||||||
1049 | APInt R(*this); | ||||||
1050 | R <<= ShiftAmt; | ||||||
1051 | return R; | ||||||
1052 | } | ||||||
1053 | |||||||
1054 | /// Rotate left by rotateAmt. | ||||||
1055 | APInt rotl(const APInt &rotateAmt) const; | ||||||
1056 | |||||||
1057 | /// Rotate right by rotateAmt. | ||||||
1058 | APInt rotr(const APInt &rotateAmt) const; | ||||||
1059 | |||||||
1060 | /// Unsigned division operation. | ||||||
1061 | /// | ||||||
1062 | /// Perform an unsigned divide operation on this APInt by RHS. Both this and | ||||||
1063 | /// RHS are treated as unsigned quantities for purposes of this division. | ||||||
1064 | /// | ||||||
1065 | /// \returns a new APInt value containing the division result, rounded towards | ||||||
1066 | /// zero. | ||||||
1067 | APInt udiv(const APInt &RHS) const; | ||||||
1068 | APInt udiv(uint64_t RHS) const; | ||||||
1069 | |||||||
1070 | /// Signed division function for APInt. | ||||||
1071 | /// | ||||||
1072 | /// Signed divide this APInt by APInt RHS. | ||||||
1073 | /// | ||||||
1074 | /// The result is rounded towards zero. | ||||||
1075 | APInt sdiv(const APInt &RHS) const; | ||||||
1076 | APInt sdiv(int64_t RHS) const; | ||||||
1077 | |||||||
1078 | /// Unsigned remainder operation. | ||||||
1079 | /// | ||||||
1080 | /// Perform an unsigned remainder operation on this APInt with RHS being the | ||||||
1081 | /// divisor. Both this and RHS are treated as unsigned quantities for purposes | ||||||
1082 | /// of this operation. Note that this is a true remainder operation and not a | ||||||
1083 | /// modulo operation because the sign follows the sign of the dividend which | ||||||
1084 | /// is *this. | ||||||
1085 | /// | ||||||
1086 | /// \returns a new APInt value containing the remainder result | ||||||
1087 | APInt urem(const APInt &RHS) const; | ||||||
1088 | uint64_t urem(uint64_t RHS) const; | ||||||
1089 | |||||||
1090 | /// Function for signed remainder operation. | ||||||
1091 | /// | ||||||
1092 | /// Signed remainder operation on APInt. | ||||||
1093 | APInt srem(const APInt &RHS) const; | ||||||
1094 | int64_t srem(int64_t RHS) const; | ||||||
1095 | |||||||
1096 | /// Dual division/remainder interface. | ||||||
1097 | /// | ||||||
1098 | /// Sometimes it is convenient to divide two APInt values and obtain both the | ||||||
1099 | /// quotient and remainder. This function does both operations in the same | ||||||
1100 | /// computation making it a little more efficient. The pair of input arguments | ||||||
1101 | /// may overlap with the pair of output arguments. It is safe to call | ||||||
1102 | /// udivrem(X, Y, X, Y), for example. | ||||||
1103 | static void udivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, | ||||||
1104 | APInt &Remainder); | ||||||
1105 | static void udivrem(const APInt &LHS, uint64_t RHS, APInt &Quotient, | ||||||
1106 | uint64_t &Remainder); | ||||||
1107 | |||||||
1108 | static void sdivrem(const APInt &LHS, const APInt &RHS, APInt &Quotient, | ||||||
1109 | APInt &Remainder); | ||||||
1110 | static void sdivrem(const APInt &LHS, int64_t RHS, APInt &Quotient, | ||||||
1111 | int64_t &Remainder); | ||||||
1112 | |||||||
1113 | // Operations that return overflow indicators. | ||||||
1114 | APInt sadd_ov(const APInt &RHS, bool &Overflow) const; | ||||||
1115 | APInt uadd_ov(const APInt &RHS, bool &Overflow) const; | ||||||
1116 | APInt ssub_ov(const APInt &RHS, bool &Overflow) const; | ||||||
1117 | APInt usub_ov(const APInt &RHS, bool &Overflow) const; | ||||||
1118 | APInt sdiv_ov(const APInt &RHS, bool &Overflow) const; | ||||||
1119 | APInt smul_ov(const APInt &RHS, bool &Overflow) const; | ||||||
1120 | APInt umul_ov(const APInt &RHS, bool &Overflow) const; | ||||||
1121 | APInt sshl_ov(const APInt &Amt, bool &Overflow) const; | ||||||
1122 | APInt ushl_ov(const APInt &Amt, bool &Overflow) const; | ||||||
1123 | |||||||
1124 | // Operations that saturate | ||||||
1125 | APInt sadd_sat(const APInt &RHS) const; | ||||||
1126 | APInt uadd_sat(const APInt &RHS) const; | ||||||
1127 | APInt ssub_sat(const APInt &RHS) const; | ||||||
1128 | APInt usub_sat(const APInt &RHS) const; | ||||||
1129 | APInt smul_sat(const APInt &RHS) const; | ||||||
1130 | APInt umul_sat(const APInt &RHS) const; | ||||||
1131 | APInt sshl_sat(const APInt &RHS) const; | ||||||
1132 | APInt ushl_sat(const APInt &RHS) const; | ||||||
1133 | |||||||
1134 | /// Array-indexing support. | ||||||
1135 | /// | ||||||
1136 | /// \returns the bit value at bitPosition | ||||||
1137 | bool operator[](unsigned bitPosition) const { | ||||||
1138 | assert(bitPosition < getBitWidth() && "Bit position out of bounds!")((bitPosition < getBitWidth() && "Bit position out of bounds!" ) ? static_cast<void> (0) : __assert_fail ("bitPosition < getBitWidth() && \"Bit position out of bounds!\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1138, __PRETTY_FUNCTION__)); | ||||||
1139 | return (maskBit(bitPosition) & getWord(bitPosition)) != 0; | ||||||
1140 | } | ||||||
1141 | |||||||
1142 | /// @} | ||||||
1143 | /// \name Comparison Operators | ||||||
1144 | /// @{ | ||||||
1145 | |||||||
1146 | /// Equality operator. | ||||||
1147 | /// | ||||||
1148 | /// Compares this APInt with RHS for the validity of the equality | ||||||
1149 | /// relationship. | ||||||
1150 | bool operator==(const APInt &RHS) const { | ||||||
1151 | assert(BitWidth == RHS.BitWidth && "Comparison requires equal bit widths")((BitWidth == RHS.BitWidth && "Comparison requires equal bit widths" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Comparison requires equal bit widths\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1151, __PRETTY_FUNCTION__)); | ||||||
1152 | if (isSingleWord()) | ||||||
1153 | return U.VAL == RHS.U.VAL; | ||||||
1154 | return EqualSlowCase(RHS); | ||||||
1155 | } | ||||||
1156 | |||||||
1157 | /// Equality operator. | ||||||
1158 | /// | ||||||
1159 | /// Compares this APInt with a uint64_t for the validity of the equality | ||||||
1160 | /// relationship. | ||||||
1161 | /// | ||||||
1162 | /// \returns true if *this == Val | ||||||
1163 | bool operator==(uint64_t Val) const { | ||||||
1164 | return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() == Val; | ||||||
1165 | } | ||||||
1166 | |||||||
1167 | /// Equality comparison. | ||||||
1168 | /// | ||||||
1169 | /// Compares this APInt with RHS for the validity of the equality | ||||||
1170 | /// relationship. | ||||||
1171 | /// | ||||||
1172 | /// \returns true if *this == Val | ||||||
1173 | bool eq(const APInt &RHS) const { return (*this) == RHS; } | ||||||
1174 | |||||||
1175 | /// Inequality operator. | ||||||
1176 | /// | ||||||
1177 | /// Compares this APInt with RHS for the validity of the inequality | ||||||
1178 | /// relationship. | ||||||
1179 | /// | ||||||
1180 | /// \returns true if *this != Val | ||||||
1181 | bool operator!=(const APInt &RHS) const { return !((*this) == RHS); } | ||||||
1182 | |||||||
1183 | /// Inequality operator. | ||||||
1184 | /// | ||||||
1185 | /// Compares this APInt with a uint64_t for the validity of the inequality | ||||||
1186 | /// relationship. | ||||||
1187 | /// | ||||||
1188 | /// \returns true if *this != Val | ||||||
1189 | bool operator!=(uint64_t Val) const { return !((*this) == Val); } | ||||||
1190 | |||||||
1191 | /// Inequality comparison | ||||||
1192 | /// | ||||||
1193 | /// Compares this APInt with RHS for the validity of the inequality | ||||||
1194 | /// relationship. | ||||||
1195 | /// | ||||||
1196 | /// \returns true if *this != Val | ||||||
1197 | bool ne(const APInt &RHS) const { return !((*this) == RHS); } | ||||||
1198 | |||||||
1199 | /// Unsigned less than comparison | ||||||
1200 | /// | ||||||
1201 | /// Regards both *this and RHS as unsigned quantities and compares them for | ||||||
1202 | /// the validity of the less-than relationship. | ||||||
1203 | /// | ||||||
1204 | /// \returns true if *this < RHS when both are considered unsigned. | ||||||
1205 | bool ult(const APInt &RHS) const { return compare(RHS) < 0; } | ||||||
1206 | |||||||
1207 | /// Unsigned less than comparison | ||||||
1208 | /// | ||||||
1209 | /// Regards both *this as an unsigned quantity and compares it with RHS for | ||||||
1210 | /// the validity of the less-than relationship. | ||||||
1211 | /// | ||||||
1212 | /// \returns true if *this < RHS when considered unsigned. | ||||||
1213 | bool ult(uint64_t RHS) const { | ||||||
1214 | // Only need to check active bits if not a single word. | ||||||
1215 | return (isSingleWord() || getActiveBits() <= 64) && getZExtValue() < RHS; | ||||||
1216 | } | ||||||
1217 | |||||||
1218 | /// Signed less than comparison | ||||||
1219 | /// | ||||||
1220 | /// Regards both *this and RHS as signed quantities and compares them for | ||||||
1221 | /// validity of the less-than relationship. | ||||||
1222 | /// | ||||||
1223 | /// \returns true if *this < RHS when both are considered signed. | ||||||
1224 | bool slt(const APInt &RHS) const { return compareSigned(RHS) < 0; } | ||||||
1225 | |||||||
1226 | /// Signed less than comparison | ||||||
1227 | /// | ||||||
1228 | /// Regards both *this as a signed quantity and compares it with RHS for | ||||||
1229 | /// the validity of the less-than relationship. | ||||||
1230 | /// | ||||||
1231 | /// \returns true if *this < RHS when considered signed. | ||||||
1232 | bool slt(int64_t RHS) const { | ||||||
1233 | return (!isSingleWord() && getMinSignedBits() > 64) ? isNegative() | ||||||
1234 | : getSExtValue() < RHS; | ||||||
1235 | } | ||||||
1236 | |||||||
1237 | /// Unsigned less or equal comparison | ||||||
1238 | /// | ||||||
1239 | /// Regards both *this and RHS as unsigned quantities and compares them for | ||||||
1240 | /// validity of the less-or-equal relationship. | ||||||
1241 | /// | ||||||
1242 | /// \returns true if *this <= RHS when both are considered unsigned. | ||||||
1243 | bool ule(const APInt &RHS) const { return compare(RHS) <= 0; } | ||||||
1244 | |||||||
1245 | /// Unsigned less or equal comparison | ||||||
1246 | /// | ||||||
1247 | /// Regards both *this as an unsigned quantity and compares it with RHS for | ||||||
1248 | /// the validity of the less-or-equal relationship. | ||||||
1249 | /// | ||||||
1250 | /// \returns true if *this <= RHS when considered unsigned. | ||||||
1251 | bool ule(uint64_t RHS) const { return !ugt(RHS); } | ||||||
1252 | |||||||
1253 | /// Signed less or equal comparison | ||||||
1254 | /// | ||||||
1255 | /// Regards both *this and RHS as signed quantities and compares them for | ||||||
1256 | /// validity of the less-or-equal relationship. | ||||||
1257 | /// | ||||||
1258 | /// \returns true if *this <= RHS when both are considered signed. | ||||||
1259 | bool sle(const APInt &RHS) const { return compareSigned(RHS) <= 0; } | ||||||
1260 | |||||||
1261 | /// Signed less or equal comparison | ||||||
1262 | /// | ||||||
1263 | /// Regards both *this as a signed quantity and compares it with RHS for the | ||||||
1264 | /// validity of the less-or-equal relationship. | ||||||
1265 | /// | ||||||
1266 | /// \returns true if *this <= RHS when considered signed. | ||||||
1267 | bool sle(uint64_t RHS) const { return !sgt(RHS); } | ||||||
1268 | |||||||
1269 | /// Unsigned greater than comparison | ||||||
1270 | /// | ||||||
1271 | /// Regards both *this and RHS as unsigned quantities and compares them for | ||||||
1272 | /// the validity of the greater-than relationship. | ||||||
1273 | /// | ||||||
1274 | /// \returns true if *this > RHS when both are considered unsigned. | ||||||
1275 | bool ugt(const APInt &RHS) const { return !ule(RHS); } | ||||||
1276 | |||||||
1277 | /// Unsigned greater than comparison | ||||||
1278 | /// | ||||||
1279 | /// Regards both *this as an unsigned quantity and compares it with RHS for | ||||||
1280 | /// the validity of the greater-than relationship. | ||||||
1281 | /// | ||||||
1282 | /// \returns true if *this > RHS when considered unsigned. | ||||||
1283 | bool ugt(uint64_t RHS) const { | ||||||
1284 | // Only need to check active bits if not a single word. | ||||||
1285 | return (!isSingleWord() && getActiveBits() > 64) || getZExtValue() > RHS; | ||||||
1286 | } | ||||||
1287 | |||||||
1288 | /// Signed greater than comparison | ||||||
1289 | /// | ||||||
1290 | /// Regards both *this and RHS as signed quantities and compares them for the | ||||||
1291 | /// validity of the greater-than relationship. | ||||||
1292 | /// | ||||||
1293 | /// \returns true if *this > RHS when both are considered signed. | ||||||
1294 | bool sgt(const APInt &RHS) const { return !sle(RHS); } | ||||||
1295 | |||||||
1296 | /// Signed greater than comparison | ||||||
1297 | /// | ||||||
1298 | /// Regards both *this as a signed quantity and compares it with RHS for | ||||||
1299 | /// the validity of the greater-than relationship. | ||||||
1300 | /// | ||||||
1301 | /// \returns true if *this > RHS when considered signed. | ||||||
1302 | bool sgt(int64_t RHS) const { | ||||||
1303 | return (!isSingleWord() && getMinSignedBits() > 64) ? !isNegative() | ||||||
1304 | : getSExtValue() > RHS; | ||||||
1305 | } | ||||||
1306 | |||||||
1307 | /// Unsigned greater or equal comparison | ||||||
1308 | /// | ||||||
1309 | /// Regards both *this and RHS as unsigned quantities and compares them for | ||||||
1310 | /// validity of the greater-or-equal relationship. | ||||||
1311 | /// | ||||||
1312 | /// \returns true if *this >= RHS when both are considered unsigned. | ||||||
1313 | bool uge(const APInt &RHS) const { return !ult(RHS); } | ||||||
1314 | |||||||
1315 | /// Unsigned greater or equal comparison | ||||||
1316 | /// | ||||||
1317 | /// Regards both *this as an unsigned quantity and compares it with RHS for | ||||||
1318 | /// the validity of the greater-or-equal relationship. | ||||||
1319 | /// | ||||||
1320 | /// \returns true if *this >= RHS when considered unsigned. | ||||||
1321 | bool uge(uint64_t RHS) const { return !ult(RHS); } | ||||||
1322 | |||||||
1323 | /// Signed greater or equal comparison | ||||||
1324 | /// | ||||||
1325 | /// Regards both *this and RHS as signed quantities and compares them for | ||||||
1326 | /// validity of the greater-or-equal relationship. | ||||||
1327 | /// | ||||||
1328 | /// \returns true if *this >= RHS when both are considered signed. | ||||||
1329 | bool sge(const APInt &RHS) const { return !slt(RHS); } | ||||||
1330 | |||||||
1331 | /// Signed greater or equal comparison | ||||||
1332 | /// | ||||||
1333 | /// Regards both *this as a signed quantity and compares it with RHS for | ||||||
1334 | /// the validity of the greater-or-equal relationship. | ||||||
1335 | /// | ||||||
1336 | /// \returns true if *this >= RHS when considered signed. | ||||||
1337 | bool sge(int64_t RHS) const { return !slt(RHS); } | ||||||
1338 | |||||||
1339 | /// This operation tests if there are any pairs of corresponding bits | ||||||
1340 | /// between this APInt and RHS that are both set. | ||||||
1341 | bool intersects(const APInt &RHS) const { | ||||||
1342 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1342, __PRETTY_FUNCTION__)); | ||||||
1343 | if (isSingleWord()) | ||||||
1344 | return (U.VAL & RHS.U.VAL) != 0; | ||||||
1345 | return intersectsSlowCase(RHS); | ||||||
1346 | } | ||||||
1347 | |||||||
1348 | /// This operation checks that all bits set in this APInt are also set in RHS. | ||||||
1349 | bool isSubsetOf(const APInt &RHS) const { | ||||||
1350 | assert(BitWidth == RHS.BitWidth && "Bit widths must be the same")((BitWidth == RHS.BitWidth && "Bit widths must be the same" ) ? static_cast<void> (0) : __assert_fail ("BitWidth == RHS.BitWidth && \"Bit widths must be the same\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1350, __PRETTY_FUNCTION__)); | ||||||
1351 | if (isSingleWord()) | ||||||
1352 | return (U.VAL & ~RHS.U.VAL) == 0; | ||||||
1353 | return isSubsetOfSlowCase(RHS); | ||||||
1354 | } | ||||||
1355 | |||||||
1356 | /// @} | ||||||
1357 | /// \name Resizing Operators | ||||||
1358 | /// @{ | ||||||
1359 | |||||||
1360 | /// Truncate to new width. | ||||||
1361 | /// | ||||||
1362 | /// Truncate the APInt to a specified width. It is an error to specify a width | ||||||
1363 | /// that is greater than or equal to the current width. | ||||||
1364 | APInt trunc(unsigned width) const; | ||||||
1365 | |||||||
1366 | /// Truncate to new width with unsigned saturation. | ||||||
1367 | /// | ||||||
1368 | /// If the APInt, treated as unsigned integer, can be losslessly truncated to | ||||||
1369 | /// the new bitwidth, then return truncated APInt. Else, return max value. | ||||||
1370 | APInt truncUSat(unsigned width) const; | ||||||
1371 | |||||||
1372 | /// Truncate to new width with signed saturation. | ||||||
1373 | /// | ||||||
1374 | /// If this APInt, treated as signed integer, can be losslessly truncated to | ||||||
1375 | /// the new bitwidth, then return truncated APInt. Else, return either | ||||||
1376 | /// signed min value if the APInt was negative, or signed max value. | ||||||
1377 | APInt truncSSat(unsigned width) const; | ||||||
1378 | |||||||
1379 | /// Sign extend to a new width. | ||||||
1380 | /// | ||||||
1381 | /// This operation sign extends the APInt to a new width. If the high order | ||||||
1382 | /// bit is set, the fill on the left will be done with 1 bits, otherwise zero. | ||||||
1383 | /// It is an error to specify a width that is less than or equal to the | ||||||
1384 | /// current width. | ||||||
1385 | APInt sext(unsigned width) const; | ||||||
1386 | |||||||
1387 | /// Zero extend to a new width. | ||||||
1388 | /// | ||||||
1389 | /// This operation zero extends the APInt to a new width. The high order bits | ||||||
1390 | /// are filled with 0 bits. It is an error to specify a width that is less | ||||||
1391 | /// than or equal to the current width. | ||||||
1392 | APInt zext(unsigned width) const; | ||||||
1393 | |||||||
1394 | /// Sign extend or truncate to width | ||||||
1395 | /// | ||||||
1396 | /// Make this APInt have the bit width given by \p width. The value is sign | ||||||
1397 | /// extended, truncated, or left alone to make it that width. | ||||||
1398 | APInt sextOrTrunc(unsigned width) const; | ||||||
1399 | |||||||
1400 | /// Zero extend or truncate to width | ||||||
1401 | /// | ||||||
1402 | /// Make this APInt have the bit width given by \p width. The value is zero | ||||||
1403 | /// extended, truncated, or left alone to make it that width. | ||||||
1404 | APInt zextOrTrunc(unsigned width) const; | ||||||
1405 | |||||||
1406 | /// Sign extend or truncate to width | ||||||
1407 | /// | ||||||
1408 | /// Make this APInt have the bit width given by \p width. The value is sign | ||||||
1409 | /// extended, or left alone to make it that width. | ||||||
1410 | APInt sextOrSelf(unsigned width) const; | ||||||
1411 | |||||||
1412 | /// Zero extend or truncate to width | ||||||
1413 | /// | ||||||
1414 | /// Make this APInt have the bit width given by \p width. The value is zero | ||||||
1415 | /// extended, or left alone to make it that width. | ||||||
1416 | APInt zextOrSelf(unsigned width) const; | ||||||
1417 | |||||||
1418 | /// @} | ||||||
1419 | /// \name Bit Manipulation Operators | ||||||
1420 | /// @{ | ||||||
1421 | |||||||
1422 | /// Set every bit to 1. | ||||||
1423 | void setAllBits() { | ||||||
1424 | if (isSingleWord()) | ||||||
1425 | U.VAL = WORDTYPE_MAX; | ||||||
1426 | else | ||||||
1427 | // Set all the bits in all the words. | ||||||
1428 | memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE); | ||||||
1429 | // Clear the unused ones | ||||||
1430 | clearUnusedBits(); | ||||||
1431 | } | ||||||
1432 | |||||||
1433 | /// Set a given bit to 1. | ||||||
1434 | /// | ||||||
1435 | /// Set the given bit to 1 whose position is given as "bitPosition". | ||||||
1436 | void setBit(unsigned BitPosition) { | ||||||
1437 | assert(BitPosition < BitWidth && "BitPosition out of range")((BitPosition < BitWidth && "BitPosition out of range" ) ? static_cast<void> (0) : __assert_fail ("BitPosition < BitWidth && \"BitPosition out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1437, __PRETTY_FUNCTION__)); | ||||||
1438 | WordType Mask = maskBit(BitPosition); | ||||||
1439 | if (isSingleWord()) | ||||||
1440 | U.VAL |= Mask; | ||||||
1441 | else | ||||||
1442 | U.pVal[whichWord(BitPosition)] |= Mask; | ||||||
1443 | } | ||||||
1444 | |||||||
1445 | /// Set the sign bit to 1. | ||||||
1446 | void setSignBit() { | ||||||
1447 | setBit(BitWidth - 1); | ||||||
1448 | } | ||||||
1449 | |||||||
1450 | /// Set a given bit to a given value. | ||||||
1451 | void setBitVal(unsigned BitPosition, bool BitValue) { | ||||||
1452 | if (BitValue) | ||||||
1453 | setBit(BitPosition); | ||||||
1454 | else | ||||||
1455 | clearBit(BitPosition); | ||||||
1456 | } | ||||||
1457 | |||||||
1458 | /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1. | ||||||
1459 | /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls | ||||||
1460 | /// setBits when \p loBit < \p hiBit. | ||||||
1461 | /// For \p loBit == \p hiBit wrap case, set every bit to 1. | ||||||
1462 | void setBitsWithWrap(unsigned loBit, unsigned hiBit) { | ||||||
1463 | assert(hiBit <= BitWidth && "hiBit out of range")((hiBit <= BitWidth && "hiBit out of range") ? static_cast <void> (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1463, __PRETTY_FUNCTION__)); | ||||||
1464 | assert(loBit <= BitWidth && "loBit out of range")((loBit <= BitWidth && "loBit out of range") ? static_cast <void> (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1464, __PRETTY_FUNCTION__)); | ||||||
1465 | if (loBit < hiBit) { | ||||||
1466 | setBits(loBit, hiBit); | ||||||
1467 | return; | ||||||
1468 | } | ||||||
1469 | setLowBits(hiBit); | ||||||
1470 | setHighBits(BitWidth - loBit); | ||||||
1471 | } | ||||||
1472 | |||||||
1473 | /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1. | ||||||
1474 | /// This function handles case when \p loBit <= \p hiBit. | ||||||
1475 | void setBits(unsigned loBit, unsigned hiBit) { | ||||||
1476 | assert(hiBit <= BitWidth && "hiBit out of range")((hiBit <= BitWidth && "hiBit out of range") ? static_cast <void> (0) : __assert_fail ("hiBit <= BitWidth && \"hiBit out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1476, __PRETTY_FUNCTION__)); | ||||||
1477 | assert(loBit <= BitWidth && "loBit out of range")((loBit <= BitWidth && "loBit out of range") ? static_cast <void> (0) : __assert_fail ("loBit <= BitWidth && \"loBit out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1477, __PRETTY_FUNCTION__)); | ||||||
1478 | assert(loBit <= hiBit && "loBit greater than hiBit")((loBit <= hiBit && "loBit greater than hiBit") ? static_cast <void> (0) : __assert_fail ("loBit <= hiBit && \"loBit greater than hiBit\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1478, __PRETTY_FUNCTION__)); | ||||||
1479 | if (loBit == hiBit) | ||||||
1480 | return; | ||||||
1481 | if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) { | ||||||
1482 | uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit)); | ||||||
1483 | mask <<= loBit; | ||||||
1484 | if (isSingleWord()) | ||||||
1485 | U.VAL |= mask; | ||||||
1486 | else | ||||||
1487 | U.pVal[0] |= mask; | ||||||
1488 | } else { | ||||||
1489 | setBitsSlowCase(loBit, hiBit); | ||||||
1490 | } | ||||||
1491 | } | ||||||
1492 | |||||||
1493 | /// Set the top bits starting from loBit. | ||||||
1494 | void setBitsFrom(unsigned loBit) { | ||||||
1495 | return setBits(loBit, BitWidth); | ||||||
1496 | } | ||||||
1497 | |||||||
1498 | /// Set the bottom loBits bits. | ||||||
1499 | void setLowBits(unsigned loBits) { | ||||||
1500 | return setBits(0, loBits); | ||||||
1501 | } | ||||||
1502 | |||||||
1503 | /// Set the top hiBits bits. | ||||||
1504 | void setHighBits(unsigned hiBits) { | ||||||
1505 | return setBits(BitWidth - hiBits, BitWidth); | ||||||
1506 | } | ||||||
1507 | |||||||
1508 | /// Set every bit to 0. | ||||||
1509 | void clearAllBits() { | ||||||
1510 | if (isSingleWord()) | ||||||
1511 | U.VAL = 0; | ||||||
1512 | else | ||||||
1513 | memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE); | ||||||
1514 | } | ||||||
1515 | |||||||
1516 | /// Set a given bit to 0. | ||||||
1517 | /// | ||||||
1518 | /// Set the given bit to 0 whose position is given as "bitPosition". | ||||||
1519 | void clearBit(unsigned BitPosition) { | ||||||
1520 | assert(BitPosition < BitWidth && "BitPosition out of range")((BitPosition < BitWidth && "BitPosition out of range" ) ? static_cast<void> (0) : __assert_fail ("BitPosition < BitWidth && \"BitPosition out of range\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1520, __PRETTY_FUNCTION__)); | ||||||
1521 | WordType Mask = ~maskBit(BitPosition); | ||||||
1522 | if (isSingleWord()) | ||||||
1523 | U.VAL &= Mask; | ||||||
1524 | else | ||||||
1525 | U.pVal[whichWord(BitPosition)] &= Mask; | ||||||
1526 | } | ||||||
1527 | |||||||
1528 | /// Set bottom loBits bits to 0. | ||||||
1529 | void clearLowBits(unsigned loBits) { | ||||||
1530 | assert(loBits <= BitWidth && "More bits than bitwidth")((loBits <= BitWidth && "More bits than bitwidth") ? static_cast<void> (0) : __assert_fail ("loBits <= BitWidth && \"More bits than bitwidth\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1530, __PRETTY_FUNCTION__)); | ||||||
1531 | APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits); | ||||||
1532 | *this &= Keep; | ||||||
1533 | } | ||||||
1534 | |||||||
1535 | /// Set the sign bit to 0. | ||||||
1536 | void clearSignBit() { | ||||||
1537 | clearBit(BitWidth - 1); | ||||||
1538 | } | ||||||
1539 | |||||||
1540 | /// Toggle every bit to its opposite value. | ||||||
1541 | void flipAllBits() { | ||||||
1542 | if (isSingleWord()) { | ||||||
1543 | U.VAL ^= WORDTYPE_MAX; | ||||||
1544 | clearUnusedBits(); | ||||||
1545 | } else { | ||||||
1546 | flipAllBitsSlowCase(); | ||||||
1547 | } | ||||||
1548 | } | ||||||
1549 | |||||||
1550 | /// Toggles a given bit to its opposite value. | ||||||
1551 | /// | ||||||
1552 | /// Toggle a given bit to its opposite value whose position is given | ||||||
1553 | /// as "bitPosition". | ||||||
1554 | void flipBit(unsigned bitPosition); | ||||||
1555 | |||||||
1556 | /// Negate this APInt in place. | ||||||
1557 | void negate() { | ||||||
1558 | flipAllBits(); | ||||||
1559 | ++(*this); | ||||||
1560 | } | ||||||
1561 | |||||||
1562 | /// Insert the bits from a smaller APInt starting at bitPosition. | ||||||
1563 | void insertBits(const APInt &SubBits, unsigned bitPosition); | ||||||
1564 | void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits); | ||||||
1565 | |||||||
1566 | /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits). | ||||||
1567 | APInt extractBits(unsigned numBits, unsigned bitPosition) const; | ||||||
1568 | uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const; | ||||||
1569 | |||||||
1570 | /// @} | ||||||
1571 | /// \name Value Characterization Functions | ||||||
1572 | /// @{ | ||||||
1573 | |||||||
1574 | /// Return the number of bits in the APInt. | ||||||
1575 | unsigned getBitWidth() const { return BitWidth; } | ||||||
1576 | |||||||
1577 | /// Get the number of words. | ||||||
1578 | /// | ||||||
1579 | /// Here one word's bitwidth equals to that of uint64_t. | ||||||
1580 | /// | ||||||
1581 | /// \returns the number of words to hold the integer value of this APInt. | ||||||
1582 | unsigned getNumWords() const { return getNumWords(BitWidth); } | ||||||
1583 | |||||||
1584 | /// Get the number of words. | ||||||
1585 | /// | ||||||
1586 | /// *NOTE* Here one word's bitwidth equals to that of uint64_t. | ||||||
1587 | /// | ||||||
1588 | /// \returns the number of words to hold the integer value with a given bit | ||||||
1589 | /// width. | ||||||
1590 | static unsigned getNumWords(unsigned BitWidth) { | ||||||
1591 | return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD; | ||||||
1592 | } | ||||||
1593 | |||||||
1594 | /// Compute the number of active bits in the value | ||||||
1595 | /// | ||||||
1596 | /// This function returns the number of active bits which is defined as the | ||||||
1597 | /// bit width minus the number of leading zeros. This is used in several | ||||||
1598 | /// computations to see how "wide" the value is. | ||||||
1599 | unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); } | ||||||
1600 | |||||||
1601 | /// Compute the number of active words in the value of this APInt. | ||||||
1602 | /// | ||||||
1603 | /// This is used in conjunction with getActiveData to extract the raw value of | ||||||
1604 | /// the APInt. | ||||||
1605 | unsigned getActiveWords() const { | ||||||
1606 | unsigned numActiveBits = getActiveBits(); | ||||||
1607 | return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1; | ||||||
1608 | } | ||||||
1609 | |||||||
1610 | /// Get the minimum bit size for this signed APInt | ||||||
1611 | /// | ||||||
1612 | /// Computes the minimum bit width for this APInt while considering it to be a | ||||||
1613 | /// signed (and probably negative) value. If the value is not negative, this | ||||||
1614 | /// function returns the same value as getActiveBits()+1. Otherwise, it | ||||||
1615 | /// returns the smallest bit width that will retain the negative value. For | ||||||
1616 | /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so | ||||||
1617 | /// for -1, this function will always return 1. | ||||||
1618 | unsigned getMinSignedBits() const { | ||||||
1619 | if (isNegative()) | ||||||
1620 | return BitWidth - countLeadingOnes() + 1; | ||||||
1621 | return getActiveBits() + 1; | ||||||
1622 | } | ||||||
1623 | |||||||
1624 | /// Get zero extended value | ||||||
1625 | /// | ||||||
1626 | /// This method attempts to return the value of this APInt as a zero extended | ||||||
1627 | /// uint64_t. The bitwidth must be <= 64 or the value must fit within a | ||||||
1628 | /// uint64_t. Otherwise an assertion will result. | ||||||
1629 | uint64_t getZExtValue() const { | ||||||
1630 | if (isSingleWord()) | ||||||
1631 | return U.VAL; | ||||||
1632 | assert(getActiveBits() <= 64 && "Too many bits for uint64_t")((getActiveBits() <= 64 && "Too many bits for uint64_t" ) ? static_cast<void> (0) : __assert_fail ("getActiveBits() <= 64 && \"Too many bits for uint64_t\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1632, __PRETTY_FUNCTION__)); | ||||||
1633 | return U.pVal[0]; | ||||||
1634 | } | ||||||
1635 | |||||||
1636 | /// Get sign extended value | ||||||
1637 | /// | ||||||
1638 | /// This method attempts to return the value of this APInt as a sign extended | ||||||
1639 | /// int64_t. The bit width must be <= 64 or the value must fit within an | ||||||
1640 | /// int64_t. Otherwise an assertion will result. | ||||||
1641 | int64_t getSExtValue() const { | ||||||
1642 | if (isSingleWord()) | ||||||
1643 | return SignExtend64(U.VAL, BitWidth); | ||||||
1644 | assert(getMinSignedBits() <= 64 && "Too many bits for int64_t")((getMinSignedBits() <= 64 && "Too many bits for int64_t" ) ? static_cast<void> (0) : __assert_fail ("getMinSignedBits() <= 64 && \"Too many bits for int64_t\"" , "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include/llvm/ADT/APInt.h" , 1644, __PRETTY_FUNCTION__)); | ||||||
1645 | return int64_t(U.pVal[0]); | ||||||
1646 | } | ||||||
1647 | |||||||
1648 | /// Get bits required for string value. | ||||||
1649 | /// | ||||||
1650 | /// This method determines how many bits are required to hold the APInt | ||||||
1651 | /// equivalent of the string given by \p str. | ||||||
1652 | static unsigned getBitsNeeded(StringRef str, uint8_t radix); | ||||||
1653 | |||||||
1654 | /// The APInt version of the countLeadingZeros functions in | ||||||
1655 | /// MathExtras.h. | ||||||
1656 | /// | ||||||
1657 | /// It counts the number of zeros from the most significant bit to the first | ||||||
1658 | /// one bit. | ||||||
1659 | /// | ||||||
1660 | /// \returns BitWidth if the value is zero, otherwise returns the number of | ||||||
1661 | /// zeros from the most significant bit to the first one bits. | ||||||
1662 | unsigned countLeadingZeros() const { | ||||||
1663 | if (isSingleWord()) { | ||||||
1664 | unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth; | ||||||
1665 | return llvm::countLeadingZeros(U.VAL) - unusedBits; | ||||||
1666 | } | ||||||
1667 | return countLeadingZerosSlowCase(); | ||||||
1668 | } | ||||||
1669 | |||||||
1670 | /// Count the number of leading one bits. | ||||||
1671 | /// | ||||||
1672 | /// This function is an APInt version of the countLeadingOnes | ||||||
1673 | /// functions in MathExtras.h. It counts the number of ones from the most | ||||||
1674 | /// significant bit to the first zero bit. | ||||||
1675 | /// | ||||||
1676 | /// \returns 0 if the high order bit is not set, otherwise returns the number | ||||||
1677 | /// of 1 bits from the most significant to the least | ||||||
1678 | unsigned countLeadingOnes() const { | ||||||
1679 | if (isSingleWord()) | ||||||
1680 | return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth)); | ||||||
1681 | return countLeadingOnesSlowCase(); | ||||||
1682 | } | ||||||
1683 | |||||||
1684 | /// Computes the number of leading bits of this APInt that are equal to its | ||||||
1685 | /// sign bit. | ||||||
1686 | unsigned getNumSignBits() const { | ||||||
1687 | return isNegative() ? countLeadingOnes() : countLeadingZeros(); | ||||||
1688 | } | ||||||
1689 | |||||||
1690 | /// Count the number of trailing zero bits. | ||||||
1691 | /// | ||||||
1692 | /// This function is an APInt version of the countTrailingZeros | ||||||
1693 | /// functions in MathExtras.h. It counts the number of zeros from the least | ||||||
1694 | /// significant bit to the first set bit. | ||||||
1695 | /// | ||||||
1696 | /// \returns BitWidth if the value is zero, otherwise returns the number of | ||||||
1697 | /// zeros from the least significant bit to the first one bit. | ||||||
1698 | unsigned countTrailingZeros() const { | ||||||
1699 | if (isSingleWord()) | ||||||
1700 | return std::min(unsigned(llvm::countTrailingZeros(U.VAL)), BitWidth); | ||||||
1701 | return countTrailingZerosSlowCase(); | ||||||
1702 | } | ||||||
1703 | |||||||
1704 | /// Count the number of trailing one bits. | ||||||
1705 | /// | ||||||
1706 | /// This function is an APInt version of the countTrailingOnes | ||||||
1707 | /// functions in MathExtras.h. It counts the number of ones from the least | ||||||
1708 | /// significant bit to the first zero bit. | ||||||
1709 | /// | ||||||
1710 | /// \returns BitWidth if the value is all ones, otherwise returns the number | ||||||
1711 | /// of ones from the least significant bit to the first zero bit. | ||||||
1712 | unsigned countTrailingOnes() const { | ||||||
1713 | if (isSingleWord()) | ||||||
1714 | return llvm::countTrailingOnes(U.VAL); | ||||||
1715 | return countTrailingOnesSlowCase(); | ||||||
1716 | } | ||||||
1717 | |||||||
1718 | /// Count the number of bits set. | ||||||
1719 | /// | ||||||
1720 | /// This function is an APInt version of the countPopulation functions | ||||||
1721 | /// in MathExtras.h. It counts the number of 1 bits in the APInt value. | ||||||
1722 | /// | ||||||
1723 | /// \returns 0 if the value is zero, otherwise returns the number of set bits. | ||||||
1724 | unsigned countPopulation() const { | ||||||
1725 | if (isSingleWord()) | ||||||
1726 | return llvm::countPopulation(U.VAL); | ||||||
1727 | return countPopulationSlowCase(); | ||||||
1728 | } | ||||||
1729 | |||||||
1730 | /// @} | ||||||
1731 | /// \name Conversion Functions | ||||||
1732 | /// @{ | ||||||
1733 | void print(raw_ostream &OS, bool isSigned) const; | ||||||
1734 | |||||||
1735 | /// Converts an APInt to a string and append it to Str. Str is commonly a | ||||||
1736 | /// SmallString. | ||||||
1737 | void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed, | ||||||
1738 | bool formatAsCLiteral = false) const; | ||||||
1739 | |||||||
1740 | /// Considers the APInt to be unsigned and converts it into a string in the | ||||||
1741 | /// radix given. The radix can be 2, 8, 10 16, or 36. | ||||||
1742 | void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { | ||||||
1743 | toString(Str, Radix, false, false); | ||||||
1744 | } | ||||||
1745 | |||||||
1746 | /// Considers the APInt to be signed and converts it into a string in the | ||||||
1747 | /// radix given. The radix can be 2, 8, 10, 16, or 36. | ||||||
1748 | void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const { | ||||||
1749 | toString(Str, Radix, true, false); | ||||||
1750 | } | ||||||
1751 | |||||||
1752 | /// Return the APInt as a std::string. | ||||||
1753 | /// | ||||||
1754 | /// Note that this is an inefficient method. It is better to pass in a | ||||||
1755 | /// SmallVector/SmallString to the methods above to avoid thrashing the heap | ||||||
1756 | /// for the string. | ||||||
1757 | std::string toString(unsigned Radix, bool Signed) const; | ||||||
1758 | |||||||
1759 | /// \returns a byte-swapped representation of this APInt Value. | ||||||
1760 | APInt byteSwap() const; | ||||||
1761 | |||||||
1762 | /// \returns the value with the bit representation reversed of this APInt | ||||||
1763 | /// Value. | ||||||
1764 | APInt reverseBits() const; | ||||||
1765 | |||||||
1766 | /// Converts this APInt to a double value. | ||||||
1767 | double roundToDouble(bool isSigned) const; | ||||||
1768 | |||||||
1769 | /// Converts this unsigned APInt to a double value. | ||||||
1770 | double roundToDouble() const { return roundToDouble(false); } | ||||||
1771 | |||||||
1772 | /// Converts this signed APInt to a double value. | ||||||
1773 | double signedRoundToDouble() const { return roundToDouble(true); } | ||||||
1774 | |||||||
1775 | /// Converts APInt bits to a double | ||||||
1776 | /// | ||||||
1777 | /// The conversion does not do a translation from integer to double, it just | ||||||
1778 | /// re-interprets the bits as a double. Note that it is valid to do this on | ||||||
1779 | /// any bit width. Exactly 64 bits will be translated. | ||||||
1780 | double bitsToDouble() const { | ||||||
1781 | return BitsToDouble(getWord(0)); | ||||||
1782 | } | ||||||
1783 | |||||||
1784 | /// Converts APInt bits to a float | ||||||
1785 | /// | ||||||
1786 | /// The conversion does not do a translation from integer to float, it just | ||||||
1787 | /// re-interprets the bits as a float. Note that it is valid to do this on | ||||||
1788 | /// any bit width. Exactly 32 bits will be translated. | ||||||
1789 | float bitsToFloat() const { | ||||||
1790 | return BitsToFloat(static_cast<uint32_t>(getWord(0))); | ||||||
1791 | } | ||||||
1792 | |||||||
1793 | /// Converts a double to APInt bits. | ||||||
1794 | /// | ||||||
1795 | /// The conversion does not do a translation from double to integer, it just | ||||||
1796 | /// re-interprets the bits of the double. | ||||||
1797 | static APInt doubleToBits(double V) { | ||||||
1798 | return APInt(sizeof(double) * CHAR_BIT8, DoubleToBits(V)); | ||||||
1799 | } | ||||||
1800 | |||||||
1801 | /// Converts a float to APInt bits. | ||||||
1802 | /// | ||||||
1803 | /// The conversion does not do a translation from float to integer, it just | ||||||
1804 | /// re-interprets the bits of the float. | ||||||
1805 | static APInt floatToBits(float V) { | ||||||
1806 | return APInt(sizeof(float) * CHAR_BIT8, FloatToBits(V)); | ||||||
1807 | } | ||||||
1808 | |||||||
1809 | /// @} | ||||||
1810 | /// \name Mathematics Operations | ||||||
1811 | /// @{ | ||||||
1812 | |||||||
1813 | /// \returns the floor log base 2 of this APInt. | ||||||
1814 | unsigned logBase2() const { return getActiveBits() - 1; } | ||||||
1815 | |||||||
1816 | /// \returns the ceil log base 2 of this APInt. | ||||||
1817 | unsigned ceilLogBase2() const { | ||||||
1818 | APInt temp(*this); | ||||||
1819 | --temp; | ||||||
1820 | return temp.getActiveBits(); | ||||||
1821 | } | ||||||
1822 | |||||||
1823 | /// \returns the nearest log base 2 of this APInt. Ties round up. | ||||||
1824 | /// | ||||||
1825 | /// NOTE: When we have a BitWidth of 1, we define: | ||||||
1826 | /// | ||||||
1827 | /// log2(0) = UINT32_MAX | ||||||
1828 | /// log2(1) = 0 | ||||||
1829 | /// | ||||||
1830 | /// to get around any mathematical concerns resulting from | ||||||
1831 | /// referencing 2 in a space where 2 does no exist. | ||||||
1832 | unsigned nearestLogBase2() const { | ||||||
1833 | // Special case when we have a bitwidth of 1. If VAL is 1, then we | ||||||
1834 | // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to | ||||||
1835 | // UINT32_MAX. | ||||||
1836 | if (BitWidth == 1) | ||||||
1837 | return U.VAL - 1; | ||||||
1838 | |||||||
1839 | // Handle the zero case. | ||||||
1840 | if (isNullValue()) | ||||||
1841 | return UINT32_MAX(4294967295U); | ||||||
1842 | |||||||
1843 | // The non-zero case is handled by computing: | ||||||
1844 | // | ||||||
1845 | // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1]. | ||||||
1846 | // | ||||||
1847 | // where x[i] is referring to the value of the ith bit of x. | ||||||
1848 | unsigned lg = logBase2(); | ||||||
1849 | return lg + unsigned((*this)[lg - 1]); | ||||||
1850 | } | ||||||
1851 | |||||||
1852 | /// \returns the log base 2 of this APInt if its an exact power of two, -1 | ||||||
1853 | /// otherwise | ||||||
1854 | int32_t exactLogBase2() const { | ||||||
1855 | if (!isPowerOf2()) | ||||||
1856 | return -1; | ||||||
1857 | return logBase2(); | ||||||
1858 | } | ||||||
1859 | |||||||
1860 | /// Compute the square root | ||||||
1861 | APInt sqrt() const; | ||||||
1862 | |||||||
1863 | /// Get the absolute value; | ||||||
1864 | /// | ||||||
1865 | /// If *this is < 0 then return -(*this), otherwise *this; | ||||||
1866 | APInt abs() const { | ||||||
1867 | if (isNegative()) | ||||||
1868 | return -(*this); | ||||||
1869 | return *this; | ||||||
1870 | } | ||||||
1871 | |||||||
1872 | /// \returns the multiplicative inverse for a given modulo. | ||||||
1873 | APInt multiplicativeInverse(const APInt &modulo) const; | ||||||
1874 | |||||||
1875 | /// @} | ||||||
1876 | /// \name Support for division by constant | ||||||
1877 | /// @{ | ||||||
1878 | |||||||
1879 | /// Calculate the magic number for signed division by a constant. | ||||||
1880 | struct ms; | ||||||
1881 | ms magic() const; | ||||||
1882 | |||||||
1883 | /// Calculate the magic number for unsigned division by a constant. | ||||||
1884 | struct mu; | ||||||
1885 | mu magicu(unsigned LeadingZeros = 0) const; | ||||||
1886 | |||||||
1887 | /// @} | ||||||
1888 | /// \name Building-block Operations for APInt and APFloat | ||||||
1889 | /// @{ | ||||||
1890 | |||||||
1891 | // These building block operations operate on a representation of arbitrary | ||||||
1892 | // precision, two's-complement, bignum integer values. They should be | ||||||
1893 | // sufficient to implement APInt and APFloat bignum requirements. Inputs are | ||||||
1894 | // generally a pointer to the base of an array of integer parts, representing | ||||||
1895 | // an unsigned bignum, and a count of how many parts there are. | ||||||
1896 | |||||||
1897 | /// Sets the least significant part of a bignum to the input value, and zeroes | ||||||
1898 | /// out higher parts. | ||||||
1899 | static void tcSet(WordType *, WordType, unsigned); | ||||||
1900 | |||||||
1901 | /// Assign one bignum to another. | ||||||
1902 | static void tcAssign(WordType *, const WordType *, unsigned); | ||||||
1903 | |||||||
1904 | /// Returns true if a bignum is zero, false otherwise. | ||||||
1905 | static bool tcIsZero(const WordType *, unsigned); | ||||||
1906 | |||||||
1907 | /// Extract the given bit of a bignum; returns 0 or 1. Zero-based. | ||||||
1908 | static int tcExtractBit(const WordType *, unsigned bit); | ||||||
1909 | |||||||
1910 | /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to | ||||||
1911 | /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least | ||||||
1912 | /// significant bit of DST. All high bits above srcBITS in DST are | ||||||
1913 | /// zero-filled. | ||||||
1914 | static void tcExtract(WordType *, unsigned dstCount, | ||||||
1915 | const WordType *, unsigned srcBits, | ||||||
1916 | unsigned srcLSB); | ||||||
1917 | |||||||
1918 | /// Set the given bit of a bignum. Zero-based. | ||||||
1919 | static void tcSetBit(WordType *, unsigned bit); | ||||||
1920 | |||||||
1921 | /// Clear the given bit of a bignum. Zero-based. | ||||||
1922 | static void tcClearBit(WordType *, unsigned bit); | ||||||
1923 | |||||||
1924 | /// Returns the bit number of the least or most significant set bit of a | ||||||
1925 | /// number. If the input number has no bits set -1U is returned. | ||||||
1926 | static unsigned tcLSB(const WordType *, unsigned n); | ||||||
1927 | static unsigned tcMSB(const WordType *parts, unsigned n); | ||||||
1928 | |||||||
1929 | /// Negate a bignum in-place. | ||||||
1930 | static void tcNegate(WordType *, unsigned); | ||||||
1931 | |||||||
1932 | /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag. | ||||||
1933 | static WordType tcAdd(WordType *, const WordType *, | ||||||
1934 | WordType carry, unsigned); | ||||||
1935 | /// DST += RHS. Returns the carry flag. | ||||||
1936 | static WordType tcAddPart(WordType *, WordType, unsigned); | ||||||
1937 | |||||||
1938 | /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag. | ||||||
1939 | static WordType tcSubtract(WordType *, const WordType *, | ||||||
1940 | WordType carry, unsigned); | ||||||
1941 | /// DST -= RHS. Returns the carry flag. | ||||||
1942 | static WordType tcSubtractPart(WordType *, WordType, unsigned); | ||||||
1943 | |||||||
1944 | /// DST += SRC * MULTIPLIER + PART if add is true | ||||||
1945 | /// DST = SRC * MULTIPLIER + PART if add is false | ||||||
1946 | /// | ||||||
1947 | /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must | ||||||
1948 | /// start at the same point, i.e. DST == SRC. | ||||||
1949 | /// | ||||||
1950 | /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned. | ||||||
1951 | /// Otherwise DST is filled with the least significant DSTPARTS parts of the | ||||||
1952 | /// result, and if all of the omitted higher parts were zero return zero, | ||||||
1953 | /// otherwise overflow occurred and return one. | ||||||
1954 | static int tcMultiplyPart(WordType *dst, const WordType *src, | ||||||
1955 | WordType multiplier, WordType carry, | ||||||
1956 | unsigned srcParts, unsigned dstParts, | ||||||
1957 | bool add); | ||||||
1958 | |||||||
1959 | /// DST = LHS * RHS, where DST has the same width as the operands and is | ||||||
1960 | /// filled with the least significant parts of the result. Returns one if | ||||||
1961 | /// overflow occurred, otherwise zero. DST must be disjoint from both | ||||||
1962 | /// operands. | ||||||
1963 | static int tcMultiply(WordType *, const WordType *, const WordType *, | ||||||
1964 | unsigned); | ||||||
1965 | |||||||
1966 | /// DST = LHS * RHS, where DST has width the sum of the widths of the | ||||||
1967 | /// operands. No overflow occurs. DST must be disjoint from both operands. | ||||||
1968 | static void tcFullMultiply(WordType *, const WordType *, | ||||||
1969 | const WordType *, unsigned, unsigned); | ||||||
1970 | |||||||
1971 | /// If RHS is zero LHS and REMAINDER are left unchanged, return one. | ||||||
1972 | /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set | ||||||
1973 | /// REMAINDER to the remainder, return zero. i.e. | ||||||
1974 | /// | ||||||
1975 | /// OLD_LHS = RHS * LHS + REMAINDER | ||||||
1976 | /// | ||||||
1977 | /// SCRATCH is a bignum of the same size as the operands and result for use by | ||||||
1978 | /// the routine; its contents need not be initialized and are destroyed. LHS, | ||||||
1979 | /// REMAINDER and SCRATCH must be distinct. | ||||||
1980 | static int tcDivide(WordType *lhs, const WordType *rhs, | ||||||
1981 | WordType *remainder, WordType *scratch, | ||||||
1982 | unsigned parts); | ||||||
1983 | |||||||
1984 | /// Shift a bignum left Count bits. Shifted in bits are zero. There are no | ||||||
1985 | /// restrictions on Count. | ||||||
1986 | static void tcShiftLeft(WordType *, unsigned Words, unsigned Count); | ||||||
1987 | |||||||
1988 | /// Shift a bignum right Count bits. Shifted in bits are zero. There are no | ||||||
1989 | /// restrictions on Count. | ||||||
1990 | static void tcShiftRight(WordType *, unsigned Words, unsigned Count); | ||||||
1991 | |||||||
1992 | /// The obvious AND, OR and XOR and complement operations. | ||||||
1993 | static void tcAnd(WordType *, const WordType *, unsigned); | ||||||
1994 | static void tcOr(WordType *, const WordType *, unsigned); | ||||||
1995 | static void tcXor(WordType *, const WordType *, unsigned); | ||||||
1996 | static void tcComplement(WordType *, unsigned); | ||||||
1997 | |||||||
1998 | /// Comparison (unsigned) of two bignums. | ||||||
1999 | static int tcCompare(const WordType *, const WordType *, unsigned); | ||||||
2000 | |||||||
2001 | /// Increment a bignum in-place. Return the carry flag. | ||||||
2002 | static WordType tcIncrement(WordType *dst, unsigned parts) { | ||||||
2003 | return tcAddPart(dst, 1, parts); | ||||||
2004 | } | ||||||
2005 | |||||||
2006 | /// Decrement a bignum in-place. Return the borrow flag. | ||||||
2007 | static WordType tcDecrement(WordType *dst, unsigned parts) { | ||||||
2008 | return tcSubtractPart(dst, 1, parts); | ||||||
2009 | } | ||||||
2010 | |||||||
2011 | /// Set the least significant BITS and clear the rest. | ||||||
2012 | static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits); | ||||||
2013 | |||||||
2014 | /// debug method | ||||||
2015 | void dump() const; | ||||||
2016 | |||||||
2017 | /// @} | ||||||
2018 | }; | ||||||
2019 | |||||||
2020 | /// Magic data for optimising signed division by a constant. | ||||||
2021 | struct APInt::ms { | ||||||
2022 | APInt m; ///< magic number | ||||||
2023 | unsigned s; ///< shift amount | ||||||
2024 | }; | ||||||
2025 | |||||||
2026 | /// Magic data for optimising unsigned division by a constant. | ||||||
2027 | struct APInt::mu { | ||||||
2028 | APInt m; ///< magic number | ||||||
2029 | bool a; ///< add indicator | ||||||
2030 | unsigned s; ///< shift amount | ||||||
2031 | }; | ||||||
2032 | |||||||
2033 | inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; } | ||||||
2034 | |||||||
2035 | inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; } | ||||||
2036 | |||||||
2037 | /// Unary bitwise complement operator. | ||||||
2038 | /// | ||||||
2039 | /// \returns an APInt that is the bitwise complement of \p v. | ||||||
2040 | inline APInt operator~(APInt v) { | ||||||
2041 | v.flipAllBits(); | ||||||
2042 | return v; | ||||||
2043 | } | ||||||
2044 | |||||||
2045 | inline APInt operator&(APInt a, const APInt &b) { | ||||||
2046 | a &= b; | ||||||
2047 | return a; | ||||||
2048 | } | ||||||
2049 | |||||||
2050 | inline APInt operator&(const APInt &a, APInt &&b) { | ||||||
2051 | b &= a; | ||||||
2052 | return std::move(b); | ||||||
2053 | } | ||||||
2054 | |||||||
2055 | inline APInt operator&(APInt a, uint64_t RHS) { | ||||||
2056 | a &= RHS; | ||||||
2057 | return a; | ||||||
2058 | } | ||||||
2059 | |||||||
2060 | inline APInt operator&(uint64_t LHS, APInt b) { | ||||||
2061 | b &= LHS; | ||||||
2062 | return b; | ||||||
2063 | } | ||||||
2064 | |||||||
2065 | inline APInt operator|(APInt a, const APInt &b) { | ||||||
2066 | a |= b; | ||||||
2067 | return a; | ||||||
2068 | } | ||||||
2069 | |||||||
2070 | inline APInt operator|(const APInt &a, APInt &&b) { | ||||||
2071 | b |= a; | ||||||
2072 | return std::move(b); | ||||||
2073 | } | ||||||
2074 | |||||||
2075 | inline APInt operator|(APInt a, uint64_t RHS) { | ||||||
2076 | a |= RHS; | ||||||
2077 | return a; | ||||||
2078 | } | ||||||
2079 | |||||||
2080 | inline APInt operator|(uint64_t LHS, APInt b) { | ||||||
2081 | b |= LHS; | ||||||
2082 | return b; | ||||||
2083 | } | ||||||
2084 | |||||||
2085 | inline APInt operator^(APInt a, const APInt &b) { | ||||||
2086 | a ^= b; | ||||||
2087 | return a; | ||||||
2088 | } | ||||||
2089 | |||||||
2090 | inline APInt operator^(const APInt &a, APInt &&b) { | ||||||
2091 | b ^= a; | ||||||
2092 | return std::move(b); | ||||||
2093 | } | ||||||
2094 | |||||||
2095 | inline APInt operator^(APInt a, uint64_t RHS) { | ||||||
2096 | a ^= RHS; | ||||||
2097 | return a; | ||||||
2098 | } | ||||||
2099 | |||||||
2100 | inline APInt operator^(uint64_t LHS, APInt b) { | ||||||
2101 | b ^= LHS; | ||||||
2102 | return b; | ||||||
2103 | } | ||||||
2104 | |||||||
2105 | inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) { | ||||||
2106 | I.print(OS, true); | ||||||
2107 | return OS; | ||||||
2108 | } | ||||||
2109 | |||||||
2110 | inline APInt operator-(APInt v) { | ||||||
2111 | v.negate(); | ||||||
2112 | return v; | ||||||
2113 | } | ||||||
2114 | |||||||
2115 | inline APInt operator+(APInt a, const APInt &b) { | ||||||
2116 | a += b; | ||||||
2117 | return a; | ||||||
2118 | } | ||||||
2119 | |||||||
2120 | inline APInt operator+(const APInt &a, APInt &&b) { | ||||||
2121 | b += a; | ||||||
2122 | return std::move(b); | ||||||
2123 | } | ||||||
2124 | |||||||
2125 | inline APInt operator+(APInt a, uint64_t RHS) { | ||||||
2126 | a += RHS; | ||||||
2127 | return a; | ||||||
2128 | } | ||||||
2129 | |||||||
2130 | inline APInt operator+(uint64_t LHS, APInt b) { | ||||||
2131 | b += LHS; | ||||||
2132 | return b; | ||||||
2133 | } | ||||||
2134 | |||||||
2135 | inline APInt operator-(APInt a, const APInt &b) { | ||||||
2136 | a -= b; | ||||||
2137 | return a; | ||||||
2138 | } | ||||||
2139 | |||||||
2140 | inline APInt operator-(const APInt &a, APInt &&b) { | ||||||
2141 | b.negate(); | ||||||
2142 | b += a; | ||||||
2143 | return std::move(b); | ||||||
2144 | } | ||||||
2145 | |||||||
2146 | inline APInt operator-(APInt a, uint64_t RHS) { | ||||||
2147 | a -= RHS; | ||||||
2148 | return a; | ||||||
2149 | } | ||||||
2150 | |||||||
2151 | inline APInt operator-(uint64_t LHS, APInt b) { | ||||||
2152 | b.negate(); | ||||||
2153 | b += LHS; | ||||||
2154 | return b; | ||||||
2155 | } | ||||||
2156 | |||||||
2157 | inline APInt operator*(APInt a, uint64_t RHS) { | ||||||
2158 | a *= RHS; | ||||||
2159 | return a; | ||||||
2160 | } | ||||||
2161 | |||||||
2162 | inline APInt operator*(uint64_t LHS, APInt b) { | ||||||
2163 | b *= LHS; | ||||||
2164 | return b; | ||||||
2165 | } | ||||||
2166 | |||||||
2167 | |||||||
2168 | namespace APIntOps { | ||||||
2169 | |||||||
2170 | /// Determine the smaller of two APInts considered to be signed. | ||||||
2171 | inline const APInt &smin(const APInt &A, const APInt &B) { | ||||||
2172 | return A.slt(B) ? A : B; | ||||||
2173 | } | ||||||
2174 | |||||||
2175 | /// Determine the larger of two APInts considered to be signed. | ||||||
2176 | inline const APInt &smax(const APInt &A, const APInt &B) { | ||||||
2177 | return A.sgt(B) ? A : B; | ||||||
2178 | } | ||||||
2179 | |||||||
2180 | /// Determine the smaller of two APInts considered to be signed. | ||||||
2181 | inline const APInt &umin(const APInt &A, const APInt &B) { | ||||||
2182 | return A.ult(B) ? A : B; | ||||||
2183 | } | ||||||
2184 | |||||||
2185 | /// Determine the larger of two APInts considered to be unsigned. | ||||||
2186 | inline const APInt &umax(const APInt &A, const APInt &B) { | ||||||
2187 | return A.ugt(B) ? A : B; | ||||||
2188 | } | ||||||
2189 | |||||||
2190 | /// Compute GCD of two unsigned APInt values. | ||||||
2191 | /// | ||||||
2192 | /// This function returns the greatest common divisor of the two APInt values | ||||||
2193 | /// using Stein's algorithm. | ||||||
2194 | /// | ||||||
2195 | /// \returns the greatest common divisor of A and B. | ||||||
2196 | APInt GreatestCommonDivisor(APInt A, APInt B); | ||||||
2197 | |||||||
2198 | /// Converts the given APInt to a double value. | ||||||
2199 | /// | ||||||
2200 | /// Treats the APInt as an unsigned value for conversion purposes. | ||||||
2201 | inline double RoundAPIntToDouble(const APInt &APIVal) { | ||||||
2202 | return APIVal.roundToDouble(); | ||||||
2203 | } | ||||||
2204 | |||||||
2205 | /// Converts the given APInt to a double value. | ||||||
2206 | /// | ||||||
2207 | /// Treats the APInt as a signed value for conversion purposes. | ||||||
2208 | inline double RoundSignedAPIntToDouble(const APInt &APIVal) { | ||||||
2209 | return APIVal.signedRoundToDouble(); | ||||||
2210 | } | ||||||
2211 | |||||||
2212 | /// Converts the given APInt to a float vlalue. | ||||||
2213 | inline float RoundAPIntToFloat(const APInt &APIVal) { | ||||||
2214 | return float(RoundAPIntToDouble(APIVal)); | ||||||
2215 | } | ||||||
2216 | |||||||
2217 | /// Converts the given APInt to a float value. | ||||||
2218 | /// | ||||||
2219 | /// Treats the APInt as a signed value for conversion purposes. | ||||||
2220 | inline float RoundSignedAPIntToFloat(const APInt &APIVal) { | ||||||
2221 | return float(APIVal.signedRoundToDouble()); | ||||||
2222 | } | ||||||
2223 | |||||||
2224 | /// Converts the given double value into a APInt. | ||||||
2225 | /// | ||||||
2226 | /// This function convert a double value to an APInt value. | ||||||
2227 | APInt RoundDoubleToAPInt(double Double, unsigned width); | ||||||
2228 | |||||||
2229 | /// Converts a float value into a APInt. | ||||||
2230 | /// | ||||||
2231 | /// Converts a float value into an APInt value. | ||||||
2232 | inline APInt RoundFloatToAPInt(float Float, unsigned width) { | ||||||
2233 | return RoundDoubleToAPInt(double(Float), width); | ||||||
2234 | } | ||||||
2235 | |||||||
2236 | /// Return A unsign-divided by B, rounded by the given rounding mode. | ||||||
2237 | APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM); | ||||||
2238 | |||||||
2239 | /// Return A sign-divided by B, rounded by the given rounding mode. | ||||||
2240 | APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM); | ||||||
2241 | |||||||
2242 | /// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range | ||||||
2243 | /// (e.g. 32 for i32). | ||||||
2244 | /// This function finds the smallest number n, such that | ||||||
2245 | /// (a) n >= 0 and q(n) = 0, or | ||||||
2246 | /// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all | ||||||
2247 | /// integers, belong to two different intervals [Rk, Rk+R), | ||||||
2248 | /// where R = 2^BW, and k is an integer. | ||||||
2249 | /// The idea here is to find when q(n) "overflows" 2^BW, while at the | ||||||
2250 | /// same time "allowing" subtraction. In unsigned modulo arithmetic a | ||||||
2251 | /// subtraction (treated as addition of negated numbers) would always | ||||||
2252 | /// count as an overflow, but here we want to allow values to decrease | ||||||
2253 | /// and increase as long as they are within the same interval. | ||||||
2254 | /// Specifically, adding of two negative numbers should not cause an | ||||||
2255 | /// overflow (as long as the magnitude does not exceed the bit width). | ||||||
2256 | /// On the other hand, given a positive number, adding a negative | ||||||
2257 | /// number to it can give a negative result, which would cause the | ||||||
2258 | /// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is | ||||||
2259 | /// treated as a special case of an overflow. | ||||||
2260 | /// | ||||||
2261 | /// This function returns None if after finding k that minimizes the | ||||||
2262 | /// positive solution to q(n) = kR, both solutions are contained between | ||||||
2263 | /// two consecutive integers. | ||||||
2264 | /// | ||||||
2265 | /// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation | ||||||
2266 | /// in arithmetic modulo 2^BW, and treating the values as signed) by the | ||||||
2267 | /// virtue of *signed* overflow. This function will *not* find such an n, | ||||||
2268 | /// however it may find a value of n satisfying the inequalities due to | ||||||
2269 | /// an *unsigned* overflow (if the values are treated as unsigned). | ||||||
2270 | /// To find a solution for a signed overflow, treat it as a problem of | ||||||
2271 | /// finding an unsigned overflow with a range with of BW-1. | ||||||
2272 | /// | ||||||
2273 | /// The returned value may have a different bit width from the input | ||||||
2274 | /// coefficients. | ||||||
2275 | Optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C, | ||||||
2276 | unsigned RangeWidth); | ||||||
2277 | |||||||
2278 | /// Compare two values, and if they are different, return the position of the | ||||||
2279 | /// most significant bit that is different in the values. | ||||||
2280 | Optional<unsigned> GetMostSignificantDifferentBit(const APInt &A, | ||||||
2281 | const APInt &B); | ||||||
2282 | |||||||
2283 | } // End of APIntOps namespace | ||||||
2284 | |||||||
2285 | // See friend declaration above. This additional declaration is required in | ||||||
2286 | // order to compile LLVM with IBM xlC compiler. | ||||||
2287 | hash_code hash_value(const APInt &Arg); | ||||||
2288 | |||||||
2289 | /// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst | ||||||
2290 | /// with the integer held in IntVal. | ||||||
2291 | void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes); | ||||||
2292 | |||||||
2293 | /// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting | ||||||
2294 | /// from Src into IntVal, which is assumed to be wide enough and to hold zero. | ||||||
2295 | void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes); | ||||||
2296 | |||||||
2297 | } // namespace llvm | ||||||
2298 | |||||||
2299 | #endif |