Bug Summary

File:llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp
Warning:line 1458, column 28
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MemCpyOptimizer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/lib/Transforms/Scalar -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/lib/Transforms/Scalar -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-14-063029-18377-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp

1//===- MemCpyOptimizer.cpp - Optimize use of memcpy and friends -----------===//
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 pass performs various transformations related to eliminating memcpy
10// calls, or transforming sets of stores into memset's.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
15#include "llvm/ADT/DenseSet.h"
16#include "llvm/ADT/None.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/ADT/iterator_range.h"
21#include "llvm/Analysis/AliasAnalysis.h"
22#include "llvm/Analysis/AssumptionCache.h"
23#include "llvm/Analysis/GlobalsModRef.h"
24#include "llvm/Analysis/Loads.h"
25#include "llvm/Analysis/MemoryDependenceAnalysis.h"
26#include "llvm/Analysis/MemoryLocation.h"
27#include "llvm/Analysis/MemorySSA.h"
28#include "llvm/Analysis/MemorySSAUpdater.h"
29#include "llvm/Analysis/TargetLibraryInfo.h"
30#include "llvm/Analysis/ValueTracking.h"
31#include "llvm/IR/Argument.h"
32#include "llvm/IR/BasicBlock.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/DerivedTypes.h"
36#include "llvm/IR/Dominators.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/GetElementPtrTypeIterator.h"
39#include "llvm/IR/GlobalVariable.h"
40#include "llvm/IR/IRBuilder.h"
41#include "llvm/IR/InstrTypes.h"
42#include "llvm/IR/Instruction.h"
43#include "llvm/IR/Instructions.h"
44#include "llvm/IR/IntrinsicInst.h"
45#include "llvm/IR/Intrinsics.h"
46#include "llvm/IR/LLVMContext.h"
47#include "llvm/IR/Module.h"
48#include "llvm/IR/Operator.h"
49#include "llvm/IR/PassManager.h"
50#include "llvm/IR/Type.h"
51#include "llvm/IR/User.h"
52#include "llvm/IR/Value.h"
53#include "llvm/InitializePasses.h"
54#include "llvm/Pass.h"
55#include "llvm/Support/Casting.h"
56#include "llvm/Support/Debug.h"
57#include "llvm/Support/MathExtras.h"
58#include "llvm/Support/raw_ostream.h"
59#include "llvm/Transforms/Scalar.h"
60#include "llvm/Transforms/Utils/Local.h"
61#include <algorithm>
62#include <cassert>
63#include <cstdint>
64#include <utility>
65
66using namespace llvm;
67
68#define DEBUG_TYPE"memcpyopt" "memcpyopt"
69
70static cl::opt<bool>
71 EnableMemorySSA("enable-memcpyopt-memoryssa", cl::init(true), cl::Hidden,
72 cl::desc("Use MemorySSA-backed MemCpyOpt."));
73
74STATISTIC(NumMemCpyInstr, "Number of memcpy instructions deleted")static llvm::Statistic NumMemCpyInstr = {"memcpyopt", "NumMemCpyInstr"
, "Number of memcpy instructions deleted"}
;
75STATISTIC(NumMemSetInfer, "Number of memsets inferred")static llvm::Statistic NumMemSetInfer = {"memcpyopt", "NumMemSetInfer"
, "Number of memsets inferred"}
;
76STATISTIC(NumMoveToCpy, "Number of memmoves converted to memcpy")static llvm::Statistic NumMoveToCpy = {"memcpyopt", "NumMoveToCpy"
, "Number of memmoves converted to memcpy"}
;
77STATISTIC(NumCpyToSet, "Number of memcpys converted to memset")static llvm::Statistic NumCpyToSet = {"memcpyopt", "NumCpyToSet"
, "Number of memcpys converted to memset"}
;
78STATISTIC(NumCallSlot, "Number of call slot optimizations performed")static llvm::Statistic NumCallSlot = {"memcpyopt", "NumCallSlot"
, "Number of call slot optimizations performed"}
;
79
80namespace {
81
82/// Represents a range of memset'd bytes with the ByteVal value.
83/// This allows us to analyze stores like:
84/// store 0 -> P+1
85/// store 0 -> P+0
86/// store 0 -> P+3
87/// store 0 -> P+2
88/// which sometimes happens with stores to arrays of structs etc. When we see
89/// the first store, we make a range [1, 2). The second store extends the range
90/// to [0, 2). The third makes a new range [2, 3). The fourth store joins the
91/// two ranges into [0, 3) which is memset'able.
92struct MemsetRange {
93 // Start/End - A semi range that describes the span that this range covers.
94 // The range is closed at the start and open at the end: [Start, End).
95 int64_t Start, End;
96
97 /// StartPtr - The getelementptr instruction that points to the start of the
98 /// range.
99 Value *StartPtr;
100
101 /// Alignment - The known alignment of the first store.
102 unsigned Alignment;
103
104 /// TheStores - The actual stores that make up this range.
105 SmallVector<Instruction*, 16> TheStores;
106
107 bool isProfitableToUseMemset(const DataLayout &DL) const;
108};
109
110} // end anonymous namespace
111
112bool MemsetRange::isProfitableToUseMemset(const DataLayout &DL) const {
113 // If we found more than 4 stores to merge or 16 bytes, use memset.
114 if (TheStores.size() >= 4 || End-Start >= 16) return true;
115
116 // If there is nothing to merge, don't do anything.
117 if (TheStores.size() < 2) return false;
118
119 // If any of the stores are a memset, then it is always good to extend the
120 // memset.
121 for (Instruction *SI : TheStores)
122 if (!isa<StoreInst>(SI))
123 return true;
124
125 // Assume that the code generator is capable of merging pairs of stores
126 // together if it wants to.
127 if (TheStores.size() == 2) return false;
128
129 // If we have fewer than 8 stores, it can still be worthwhile to do this.
130 // For example, merging 4 i8 stores into an i32 store is useful almost always.
131 // However, merging 2 32-bit stores isn't useful on a 32-bit architecture (the
132 // memset will be split into 2 32-bit stores anyway) and doing so can
133 // pessimize the llvm optimizer.
134 //
135 // Since we don't have perfect knowledge here, make some assumptions: assume
136 // the maximum GPR width is the same size as the largest legal integer
137 // size. If so, check to see whether we will end up actually reducing the
138 // number of stores used.
139 unsigned Bytes = unsigned(End-Start);
140 unsigned MaxIntSize = DL.getLargestLegalIntTypeSizeInBits() / 8;
141 if (MaxIntSize == 0)
142 MaxIntSize = 1;
143 unsigned NumPointerStores = Bytes / MaxIntSize;
144
145 // Assume the remaining bytes if any are done a byte at a time.
146 unsigned NumByteStores = Bytes % MaxIntSize;
147
148 // If we will reduce the # stores (according to this heuristic), do the
149 // transformation. This encourages merging 4 x i8 -> i32 and 2 x i16 -> i32
150 // etc.
151 return TheStores.size() > NumPointerStores+NumByteStores;
152}
153
154namespace {
155
156class MemsetRanges {
157 using range_iterator = SmallVectorImpl<MemsetRange>::iterator;
158
159 /// A sorted list of the memset ranges.
160 SmallVector<MemsetRange, 8> Ranges;
161
162 const DataLayout &DL;
163
164public:
165 MemsetRanges(const DataLayout &DL) : DL(DL) {}
166
167 using const_iterator = SmallVectorImpl<MemsetRange>::const_iterator;
168
169 const_iterator begin() const { return Ranges.begin(); }
170 const_iterator end() const { return Ranges.end(); }
171 bool empty() const { return Ranges.empty(); }
172
173 void addInst(int64_t OffsetFromFirst, Instruction *Inst) {
174 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
175 addStore(OffsetFromFirst, SI);
176 else
177 addMemSet(OffsetFromFirst, cast<MemSetInst>(Inst));
178 }
179
180 void addStore(int64_t OffsetFromFirst, StoreInst *SI) {
181 int64_t StoreSize = DL.getTypeStoreSize(SI->getOperand(0)->getType());
182
183 addRange(OffsetFromFirst, StoreSize, SI->getPointerOperand(),
184 SI->getAlign().value(), SI);
185 }
186
187 void addMemSet(int64_t OffsetFromFirst, MemSetInst *MSI) {
188 int64_t Size = cast<ConstantInt>(MSI->getLength())->getZExtValue();
189 addRange(OffsetFromFirst, Size, MSI->getDest(), MSI->getDestAlignment(), MSI);
190 }
191
192 void addRange(int64_t Start, int64_t Size, Value *Ptr,
193 unsigned Alignment, Instruction *Inst);
194};
195
196} // end anonymous namespace
197
198/// Add a new store to the MemsetRanges data structure. This adds a
199/// new range for the specified store at the specified offset, merging into
200/// existing ranges as appropriate.
201void MemsetRanges::addRange(int64_t Start, int64_t Size, Value *Ptr,
202 unsigned Alignment, Instruction *Inst) {
203 int64_t End = Start+Size;
204
205 range_iterator I = partition_point(
206 Ranges, [=](const MemsetRange &O) { return O.End < Start; });
207
208 // We now know that I == E, in which case we didn't find anything to merge
209 // with, or that Start <= I->End. If End < I->Start or I == E, then we need
210 // to insert a new range. Handle this now.
211 if (I == Ranges.end() || End < I->Start) {
212 MemsetRange &R = *Ranges.insert(I, MemsetRange());
213 R.Start = Start;
214 R.End = End;
215 R.StartPtr = Ptr;
216 R.Alignment = Alignment;
217 R.TheStores.push_back(Inst);
218 return;
219 }
220
221 // This store overlaps with I, add it.
222 I->TheStores.push_back(Inst);
223
224 // At this point, we may have an interval that completely contains our store.
225 // If so, just add it to the interval and return.
226 if (I->Start <= Start && I->End >= End)
227 return;
228
229 // Now we know that Start <= I->End and End >= I->Start so the range overlaps
230 // but is not entirely contained within the range.
231
232 // See if the range extends the start of the range. In this case, it couldn't
233 // possibly cause it to join the prior range, because otherwise we would have
234 // stopped on *it*.
235 if (Start < I->Start) {
236 I->Start = Start;
237 I->StartPtr = Ptr;
238 I->Alignment = Alignment;
239 }
240
241 // Now we know that Start <= I->End and Start >= I->Start (so the startpoint
242 // is in or right at the end of I), and that End >= I->Start. Extend I out to
243 // End.
244 if (End > I->End) {
245 I->End = End;
246 range_iterator NextI = I;
247 while (++NextI != Ranges.end() && End >= NextI->Start) {
248 // Merge the range in.
249 I->TheStores.append(NextI->TheStores.begin(), NextI->TheStores.end());
250 if (NextI->End > I->End)
251 I->End = NextI->End;
252 Ranges.erase(NextI);
253 NextI = I;
254 }
255 }
256}
257
258//===----------------------------------------------------------------------===//
259// MemCpyOptLegacyPass Pass
260//===----------------------------------------------------------------------===//
261
262namespace {
263
264class MemCpyOptLegacyPass : public FunctionPass {
265 MemCpyOptPass Impl;
266
267public:
268 static char ID; // Pass identification, replacement for typeid
269
270 MemCpyOptLegacyPass() : FunctionPass(ID) {
271 initializeMemCpyOptLegacyPassPass(*PassRegistry::getPassRegistry());
272 }
273
274 bool runOnFunction(Function &F) override;
275
276private:
277 // This transformation requires dominator postdominator info
278 void getAnalysisUsage(AnalysisUsage &AU) const override {
279 AU.setPreservesCFG();
280 AU.addRequired<AssumptionCacheTracker>();
281 AU.addRequired<DominatorTreeWrapperPass>();
282 AU.addPreserved<DominatorTreeWrapperPass>();
283 AU.addPreserved<GlobalsAAWrapperPass>();
284 AU.addRequired<TargetLibraryInfoWrapperPass>();
285 if (!EnableMemorySSA)
286 AU.addRequired<MemoryDependenceWrapperPass>();
287 AU.addPreserved<MemoryDependenceWrapperPass>();
288 AU.addRequired<AAResultsWrapperPass>();
289 AU.addPreserved<AAResultsWrapperPass>();
290 if (EnableMemorySSA)
291 AU.addRequired<MemorySSAWrapperPass>();
292 AU.addPreserved<MemorySSAWrapperPass>();
293 }
294};
295
296} // end anonymous namespace
297
298char MemCpyOptLegacyPass::ID = 0;
299
300/// The public interface to this file...
301FunctionPass *llvm::createMemCpyOptPass() { return new MemCpyOptLegacyPass(); }
302
303INITIALIZE_PASS_BEGIN(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",static void *initializeMemCpyOptLegacyPassPassOnce(PassRegistry
&Registry) {
304 false, false)static void *initializeMemCpyOptLegacyPassPassOnce(PassRegistry
&Registry) {
305INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)initializeAssumptionCacheTrackerPass(Registry);
306INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)initializeDominatorTreeWrapperPassPass(Registry);
307INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)initializeMemoryDependenceWrapperPassPass(Registry);
308INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)initializeTargetLibraryInfoWrapperPassPass(Registry);
309INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)initializeAAResultsWrapperPassPass(Registry);
310INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)initializeGlobalsAAWrapperPassPass(Registry);
311INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)initializeMemorySSAWrapperPassPass(Registry);
312INITIALIZE_PASS_END(MemCpyOptLegacyPass, "memcpyopt", "MemCpy Optimization",PassInfo *PI = new PassInfo( "MemCpy Optimization", "memcpyopt"
, &MemCpyOptLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<MemCpyOptLegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeMemCpyOptLegacyPassPassFlag
; void llvm::initializeMemCpyOptLegacyPassPass(PassRegistry &
Registry) { llvm::call_once(InitializeMemCpyOptLegacyPassPassFlag
, initializeMemCpyOptLegacyPassPassOnce, std::ref(Registry));
}
313 false, false)PassInfo *PI = new PassInfo( "MemCpy Optimization", "memcpyopt"
, &MemCpyOptLegacyPass::ID, PassInfo::NormalCtor_t(callDefaultCtor
<MemCpyOptLegacyPass>), false, false); Registry.registerPass
(*PI, true); return PI; } static llvm::once_flag InitializeMemCpyOptLegacyPassPassFlag
; void llvm::initializeMemCpyOptLegacyPassPass(PassRegistry &
Registry) { llvm::call_once(InitializeMemCpyOptLegacyPassPassFlag
, initializeMemCpyOptLegacyPassPassOnce, std::ref(Registry));
}
314
315// Check that V is either not accessible by the caller, or unwinding cannot
316// occur between Start and End.
317static bool mayBeVisibleThroughUnwinding(Value *V, Instruction *Start,
318 Instruction *End) {
319 assert(Start->getParent() == End->getParent() && "Must be in same block")((Start->getParent() == End->getParent() && "Must be in same block"
) ? static_cast<void> (0) : __assert_fail ("Start->getParent() == End->getParent() && \"Must be in same block\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 319, __PRETTY_FUNCTION__))
;
320 if (!Start->getFunction()->doesNotThrow() &&
321 !isa<AllocaInst>(getUnderlyingObject(V))) {
322 for (const Instruction &I :
323 make_range(Start->getIterator(), End->getIterator())) {
324 if (I.mayThrow())
325 return true;
326 }
327 }
328 return false;
329}
330
331void MemCpyOptPass::eraseInstruction(Instruction *I) {
332 if (MSSAU)
333 MSSAU->removeMemoryAccess(I);
334 if (MD)
335 MD->removeInstruction(I);
336 I->eraseFromParent();
337}
338
339// Check for mod or ref of Loc between Start and End, excluding both boundaries.
340// Start and End must be in the same block
341static bool accessedBetween(AliasAnalysis &AA, MemoryLocation Loc,
342 const MemoryUseOrDef *Start,
343 const MemoryUseOrDef *End) {
344 assert(Start->getBlock() == End->getBlock() && "Only local supported")((Start->getBlock() == End->getBlock() && "Only local supported"
) ? static_cast<void> (0) : __assert_fail ("Start->getBlock() == End->getBlock() && \"Only local supported\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 344, __PRETTY_FUNCTION__))
;
345 for (const MemoryAccess &MA :
346 make_range(++Start->getIterator(), End->getIterator())) {
347 if (isModOrRefSet(AA.getModRefInfo(cast<MemoryUseOrDef>(MA).getMemoryInst(),
348 Loc)))
349 return true;
350 }
351 return false;
352}
353
354// Check for mod of Loc between Start and End, excluding both boundaries.
355// Start and End can be in different blocks.
356static bool writtenBetween(MemorySSA *MSSA, MemoryLocation Loc,
357 const MemoryUseOrDef *Start,
358 const MemoryUseOrDef *End) {
359 // TODO: Only walk until we hit Start.
360 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
361 End->getDefiningAccess(), Loc);
362 return !MSSA->dominates(Clobber, Start);
363}
364
365/// When scanning forward over instructions, we look for some other patterns to
366/// fold away. In particular, this looks for stores to neighboring locations of
367/// memory. If it sees enough consecutive ones, it attempts to merge them
368/// together into a memcpy/memset.
369Instruction *MemCpyOptPass::tryMergingIntoMemset(Instruction *StartInst,
370 Value *StartPtr,
371 Value *ByteVal) {
372 const DataLayout &DL = StartInst->getModule()->getDataLayout();
373
374 // Okay, so we now have a single store that can be splatable. Scan to find
375 // all subsequent stores of the same value to offset from the same pointer.
376 // Join these together into ranges, so we can decide whether contiguous blocks
377 // are stored.
378 MemsetRanges Ranges(DL);
379
380 BasicBlock::iterator BI(StartInst);
381
382 // Keeps track of the last memory use or def before the insertion point for
383 // the new memset. The new MemoryDef for the inserted memsets will be inserted
384 // after MemInsertPoint. It points to either LastMemDef or to the last user
385 // before the insertion point of the memset, if there are any such users.
386 MemoryUseOrDef *MemInsertPoint = nullptr;
387 // Keeps track of the last MemoryDef between StartInst and the insertion point
388 // for the new memset. This will become the defining access of the inserted
389 // memsets.
390 MemoryDef *LastMemDef = nullptr;
391 for (++BI; !BI->isTerminator(); ++BI) {
392 if (MSSAU) {
393 auto *CurrentAcc = cast_or_null<MemoryUseOrDef>(
394 MSSAU->getMemorySSA()->getMemoryAccess(&*BI));
395 if (CurrentAcc) {
396 MemInsertPoint = CurrentAcc;
397 if (auto *CurrentDef = dyn_cast<MemoryDef>(CurrentAcc))
398 LastMemDef = CurrentDef;
399 }
400 }
401
402 if (!isa<StoreInst>(BI) && !isa<MemSetInst>(BI)) {
403 // If the instruction is readnone, ignore it, otherwise bail out. We
404 // don't even allow readonly here because we don't want something like:
405 // A[1] = 2; strlen(A); A[2] = 2; -> memcpy(A, ...); strlen(A).
406 if (BI->mayWriteToMemory() || BI->mayReadFromMemory())
407 break;
408 continue;
409 }
410
411 if (StoreInst *NextStore = dyn_cast<StoreInst>(BI)) {
412 // If this is a store, see if we can merge it in.
413 if (!NextStore->isSimple()) break;
414
415 Value *StoredVal = NextStore->getValueOperand();
416
417 // Don't convert stores of non-integral pointer types to memsets (which
418 // stores integers).
419 if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
420 break;
421
422 // Check to see if this stored value is of the same byte-splattable value.
423 Value *StoredByte = isBytewiseValue(StoredVal, DL);
424 if (isa<UndefValue>(ByteVal) && StoredByte)
425 ByteVal = StoredByte;
426 if (ByteVal != StoredByte)
427 break;
428
429 // Check to see if this store is to a constant offset from the start ptr.
430 Optional<int64_t> Offset =
431 isPointerOffset(StartPtr, NextStore->getPointerOperand(), DL);
432 if (!Offset)
433 break;
434
435 Ranges.addStore(*Offset, NextStore);
436 } else {
437 MemSetInst *MSI = cast<MemSetInst>(BI);
438
439 if (MSI->isVolatile() || ByteVal != MSI->getValue() ||
440 !isa<ConstantInt>(MSI->getLength()))
441 break;
442
443 // Check to see if this store is to a constant offset from the start ptr.
444 Optional<int64_t> Offset = isPointerOffset(StartPtr, MSI->getDest(), DL);
445 if (!Offset)
446 break;
447
448 Ranges.addMemSet(*Offset, MSI);
449 }
450 }
451
452 // If we have no ranges, then we just had a single store with nothing that
453 // could be merged in. This is a very common case of course.
454 if (Ranges.empty())
455 return nullptr;
456
457 // If we had at least one store that could be merged in, add the starting
458 // store as well. We try to avoid this unless there is at least something
459 // interesting as a small compile-time optimization.
460 Ranges.addInst(0, StartInst);
461
462 // If we create any memsets, we put it right before the first instruction that
463 // isn't part of the memset block. This ensure that the memset is dominated
464 // by any addressing instruction needed by the start of the block.
465 IRBuilder<> Builder(&*BI);
466
467 // Now that we have full information about ranges, loop over the ranges and
468 // emit memset's for anything big enough to be worthwhile.
469 Instruction *AMemSet = nullptr;
470 for (const MemsetRange &Range : Ranges) {
471 if (Range.TheStores.size() == 1) continue;
472
473 // If it is profitable to lower this range to memset, do so now.
474 if (!Range.isProfitableToUseMemset(DL))
475 continue;
476
477 // Otherwise, we do want to transform this! Create a new memset.
478 // Get the starting pointer of the block.
479 StartPtr = Range.StartPtr;
480
481 AMemSet = Builder.CreateMemSet(StartPtr, ByteVal, Range.End - Range.Start,
482 MaybeAlign(Range.Alignment));
483 LLVM_DEBUG(dbgs() << "Replace stores:\n"; for (Instruction *SIdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction
*SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs
() << "With: " << *AMemSet << '\n'; } } while
(false)
484 : Range.TheStores) dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction
*SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs
() << "With: " << *AMemSet << '\n'; } } while
(false)
485 << *SI << '\n';do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction
*SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs
() << "With: " << *AMemSet << '\n'; } } while
(false)
486 dbgs() << "With: " << *AMemSet << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Replace stores:\n"; for (Instruction
*SI : Range.TheStores) dbgs() << *SI << '\n'; dbgs
() << "With: " << *AMemSet << '\n'; } } while
(false)
;
487 if (!Range.TheStores.empty())
488 AMemSet->setDebugLoc(Range.TheStores[0]->getDebugLoc());
489
490 if (MSSAU) {
491 assert(LastMemDef && MemInsertPoint &&((LastMemDef && MemInsertPoint && "Both LastMemDef and MemInsertPoint need to be set"
) ? static_cast<void> (0) : __assert_fail ("LastMemDef && MemInsertPoint && \"Both LastMemDef and MemInsertPoint need to be set\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 492, __PRETTY_FUNCTION__))
492 "Both LastMemDef and MemInsertPoint need to be set")((LastMemDef && MemInsertPoint && "Both LastMemDef and MemInsertPoint need to be set"
) ? static_cast<void> (0) : __assert_fail ("LastMemDef && MemInsertPoint && \"Both LastMemDef and MemInsertPoint need to be set\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 492, __PRETTY_FUNCTION__))
;
493 auto *NewDef =
494 cast<MemoryDef>(MemInsertPoint->getMemoryInst() == &*BI
495 ? MSSAU->createMemoryAccessBefore(
496 AMemSet, LastMemDef, MemInsertPoint)
497 : MSSAU->createMemoryAccessAfter(
498 AMemSet, LastMemDef, MemInsertPoint));
499 MSSAU->insertDef(NewDef, /*RenameUses=*/true);
500 LastMemDef = NewDef;
501 MemInsertPoint = NewDef;
502 }
503
504 // Zap all the stores.
505 for (Instruction *SI : Range.TheStores)
506 eraseInstruction(SI);
507
508 ++NumMemSetInfer;
509 }
510
511 return AMemSet;
512}
513
514// This method try to lift a store instruction before position P.
515// It will lift the store and its argument + that anything that
516// may alias with these.
517// The method returns true if it was successful.
518bool MemCpyOptPass::moveUp(StoreInst *SI, Instruction *P, const LoadInst *LI) {
519 // If the store alias this position, early bail out.
520 MemoryLocation StoreLoc = MemoryLocation::get(SI);
521 if (isModOrRefSet(AA->getModRefInfo(P, StoreLoc)))
522 return false;
523
524 // Keep track of the arguments of all instruction we plan to lift
525 // so we can make sure to lift them as well if appropriate.
526 DenseSet<Instruction*> Args;
527 if (auto *Ptr = dyn_cast<Instruction>(SI->getPointerOperand()))
528 if (Ptr->getParent() == SI->getParent())
529 Args.insert(Ptr);
530
531 // Instruction to lift before P.
532 SmallVector<Instruction *, 8> ToLift{SI};
533
534 // Memory locations of lifted instructions.
535 SmallVector<MemoryLocation, 8> MemLocs{StoreLoc};
536
537 // Lifted calls.
538 SmallVector<const CallBase *, 8> Calls;
539
540 const MemoryLocation LoadLoc = MemoryLocation::get(LI);
541
542 for (auto I = --SI->getIterator(), E = P->getIterator(); I != E; --I) {
543 auto *C = &*I;
544
545 // Make sure hoisting does not perform a store that was not guaranteed to
546 // happen.
547 if (!isGuaranteedToTransferExecutionToSuccessor(C))
548 return false;
549
550 bool MayAlias = isModOrRefSet(AA->getModRefInfo(C, None));
551
552 bool NeedLift = false;
553 if (Args.erase(C))
554 NeedLift = true;
555 else if (MayAlias) {
556 NeedLift = llvm::any_of(MemLocs, [C, this](const MemoryLocation &ML) {
557 return isModOrRefSet(AA->getModRefInfo(C, ML));
558 });
559
560 if (!NeedLift)
561 NeedLift = llvm::any_of(Calls, [C, this](const CallBase *Call) {
562 return isModOrRefSet(AA->getModRefInfo(C, Call));
563 });
564 }
565
566 if (!NeedLift)
567 continue;
568
569 if (MayAlias) {
570 // Since LI is implicitly moved downwards past the lifted instructions,
571 // none of them may modify its source.
572 if (isModSet(AA->getModRefInfo(C, LoadLoc)))
573 return false;
574 else if (const auto *Call = dyn_cast<CallBase>(C)) {
575 // If we can't lift this before P, it's game over.
576 if (isModOrRefSet(AA->getModRefInfo(P, Call)))
577 return false;
578
579 Calls.push_back(Call);
580 } else if (isa<LoadInst>(C) || isa<StoreInst>(C) || isa<VAArgInst>(C)) {
581 // If we can't lift this before P, it's game over.
582 auto ML = MemoryLocation::get(C);
583 if (isModOrRefSet(AA->getModRefInfo(P, ML)))
584 return false;
585
586 MemLocs.push_back(ML);
587 } else
588 // We don't know how to lift this instruction.
589 return false;
590 }
591
592 ToLift.push_back(C);
593 for (unsigned k = 0, e = C->getNumOperands(); k != e; ++k)
594 if (auto *A = dyn_cast<Instruction>(C->getOperand(k))) {
595 if (A->getParent() == SI->getParent()) {
596 // Cannot hoist user of P above P
597 if(A == P) return false;
598 Args.insert(A);
599 }
600 }
601 }
602
603 // Find MSSA insertion point. Normally P will always have a corresponding
604 // memory access before which we can insert. However, with non-standard AA
605 // pipelines, there may be a mismatch between AA and MSSA, in which case we
606 // will scan for a memory access before P. In either case, we know for sure
607 // that at least the load will have a memory access.
608 // TODO: Simplify this once P will be determined by MSSA, in which case the
609 // discrepancy can no longer occur.
610 MemoryUseOrDef *MemInsertPoint = nullptr;
611 if (MSSAU) {
612 if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(P)) {
613 MemInsertPoint = cast<MemoryUseOrDef>(--MA->getIterator());
614 } else {
615 const Instruction *ConstP = P;
616 for (const Instruction &I : make_range(++ConstP->getReverseIterator(),
617 ++LI->getReverseIterator())) {
618 if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(&I)) {
619 MemInsertPoint = MA;
620 break;
621 }
622 }
623 }
624 }
625
626 // We made it, we need to lift.
627 for (auto *I : llvm::reverse(ToLift)) {
628 LLVM_DEBUG(dbgs() << "Lifting " << *I << " before " << *P << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Lifting " << *I <<
" before " << *P << "\n"; } } while (false)
;
629 I->moveBefore(P);
630 if (MSSAU) {
631 assert(MemInsertPoint && "Must have found insert point")((MemInsertPoint && "Must have found insert point") ?
static_cast<void> (0) : __assert_fail ("MemInsertPoint && \"Must have found insert point\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 631, __PRETTY_FUNCTION__))
;
632 if (MemoryUseOrDef *MA = MSSAU->getMemorySSA()->getMemoryAccess(I)) {
633 MSSAU->moveAfter(MA, MemInsertPoint);
634 MemInsertPoint = MA;
635 }
636 }
637 }
638
639 return true;
640}
641
642bool MemCpyOptPass::processStore(StoreInst *SI, BasicBlock::iterator &BBI) {
643 if (!SI->isSimple()) return false;
644
645 // Avoid merging nontemporal stores since the resulting
646 // memcpy/memset would not be able to preserve the nontemporal hint.
647 // In theory we could teach how to propagate the !nontemporal metadata to
648 // memset calls. However, that change would force the backend to
649 // conservatively expand !nontemporal memset calls back to sequences of
650 // store instructions (effectively undoing the merging).
651 if (SI->getMetadata(LLVMContext::MD_nontemporal))
652 return false;
653
654 const DataLayout &DL = SI->getModule()->getDataLayout();
655
656 Value *StoredVal = SI->getValueOperand();
657
658 // Not all the transforms below are correct for non-integral pointers, bail
659 // until we've audited the individual pieces.
660 if (DL.isNonIntegralPointerType(StoredVal->getType()->getScalarType()))
661 return false;
662
663 // Load to store forwarding can be interpreted as memcpy.
664 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
665 if (LI->isSimple() && LI->hasOneUse() &&
666 LI->getParent() == SI->getParent()) {
667
668 auto *T = LI->getType();
669 if (T->isAggregateType()) {
670 MemoryLocation LoadLoc = MemoryLocation::get(LI);
671
672 // We use alias analysis to check if an instruction may store to
673 // the memory we load from in between the load and the store. If
674 // such an instruction is found, we try to promote there instead
675 // of at the store position.
676 // TODO: Can use MSSA for this.
677 Instruction *P = SI;
678 for (auto &I : make_range(++LI->getIterator(), SI->getIterator())) {
679 if (isModSet(AA->getModRefInfo(&I, LoadLoc))) {
680 P = &I;
681 break;
682 }
683 }
684
685 // We found an instruction that may write to the loaded memory.
686 // We can try to promote at this position instead of the store
687 // position if nothing alias the store memory after this and the store
688 // destination is not in the range.
689 if (P && P != SI) {
690 if (!moveUp(SI, P, LI))
691 P = nullptr;
692 }
693
694 // If a valid insertion position is found, then we can promote
695 // the load/store pair to a memcpy.
696 if (P) {
697 // If we load from memory that may alias the memory we store to,
698 // memmove must be used to preserve semantic. If not, memcpy can
699 // be used.
700 bool UseMemMove = false;
701 if (!AA->isNoAlias(MemoryLocation::get(SI), LoadLoc))
702 UseMemMove = true;
703
704 uint64_t Size = DL.getTypeStoreSize(T);
705
706 IRBuilder<> Builder(P);
707 Instruction *M;
708 if (UseMemMove)
709 M = Builder.CreateMemMove(
710 SI->getPointerOperand(), SI->getAlign(),
711 LI->getPointerOperand(), LI->getAlign(), Size);
712 else
713 M = Builder.CreateMemCpy(
714 SI->getPointerOperand(), SI->getAlign(),
715 LI->getPointerOperand(), LI->getAlign(), Size);
716
717 LLVM_DEBUG(dbgs() << "Promoting " << *LI << " to " << *SI << " => "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Promoting " << *LI <<
" to " << *SI << " => " << *M << "\n"
; } } while (false)
718 << *M << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Promoting " << *LI <<
" to " << *SI << " => " << *M << "\n"
; } } while (false)
;
719
720 if (MSSAU) {
721 auto *LastDef =
722 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
723 auto *NewAccess =
724 MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
725 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
726 }
727
728 eraseInstruction(SI);
729 eraseInstruction(LI);
730 ++NumMemCpyInstr;
731
732 // Make sure we do not invalidate the iterator.
733 BBI = M->getIterator();
734 return true;
735 }
736 }
737
738 // Detect cases where we're performing call slot forwarding, but
739 // happen to be using a load-store pair to implement it, rather than
740 // a memcpy.
741 CallInst *C = nullptr;
742 if (EnableMemorySSA) {
743 if (auto *LoadClobber = dyn_cast<MemoryUseOrDef>(
744 MSSA->getWalker()->getClobberingMemoryAccess(LI))) {
745 // The load most post-dom the call. Limit to the same block for now.
746 // TODO: Support non-local call-slot optimization?
747 if (LoadClobber->getBlock() == SI->getParent())
748 C = dyn_cast_or_null<CallInst>(LoadClobber->getMemoryInst());
749 }
750 } else {
751 MemDepResult ldep = MD->getDependency(LI);
752 if (ldep.isClobber() && !isa<MemCpyInst>(ldep.getInst()))
753 C = dyn_cast<CallInst>(ldep.getInst());
754 }
755
756 if (C) {
757 // Check that nothing touches the dest of the "copy" between
758 // the call and the store.
759 MemoryLocation StoreLoc = MemoryLocation::get(SI);
760 if (EnableMemorySSA) {
761 if (accessedBetween(*AA, StoreLoc, MSSA->getMemoryAccess(C),
762 MSSA->getMemoryAccess(SI)))
763 C = nullptr;
764 } else {
765 for (BasicBlock::iterator I = --SI->getIterator(),
766 E = C->getIterator();
767 I != E; --I) {
768 if (isModOrRefSet(AA->getModRefInfo(&*I, StoreLoc))) {
769 C = nullptr;
770 break;
771 }
772 }
773 }
774 }
775
776 if (C) {
777 bool changed = performCallSlotOptzn(
778 LI, SI, SI->getPointerOperand()->stripPointerCasts(),
779 LI->getPointerOperand()->stripPointerCasts(),
780 DL.getTypeStoreSize(SI->getOperand(0)->getType()),
781 commonAlignment(SI->getAlign(), LI->getAlign()), C);
782 if (changed) {
783 eraseInstruction(SI);
784 eraseInstruction(LI);
785 ++NumMemCpyInstr;
786 return true;
787 }
788 }
789 }
790 }
791
792 // There are two cases that are interesting for this code to handle: memcpy
793 // and memset. Right now we only handle memset.
794
795 // Ensure that the value being stored is something that can be memset'able a
796 // byte at a time like "0" or "-1" or any width, as well as things like
797 // 0xA0A0A0A0 and 0.0.
798 auto *V = SI->getOperand(0);
799 if (Value *ByteVal = isBytewiseValue(V, DL)) {
800 if (Instruction *I = tryMergingIntoMemset(SI, SI->getPointerOperand(),
801 ByteVal)) {
802 BBI = I->getIterator(); // Don't invalidate iterator.
803 return true;
804 }
805
806 // If we have an aggregate, we try to promote it to memset regardless
807 // of opportunity for merging as it can expose optimization opportunities
808 // in subsequent passes.
809 auto *T = V->getType();
810 if (T->isAggregateType()) {
811 uint64_t Size = DL.getTypeStoreSize(T);
812 IRBuilder<> Builder(SI);
813 auto *M = Builder.CreateMemSet(SI->getPointerOperand(), ByteVal, Size,
814 SI->getAlign());
815
816 LLVM_DEBUG(dbgs() << "Promoting " << *SI << " to " << *M << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Promoting " << *SI <<
" to " << *M << "\n"; } } while (false)
;
817
818 if (MSSAU) {
819 assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI)))((isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess
(SI))) ? static_cast<void> (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI))"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 819, __PRETTY_FUNCTION__))
;
820 auto *LastDef =
821 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(SI));
822 auto *NewAccess = MSSAU->createMemoryAccessAfter(M, LastDef, LastDef);
823 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
824 }
825
826 eraseInstruction(SI);
827 NumMemSetInfer++;
828
829 // Make sure we do not invalidate the iterator.
830 BBI = M->getIterator();
831 return true;
832 }
833 }
834
835 return false;
836}
837
838bool MemCpyOptPass::processMemSet(MemSetInst *MSI, BasicBlock::iterator &BBI) {
839 // See if there is another memset or store neighboring this memset which
840 // allows us to widen out the memset to do a single larger store.
841 if (isa<ConstantInt>(MSI->getLength()) && !MSI->isVolatile())
842 if (Instruction *I = tryMergingIntoMemset(MSI, MSI->getDest(),
843 MSI->getValue())) {
844 BBI = I->getIterator(); // Don't invalidate iterator.
845 return true;
846 }
847 return false;
848}
849
850/// Takes a memcpy and a call that it depends on,
851/// and checks for the possibility of a call slot optimization by having
852/// the call write its result directly into the destination of the memcpy.
853bool MemCpyOptPass::performCallSlotOptzn(Instruction *cpyLoad,
854 Instruction *cpyStore, Value *cpyDest,
855 Value *cpySrc, uint64_t cpyLen,
856 Align cpyAlign, CallInst *C) {
857 // The general transformation to keep in mind is
858 //
859 // call @func(..., src, ...)
860 // memcpy(dest, src, ...)
861 //
862 // ->
863 //
864 // memcpy(dest, src, ...)
865 // call @func(..., dest, ...)
866 //
867 // Since moving the memcpy is technically awkward, we additionally check that
868 // src only holds uninitialized values at the moment of the call, meaning that
869 // the memcpy can be discarded rather than moved.
870
871 // Lifetime marks shouldn't be operated on.
872 if (Function *F = C->getCalledFunction())
873 if (F->isIntrinsic() && F->getIntrinsicID() == Intrinsic::lifetime_start)
874 return false;
875
876 // Require that src be an alloca. This simplifies the reasoning considerably.
877 AllocaInst *srcAlloca = dyn_cast<AllocaInst>(cpySrc);
878 if (!srcAlloca)
879 return false;
880
881 ConstantInt *srcArraySize = dyn_cast<ConstantInt>(srcAlloca->getArraySize());
882 if (!srcArraySize)
883 return false;
884
885 const DataLayout &DL = cpyLoad->getModule()->getDataLayout();
886 uint64_t srcSize = DL.getTypeAllocSize(srcAlloca->getAllocatedType()) *
887 srcArraySize->getZExtValue();
888
889 if (cpyLen < srcSize)
890 return false;
891
892 // Check that accessing the first srcSize bytes of dest will not cause a
893 // trap. Otherwise the transform is invalid since it might cause a trap
894 // to occur earlier than it otherwise would.
895 if (!isDereferenceableAndAlignedPointer(cpyDest, Align(1), APInt(64, cpyLen),
896 DL, C, DT))
897 return false;
898
899 // Make sure that nothing can observe cpyDest being written early. There are
900 // a number of cases to consider:
901 // 1. cpyDest cannot be accessed between C and cpyStore as a precondition of
902 // the transform.
903 // 2. C itself may not access cpyDest (prior to the transform). This is
904 // checked further below.
905 // 3. If cpyDest is accessible to the caller of this function (potentially
906 // captured and not based on an alloca), we need to ensure that we cannot
907 // unwind between C and cpyStore. This is checked here.
908 // 4. If cpyDest is potentially captured, there may be accesses to it from
909 // another thread. In this case, we need to check that cpyStore is
910 // guaranteed to be executed if C is. As it is a non-atomic access, it
911 // renders accesses from other threads undefined.
912 // TODO: This is currently not checked.
913 if (mayBeVisibleThroughUnwinding(cpyDest, C, cpyStore))
914 return false;
915
916 // Check that dest points to memory that is at least as aligned as src.
917 Align srcAlign = srcAlloca->getAlign();
918 bool isDestSufficientlyAligned = srcAlign <= cpyAlign;
919 // If dest is not aligned enough and we can't increase its alignment then
920 // bail out.
921 if (!isDestSufficientlyAligned && !isa<AllocaInst>(cpyDest))
922 return false;
923
924 // Check that src is not accessed except via the call and the memcpy. This
925 // guarantees that it holds only undefined values when passed in (so the final
926 // memcpy can be dropped), that it is not read or written between the call and
927 // the memcpy, and that writing beyond the end of it is undefined.
928 SmallVector<User *, 8> srcUseList(srcAlloca->users());
929 while (!srcUseList.empty()) {
930 User *U = srcUseList.pop_back_val();
931
932 if (isa<BitCastInst>(U) || isa<AddrSpaceCastInst>(U)) {
933 append_range(srcUseList, U->users());
934 continue;
935 }
936 if (GetElementPtrInst *G = dyn_cast<GetElementPtrInst>(U)) {
937 if (!G->hasAllZeroIndices())
938 return false;
939
940 append_range(srcUseList, U->users());
941 continue;
942 }
943 if (const IntrinsicInst *IT = dyn_cast<IntrinsicInst>(U))
944 if (IT->isLifetimeStartOrEnd())
945 continue;
946
947 if (U != C && U != cpyLoad)
948 return false;
949 }
950
951 // Check that src isn't captured by the called function since the
952 // transformation can cause aliasing issues in that case.
953 for (unsigned ArgI = 0, E = C->arg_size(); ArgI != E; ++ArgI)
954 if (C->getArgOperand(ArgI) == cpySrc && !C->doesNotCapture(ArgI))
955 return false;
956
957 // Since we're changing the parameter to the callsite, we need to make sure
958 // that what would be the new parameter dominates the callsite.
959 if (!DT->dominates(cpyDest, C)) {
960 // Support moving a constant index GEP before the call.
961 auto *GEP = dyn_cast<GetElementPtrInst>(cpyDest);
962 if (GEP && GEP->hasAllConstantIndices() &&
963 DT->dominates(GEP->getPointerOperand(), C))
964 GEP->moveBefore(C);
965 else
966 return false;
967 }
968
969 // In addition to knowing that the call does not access src in some
970 // unexpected manner, for example via a global, which we deduce from
971 // the use analysis, we also need to know that it does not sneakily
972 // access dest. We rely on AA to figure this out for us.
973 ModRefInfo MR = AA->getModRefInfo(C, cpyDest, LocationSize::precise(srcSize));
974 // If necessary, perform additional analysis.
975 if (isModOrRefSet(MR))
976 MR = AA->callCapturesBefore(C, cpyDest, LocationSize::precise(srcSize), DT);
977 if (isModOrRefSet(MR))
978 return false;
979
980 // We can't create address space casts here because we don't know if they're
981 // safe for the target.
982 if (cpySrc->getType()->getPointerAddressSpace() !=
983 cpyDest->getType()->getPointerAddressSpace())
984 return false;
985 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
986 if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc &&
987 cpySrc->getType()->getPointerAddressSpace() !=
988 C->getArgOperand(ArgI)->getType()->getPointerAddressSpace())
989 return false;
990
991 // All the checks have passed, so do the transformation.
992 bool changedArgument = false;
993 for (unsigned ArgI = 0; ArgI < C->arg_size(); ++ArgI)
994 if (C->getArgOperand(ArgI)->stripPointerCasts() == cpySrc) {
995 Value *Dest = cpySrc->getType() == cpyDest->getType() ? cpyDest
996 : CastInst::CreatePointerCast(cpyDest, cpySrc->getType(),
997 cpyDest->getName(), C);
998 changedArgument = true;
999 if (C->getArgOperand(ArgI)->getType() == Dest->getType())
1000 C->setArgOperand(ArgI, Dest);
1001 else
1002 C->setArgOperand(ArgI, CastInst::CreatePointerCast(
1003 Dest, C->getArgOperand(ArgI)->getType(),
1004 Dest->getName(), C));
1005 }
1006
1007 if (!changedArgument)
1008 return false;
1009
1010 // If the destination wasn't sufficiently aligned then increase its alignment.
1011 if (!isDestSufficientlyAligned) {
1012 assert(isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!")((isa<AllocaInst>(cpyDest) && "Can only increase alloca alignment!"
) ? static_cast<void> (0) : __assert_fail ("isa<AllocaInst>(cpyDest) && \"Can only increase alloca alignment!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 1012, __PRETTY_FUNCTION__))
;
1013 cast<AllocaInst>(cpyDest)->setAlignment(srcAlign);
1014 }
1015
1016 // Drop any cached information about the call, because we may have changed
1017 // its dependence information by changing its parameter.
1018 if (MD)
1019 MD->removeInstruction(C);
1020
1021 // Update AA metadata
1022 // FIXME: MD_tbaa_struct and MD_mem_parallel_loop_access should also be
1023 // handled here, but combineMetadata doesn't support them yet
1024 unsigned KnownIDs[] = {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
1025 LLVMContext::MD_noalias,
1026 LLVMContext::MD_invariant_group,
1027 LLVMContext::MD_access_group};
1028 combineMetadata(C, cpyLoad, KnownIDs, true);
1029
1030 ++NumCallSlot;
1031 return true;
1032}
1033
1034/// We've found that the (upward scanning) memory dependence of memcpy 'M' is
1035/// the memcpy 'MDep'. Try to simplify M to copy from MDep's input if we can.
1036bool MemCpyOptPass::processMemCpyMemCpyDependence(MemCpyInst *M,
1037 MemCpyInst *MDep) {
1038 // We can only transforms memcpy's where the dest of one is the source of the
1039 // other.
1040 if (M->getSource() != MDep->getDest() || MDep->isVolatile())
1041 return false;
1042
1043 // If dep instruction is reading from our current input, then it is a noop
1044 // transfer and substituting the input won't change this instruction. Just
1045 // ignore the input and let someone else zap MDep. This handles cases like:
1046 // memcpy(a <- a)
1047 // memcpy(b <- a)
1048 if (M->getSource() == MDep->getSource())
1049 return false;
1050
1051 // Second, the length of the memcpy's must be the same, or the preceding one
1052 // must be larger than the following one.
1053 ConstantInt *MDepLen = dyn_cast<ConstantInt>(MDep->getLength());
1054 ConstantInt *MLen = dyn_cast<ConstantInt>(M->getLength());
1055 if (!MDepLen || !MLen || MDepLen->getZExtValue() < MLen->getZExtValue())
1056 return false;
1057
1058 // Verify that the copied-from memory doesn't change in between the two
1059 // transfers. For example, in:
1060 // memcpy(a <- b)
1061 // *b = 42;
1062 // memcpy(c <- a)
1063 // It would be invalid to transform the second memcpy into memcpy(c <- b).
1064 //
1065 // TODO: If the code between M and MDep is transparent to the destination "c",
1066 // then we could still perform the xform by moving M up to the first memcpy.
1067 if (EnableMemorySSA) {
1068 // TODO: It would be sufficient to check the MDep source up to the memcpy
1069 // size of M, rather than MDep.
1070 if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep),
1071 MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(M)))
1072 return false;
1073 } else {
1074 // NOTE: This is conservative, it will stop on any read from the source loc,
1075 // not just the defining memcpy.
1076 MemDepResult SourceDep =
1077 MD->getPointerDependencyFrom(MemoryLocation::getForSource(MDep), false,
1078 M->getIterator(), M->getParent());
1079 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1080 return false;
1081 }
1082
1083 // If the dest of the second might alias the source of the first, then the
1084 // source and dest might overlap. We still want to eliminate the intermediate
1085 // value, but we have to generate a memmove instead of memcpy.
1086 bool UseMemMove = false;
1087 if (!AA->isNoAlias(MemoryLocation::getForDest(M),
1088 MemoryLocation::getForSource(MDep)))
1089 UseMemMove = true;
1090
1091 // If all checks passed, then we can transform M.
1092 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
<< *MDep << '\n' << *M << '\n'; } } while
(false)
1093 << *MDep << '\n' << *M << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy->memcpy src:\n"
<< *MDep << '\n' << *M << '\n'; } } while
(false)
;
1094
1095 // TODO: Is this worth it if we're creating a less aligned memcpy? For
1096 // example we could be moving from movaps -> movq on x86.
1097 IRBuilder<> Builder(M);
1098 Instruction *NewM;
1099 if (UseMemMove)
1100 NewM = Builder.CreateMemMove(M->getRawDest(), M->getDestAlign(),
1101 MDep->getRawSource(), MDep->getSourceAlign(),
1102 M->getLength(), M->isVolatile());
1103 else
1104 NewM = Builder.CreateMemCpy(M->getRawDest(), M->getDestAlign(),
1105 MDep->getRawSource(), MDep->getSourceAlign(),
1106 M->getLength(), M->isVolatile());
1107
1108 if (MSSAU) {
1109 assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M)))((isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess
(M))) ? static_cast<void> (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M))"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 1109, __PRETTY_FUNCTION__))
;
1110 auto *LastDef = cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1111 auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1112 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1113 }
1114
1115 // Remove the instruction we're replacing.
1116 eraseInstruction(M);
1117 ++NumMemCpyInstr;
1118 return true;
1119}
1120
1121/// We've found that the (upward scanning) memory dependence of \p MemCpy is
1122/// \p MemSet. Try to simplify \p MemSet to only set the trailing bytes that
1123/// weren't copied over by \p MemCpy.
1124///
1125/// In other words, transform:
1126/// \code
1127/// memset(dst, c, dst_size);
1128/// memcpy(dst, src, src_size);
1129/// \endcode
1130/// into:
1131/// \code
1132/// memcpy(dst, src, src_size);
1133/// memset(dst + src_size, c, dst_size <= src_size ? 0 : dst_size - src_size);
1134/// \endcode
1135bool MemCpyOptPass::processMemSetMemCpyDependence(MemCpyInst *MemCpy,
1136 MemSetInst *MemSet) {
1137 // We can only transform memset/memcpy with the same destination.
1138 if (!AA->isMustAlias(MemSet->getDest(), MemCpy->getDest()))
1139 return false;
1140
1141 // Check that src and dst of the memcpy aren't the same. While memcpy
1142 // operands cannot partially overlap, exact equality is allowed.
1143 if (!AA->isNoAlias(MemoryLocation(MemCpy->getSource(),
1144 LocationSize::precise(1)),
1145 MemoryLocation(MemCpy->getDest(),
1146 LocationSize::precise(1))))
1147 return false;
1148
1149 if (EnableMemorySSA) {
1150 // We know that dst up to src_size is not written. We now need to make sure
1151 // that dst up to dst_size is not accessed. (If we did not move the memset,
1152 // checking for reads would be sufficient.)
1153 if (accessedBetween(*AA, MemoryLocation::getForDest(MemSet),
1154 MSSA->getMemoryAccess(MemSet),
1155 MSSA->getMemoryAccess(MemCpy))) {
1156 return false;
1157 }
1158 } else {
1159 // We have already checked that dst up to src_size is not accessed. We
1160 // need to make sure that there are no accesses up to dst_size either.
1161 MemDepResult DstDepInfo = MD->getPointerDependencyFrom(
1162 MemoryLocation::getForDest(MemSet), false, MemCpy->getIterator(),
1163 MemCpy->getParent());
1164 if (DstDepInfo.getInst() != MemSet)
1165 return false;
1166 }
1167
1168 // Use the same i8* dest as the memcpy, killing the memset dest if different.
1169 Value *Dest = MemCpy->getRawDest();
1170 Value *DestSize = MemSet->getLength();
1171 Value *SrcSize = MemCpy->getLength();
1172
1173 if (mayBeVisibleThroughUnwinding(Dest, MemSet, MemCpy))
1174 return false;
1175
1176 // If the sizes are the same, simply drop the memset instead of generating
1177 // a replacement with zero size.
1178 if (DestSize == SrcSize) {
1179 eraseInstruction(MemSet);
1180 return true;
1181 }
1182
1183 // By default, create an unaligned memset.
1184 unsigned Align = 1;
1185 // If Dest is aligned, and SrcSize is constant, use the minimum alignment
1186 // of the sum.
1187 const unsigned DestAlign =
1188 std::max(MemSet->getDestAlignment(), MemCpy->getDestAlignment());
1189 if (DestAlign > 1)
1190 if (ConstantInt *SrcSizeC = dyn_cast<ConstantInt>(SrcSize))
1191 Align = MinAlign(SrcSizeC->getZExtValue(), DestAlign);
1192
1193 IRBuilder<> Builder(MemCpy);
1194
1195 // If the sizes have different types, zext the smaller one.
1196 if (DestSize->getType() != SrcSize->getType()) {
1197 if (DestSize->getType()->getIntegerBitWidth() >
1198 SrcSize->getType()->getIntegerBitWidth())
1199 SrcSize = Builder.CreateZExt(SrcSize, DestSize->getType());
1200 else
1201 DestSize = Builder.CreateZExt(DestSize, SrcSize->getType());
1202 }
1203
1204 Value *Ule = Builder.CreateICmpULE(DestSize, SrcSize);
1205 Value *SizeDiff = Builder.CreateSub(DestSize, SrcSize);
1206 Value *MemsetLen = Builder.CreateSelect(
1207 Ule, ConstantInt::getNullValue(DestSize->getType()), SizeDiff);
1208 Instruction *NewMemSet = Builder.CreateMemSet(
1209 Builder.CreateGEP(Dest->getType()->getPointerElementType(), Dest,
1210 SrcSize),
1211 MemSet->getOperand(1), MemsetLen, MaybeAlign(Align));
1212
1213 if (MSSAU) {
1214 assert(isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) &&((isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess
(MemCpy)) && "MemCpy must be a MemoryDef") ? static_cast
<void> (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) && \"MemCpy must be a MemoryDef\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 1215, __PRETTY_FUNCTION__))
1215 "MemCpy must be a MemoryDef")((isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess
(MemCpy)) && "MemCpy must be a MemoryDef") ? static_cast
<void> (0) : __assert_fail ("isa<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy)) && \"MemCpy must be a MemoryDef\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/lib/Transforms/Scalar/MemCpyOptimizer.cpp"
, 1215, __PRETTY_FUNCTION__))
;
1216 // The new memset is inserted after the memcpy, but it is known that its
1217 // defining access is the memset about to be removed which immediately
1218 // precedes the memcpy.
1219 auto *LastDef =
1220 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1221 auto *NewAccess = MSSAU->createMemoryAccessBefore(
1222 NewMemSet, LastDef->getDefiningAccess(), LastDef);
1223 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1224 }
1225
1226 eraseInstruction(MemSet);
1227 return true;
1228}
1229
1230/// Determine whether the instruction has undefined content for the given Size,
1231/// either because it was freshly alloca'd or started its lifetime.
1232static bool hasUndefContents(Instruction *I, ConstantInt *Size) {
1233 if (isa<AllocaInst>(I))
1234 return true;
1235
1236 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1237 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1238 if (ConstantInt *LTSize = dyn_cast<ConstantInt>(II->getArgOperand(0)))
1239 if (LTSize->getZExtValue() >= Size->getZExtValue())
1240 return true;
1241
1242 return false;
1243}
1244
1245static bool hasUndefContentsMSSA(MemorySSA *MSSA, AliasAnalysis *AA, Value *V,
1246 MemoryDef *Def, ConstantInt *Size) {
1247 if (MSSA->isLiveOnEntryDef(Def))
1248 return isa<AllocaInst>(getUnderlyingObject(V));
1249
1250 if (IntrinsicInst *II =
1251 dyn_cast_or_null<IntrinsicInst>(Def->getMemoryInst())) {
1252 if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
1253 ConstantInt *LTSize = cast<ConstantInt>(II->getArgOperand(0));
1254 if (AA->isMustAlias(V, II->getArgOperand(1)) &&
1255 LTSize->getZExtValue() >= Size->getZExtValue())
1256 return true;
1257
1258 // If the lifetime.start covers a whole alloca (as it almost always does)
1259 // and we're querying a pointer based on that alloca, then we know the
1260 // memory is definitely undef, regardless of how exactly we alias. The
1261 // size also doesn't matter, as an out-of-bounds access would be UB.
1262 AllocaInst *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(V));
1263 if (getUnderlyingObject(II->getArgOperand(1)) == Alloca) {
1264 DataLayout DL = Alloca->getModule()->getDataLayout();
1265 if (Optional<TypeSize> AllocaSize = Alloca->getAllocationSizeInBits(DL))
1266 if (*AllocaSize == LTSize->getValue() * 8)
1267 return true;
1268 }
1269 }
1270 }
1271
1272 return false;
1273}
1274
1275/// Transform memcpy to memset when its source was just memset.
1276/// In other words, turn:
1277/// \code
1278/// memset(dst1, c, dst1_size);
1279/// memcpy(dst2, dst1, dst2_size);
1280/// \endcode
1281/// into:
1282/// \code
1283/// memset(dst1, c, dst1_size);
1284/// memset(dst2, c, dst2_size);
1285/// \endcode
1286/// When dst2_size <= dst1_size.
1287///
1288/// The \p MemCpy must have a Constant length.
1289bool MemCpyOptPass::performMemCpyToMemSetOptzn(MemCpyInst *MemCpy,
1290 MemSetInst *MemSet) {
1291 // Make sure that memcpy(..., memset(...), ...), that is we are memsetting and
1292 // memcpying from the same address. Otherwise it is hard to reason about.
1293 if (!AA->isMustAlias(MemSet->getRawDest(), MemCpy->getRawSource()))
1294 return false;
1295
1296 // A known memset size is required.
1297 ConstantInt *MemSetSize = dyn_cast<ConstantInt>(MemSet->getLength());
1298 if (!MemSetSize)
1299 return false;
1300
1301 // Make sure the memcpy doesn't read any more than what the memset wrote.
1302 // Don't worry about sizes larger than i64.
1303 ConstantInt *CopySize = cast<ConstantInt>(MemCpy->getLength());
1304 if (CopySize->getZExtValue() > MemSetSize->getZExtValue()) {
1305 // If the memcpy is larger than the memset, but the memory was undef prior
1306 // to the memset, we can just ignore the tail. Technically we're only
1307 // interested in the bytes from MemSetSize..CopySize here, but as we can't
1308 // easily represent this location, we use the full 0..CopySize range.
1309 MemoryLocation MemCpyLoc = MemoryLocation::getForSource(MemCpy);
1310 bool CanReduceSize = false;
1311 if (EnableMemorySSA) {
1312 MemoryUseOrDef *MemSetAccess = MSSA->getMemoryAccess(MemSet);
1313 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1314 MemSetAccess->getDefiningAccess(), MemCpyLoc);
1315 if (auto *MD = dyn_cast<MemoryDef>(Clobber))
1316 if (hasUndefContentsMSSA(MSSA, AA, MemCpy->getSource(), MD, CopySize))
1317 CanReduceSize = true;
1318 } else {
1319 MemDepResult DepInfo = MD->getPointerDependencyFrom(
1320 MemCpyLoc, true, MemSet->getIterator(), MemSet->getParent());
1321 if (DepInfo.isDef() && hasUndefContents(DepInfo.getInst(), CopySize))
1322 CanReduceSize = true;
1323 }
1324
1325 if (!CanReduceSize)
1326 return false;
1327 CopySize = MemSetSize;
1328 }
1329
1330 IRBuilder<> Builder(MemCpy);
1331 Instruction *NewM =
1332 Builder.CreateMemSet(MemCpy->getRawDest(), MemSet->getOperand(1),
1333 CopySize, MaybeAlign(MemCpy->getDestAlignment()));
1334 if (MSSAU) {
1335 auto *LastDef =
1336 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(MemCpy));
1337 auto *NewAccess = MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1338 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1339 }
1340
1341 return true;
1342}
1343
1344/// Perform simplification of memcpy's. If we have memcpy A
1345/// which copies X to Y, and memcpy B which copies Y to Z, then we can rewrite
1346/// B to be a memcpy from X to Z (or potentially a memmove, depending on
1347/// circumstances). This allows later passes to remove the first memcpy
1348/// altogether.
1349bool MemCpyOptPass::processMemCpy(MemCpyInst *M, BasicBlock::iterator &BBI) {
1350 // We can only optimize non-volatile memcpy's.
1351 if (M->isVolatile()) return false;
27
Calling 'MemIntrinsic::isVolatile'
44
Returning from 'MemIntrinsic::isVolatile'
45
Taking false branch
1352
1353 // If the source and destination of the memcpy are the same, then zap it.
1354 if (M->getSource() == M->getDest()) {
46
Assuming the condition is false
47
Taking false branch
1355 ++BBI;
1356 eraseInstruction(M);
1357 return true;
1358 }
1359
1360 // If copying from a constant, try to turn the memcpy into a memset.
1361 if (GlobalVariable *GV
48.1
'GV' is null
48.1
'GV' is null
48.1
'GV' is null
48.1
'GV' is null
= dyn_cast<GlobalVariable>(M->getSource()))
48
Assuming the object is not a 'GlobalVariable'
49
Taking false branch
1362 if (GV->isConstant() && GV->hasDefinitiveInitializer())
1363 if (Value *ByteVal = isBytewiseValue(GV->getInitializer(),
1364 M->getModule()->getDataLayout())) {
1365 IRBuilder<> Builder(M);
1366 Instruction *NewM =
1367 Builder.CreateMemSet(M->getRawDest(), ByteVal, M->getLength(),
1368 MaybeAlign(M->getDestAlignment()), false);
1369 if (MSSAU) {
1370 auto *LastDef =
1371 cast<MemoryDef>(MSSAU->getMemorySSA()->getMemoryAccess(M));
1372 auto *NewAccess =
1373 MSSAU->createMemoryAccessAfter(NewM, LastDef, LastDef);
1374 MSSAU->insertDef(cast<MemoryDef>(NewAccess), /*RenameUses=*/true);
1375 }
1376
1377 eraseInstruction(M);
1378 ++NumCpyToSet;
1379 return true;
1380 }
1381
1382 if (EnableMemorySSA) {
50
Assuming the condition is false
51
Taking false branch
1383 MemoryUseOrDef *MA = MSSA->getMemoryAccess(M);
1384 MemoryAccess *AnyClobber = MSSA->getWalker()->getClobberingMemoryAccess(MA);
1385 MemoryLocation DestLoc = MemoryLocation::getForDest(M);
1386 const MemoryAccess *DestClobber =
1387 MSSA->getWalker()->getClobberingMemoryAccess(AnyClobber, DestLoc);
1388
1389 // Try to turn a partially redundant memset + memcpy into
1390 // memcpy + smaller memset. We don't need the memcpy size for this.
1391 // The memcpy most post-dom the memset, so limit this to the same basic
1392 // block. A non-local generalization is likely not worthwhile.
1393 if (auto *MD = dyn_cast<MemoryDef>(DestClobber))
1394 if (auto *MDep = dyn_cast_or_null<MemSetInst>(MD->getMemoryInst()))
1395 if (DestClobber->getBlock() == M->getParent())
1396 if (processMemSetMemCpyDependence(M, MDep))
1397 return true;
1398
1399 // The optimizations after this point require the memcpy size.
1400 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
1401 if (!CopySize) return false;
1402
1403 MemoryAccess *SrcClobber = MSSA->getWalker()->getClobberingMemoryAccess(
1404 AnyClobber, MemoryLocation::getForSource(M));
1405
1406 // There are four possible optimizations we can do for memcpy:
1407 // a) memcpy-memcpy xform which exposes redundance for DSE.
1408 // b) call-memcpy xform for return slot optimization.
1409 // c) memcpy from freshly alloca'd space or space that has just started
1410 // its lifetime copies undefined data, and we can therefore eliminate
1411 // the memcpy in favor of the data that was already at the destination.
1412 // d) memcpy from a just-memset'd source can be turned into memset.
1413 if (auto *MD = dyn_cast<MemoryDef>(SrcClobber)) {
1414 if (Instruction *MI = MD->getMemoryInst()) {
1415 if (auto *C = dyn_cast<CallInst>(MI)) {
1416 // The memcpy must post-dom the call. Limit to the same block for now.
1417 // Additionally, we need to ensure that there are no accesses to dest
1418 // between the call and the memcpy. Accesses to src will be checked
1419 // by performCallSlotOptzn().
1420 // TODO: Support non-local call-slot optimization?
1421 if (C->getParent() == M->getParent() &&
1422 !accessedBetween(*AA, DestLoc, MD, MA)) {
1423 // FIXME: Can we pass in either of dest/src alignment here instead
1424 // of conservatively taking the minimum?
1425 Align Alignment = std::min(M->getDestAlign().valueOrOne(),
1426 M->getSourceAlign().valueOrOne());
1427 if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(),
1428 CopySize->getZExtValue(), Alignment, C)) {
1429 LLVM_DEBUG(dbgs() << "Performed call slot optimization:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Performed call slot optimization:\n"
<< " call: " << *C << "\n" << " memcpy: "
<< *M << "\n"; } } while (false)
1430 << " call: " << *C << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Performed call slot optimization:\n"
<< " call: " << *C << "\n" << " memcpy: "
<< *M << "\n"; } } while (false)
1431 << " memcpy: " << *M << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Performed call slot optimization:\n"
<< " call: " << *C << "\n" << " memcpy: "
<< *M << "\n"; } } while (false)
;
1432 eraseInstruction(M);
1433 ++NumMemCpyInstr;
1434 return true;
1435 }
1436 }
1437 }
1438 if (auto *MDep = dyn_cast<MemCpyInst>(MI))
1439 return processMemCpyMemCpyDependence(M, MDep);
1440 if (auto *MDep = dyn_cast<MemSetInst>(MI)) {
1441 if (performMemCpyToMemSetOptzn(M, MDep)) {
1442 LLVM_DEBUG(dbgs() << "Converted memcpy to memset\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Converted memcpy to memset\n"
; } } while (false)
;
1443 eraseInstruction(M);
1444 ++NumCpyToSet;
1445 return true;
1446 }
1447 }
1448 }
1449
1450 if (hasUndefContentsMSSA(MSSA, AA, M->getSource(), MD, CopySize)) {
1451 LLVM_DEBUG(dbgs() << "Removed memcpy from undef\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "Removed memcpy from undef\n"
; } } while (false)
;
1452 eraseInstruction(M);
1453 ++NumMemCpyInstr;
1454 return true;
1455 }
1456 }
1457 } else {
1458 MemDepResult DepInfo = MD->getDependency(M);
52
Called C++ object pointer is null
1459
1460 // Try to turn a partially redundant memset + memcpy into
1461 // memcpy + smaller memset. We don't need the memcpy size for this.
1462 if (DepInfo.isClobber())
1463 if (MemSetInst *MDep = dyn_cast<MemSetInst>(DepInfo.getInst()))
1464 if (processMemSetMemCpyDependence(M, MDep))
1465 return true;
1466
1467 // The optimizations after this point require the memcpy size.
1468 ConstantInt *CopySize = dyn_cast<ConstantInt>(M->getLength());
1469 if (!CopySize) return false;
1470
1471 // There are four possible optimizations we can do for memcpy:
1472 // a) memcpy-memcpy xform which exposes redundance for DSE.
1473 // b) call-memcpy xform for return slot optimization.
1474 // c) memcpy from freshly alloca'd space or space that has just started
1475 // its lifetime copies undefined data, and we can therefore eliminate
1476 // the memcpy in favor of the data that was already at the destination.
1477 // d) memcpy from a just-memset'd source can be turned into memset.
1478 if (DepInfo.isClobber()) {
1479 if (CallInst *C = dyn_cast<CallInst>(DepInfo.getInst())) {
1480 // FIXME: Can we pass in either of dest/src alignment here instead
1481 // of conservatively taking the minimum?
1482 Align Alignment = std::min(M->getDestAlign().valueOrOne(),
1483 M->getSourceAlign().valueOrOne());
1484 if (performCallSlotOptzn(M, M, M->getDest(), M->getSource(),
1485 CopySize->getZExtValue(), Alignment, C)) {
1486 eraseInstruction(M);
1487 ++NumMemCpyInstr;
1488 return true;
1489 }
1490 }
1491 }
1492
1493 MemoryLocation SrcLoc = MemoryLocation::getForSource(M);
1494 MemDepResult SrcDepInfo = MD->getPointerDependencyFrom(
1495 SrcLoc, true, M->getIterator(), M->getParent());
1496
1497 if (SrcDepInfo.isClobber()) {
1498 if (MemCpyInst *MDep = dyn_cast<MemCpyInst>(SrcDepInfo.getInst()))
1499 return processMemCpyMemCpyDependence(M, MDep);
1500 } else if (SrcDepInfo.isDef()) {
1501 if (hasUndefContents(SrcDepInfo.getInst(), CopySize)) {
1502 eraseInstruction(M);
1503 ++NumMemCpyInstr;
1504 return true;
1505 }
1506 }
1507
1508 if (SrcDepInfo.isClobber())
1509 if (MemSetInst *MDep = dyn_cast<MemSetInst>(SrcDepInfo.getInst()))
1510 if (performMemCpyToMemSetOptzn(M, MDep)) {
1511 eraseInstruction(M);
1512 ++NumCpyToSet;
1513 return true;
1514 }
1515 }
1516
1517 return false;
1518}
1519
1520/// Transforms memmove calls to memcpy calls when the src/dst are guaranteed
1521/// not to alias.
1522bool MemCpyOptPass::processMemMove(MemMoveInst *M) {
1523 if (!TLI->has(LibFunc_memmove))
1524 return false;
1525
1526 // See if the pointers alias.
1527 if (!AA->isNoAlias(MemoryLocation::getForDest(M),
1528 MemoryLocation::getForSource(M)))
1529 return false;
1530
1531 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: " << *Mdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: "
<< *M << "\n"; } } while (false)
1532 << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Optimizing memmove -> memcpy: "
<< *M << "\n"; } } while (false)
;
1533
1534 // If not, then we know we can transform this.
1535 Type *ArgTys[3] = { M->getRawDest()->getType(),
1536 M->getRawSource()->getType(),
1537 M->getLength()->getType() };
1538 M->setCalledFunction(Intrinsic::getDeclaration(M->getModule(),
1539 Intrinsic::memcpy, ArgTys));
1540
1541 // For MemorySSA nothing really changes (except that memcpy may imply stricter
1542 // aliasing guarantees).
1543
1544 // MemDep may have over conservative information about this instruction, just
1545 // conservatively flush it from the cache.
1546 if (MD)
1547 MD->removeInstruction(M);
1548
1549 ++NumMoveToCpy;
1550 return true;
1551}
1552
1553/// This is called on every byval argument in call sites.
1554bool MemCpyOptPass::processByValArgument(CallBase &CB, unsigned ArgNo) {
1555 const DataLayout &DL = CB.getCaller()->getParent()->getDataLayout();
1556 // Find out what feeds this byval argument.
1557 Value *ByValArg = CB.getArgOperand(ArgNo);
1558 Type *ByValTy = cast<PointerType>(ByValArg->getType())->getElementType();
1559 uint64_t ByValSize = DL.getTypeAllocSize(ByValTy);
1560 MemoryLocation Loc(ByValArg, LocationSize::precise(ByValSize));
1561 MemCpyInst *MDep = nullptr;
1562 if (EnableMemorySSA) {
1563 MemoryUseOrDef *CallAccess = MSSA->getMemoryAccess(&CB);
1564 if (!CallAccess)
1565 return false;
1566 MemoryAccess *Clobber = MSSA->getWalker()->getClobberingMemoryAccess(
1567 CallAccess->getDefiningAccess(), Loc);
1568 if (auto *MD = dyn_cast<MemoryDef>(Clobber))
1569 MDep = dyn_cast_or_null<MemCpyInst>(MD->getMemoryInst());
1570 } else {
1571 MemDepResult DepInfo = MD->getPointerDependencyFrom(
1572 Loc, true, CB.getIterator(), CB.getParent());
1573 if (!DepInfo.isClobber())
1574 return false;
1575 MDep = dyn_cast<MemCpyInst>(DepInfo.getInst());
1576 }
1577
1578 // If the byval argument isn't fed by a memcpy, ignore it. If it is fed by
1579 // a memcpy, see if we can byval from the source of the memcpy instead of the
1580 // result.
1581 if (!MDep || MDep->isVolatile() ||
1582 ByValArg->stripPointerCasts() != MDep->getDest())
1583 return false;
1584
1585 // The length of the memcpy must be larger or equal to the size of the byval.
1586 ConstantInt *C1 = dyn_cast<ConstantInt>(MDep->getLength());
1587 if (!C1 || C1->getValue().getZExtValue() < ByValSize)
1588 return false;
1589
1590 // Get the alignment of the byval. If the call doesn't specify the alignment,
1591 // then it is some target specific value that we can't know.
1592 MaybeAlign ByValAlign = CB.getParamAlign(ArgNo);
1593 if (!ByValAlign) return false;
1594
1595 // If it is greater than the memcpy, then we check to see if we can force the
1596 // source of the memcpy to the alignment we need. If we fail, we bail out.
1597 MaybeAlign MemDepAlign = MDep->getSourceAlign();
1598 if ((!MemDepAlign || *MemDepAlign < *ByValAlign) &&
1599 getOrEnforceKnownAlignment(MDep->getSource(), ByValAlign, DL, &CB, AC,
1600 DT) < *ByValAlign)
1601 return false;
1602
1603 // The address space of the memcpy source must match the byval argument
1604 if (MDep->getSource()->getType()->getPointerAddressSpace() !=
1605 ByValArg->getType()->getPointerAddressSpace())
1606 return false;
1607
1608 // Verify that the copied-from memory doesn't change in between the memcpy and
1609 // the byval call.
1610 // memcpy(a <- b)
1611 // *b = 42;
1612 // foo(*a)
1613 // It would be invalid to transform the second memcpy into foo(*b).
1614 if (EnableMemorySSA) {
1615 if (writtenBetween(MSSA, MemoryLocation::getForSource(MDep),
1616 MSSA->getMemoryAccess(MDep), MSSA->getMemoryAccess(&CB)))
1617 return false;
1618 } else {
1619 // NOTE: This is conservative, it will stop on any read from the source loc,
1620 // not just the defining memcpy.
1621 MemDepResult SourceDep = MD->getPointerDependencyFrom(
1622 MemoryLocation::getForSource(MDep), false,
1623 CB.getIterator(), MDep->getParent());
1624 if (!SourceDep.isClobber() || SourceDep.getInst() != MDep)
1625 return false;
1626 }
1627
1628 Value *TmpCast = MDep->getSource();
1629 if (MDep->getSource()->getType() != ByValArg->getType()) {
1630 BitCastInst *TmpBitCast = new BitCastInst(MDep->getSource(), ByValArg->getType(),
1631 "tmpcast", &CB);
1632 // Set the tmpcast's DebugLoc to MDep's
1633 TmpBitCast->setDebugLoc(MDep->getDebugLoc());
1634 TmpCast = TmpBitCast;
1635 }
1636
1637 LLVM_DEBUG(dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
<< " " << *MDep << "\n" << " " <<
CB << "\n"; } } while (false)
1638 << " " << *MDep << "\n"do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
<< " " << *MDep << "\n" << " " <<
CB << "\n"; } } while (false)
1639 << " " << CB << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("memcpyopt")) { dbgs() << "MemCpyOptPass: Forwarding memcpy to byval:\n"
<< " " << *MDep << "\n" << " " <<
CB << "\n"; } } while (false)
;
1640
1641 // Otherwise we're good! Update the byval argument.
1642 CB.setArgOperand(ArgNo, TmpCast);
1643 ++NumMemCpyInstr;
1644 return true;
1645}
1646
1647/// Executes one iteration of MemCpyOptPass.
1648bool MemCpyOptPass::iterateOnFunction(Function &F) {
1649 bool MadeChange = false;
1650
1651 // Walk all instruction in the function.
1652 for (BasicBlock &BB : F) {
1653 // Skip unreachable blocks. For example processStore assumes that an
1654 // instruction in a BB can't be dominated by a later instruction in the
1655 // same BB (which is a scenario that can happen for an unreachable BB that
1656 // has itself as a predecessor).
1657 if (!DT->isReachableFromEntry(&BB))
17
Assuming the condition is false
18
Taking false branch
1658 continue;
1659
1660 for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
19
Loop condition is true. Entering loop body
1661 // Avoid invalidating the iterator.
1662 Instruction *I = &*BI++;
1663
1664 bool RepeatInstruction = false;
1665
1666 if (StoreInst *SI
20.1
'SI' is null
20.1
'SI' is null
20.1
'SI' is null
20.1
'SI' is null
= dyn_cast<StoreInst>(I))
20
Assuming 'I' is not a 'StoreInst'
21
Taking false branch
1667 MadeChange |= processStore(SI, BI);
1668 else if (MemSetInst *M
22.1
'M' is null
22.1
'M' is null
22.1
'M' is null
22.1
'M' is null
= dyn_cast<MemSetInst>(I))
22
Assuming 'I' is not a 'MemSetInst'
23
Taking false branch
1669 RepeatInstruction = processMemSet(M, BI);
1670 else if (MemCpyInst *M
24.1
'M' is non-null
24.1
'M' is non-null
24.1
'M' is non-null
24.1
'M' is non-null
= dyn_cast<MemCpyInst>(I))
24
Assuming 'I' is a 'MemCpyInst'
25
Taking true branch
1671 RepeatInstruction = processMemCpy(M, BI);
26
Calling 'MemCpyOptPass::processMemCpy'
1672 else if (MemMoveInst *M = dyn_cast<MemMoveInst>(I))
1673 RepeatInstruction = processMemMove(M);
1674 else if (auto *CB = dyn_cast<CallBase>(I)) {
1675 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i)
1676 if (CB->isByValArgument(i))
1677 MadeChange |= processByValArgument(*CB, i);
1678 }
1679
1680 // Reprocess the instruction if desired.
1681 if (RepeatInstruction) {
1682 if (BI != BB.begin())
1683 --BI;
1684 MadeChange = true;
1685 }
1686 }
1687 }
1688
1689 return MadeChange;
1690}
1691
1692PreservedAnalyses MemCpyOptPass::run(Function &F, FunctionAnalysisManager &AM) {
1693 auto *MD = !EnableMemorySSA ? &AM.getResult<MemoryDependenceAnalysis>(F)
1694 : AM.getCachedResult<MemoryDependenceAnalysis>(F);
1695 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
1696 auto *AA = &AM.getResult<AAManager>(F);
1697 auto *AC = &AM.getResult<AssumptionAnalysis>(F);
1698 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
1699 auto *MSSA = EnableMemorySSA ? &AM.getResult<MemorySSAAnalysis>(F)
1700 : AM.getCachedResult<MemorySSAAnalysis>(F);
1701
1702 bool MadeChange =
1703 runImpl(F, MD, &TLI, AA, AC, DT, MSSA ? &MSSA->getMSSA() : nullptr);
1704 if (!MadeChange)
1705 return PreservedAnalyses::all();
1706
1707 PreservedAnalyses PA;
1708 PA.preserveSet<CFGAnalyses>();
1709 PA.preserve<GlobalsAA>();
1710 if (MD)
1711 PA.preserve<MemoryDependenceAnalysis>();
1712 if (MSSA)
1713 PA.preserve<MemorySSAAnalysis>();
1714 return PA;
1715}
1716
1717bool MemCpyOptPass::runImpl(Function &F, MemoryDependenceResults *MD_,
1718 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
1719 AssumptionCache *AC_, DominatorTree *DT_,
1720 MemorySSA *MSSA_) {
1721 bool MadeChange = false;
1722 MD = MD_;
12
Null pointer value stored to field 'MD'
1723 TLI = TLI_;
1724 AA = AA_;
1725 AC = AC_;
1726 DT = DT_;
1727 MSSA = MSSA_;
1728 MemorySSAUpdater MSSAU_(MSSA_);
1729 MSSAU = MSSA_
12.1
'MSSA_' is null
12.1
'MSSA_' is null
12.1
'MSSA_' is null
12.1
'MSSA_' is null
? &MSSAU_ : nullptr;
13
'?' condition is false
1730 // If we don't have at least memset and memcpy, there is little point of doing
1731 // anything here. These are required by a freestanding implementation, so if
1732 // even they are disabled, there is no point in trying hard.
1733 if (!TLI->has(LibFunc_memset) || !TLI->has(LibFunc_memcpy))
14
Taking false branch
1734 return false;
1735
1736 while (true) {
15
Loop condition is true. Entering loop body
1737 if (!iterateOnFunction(F))
16
Calling 'MemCpyOptPass::iterateOnFunction'
1738 break;
1739 MadeChange = true;
1740 }
1741
1742 if (MSSA_ && VerifyMemorySSA)
1743 MSSA_->verifyMemorySSA();
1744
1745 MD = nullptr;
1746 return MadeChange;
1747}
1748
1749/// This is the main transformation entry point for a function.
1750bool MemCpyOptLegacyPass::runOnFunction(Function &F) {
1751 if (skipFunction(F))
1
Assuming the condition is false
2
Taking false branch
1752 return false;
1753
1754 auto *MDWP = !EnableMemorySSA
3
Assuming the condition is false
4
'?' condition is false
1755 ? &getAnalysis<MemoryDependenceWrapperPass>()
1756 : getAnalysisIfAvailable<MemoryDependenceWrapperPass>();
1757 auto *TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1758 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
1759 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
1760 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1761 auto *MSSAWP = EnableMemorySSA
5
Assuming the condition is false
6
'?' condition is false
1762 ? &getAnalysis<MemorySSAWrapperPass>()
1763 : getAnalysisIfAvailable<MemorySSAWrapperPass>();
1764
1765 return Impl.runImpl(F, MDWP ? & MDWP->getMemDep() : nullptr, TLI, AA, AC, DT,
7
Assuming 'MDWP' is null
8
'?' condition is false
10
Passing null pointer value via 2nd parameter 'MD_'
11
Calling 'MemCpyOptPass::runImpl'
1766 MSSAWP
8.1
'MSSAWP' is null
8.1
'MSSAWP' is null
8.1
'MSSAWP' is null
8.1
'MSSAWP' is null
? &MSSAWP->getMSSA() : nullptr)
;
9
'?' condition is false
1767}

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h

1//===-- llvm/IntrinsicInst.h - Intrinsic Instruction Wrappers ---*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines classes that make it really easy to deal with intrinsic
10// functions with the isa/dyncast family of functions. In particular, this
11// allows you to do things like:
12//
13// if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(Inst))
14// ... MCI->getDest() ... MCI->getSource() ...
15//
16// All intrinsic function calls are instances of the call instruction, so these
17// are all subclasses of the CallInst class. Note that none of these classes
18// has state or virtual methods, which is an important part of this gross/neat
19// hack working.
20//
21//===----------------------------------------------------------------------===//
22
23#ifndef LLVM_IR_INTRINSICINST_H
24#define LLVM_IR_INTRINSICINST_H
25
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DebugInfoMetadata.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/FPEnv.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/Instructions.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/Value.h"
36#include "llvm/Support/Casting.h"
37#include <cassert>
38#include <cstdint>
39
40namespace llvm {
41
42/// A wrapper class for inspecting calls to intrinsic functions.
43/// This allows the standard isa/dyncast/cast functionality to work with calls
44/// to intrinsic functions.
45class IntrinsicInst : public CallInst {
46public:
47 IntrinsicInst() = delete;
48 IntrinsicInst(const IntrinsicInst &) = delete;
49 IntrinsicInst &operator=(const IntrinsicInst &) = delete;
50
51 /// Return the intrinsic ID of this intrinsic.
52 Intrinsic::ID getIntrinsicID() const {
53 return getCalledFunction()->getIntrinsicID();
54 }
55
56 /// Return true if swapping the first two arguments to the intrinsic produces
57 /// the same result.
58 bool isCommutative() const {
59 switch (getIntrinsicID()) {
60 case Intrinsic::maxnum:
61 case Intrinsic::minnum:
62 case Intrinsic::maximum:
63 case Intrinsic::minimum:
64 case Intrinsic::smax:
65 case Intrinsic::smin:
66 case Intrinsic::umax:
67 case Intrinsic::umin:
68 case Intrinsic::sadd_sat:
69 case Intrinsic::uadd_sat:
70 case Intrinsic::sadd_with_overflow:
71 case Intrinsic::uadd_with_overflow:
72 case Intrinsic::smul_with_overflow:
73 case Intrinsic::umul_with_overflow:
74 case Intrinsic::smul_fix:
75 case Intrinsic::umul_fix:
76 case Intrinsic::smul_fix_sat:
77 case Intrinsic::umul_fix_sat:
78 case Intrinsic::fma:
79 case Intrinsic::fmuladd:
80 return true;
81 default:
82 return false;
83 }
84 }
85
86 // Checks if the intrinsic is an annotation.
87 bool isAssumeLikeIntrinsic() const {
88 switch (getIntrinsicID()) {
89 default: break;
90 case Intrinsic::assume:
91 case Intrinsic::sideeffect:
92 case Intrinsic::pseudoprobe:
93 case Intrinsic::dbg_declare:
94 case Intrinsic::dbg_value:
95 case Intrinsic::dbg_label:
96 case Intrinsic::invariant_start:
97 case Intrinsic::invariant_end:
98 case Intrinsic::lifetime_start:
99 case Intrinsic::lifetime_end:
100 case Intrinsic::experimental_noalias_scope_decl:
101 case Intrinsic::objectsize:
102 case Intrinsic::ptr_annotation:
103 case Intrinsic::var_annotation:
104 return true;
105 }
106 return false;
107 }
108
109 // Methods for support type inquiry through isa, cast, and dyn_cast:
110 static bool classof(const CallInst *I) {
111 if (const Function *CF = I->getCalledFunction())
112 return CF->isIntrinsic();
113 return false;
114 }
115 static bool classof(const Value *V) {
116 return isa<CallInst>(V) && classof(cast<CallInst>(V));
117 }
118};
119
120/// Check if \p ID corresponds to a debug info intrinsic.
121static inline bool isDbgInfoIntrinsic(Intrinsic::ID ID) {
122 switch (ID) {
123 case Intrinsic::dbg_declare:
124 case Intrinsic::dbg_value:
125 case Intrinsic::dbg_addr:
126 case Intrinsic::dbg_label:
127 return true;
128 default:
129 return false;
130 }
131}
132
133/// This is the common base class for debug info intrinsics.
134class DbgInfoIntrinsic : public IntrinsicInst {
135public:
136 /// \name Casting methods
137 /// @{
138 static bool classof(const IntrinsicInst *I) {
139 return isDbgInfoIntrinsic(I->getIntrinsicID());
140 }
141 static bool classof(const Value *V) {
142 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
143 }
144 /// @}
145};
146
147/// This is the common base class for debug info intrinsics for variables.
148class DbgVariableIntrinsic : public DbgInfoIntrinsic {
149public:
150 // Iterator for ValueAsMetadata that internally uses direct pointer iteration
151 // over either a ValueAsMetadata* or a ValueAsMetadata**, dereferencing to the
152 // ValueAsMetadata .
153 class location_op_iterator
154 : public iterator_facade_base<location_op_iterator,
155 std::bidirectional_iterator_tag, Value *> {
156 PointerUnion<ValueAsMetadata *, ValueAsMetadata **> I;
157
158 public:
159 location_op_iterator(ValueAsMetadata *SingleIter) : I(SingleIter) {}
160 location_op_iterator(ValueAsMetadata **MultiIter) : I(MultiIter) {}
161
162 location_op_iterator(const location_op_iterator &R) : I(R.I) {}
163 location_op_iterator &operator=(const location_op_iterator &R) {
164 I = R.I;
165 return *this;
166 }
167 bool operator==(const location_op_iterator &RHS) const {
168 return I == RHS.I;
169 }
170 const Value *operator*() const {
171 ValueAsMetadata *VAM = I.is<ValueAsMetadata *>()
172 ? I.get<ValueAsMetadata *>()
173 : *I.get<ValueAsMetadata **>();
174 return VAM->getValue();
175 };
176 Value *operator*() {
177 ValueAsMetadata *VAM = I.is<ValueAsMetadata *>()
178 ? I.get<ValueAsMetadata *>()
179 : *I.get<ValueAsMetadata **>();
180 return VAM->getValue();
181 }
182 location_op_iterator &operator++() {
183 if (I.is<ValueAsMetadata *>())
184 I = I.get<ValueAsMetadata *>() + 1;
185 else
186 I = I.get<ValueAsMetadata **>() + 1;
187 return *this;
188 }
189 location_op_iterator &operator--() {
190 if (I.is<ValueAsMetadata *>())
191 I = I.get<ValueAsMetadata *>() - 1;
192 else
193 I = I.get<ValueAsMetadata **>() - 1;
194 return *this;
195 }
196 };
197
198 /// Get the locations corresponding to the variable referenced by the debug
199 /// info intrinsic. Depending on the intrinsic, this could be the
200 /// variable's value or its address.
201 iterator_range<location_op_iterator> location_ops() const;
202
203 Value *getVariableLocationOp(unsigned OpIdx) const;
204
205 void replaceVariableLocationOp(Value *OldValue, Value *NewValue);
206 void replaceVariableLocationOp(unsigned OpIdx, Value *NewValue);
207
208 void setVariable(DILocalVariable *NewVar) {
209 setArgOperand(1, MetadataAsValue::get(NewVar->getContext(), NewVar));
210 }
211
212 void setExpression(DIExpression *NewExpr) {
213 setArgOperand(2, MetadataAsValue::get(NewExpr->getContext(), NewExpr));
214 }
215
216 unsigned getNumVariableLocationOps() const {
217 if (hasArgList())
218 return cast<DIArgList>(getRawLocation())->getArgs().size();
219 return 1;
220 }
221
222 bool hasArgList() const { return isa<DIArgList>(getRawLocation()); }
223
224 /// Does this describe the address of a local variable. True for dbg.addr
225 /// and dbg.declare, but not dbg.value, which describes its value.
226 bool isAddressOfVariable() const {
227 return getIntrinsicID() != Intrinsic::dbg_value;
228 }
229
230 void setUndef() {
231 // TODO: When/if we remove duplicate values from DIArgLists, we don't need
232 // this set anymore.
233 SmallPtrSet<Value *, 4> RemovedValues;
234 for (Value *OldValue : location_ops()) {
235 if (!RemovedValues.insert(OldValue).second)
236 continue;
237 Value *Undef = UndefValue::get(OldValue->getType());
238 replaceVariableLocationOp(OldValue, Undef);
239 }
240 }
241
242 bool isUndef() const {
243 return (getNumVariableLocationOps() == 0 &&
244 !getExpression()->isComplex()) ||
245 any_of(location_ops(), [](Value *V) { return isa<UndefValue>(V); });
246 }
247
248 DILocalVariable *getVariable() const {
249 return cast<DILocalVariable>(getRawVariable());
250 }
251
252 DIExpression *getExpression() const {
253 return cast<DIExpression>(getRawExpression());
254 }
255
256 Metadata *getRawLocation() const {
257 return cast<MetadataAsValue>(getArgOperand(0))->getMetadata();
258 }
259
260 Metadata *getRawVariable() const {
261 return cast<MetadataAsValue>(getArgOperand(1))->getMetadata();
262 }
263
264 Metadata *getRawExpression() const {
265 return cast<MetadataAsValue>(getArgOperand(2))->getMetadata();
266 }
267
268 /// Use of this should generally be avoided; instead,
269 /// replaceVariableLocationOp and addVariableLocationOps should be used where
270 /// possible to avoid creating invalid state.
271 void setRawLocation(Metadata *Location) {
272 return setArgOperand(0, MetadataAsValue::get(getContext(), Location));
273 }
274
275 /// Get the size (in bits) of the variable, or fragment of the variable that
276 /// is described.
277 Optional<uint64_t> getFragmentSizeInBits() const;
278
279 /// \name Casting methods
280 /// @{
281 static bool classof(const IntrinsicInst *I) {
282 switch (I->getIntrinsicID()) {
283 case Intrinsic::dbg_declare:
284 case Intrinsic::dbg_value:
285 case Intrinsic::dbg_addr:
286 return true;
287 default:
288 return false;
289 }
290 }
291 static bool classof(const Value *V) {
292 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
293 }
294 /// @}
295private:
296 void setArgOperand(unsigned i, Value *v) {
297 DbgInfoIntrinsic::setArgOperand(i, v);
298 }
299 void setOperand(unsigned i, Value *v) { DbgInfoIntrinsic::setOperand(i, v); }
300};
301
302/// This represents the llvm.dbg.declare instruction.
303class DbgDeclareInst : public DbgVariableIntrinsic {
304public:
305 Value *getAddress() const {
306 assert(getNumVariableLocationOps() == 1 &&((getNumVariableLocationOps() == 1 && "dbg.declare must have exactly 1 location operand."
) ? static_cast<void> (0) : __assert_fail ("getNumVariableLocationOps() == 1 && \"dbg.declare must have exactly 1 location operand.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 307, __PRETTY_FUNCTION__))
307 "dbg.declare must have exactly 1 location operand.")((getNumVariableLocationOps() == 1 && "dbg.declare must have exactly 1 location operand."
) ? static_cast<void> (0) : __assert_fail ("getNumVariableLocationOps() == 1 && \"dbg.declare must have exactly 1 location operand.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 307, __PRETTY_FUNCTION__))
;
308 return getVariableLocationOp(0);
309 }
310
311 /// \name Casting methods
312 /// @{
313 static bool classof(const IntrinsicInst *I) {
314 return I->getIntrinsicID() == Intrinsic::dbg_declare;
315 }
316 static bool classof(const Value *V) {
317 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
318 }
319 /// @}
320};
321
322/// This represents the llvm.dbg.addr instruction.
323class DbgAddrIntrinsic : public DbgVariableIntrinsic {
324public:
325 Value *getAddress() const {
326 assert(getNumVariableLocationOps() == 1 &&((getNumVariableLocationOps() == 1 && "dbg.addr must have exactly 1 location operand."
) ? static_cast<void> (0) : __assert_fail ("getNumVariableLocationOps() == 1 && \"dbg.addr must have exactly 1 location operand.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 327, __PRETTY_FUNCTION__))
327 "dbg.addr must have exactly 1 location operand.")((getNumVariableLocationOps() == 1 && "dbg.addr must have exactly 1 location operand."
) ? static_cast<void> (0) : __assert_fail ("getNumVariableLocationOps() == 1 && \"dbg.addr must have exactly 1 location operand.\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 327, __PRETTY_FUNCTION__))
;
328 return getVariableLocationOp(0);
329 }
330
331 /// \name Casting methods
332 /// @{
333 static bool classof(const IntrinsicInst *I) {
334 return I->getIntrinsicID() == Intrinsic::dbg_addr;
335 }
336 static bool classof(const Value *V) {
337 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
338 }
339};
340
341/// This represents the llvm.dbg.value instruction.
342class DbgValueInst : public DbgVariableIntrinsic {
343public:
344 // The default argument should only be used in ISel, and the default option
345 // should be removed once ISel support for multiple location ops is complete.
346 Value *getValue(unsigned OpIdx = 0) const {
347 return getVariableLocationOp(OpIdx);
348 }
349 iterator_range<location_op_iterator> getValues() const {
350 return location_ops();
351 }
352
353 /// \name Casting methods
354 /// @{
355 static bool classof(const IntrinsicInst *I) {
356 return I->getIntrinsicID() == Intrinsic::dbg_value;
357 }
358 static bool classof(const Value *V) {
359 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
360 }
361 /// @}
362};
363
364/// This represents the llvm.dbg.label instruction.
365class DbgLabelInst : public DbgInfoIntrinsic {
366public:
367 DILabel *getLabel() const { return cast<DILabel>(getRawLabel()); }
368
369 Metadata *getRawLabel() const {
370 return cast<MetadataAsValue>(getArgOperand(0))->getMetadata();
371 }
372
373 /// Methods for support type inquiry through isa, cast, and dyn_cast:
374 /// @{
375 static bool classof(const IntrinsicInst *I) {
376 return I->getIntrinsicID() == Intrinsic::dbg_label;
377 }
378 static bool classof(const Value *V) {
379 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
380 }
381 /// @}
382};
383
384/// This is the common base class for vector predication intrinsics.
385class VPIntrinsic : public IntrinsicInst {
386public:
387 static Optional<int> GetMaskParamPos(Intrinsic::ID IntrinsicID);
388 static Optional<int> GetVectorLengthParamPos(Intrinsic::ID IntrinsicID);
389
390 /// The llvm.vp.* intrinsics for this instruction Opcode
391 static Intrinsic::ID GetForOpcode(unsigned OC);
392
393 // Whether \p ID is a VP intrinsic ID.
394 static bool IsVPIntrinsic(Intrinsic::ID);
395
396 /// \return the mask parameter or nullptr.
397 Value *getMaskParam() const;
398
399 /// \return the vector length parameter or nullptr.
400 Value *getVectorLengthParam() const;
401
402 /// \return whether the vector length param can be ignored.
403 bool canIgnoreVectorLengthParam() const;
404
405 /// \return the static element count (vector number of elements) the vector
406 /// length parameter applies to.
407 ElementCount getStaticVectorLength() const;
408
409 // Methods for support type inquiry through isa, cast, and dyn_cast:
410 static bool classof(const IntrinsicInst *I) {
411 return IsVPIntrinsic(I->getIntrinsicID());
412 }
413 static bool classof(const Value *V) {
414 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
415 }
416
417 // Equivalent non-predicated opcode
418 unsigned getFunctionalOpcode() const {
419 return GetFunctionalOpcodeForVP(getIntrinsicID());
420 }
421
422 // Equivalent non-predicated opcode
423 static unsigned GetFunctionalOpcodeForVP(Intrinsic::ID ID);
424};
425
426/// This is the common base class for constrained floating point intrinsics.
427class ConstrainedFPIntrinsic : public IntrinsicInst {
428public:
429 bool isUnaryOp() const;
430 bool isTernaryOp() const;
431 Optional<RoundingMode> getRoundingMode() const;
432 Optional<fp::ExceptionBehavior> getExceptionBehavior() const;
433
434 // Methods for support type inquiry through isa, cast, and dyn_cast:
435 static bool classof(const IntrinsicInst *I);
436 static bool classof(const Value *V) {
437 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
438 }
439};
440
441/// Constrained floating point compare intrinsics.
442class ConstrainedFPCmpIntrinsic : public ConstrainedFPIntrinsic {
443public:
444 FCmpInst::Predicate getPredicate() const;
445
446 // Methods for support type inquiry through isa, cast, and dyn_cast:
447 static bool classof(const IntrinsicInst *I) {
448 switch (I->getIntrinsicID()) {
449 case Intrinsic::experimental_constrained_fcmp:
450 case Intrinsic::experimental_constrained_fcmps:
451 return true;
452 default:
453 return false;
454 }
455 }
456 static bool classof(const Value *V) {
457 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
458 }
459};
460
461/// This class represents min/max intrinsics.
462class MinMaxIntrinsic : public IntrinsicInst {
463public:
464 static bool classof(const IntrinsicInst *I) {
465 switch (I->getIntrinsicID()) {
466 case Intrinsic::umin:
467 case Intrinsic::umax:
468 case Intrinsic::smin:
469 case Intrinsic::smax:
470 return true;
471 default:
472 return false;
473 }
474 }
475 static bool classof(const Value *V) {
476 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
477 }
478
479 Value *getLHS() const { return const_cast<Value *>(getArgOperand(0)); }
480 Value *getRHS() const { return const_cast<Value *>(getArgOperand(1)); }
481
482 /// Returns the comparison predicate underlying the intrinsic.
483 ICmpInst::Predicate getPredicate() const {
484 switch (getIntrinsicID()) {
485 case Intrinsic::umin:
486 return ICmpInst::Predicate::ICMP_ULT;
487 case Intrinsic::umax:
488 return ICmpInst::Predicate::ICMP_UGT;
489 case Intrinsic::smin:
490 return ICmpInst::Predicate::ICMP_SLT;
491 case Intrinsic::smax:
492 return ICmpInst::Predicate::ICMP_SGT;
493 default:
494 llvm_unreachable("Invalid intrinsic")::llvm::llvm_unreachable_internal("Invalid intrinsic", "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 494)
;
495 }
496 }
497
498 /// Whether the intrinsic is signed or unsigned.
499 bool isSigned() const { return ICmpInst::isSigned(getPredicate()); };
500};
501
502/// This class represents an intrinsic that is based on a binary operation.
503/// This includes op.with.overflow and saturating add/sub intrinsics.
504class BinaryOpIntrinsic : public IntrinsicInst {
505public:
506 static bool classof(const IntrinsicInst *I) {
507 switch (I->getIntrinsicID()) {
508 case Intrinsic::uadd_with_overflow:
509 case Intrinsic::sadd_with_overflow:
510 case Intrinsic::usub_with_overflow:
511 case Intrinsic::ssub_with_overflow:
512 case Intrinsic::umul_with_overflow:
513 case Intrinsic::smul_with_overflow:
514 case Intrinsic::uadd_sat:
515 case Intrinsic::sadd_sat:
516 case Intrinsic::usub_sat:
517 case Intrinsic::ssub_sat:
518 return true;
519 default:
520 return false;
521 }
522 }
523 static bool classof(const Value *V) {
524 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
525 }
526
527 Value *getLHS() const { return const_cast<Value *>(getArgOperand(0)); }
528 Value *getRHS() const { return const_cast<Value *>(getArgOperand(1)); }
529
530 /// Returns the binary operation underlying the intrinsic.
531 Instruction::BinaryOps getBinaryOp() const;
532
533 /// Whether the intrinsic is signed or unsigned.
534 bool isSigned() const;
535
536 /// Returns one of OBO::NoSignedWrap or OBO::NoUnsignedWrap.
537 unsigned getNoWrapKind() const;
538};
539
540/// Represents an op.with.overflow intrinsic.
541class WithOverflowInst : public BinaryOpIntrinsic {
542public:
543 static bool classof(const IntrinsicInst *I) {
544 switch (I->getIntrinsicID()) {
545 case Intrinsic::uadd_with_overflow:
546 case Intrinsic::sadd_with_overflow:
547 case Intrinsic::usub_with_overflow:
548 case Intrinsic::ssub_with_overflow:
549 case Intrinsic::umul_with_overflow:
550 case Intrinsic::smul_with_overflow:
551 return true;
552 default:
553 return false;
554 }
555 }
556 static bool classof(const Value *V) {
557 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
558 }
559};
560
561/// Represents a saturating add/sub intrinsic.
562class SaturatingInst : public BinaryOpIntrinsic {
563public:
564 static bool classof(const IntrinsicInst *I) {
565 switch (I->getIntrinsicID()) {
566 case Intrinsic::uadd_sat:
567 case Intrinsic::sadd_sat:
568 case Intrinsic::usub_sat:
569 case Intrinsic::ssub_sat:
570 return true;
571 default:
572 return false;
573 }
574 }
575 static bool classof(const Value *V) {
576 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
577 }
578};
579
580/// Common base class for all memory intrinsics. Simply provides
581/// common methods.
582/// Written as CRTP to avoid a common base class amongst the
583/// three atomicity hierarchies.
584template <typename Derived> class MemIntrinsicBase : public IntrinsicInst {
585private:
586 enum { ARG_DEST = 0, ARG_LENGTH = 2 };
587
588public:
589 Value *getRawDest() const {
590 return const_cast<Value *>(getArgOperand(ARG_DEST));
591 }
592 const Use &getRawDestUse() const { return getArgOperandUse(ARG_DEST); }
593 Use &getRawDestUse() { return getArgOperandUse(ARG_DEST); }
594
595 Value *getLength() const {
596 return const_cast<Value *>(getArgOperand(ARG_LENGTH));
597 }
598 const Use &getLengthUse() const { return getArgOperandUse(ARG_LENGTH); }
599 Use &getLengthUse() { return getArgOperandUse(ARG_LENGTH); }
600
601 /// This is just like getRawDest, but it strips off any cast
602 /// instructions (including addrspacecast) that feed it, giving the
603 /// original input. The returned value is guaranteed to be a pointer.
604 Value *getDest() const { return getRawDest()->stripPointerCasts(); }
605
606 unsigned getDestAddressSpace() const {
607 return cast<PointerType>(getRawDest()->getType())->getAddressSpace();
608 }
609
610 /// FIXME: Remove this function once transition to Align is over.
611 /// Use getDestAlign() instead.
612 unsigned getDestAlignment() const {
613 if (auto MA = getParamAlign(ARG_DEST))
614 return MA->value();
615 return 0;
616 }
617 MaybeAlign getDestAlign() const { return getParamAlign(ARG_DEST); }
618
619 /// Set the specified arguments of the instruction.
620 void setDest(Value *Ptr) {
621 assert(getRawDest()->getType() == Ptr->getType() &&((getRawDest()->getType() == Ptr->getType() && "setDest called with pointer of wrong type!"
) ? static_cast<void> (0) : __assert_fail ("getRawDest()->getType() == Ptr->getType() && \"setDest called with pointer of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 622, __PRETTY_FUNCTION__))
622 "setDest called with pointer of wrong type!")((getRawDest()->getType() == Ptr->getType() && "setDest called with pointer of wrong type!"
) ? static_cast<void> (0) : __assert_fail ("getRawDest()->getType() == Ptr->getType() && \"setDest called with pointer of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 622, __PRETTY_FUNCTION__))
;
623 setArgOperand(ARG_DEST, Ptr);
624 }
625
626 /// FIXME: Remove this function once transition to Align is over.
627 /// Use the version that takes MaybeAlign instead of this one.
628 void setDestAlignment(unsigned Alignment) {
629 setDestAlignment(MaybeAlign(Alignment));
630 }
631 void setDestAlignment(MaybeAlign Alignment) {
632 removeParamAttr(ARG_DEST, Attribute::Alignment);
633 if (Alignment)
634 addParamAttr(ARG_DEST,
635 Attribute::getWithAlignment(getContext(), *Alignment));
636 }
637 void setDestAlignment(Align Alignment) {
638 removeParamAttr(ARG_DEST, Attribute::Alignment);
639 addParamAttr(ARG_DEST,
640 Attribute::getWithAlignment(getContext(), Alignment));
641 }
642
643 void setLength(Value *L) {
644 assert(getLength()->getType() == L->getType() &&((getLength()->getType() == L->getType() && "setLength called with value of wrong type!"
) ? static_cast<void> (0) : __assert_fail ("getLength()->getType() == L->getType() && \"setLength called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 645, __PRETTY_FUNCTION__))
645 "setLength called with value of wrong type!")((getLength()->getType() == L->getType() && "setLength called with value of wrong type!"
) ? static_cast<void> (0) : __assert_fail ("getLength()->getType() == L->getType() && \"setLength called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 645, __PRETTY_FUNCTION__))
;
646 setArgOperand(ARG_LENGTH, L);
647 }
648};
649
650/// Common base class for all memory transfer intrinsics. Simply provides
651/// common methods.
652template <class BaseCL> class MemTransferBase : public BaseCL {
653private:
654 enum { ARG_SOURCE = 1 };
655
656public:
657 /// Return the arguments to the instruction.
658 Value *getRawSource() const {
659 return const_cast<Value *>(BaseCL::getArgOperand(ARG_SOURCE));
660 }
661 const Use &getRawSourceUse() const {
662 return BaseCL::getArgOperandUse(ARG_SOURCE);
663 }
664 Use &getRawSourceUse() { return BaseCL::getArgOperandUse(ARG_SOURCE); }
665
666 /// This is just like getRawSource, but it strips off any cast
667 /// instructions that feed it, giving the original input. The returned
668 /// value is guaranteed to be a pointer.
669 Value *getSource() const { return getRawSource()->stripPointerCasts(); }
670
671 unsigned getSourceAddressSpace() const {
672 return cast<PointerType>(getRawSource()->getType())->getAddressSpace();
673 }
674
675 /// FIXME: Remove this function once transition to Align is over.
676 /// Use getSourceAlign() instead.
677 unsigned getSourceAlignment() const {
678 if (auto MA = BaseCL::getParamAlign(ARG_SOURCE))
679 return MA->value();
680 return 0;
681 }
682
683 MaybeAlign getSourceAlign() const {
684 return BaseCL::getParamAlign(ARG_SOURCE);
685 }
686
687 void setSource(Value *Ptr) {
688 assert(getRawSource()->getType() == Ptr->getType() &&((getRawSource()->getType() == Ptr->getType() &&
"setSource called with pointer of wrong type!") ? static_cast
<void> (0) : __assert_fail ("getRawSource()->getType() == Ptr->getType() && \"setSource called with pointer of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 689, __PRETTY_FUNCTION__))
689 "setSource called with pointer of wrong type!")((getRawSource()->getType() == Ptr->getType() &&
"setSource called with pointer of wrong type!") ? static_cast
<void> (0) : __assert_fail ("getRawSource()->getType() == Ptr->getType() && \"setSource called with pointer of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 689, __PRETTY_FUNCTION__))
;
690 BaseCL::setArgOperand(ARG_SOURCE, Ptr);
691 }
692
693 /// FIXME: Remove this function once transition to Align is over.
694 /// Use the version that takes MaybeAlign instead of this one.
695 void setSourceAlignment(unsigned Alignment) {
696 setSourceAlignment(MaybeAlign(Alignment));
697 }
698 void setSourceAlignment(MaybeAlign Alignment) {
699 BaseCL::removeParamAttr(ARG_SOURCE, Attribute::Alignment);
700 if (Alignment)
701 BaseCL::addParamAttr(ARG_SOURCE, Attribute::getWithAlignment(
702 BaseCL::getContext(), *Alignment));
703 }
704 void setSourceAlignment(Align Alignment) {
705 BaseCL::removeParamAttr(ARG_SOURCE, Attribute::Alignment);
706 BaseCL::addParamAttr(ARG_SOURCE, Attribute::getWithAlignment(
707 BaseCL::getContext(), Alignment));
708 }
709};
710
711/// Common base class for all memset intrinsics. Simply provides
712/// common methods.
713template <class BaseCL> class MemSetBase : public BaseCL {
714private:
715 enum { ARG_VALUE = 1 };
716
717public:
718 Value *getValue() const {
719 return const_cast<Value *>(BaseCL::getArgOperand(ARG_VALUE));
720 }
721 const Use &getValueUse() const { return BaseCL::getArgOperandUse(ARG_VALUE); }
722 Use &getValueUse() { return BaseCL::getArgOperandUse(ARG_VALUE); }
723
724 void setValue(Value *Val) {
725 assert(getValue()->getType() == Val->getType() &&((getValue()->getType() == Val->getType() && "setValue called with value of wrong type!"
) ? static_cast<void> (0) : __assert_fail ("getValue()->getType() == Val->getType() && \"setValue called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 726, __PRETTY_FUNCTION__))
726 "setValue called with value of wrong type!")((getValue()->getType() == Val->getType() && "setValue called with value of wrong type!"
) ? static_cast<void> (0) : __assert_fail ("getValue()->getType() == Val->getType() && \"setValue called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 726, __PRETTY_FUNCTION__))
;
727 BaseCL::setArgOperand(ARG_VALUE, Val);
728 }
729};
730
731// The common base class for the atomic memset/memmove/memcpy intrinsics
732// i.e. llvm.element.unordered.atomic.memset/memcpy/memmove
733class AtomicMemIntrinsic : public MemIntrinsicBase<AtomicMemIntrinsic> {
734private:
735 enum { ARG_ELEMENTSIZE = 3 };
736
737public:
738 Value *getRawElementSizeInBytes() const {
739 return const_cast<Value *>(getArgOperand(ARG_ELEMENTSIZE));
740 }
741
742 ConstantInt *getElementSizeInBytesCst() const {
743 return cast<ConstantInt>(getRawElementSizeInBytes());
744 }
745
746 uint32_t getElementSizeInBytes() const {
747 return getElementSizeInBytesCst()->getZExtValue();
748 }
749
750 void setElementSizeInBytes(Constant *V) {
751 assert(V->getType() == Type::getInt8Ty(getContext()) &&((V->getType() == Type::getInt8Ty(getContext()) &&
"setElementSizeInBytes called with value of wrong type!") ? static_cast
<void> (0) : __assert_fail ("V->getType() == Type::getInt8Ty(getContext()) && \"setElementSizeInBytes called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 752, __PRETTY_FUNCTION__))
752 "setElementSizeInBytes called with value of wrong type!")((V->getType() == Type::getInt8Ty(getContext()) &&
"setElementSizeInBytes called with value of wrong type!") ? static_cast
<void> (0) : __assert_fail ("V->getType() == Type::getInt8Ty(getContext()) && \"setElementSizeInBytes called with value of wrong type!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/IntrinsicInst.h"
, 752, __PRETTY_FUNCTION__))
;
753 setArgOperand(ARG_ELEMENTSIZE, V);
754 }
755
756 static bool classof(const IntrinsicInst *I) {
757 switch (I->getIntrinsicID()) {
758 case Intrinsic::memcpy_element_unordered_atomic:
759 case Intrinsic::memmove_element_unordered_atomic:
760 case Intrinsic::memset_element_unordered_atomic:
761 return true;
762 default:
763 return false;
764 }
765 }
766 static bool classof(const Value *V) {
767 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
768 }
769};
770
771/// This class represents atomic memset intrinsic
772// i.e. llvm.element.unordered.atomic.memset
773class AtomicMemSetInst : public MemSetBase<AtomicMemIntrinsic> {
774public:
775 static bool classof(const IntrinsicInst *I) {
776 return I->getIntrinsicID() == Intrinsic::memset_element_unordered_atomic;
777 }
778 static bool classof(const Value *V) {
779 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
780 }
781};
782
783// This class wraps the atomic memcpy/memmove intrinsics
784// i.e. llvm.element.unordered.atomic.memcpy/memmove
785class AtomicMemTransferInst : public MemTransferBase<AtomicMemIntrinsic> {
786public:
787 static bool classof(const IntrinsicInst *I) {
788 switch (I->getIntrinsicID()) {
789 case Intrinsic::memcpy_element_unordered_atomic:
790 case Intrinsic::memmove_element_unordered_atomic:
791 return true;
792 default:
793 return false;
794 }
795 }
796 static bool classof(const Value *V) {
797 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
798 }
799};
800
801/// This class represents the atomic memcpy intrinsic
802/// i.e. llvm.element.unordered.atomic.memcpy
803class AtomicMemCpyInst : public AtomicMemTransferInst {
804public:
805 static bool classof(const IntrinsicInst *I) {
806 return I->getIntrinsicID() == Intrinsic::memcpy_element_unordered_atomic;
807 }
808 static bool classof(const Value *V) {
809 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
810 }
811};
812
813/// This class represents the atomic memmove intrinsic
814/// i.e. llvm.element.unordered.atomic.memmove
815class AtomicMemMoveInst : public AtomicMemTransferInst {
816public:
817 static bool classof(const IntrinsicInst *I) {
818 return I->getIntrinsicID() == Intrinsic::memmove_element_unordered_atomic;
819 }
820 static bool classof(const Value *V) {
821 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
822 }
823};
824
825/// This is the common base class for memset/memcpy/memmove.
826class MemIntrinsic : public MemIntrinsicBase<MemIntrinsic> {
827private:
828 enum { ARG_VOLATILE = 3 };
829
830public:
831 ConstantInt *getVolatileCst() const {
832 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(ARG_VOLATILE)));
833 }
834
835 bool isVolatile() const { return !getVolatileCst()->isZero(); }
28
Calling 'ConstantInt::isZero'
42
Returning from 'ConstantInt::isZero'
43
Returning zero, which participates in a condition later
836
837 void setVolatile(Constant *V) { setArgOperand(ARG_VOLATILE, V); }
838
839 // Methods for support type inquiry through isa, cast, and dyn_cast:
840 static bool classof(const IntrinsicInst *I) {
841 switch (I->getIntrinsicID()) {
842 case Intrinsic::memcpy:
843 case Intrinsic::memmove:
844 case Intrinsic::memset:
845 case Intrinsic::memcpy_inline:
846 return true;
847 default:
848 return false;
849 }
850 }
851 static bool classof(const Value *V) {
852 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
853 }
854};
855
856/// This class wraps the llvm.memset intrinsic.
857class MemSetInst : public MemSetBase<MemIntrinsic> {
858public:
859 // Methods for support type inquiry through isa, cast, and dyn_cast:
860 static bool classof(const IntrinsicInst *I) {
861 return I->getIntrinsicID() == Intrinsic::memset;
862 }
863 static bool classof(const Value *V) {
864 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
865 }
866};
867
868/// This class wraps the llvm.memcpy/memmove intrinsics.
869class MemTransferInst : public MemTransferBase<MemIntrinsic> {
870public:
871 // Methods for support type inquiry through isa, cast, and dyn_cast:
872 static bool classof(const IntrinsicInst *I) {
873 switch (I->getIntrinsicID()) {
874 case Intrinsic::memcpy:
875 case Intrinsic::memmove:
876 case Intrinsic::memcpy_inline:
877 return true;
878 default:
879 return false;
880 }
881 }
882 static bool classof(const Value *V) {
883 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
884 }
885};
886
887/// This class wraps the llvm.memcpy intrinsic.
888class MemCpyInst : public MemTransferInst {
889public:
890 // Methods for support type inquiry through isa, cast, and dyn_cast:
891 static bool classof(const IntrinsicInst *I) {
892 return I->getIntrinsicID() == Intrinsic::memcpy;
893 }
894 static bool classof(const Value *V) {
895 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
896 }
897};
898
899/// This class wraps the llvm.memmove intrinsic.
900class MemMoveInst : public MemTransferInst {
901public:
902 // Methods for support type inquiry through isa, cast, and dyn_cast:
903 static bool classof(const IntrinsicInst *I) {
904 return I->getIntrinsicID() == Intrinsic::memmove;
905 }
906 static bool classof(const Value *V) {
907 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
908 }
909};
910
911/// This class wraps the llvm.memcpy.inline intrinsic.
912class MemCpyInlineInst : public MemTransferInst {
913public:
914 ConstantInt *getLength() const {
915 return cast<ConstantInt>(MemTransferInst::getLength());
916 }
917 // Methods for support type inquiry through isa, cast, and dyn_cast:
918 static bool classof(const IntrinsicInst *I) {
919 return I->getIntrinsicID() == Intrinsic::memcpy_inline;
920 }
921 static bool classof(const Value *V) {
922 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
923 }
924};
925
926// The common base class for any memset/memmove/memcpy intrinsics;
927// whether they be atomic or non-atomic.
928// i.e. llvm.element.unordered.atomic.memset/memcpy/memmove
929// and llvm.memset/memcpy/memmove
930class AnyMemIntrinsic : public MemIntrinsicBase<AnyMemIntrinsic> {
931public:
932 bool isVolatile() const {
933 // Only the non-atomic intrinsics can be volatile
934 if (auto *MI = dyn_cast<MemIntrinsic>(this))
935 return MI->isVolatile();
936 return false;
937 }
938
939 static bool classof(const IntrinsicInst *I) {
940 switch (I->getIntrinsicID()) {
941 case Intrinsic::memcpy:
942 case Intrinsic::memcpy_inline:
943 case Intrinsic::memmove:
944 case Intrinsic::memset:
945 case Intrinsic::memcpy_element_unordered_atomic:
946 case Intrinsic::memmove_element_unordered_atomic:
947 case Intrinsic::memset_element_unordered_atomic:
948 return true;
949 default:
950 return false;
951 }
952 }
953 static bool classof(const Value *V) {
954 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
955 }
956};
957
958/// This class represents any memset intrinsic
959// i.e. llvm.element.unordered.atomic.memset
960// and llvm.memset
961class AnyMemSetInst : public MemSetBase<AnyMemIntrinsic> {
962public:
963 static bool classof(const IntrinsicInst *I) {
964 switch (I->getIntrinsicID()) {
965 case Intrinsic::memset:
966 case Intrinsic::memset_element_unordered_atomic:
967 return true;
968 default:
969 return false;
970 }
971 }
972 static bool classof(const Value *V) {
973 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
974 }
975};
976
977// This class wraps any memcpy/memmove intrinsics
978// i.e. llvm.element.unordered.atomic.memcpy/memmove
979// and llvm.memcpy/memmove
980class AnyMemTransferInst : public MemTransferBase<AnyMemIntrinsic> {
981public:
982 static bool classof(const IntrinsicInst *I) {
983 switch (I->getIntrinsicID()) {
984 case Intrinsic::memcpy:
985 case Intrinsic::memcpy_inline:
986 case Intrinsic::memmove:
987 case Intrinsic::memcpy_element_unordered_atomic:
988 case Intrinsic::memmove_element_unordered_atomic:
989 return true;
990 default:
991 return false;
992 }
993 }
994 static bool classof(const Value *V) {
995 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
996 }
997};
998
999/// This class represents any memcpy intrinsic
1000/// i.e. llvm.element.unordered.atomic.memcpy
1001/// and llvm.memcpy
1002class AnyMemCpyInst : public AnyMemTransferInst {
1003public:
1004 static bool classof(const IntrinsicInst *I) {
1005 switch (I->getIntrinsicID()) {
1006 case Intrinsic::memcpy:
1007 case Intrinsic::memcpy_inline:
1008 case Intrinsic::memcpy_element_unordered_atomic:
1009 return true;
1010 default:
1011 return false;
1012 }
1013 }
1014 static bool classof(const Value *V) {
1015 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1016 }
1017};
1018
1019/// This class represents any memmove intrinsic
1020/// i.e. llvm.element.unordered.atomic.memmove
1021/// and llvm.memmove
1022class AnyMemMoveInst : public AnyMemTransferInst {
1023public:
1024 static bool classof(const IntrinsicInst *I) {
1025 switch (I->getIntrinsicID()) {
1026 case Intrinsic::memmove:
1027 case Intrinsic::memmove_element_unordered_atomic:
1028 return true;
1029 default:
1030 return false;
1031 }
1032 }
1033 static bool classof(const Value *V) {
1034 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1035 }
1036};
1037
1038/// This represents the llvm.va_start intrinsic.
1039class VAStartInst : public IntrinsicInst {
1040public:
1041 static bool classof(const IntrinsicInst *I) {
1042 return I->getIntrinsicID() == Intrinsic::vastart;
1043 }
1044 static bool classof(const Value *V) {
1045 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1046 }
1047
1048 Value *getArgList() const { return const_cast<Value *>(getArgOperand(0)); }
1049};
1050
1051/// This represents the llvm.va_end intrinsic.
1052class VAEndInst : public IntrinsicInst {
1053public:
1054 static bool classof(const IntrinsicInst *I) {
1055 return I->getIntrinsicID() == Intrinsic::vaend;
1056 }
1057 static bool classof(const Value *V) {
1058 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1059 }
1060
1061 Value *getArgList() const { return const_cast<Value *>(getArgOperand(0)); }
1062};
1063
1064/// This represents the llvm.va_copy intrinsic.
1065class VACopyInst : public IntrinsicInst {
1066public:
1067 static bool classof(const IntrinsicInst *I) {
1068 return I->getIntrinsicID() == Intrinsic::vacopy;
1069 }
1070 static bool classof(const Value *V) {
1071 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1072 }
1073
1074 Value *getDest() const { return const_cast<Value *>(getArgOperand(0)); }
1075 Value *getSrc() const { return const_cast<Value *>(getArgOperand(1)); }
1076};
1077
1078/// This represents the llvm.instrprof_increment intrinsic.
1079class InstrProfIncrementInst : public IntrinsicInst {
1080public:
1081 static bool classof(const IntrinsicInst *I) {
1082 return I->getIntrinsicID() == Intrinsic::instrprof_increment;
1083 }
1084 static bool classof(const Value *V) {
1085 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1086 }
1087
1088 GlobalVariable *getName() const {
1089 return cast<GlobalVariable>(
1090 const_cast<Value *>(getArgOperand(0))->stripPointerCasts());
1091 }
1092
1093 ConstantInt *getHash() const {
1094 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(1)));
1095 }
1096
1097 ConstantInt *getNumCounters() const {
1098 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(2)));
1099 }
1100
1101 ConstantInt *getIndex() const {
1102 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(3)));
1103 }
1104
1105 Value *getStep() const;
1106};
1107
1108class InstrProfIncrementInstStep : public InstrProfIncrementInst {
1109public:
1110 static bool classof(const IntrinsicInst *I) {
1111 return I->getIntrinsicID() == Intrinsic::instrprof_increment_step;
1112 }
1113 static bool classof(const Value *V) {
1114 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1115 }
1116};
1117
1118/// This represents the llvm.instrprof_value_profile intrinsic.
1119class InstrProfValueProfileInst : public IntrinsicInst {
1120public:
1121 static bool classof(const IntrinsicInst *I) {
1122 return I->getIntrinsicID() == Intrinsic::instrprof_value_profile;
1123 }
1124 static bool classof(const Value *V) {
1125 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1126 }
1127
1128 GlobalVariable *getName() const {
1129 return cast<GlobalVariable>(
1130 const_cast<Value *>(getArgOperand(0))->stripPointerCasts());
1131 }
1132
1133 ConstantInt *getHash() const {
1134 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(1)));
1135 }
1136
1137 Value *getTargetValue() const {
1138 return cast<Value>(const_cast<Value *>(getArgOperand(2)));
1139 }
1140
1141 ConstantInt *getValueKind() const {
1142 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(3)));
1143 }
1144
1145 // Returns the value site index.
1146 ConstantInt *getIndex() const {
1147 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(4)));
1148 }
1149};
1150
1151class PseudoProbeInst : public IntrinsicInst {
1152public:
1153 static bool classof(const IntrinsicInst *I) {
1154 return I->getIntrinsicID() == Intrinsic::pseudoprobe;
1155 }
1156
1157 static bool classof(const Value *V) {
1158 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1159 }
1160
1161 ConstantInt *getFuncGuid() const {
1162 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(0)));
1163 }
1164
1165 ConstantInt *getIndex() const {
1166 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(1)));
1167 }
1168
1169 ConstantInt *getAttributes() const {
1170 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(2)));
1171 }
1172
1173 ConstantInt *getFactor() const {
1174 return cast<ConstantInt>(const_cast<Value *>(getArgOperand(3)));
1175 }
1176};
1177
1178class NoAliasScopeDeclInst : public IntrinsicInst {
1179public:
1180 static bool classof(const IntrinsicInst *I) {
1181 return I->getIntrinsicID() == Intrinsic::experimental_noalias_scope_decl;
1182 }
1183
1184 static bool classof(const Value *V) {
1185 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1186 }
1187
1188 MDNode *getScopeList() const {
1189 auto *MV =
1190 cast<MetadataAsValue>(getOperand(Intrinsic::NoAliasScopeDeclScopeArg));
1191 return cast<MDNode>(MV->getMetadata());
1192 }
1193
1194 void setScopeList(MDNode *ScopeList) {
1195 setOperand(Intrinsic::NoAliasScopeDeclScopeArg,
1196 MetadataAsValue::get(getContext(), ScopeList));
1197 }
1198};
1199
1200// Defined in Statepoint.h -- NOT a subclass of IntrinsicInst
1201class GCStatepointInst;
1202
1203/// Common base class for representing values projected from a statepoint.
1204/// Currently, the only projections available are gc.result and gc.relocate.
1205class GCProjectionInst : public IntrinsicInst {
1206public:
1207 static bool classof(const IntrinsicInst *I) {
1208 return I->getIntrinsicID() == Intrinsic::experimental_gc_relocate ||
1209 I->getIntrinsicID() == Intrinsic::experimental_gc_result;
1210 }
1211
1212 static bool classof(const Value *V) {
1213 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1214 }
1215
1216 /// Return true if this relocate is tied to the invoke statepoint.
1217 /// This includes relocates which are on the unwinding path.
1218 bool isTiedToInvoke() const {
1219 const Value *Token = getArgOperand(0);
1220
1221 return isa<LandingPadInst>(Token) || isa<InvokeInst>(Token);
1222 }
1223
1224 /// The statepoint with which this gc.relocate is associated.
1225 const GCStatepointInst *getStatepoint() const;
1226};
1227
1228/// Represents calls to the gc.relocate intrinsic.
1229class GCRelocateInst : public GCProjectionInst {
1230public:
1231 static bool classof(const IntrinsicInst *I) {
1232 return I->getIntrinsicID() == Intrinsic::experimental_gc_relocate;
1233 }
1234
1235 static bool classof(const Value *V) {
1236 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1237 }
1238
1239 /// The index into the associate statepoint's argument list
1240 /// which contains the base pointer of the pointer whose
1241 /// relocation this gc.relocate describes.
1242 unsigned getBasePtrIndex() const {
1243 return cast<ConstantInt>(getArgOperand(1))->getZExtValue();
1244 }
1245
1246 /// The index into the associate statepoint's argument list which
1247 /// contains the pointer whose relocation this gc.relocate describes.
1248 unsigned getDerivedPtrIndex() const {
1249 return cast<ConstantInt>(getArgOperand(2))->getZExtValue();
1250 }
1251
1252 Value *getBasePtr() const;
1253 Value *getDerivedPtr() const;
1254};
1255
1256/// Represents calls to the gc.result intrinsic.
1257class GCResultInst : public GCProjectionInst {
1258public:
1259 static bool classof(const IntrinsicInst *I) {
1260 return I->getIntrinsicID() == Intrinsic::experimental_gc_result;
1261 }
1262
1263 static bool classof(const Value *V) {
1264 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1265 }
1266};
1267
1268
1269/// This represents the llvm.assume intrinsic.
1270class AssumeInst : public IntrinsicInst {
1271public:
1272 static bool classof(const IntrinsicInst *I) {
1273 return I->getIntrinsicID() == Intrinsic::assume;
1274 }
1275 static bool classof(const Value *V) {
1276 return isa<IntrinsicInst>(V) && classof(cast<IntrinsicInst>(V));
1277 }
1278};
1279
1280} // end namespace llvm
1281
1282#endif // LLVM_IR_INTRINSICINST_H

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h

1//===-- llvm/Constants.h - Constant class subclass definitions --*- 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 contains the declarations for the subclasses of Constant,
11/// which represent the different flavors of constant values that live in LLVM.
12/// Note that Constants are immutable (once created they never change) and are
13/// fully shared by structural equivalence. This means that two structurally
14/// equivalent constants will always have the same address. Constants are
15/// created on demand as needed and never deleted: thus clients don't have to
16/// worry about the lifetime of the objects.
17//
18//===----------------------------------------------------------------------===//
19
20#ifndef LLVM_IR_CONSTANTS_H
21#define LLVM_IR_CONSTANTS_H
22
23#include "llvm/ADT/APFloat.h"
24#include "llvm/ADT/APInt.h"
25#include "llvm/ADT/ArrayRef.h"
26#include "llvm/ADT/None.h"
27#include "llvm/ADT/Optional.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/IR/Constant.h"
31#include "llvm/IR/DerivedTypes.h"
32#include "llvm/IR/OperandTraits.h"
33#include "llvm/IR/User.h"
34#include "llvm/IR/Value.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/ErrorHandling.h"
38#include <cassert>
39#include <cstddef>
40#include <cstdint>
41
42namespace llvm {
43
44template <class ConstantClass> struct ConstantAggrKeyType;
45
46/// Base class for constants with no operands.
47///
48/// These constants have no operands; they represent their data directly.
49/// Since they can be in use by unrelated modules (and are never based on
50/// GlobalValues), it never makes sense to RAUW them.
51class ConstantData : public Constant {
52 friend class Constant;
53
54 Value *handleOperandChangeImpl(Value *From, Value *To) {
55 llvm_unreachable("Constant data does not have operands!")::llvm::llvm_unreachable_internal("Constant data does not have operands!"
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 55)
;
56 }
57
58protected:
59 explicit ConstantData(Type *Ty, ValueTy VT) : Constant(Ty, VT, nullptr, 0) {}
60
61 void *operator new(size_t s) { return User::operator new(s, 0); }
62
63public:
64 ConstantData(const ConstantData &) = delete;
65
66 /// Methods to support type inquiry through isa, cast, and dyn_cast.
67 static bool classof(const Value *V) {
68 return V->getValueID() >= ConstantDataFirstVal &&
69 V->getValueID() <= ConstantDataLastVal;
70 }
71};
72
73//===----------------------------------------------------------------------===//
74/// This is the shared class of boolean and integer constants. This class
75/// represents both boolean and integral constants.
76/// Class for constant integers.
77class ConstantInt final : public ConstantData {
78 friend class Constant;
79
80 APInt Val;
81
82 ConstantInt(IntegerType *Ty, const APInt &V);
83
84 void destroyConstantImpl();
85
86public:
87 ConstantInt(const ConstantInt &) = delete;
88
89 static ConstantInt *getTrue(LLVMContext &Context);
90 static ConstantInt *getFalse(LLVMContext &Context);
91 static ConstantInt *getBool(LLVMContext &Context, bool V);
92 static Constant *getTrue(Type *Ty);
93 static Constant *getFalse(Type *Ty);
94 static Constant *getBool(Type *Ty, bool V);
95
96 /// If Ty is a vector type, return a Constant with a splat of the given
97 /// value. Otherwise return a ConstantInt for the given value.
98 static Constant *get(Type *Ty, uint64_t V, bool IsSigned = false);
99
100 /// Return a ConstantInt with the specified integer value for the specified
101 /// type. If the type is wider than 64 bits, the value will be zero-extended
102 /// to fit the type, unless IsSigned is true, in which case the value will
103 /// be interpreted as a 64-bit signed integer and sign-extended to fit
104 /// the type.
105 /// Get a ConstantInt for a specific value.
106 static ConstantInt *get(IntegerType *Ty, uint64_t V, bool IsSigned = false);
107
108 /// Return a ConstantInt with the specified value for the specified type. The
109 /// value V will be canonicalized to a an unsigned APInt. Accessing it with
110 /// either getSExtValue() or getZExtValue() will yield a correctly sized and
111 /// signed value for the type Ty.
112 /// Get a ConstantInt for a specific signed value.
113 static ConstantInt *getSigned(IntegerType *Ty, int64_t V);
114 static Constant *getSigned(Type *Ty, int64_t V);
115
116 /// Return a ConstantInt with the specified value and an implied Type. The
117 /// type is the integer type that corresponds to the bit width of the value.
118 static ConstantInt *get(LLVMContext &Context, const APInt &V);
119
120 /// Return a ConstantInt constructed from the string strStart with the given
121 /// radix.
122 static ConstantInt *get(IntegerType *Ty, StringRef Str, uint8_t Radix);
123
124 /// If Ty is a vector type, return a Constant with a splat of the given
125 /// value. Otherwise return a ConstantInt for the given value.
126 static Constant *get(Type *Ty, const APInt &V);
127
128 /// Return the constant as an APInt value reference. This allows clients to
129 /// obtain a full-precision copy of the value.
130 /// Return the constant's value.
131 inline const APInt &getValue() const { return Val; }
132
133 /// getBitWidth - Return the bitwidth of this constant.
134 unsigned getBitWidth() const { return Val.getBitWidth(); }
135
136 /// Return the constant as a 64-bit unsigned integer value after it
137 /// has been zero extended as appropriate for the type of this constant. Note
138 /// that this method can assert if the value does not fit in 64 bits.
139 /// Return the zero extended value.
140 inline uint64_t getZExtValue() const { return Val.getZExtValue(); }
141
142 /// Return the constant as a 64-bit integer value after it has been sign
143 /// extended as appropriate for the type of this constant. Note that
144 /// this method can assert if the value does not fit in 64 bits.
145 /// Return the sign extended value.
146 inline int64_t getSExtValue() const { return Val.getSExtValue(); }
147
148 /// Return the constant as an llvm::MaybeAlign.
149 /// Note that this method can assert if the value does not fit in 64 bits or
150 /// is not a power of two.
151 inline MaybeAlign getMaybeAlignValue() const {
152 return MaybeAlign(getZExtValue());
153 }
154
155 /// Return the constant as an llvm::Align, interpreting `0` as `Align(1)`.
156 /// Note that this method can assert if the value does not fit in 64 bits or
157 /// is not a power of two.
158 inline Align getAlignValue() const {
159 return getMaybeAlignValue().valueOrOne();
160 }
161
162 /// A helper method that can be used to determine if the constant contained
163 /// within is equal to a constant. This only works for very small values,
164 /// because this is all that can be represented with all types.
165 /// Determine if this constant's value is same as an unsigned char.
166 bool equalsInt(uint64_t V) const { return Val == V; }
167
168 /// getType - Specialize the getType() method to always return an IntegerType,
169 /// which reduces the amount of casting needed in parts of the compiler.
170 ///
171 inline IntegerType *getType() const {
172 return cast<IntegerType>(Value::getType());
173 }
174
175 /// This static method returns true if the type Ty is big enough to
176 /// represent the value V. This can be used to avoid having the get method
177 /// assert when V is larger than Ty can represent. Note that there are two
178 /// versions of this method, one for unsigned and one for signed integers.
179 /// Although ConstantInt canonicalizes everything to an unsigned integer,
180 /// the signed version avoids callers having to convert a signed quantity
181 /// to the appropriate unsigned type before calling the method.
182 /// @returns true if V is a valid value for type Ty
183 /// Determine if the value is in range for the given type.
184 static bool isValueValidForType(Type *Ty, uint64_t V);
185 static bool isValueValidForType(Type *Ty, int64_t V);
186
187 bool isNegative() const { return Val.isNegative(); }
188
189 /// This is just a convenience method to make client code smaller for a
190 /// common code. It also correctly performs the comparison without the
191 /// potential for an assertion from getZExtValue().
192 bool isZero() const { return Val.isNullValue(); }
29
Calling 'APInt::isNullValue'
40
Returning from 'APInt::isNullValue'
41
Returning the value 1, which participates in a condition later
193
194 /// This is just a convenience method to make client code smaller for a
195 /// common case. It also correctly performs the comparison without the
196 /// potential for an assertion from getZExtValue().
197 /// Determine if the value is one.
198 bool isOne() const { return Val.isOneValue(); }
199
200 /// This function will return true iff every bit in this constant is set
201 /// to true.
202 /// @returns true iff this constant's bits are all set to true.
203 /// Determine if the value is all ones.
204 bool isMinusOne() const { return Val.isAllOnesValue(); }
205
206 /// This function will return true iff this constant represents the largest
207 /// value that may be represented by the constant's type.
208 /// @returns true iff this is the largest value that may be represented
209 /// by this type.
210 /// Determine if the value is maximal.
211 bool isMaxValue(bool IsSigned) const {
212 if (IsSigned)
213 return Val.isMaxSignedValue();
214 else
215 return Val.isMaxValue();
216 }
217
218 /// This function will return true iff this constant represents the smallest
219 /// value that may be represented by this constant's type.
220 /// @returns true if this is the smallest value that may be represented by
221 /// this type.
222 /// Determine if the value is minimal.
223 bool isMinValue(bool IsSigned) const {
224 if (IsSigned)
225 return Val.isMinSignedValue();
226 else
227 return Val.isMinValue();
228 }
229
230 /// This function will return true iff this constant represents a value with
231 /// active bits bigger than 64 bits or a value greater than the given uint64_t
232 /// value.
233 /// @returns true iff this constant is greater or equal to the given number.
234 /// Determine if the value is greater or equal to the given number.
235 bool uge(uint64_t Num) const { return Val.uge(Num); }
236
237 /// getLimitedValue - If the value is smaller than the specified limit,
238 /// return it, otherwise return the limit value. This causes the value
239 /// to saturate to the limit.
240 /// @returns the min of the value of the constant and the specified value
241 /// Get the constant's value with a saturation limit
242 uint64_t getLimitedValue(uint64_t Limit = ~0ULL) const {
243 return Val.getLimitedValue(Limit);
244 }
245
246 /// Methods to support type inquiry through isa, cast, and dyn_cast.
247 static bool classof(const Value *V) {
248 return V->getValueID() == ConstantIntVal;
249 }
250};
251
252//===----------------------------------------------------------------------===//
253/// ConstantFP - Floating Point Values [float, double]
254///
255class ConstantFP final : public ConstantData {
256 friend class Constant;
257
258 APFloat Val;
259
260 ConstantFP(Type *Ty, const APFloat &V);
261
262 void destroyConstantImpl();
263
264public:
265 ConstantFP(const ConstantFP &) = delete;
266
267 /// Floating point negation must be implemented with f(x) = -0.0 - x. This
268 /// method returns the negative zero constant for floating point or vector
269 /// floating point types; for all other types, it returns the null value.
270 static Constant *getZeroValueForNegation(Type *Ty);
271
272 /// This returns a ConstantFP, or a vector containing a splat of a ConstantFP,
273 /// for the specified value in the specified type. This should only be used
274 /// for simple constant values like 2.0/1.0 etc, that are known-valid both as
275 /// host double and as the target format.
276 static Constant *get(Type *Ty, double V);
277
278 /// If Ty is a vector type, return a Constant with a splat of the given
279 /// value. Otherwise return a ConstantFP for the given value.
280 static Constant *get(Type *Ty, const APFloat &V);
281
282 static Constant *get(Type *Ty, StringRef Str);
283 static ConstantFP *get(LLVMContext &Context, const APFloat &V);
284 static Constant *getNaN(Type *Ty, bool Negative = false,
285 uint64_t Payload = 0);
286 static Constant *getQNaN(Type *Ty, bool Negative = false,
287 APInt *Payload = nullptr);
288 static Constant *getSNaN(Type *Ty, bool Negative = false,
289 APInt *Payload = nullptr);
290 static Constant *getNegativeZero(Type *Ty);
291 static Constant *getInfinity(Type *Ty, bool Negative = false);
292
293 /// Return true if Ty is big enough to represent V.
294 static bool isValueValidForType(Type *Ty, const APFloat &V);
295 inline const APFloat &getValueAPF() const { return Val; }
296 inline const APFloat &getValue() const { return Val; }
297
298 /// Return true if the value is positive or negative zero.
299 bool isZero() const { return Val.isZero(); }
300
301 /// Return true if the sign bit is set.
302 bool isNegative() const { return Val.isNegative(); }
303
304 /// Return true if the value is infinity
305 bool isInfinity() const { return Val.isInfinity(); }
306
307 /// Return true if the value is a NaN.
308 bool isNaN() const { return Val.isNaN(); }
309
310 /// We don't rely on operator== working on double values, as it returns true
311 /// for things that are clearly not equal, like -0.0 and 0.0.
312 /// As such, this method can be used to do an exact bit-for-bit comparison of
313 /// two floating point values. The version with a double operand is retained
314 /// because it's so convenient to write isExactlyValue(2.0), but please use
315 /// it only for simple constants.
316 bool isExactlyValue(const APFloat &V) const;
317
318 bool isExactlyValue(double V) const {
319 bool ignored;
320 APFloat FV(V);
321 FV.convert(Val.getSemantics(), APFloat::rmNearestTiesToEven, &ignored);
322 return isExactlyValue(FV);
323 }
324
325 /// Methods for support type inquiry through isa, cast, and dyn_cast:
326 static bool classof(const Value *V) {
327 return V->getValueID() == ConstantFPVal;
328 }
329};
330
331//===----------------------------------------------------------------------===//
332/// All zero aggregate value
333///
334class ConstantAggregateZero final : public ConstantData {
335 friend class Constant;
336
337 explicit ConstantAggregateZero(Type *Ty)
338 : ConstantData(Ty, ConstantAggregateZeroVal) {}
339
340 void destroyConstantImpl();
341
342public:
343 ConstantAggregateZero(const ConstantAggregateZero &) = delete;
344
345 static ConstantAggregateZero *get(Type *Ty);
346
347 /// If this CAZ has array or vector type, return a zero with the right element
348 /// type.
349 Constant *getSequentialElement() const;
350
351 /// If this CAZ has struct type, return a zero with the right element type for
352 /// the specified element.
353 Constant *getStructElement(unsigned Elt) const;
354
355 /// Return a zero of the right value for the specified GEP index if we can,
356 /// otherwise return null (e.g. if C is a ConstantExpr).
357 Constant *getElementValue(Constant *C) const;
358
359 /// Return a zero of the right value for the specified GEP index.
360 Constant *getElementValue(unsigned Idx) const;
361
362 /// Return the number of elements in the array, vector, or struct.
363 unsigned getNumElements() const;
364
365 /// Methods for support type inquiry through isa, cast, and dyn_cast:
366 ///
367 static bool classof(const Value *V) {
368 return V->getValueID() == ConstantAggregateZeroVal;
369 }
370};
371
372/// Base class for aggregate constants (with operands).
373///
374/// These constants are aggregates of other constants, which are stored as
375/// operands.
376///
377/// Subclasses are \a ConstantStruct, \a ConstantArray, and \a
378/// ConstantVector.
379///
380/// \note Some subclasses of \a ConstantData are semantically aggregates --
381/// such as \a ConstantDataArray -- but are not subclasses of this because they
382/// use operands.
383class ConstantAggregate : public Constant {
384protected:
385 ConstantAggregate(Type *T, ValueTy VT, ArrayRef<Constant *> V);
386
387public:
388 /// Transparently provide more efficient getOperand methods.
389 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant)public: inline Constant *getOperand(unsigned) const; inline void
setOperand(unsigned, Constant*); inline op_iterator op_begin
(); inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
390
391 /// Methods for support type inquiry through isa, cast, and dyn_cast:
392 static bool classof(const Value *V) {
393 return V->getValueID() >= ConstantAggregateFirstVal &&
394 V->getValueID() <= ConstantAggregateLastVal;
395 }
396};
397
398template <>
399struct OperandTraits<ConstantAggregate>
400 : public VariadicOperandTraits<ConstantAggregate> {};
401
402DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantAggregate, Constant)ConstantAggregate::op_iterator ConstantAggregate::op_begin() {
return OperandTraits<ConstantAggregate>::op_begin(this
); } ConstantAggregate::const_op_iterator ConstantAggregate::
op_begin() const { return OperandTraits<ConstantAggregate>
::op_begin(const_cast<ConstantAggregate*>(this)); } ConstantAggregate
::op_iterator ConstantAggregate::op_end() { return OperandTraits
<ConstantAggregate>::op_end(this); } ConstantAggregate::
const_op_iterator ConstantAggregate::op_end() const { return OperandTraits
<ConstantAggregate>::op_end(const_cast<ConstantAggregate
*>(this)); } Constant *ConstantAggregate::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<ConstantAggregate
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantAggregate>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 402, __PRETTY_FUNCTION__)); return cast_or_null<Constant
>( OperandTraits<ConstantAggregate>::op_begin(const_cast
<ConstantAggregate*>(this))[i_nocapture].get()); } void
ConstantAggregate::setOperand(unsigned i_nocapture, Constant
*Val_nocapture) { ((i_nocapture < OperandTraits<ConstantAggregate
>::operands(this) && "setOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantAggregate>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 402, __PRETTY_FUNCTION__)); OperandTraits<ConstantAggregate
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
ConstantAggregate::getNumOperands() const { return OperandTraits
<ConstantAggregate>::operands(this); } template <int
Idx_nocapture> Use &ConstantAggregate::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &ConstantAggregate::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
403
404//===----------------------------------------------------------------------===//
405/// ConstantArray - Constant Array Declarations
406///
407class ConstantArray final : public ConstantAggregate {
408 friend struct ConstantAggrKeyType<ConstantArray>;
409 friend class Constant;
410
411 ConstantArray(ArrayType *T, ArrayRef<Constant *> Val);
412
413 void destroyConstantImpl();
414 Value *handleOperandChangeImpl(Value *From, Value *To);
415
416public:
417 // ConstantArray accessors
418 static Constant *get(ArrayType *T, ArrayRef<Constant *> V);
419
420private:
421 static Constant *getImpl(ArrayType *T, ArrayRef<Constant *> V);
422
423public:
424 /// Specialize the getType() method to always return an ArrayType,
425 /// which reduces the amount of casting needed in parts of the compiler.
426 inline ArrayType *getType() const {
427 return cast<ArrayType>(Value::getType());
428 }
429
430 /// Methods for support type inquiry through isa, cast, and dyn_cast:
431 static bool classof(const Value *V) {
432 return V->getValueID() == ConstantArrayVal;
433 }
434};
435
436//===----------------------------------------------------------------------===//
437// Constant Struct Declarations
438//
439class ConstantStruct final : public ConstantAggregate {
440 friend struct ConstantAggrKeyType<ConstantStruct>;
441 friend class Constant;
442
443 ConstantStruct(StructType *T, ArrayRef<Constant *> Val);
444
445 void destroyConstantImpl();
446 Value *handleOperandChangeImpl(Value *From, Value *To);
447
448public:
449 // ConstantStruct accessors
450 static Constant *get(StructType *T, ArrayRef<Constant *> V);
451
452 template <typename... Csts>
453 static std::enable_if_t<are_base_of<Constant, Csts...>::value, Constant *>
454 get(StructType *T, Csts *...Vs) {
455 SmallVector<Constant *, 8> Values({Vs...});
456 return get(T, Values);
457 }
458
459 /// Return an anonymous struct that has the specified elements.
460 /// If the struct is possibly empty, then you must specify a context.
461 static Constant *getAnon(ArrayRef<Constant *> V, bool Packed = false) {
462 return get(getTypeForElements(V, Packed), V);
463 }
464 static Constant *getAnon(LLVMContext &Ctx, ArrayRef<Constant *> V,
465 bool Packed = false) {
466 return get(getTypeForElements(Ctx, V, Packed), V);
467 }
468
469 /// Return an anonymous struct type to use for a constant with the specified
470 /// set of elements. The list must not be empty.
471 static StructType *getTypeForElements(ArrayRef<Constant *> V,
472 bool Packed = false);
473 /// This version of the method allows an empty list.
474 static StructType *getTypeForElements(LLVMContext &Ctx,
475 ArrayRef<Constant *> V,
476 bool Packed = false);
477
478 /// Specialization - reduce amount of casting.
479 inline StructType *getType() const {
480 return cast<StructType>(Value::getType());
481 }
482
483 /// Methods for support type inquiry through isa, cast, and dyn_cast:
484 static bool classof(const Value *V) {
485 return V->getValueID() == ConstantStructVal;
486 }
487};
488
489//===----------------------------------------------------------------------===//
490/// Constant Vector Declarations
491///
492class ConstantVector final : public ConstantAggregate {
493 friend struct ConstantAggrKeyType<ConstantVector>;
494 friend class Constant;
495
496 ConstantVector(VectorType *T, ArrayRef<Constant *> Val);
497
498 void destroyConstantImpl();
499 Value *handleOperandChangeImpl(Value *From, Value *To);
500
501public:
502 // ConstantVector accessors
503 static Constant *get(ArrayRef<Constant *> V);
504
505private:
506 static Constant *getImpl(ArrayRef<Constant *> V);
507
508public:
509 /// Return a ConstantVector with the specified constant in each element.
510 /// Note that this might not return an instance of ConstantVector
511 static Constant *getSplat(ElementCount EC, Constant *Elt);
512
513 /// Specialize the getType() method to always return a FixedVectorType,
514 /// which reduces the amount of casting needed in parts of the compiler.
515 inline FixedVectorType *getType() const {
516 return cast<FixedVectorType>(Value::getType());
517 }
518
519 /// If all elements of the vector constant have the same value, return that
520 /// value. Otherwise, return nullptr. Ignore undefined elements by setting
521 /// AllowUndefs to true.
522 Constant *getSplatValue(bool AllowUndefs = false) const;
523
524 /// Methods for support type inquiry through isa, cast, and dyn_cast:
525 static bool classof(const Value *V) {
526 return V->getValueID() == ConstantVectorVal;
527 }
528};
529
530//===----------------------------------------------------------------------===//
531/// A constant pointer value that points to null
532///
533class ConstantPointerNull final : public ConstantData {
534 friend class Constant;
535
536 explicit ConstantPointerNull(PointerType *T)
537 : ConstantData(T, Value::ConstantPointerNullVal) {}
538
539 void destroyConstantImpl();
540
541public:
542 ConstantPointerNull(const ConstantPointerNull &) = delete;
543
544 /// Static factory methods - Return objects of the specified value
545 static ConstantPointerNull *get(PointerType *T);
546
547 /// Specialize the getType() method to always return an PointerType,
548 /// which reduces the amount of casting needed in parts of the compiler.
549 inline PointerType *getType() const {
550 return cast<PointerType>(Value::getType());
551 }
552
553 /// Methods for support type inquiry through isa, cast, and dyn_cast:
554 static bool classof(const Value *V) {
555 return V->getValueID() == ConstantPointerNullVal;
556 }
557};
558
559//===----------------------------------------------------------------------===//
560/// ConstantDataSequential - A vector or array constant whose element type is a
561/// simple 1/2/4/8-byte integer or half/bfloat/float/double, and whose elements
562/// are just simple data values (i.e. ConstantInt/ConstantFP). This Constant
563/// node has no operands because it stores all of the elements of the constant
564/// as densely packed data, instead of as Value*'s.
565///
566/// This is the common base class of ConstantDataArray and ConstantDataVector.
567///
568class ConstantDataSequential : public ConstantData {
569 friend class LLVMContextImpl;
570 friend class Constant;
571
572 /// A pointer to the bytes underlying this constant (which is owned by the
573 /// uniquing StringMap).
574 const char *DataElements;
575
576 /// This forms a link list of ConstantDataSequential nodes that have
577 /// the same value but different type. For example, 0,0,0,1 could be a 4
578 /// element array of i8, or a 1-element array of i32. They'll both end up in
579 /// the same StringMap bucket, linked up.
580 std::unique_ptr<ConstantDataSequential> Next;
581
582 void destroyConstantImpl();
583
584protected:
585 explicit ConstantDataSequential(Type *ty, ValueTy VT, const char *Data)
586 : ConstantData(ty, VT), DataElements(Data) {}
587
588 static Constant *getImpl(StringRef Bytes, Type *Ty);
589
590public:
591 ConstantDataSequential(const ConstantDataSequential &) = delete;
592
593 /// Return true if a ConstantDataSequential can be formed with a vector or
594 /// array of the specified element type.
595 /// ConstantDataArray only works with normal float and int types that are
596 /// stored densely in memory, not with things like i42 or x86_f80.
597 static bool isElementTypeCompatible(Type *Ty);
598
599 /// If this is a sequential container of integers (of any size), return the
600 /// specified element in the low bits of a uint64_t.
601 uint64_t getElementAsInteger(unsigned i) const;
602
603 /// If this is a sequential container of integers (of any size), return the
604 /// specified element as an APInt.
605 APInt getElementAsAPInt(unsigned i) const;
606
607 /// If this is a sequential container of floating point type, return the
608 /// specified element as an APFloat.
609 APFloat getElementAsAPFloat(unsigned i) const;
610
611 /// If this is an sequential container of floats, return the specified element
612 /// as a float.
613 float getElementAsFloat(unsigned i) const;
614
615 /// If this is an sequential container of doubles, return the specified
616 /// element as a double.
617 double getElementAsDouble(unsigned i) const;
618
619 /// Return a Constant for a specified index's element.
620 /// Note that this has to compute a new constant to return, so it isn't as
621 /// efficient as getElementAsInteger/Float/Double.
622 Constant *getElementAsConstant(unsigned i) const;
623
624 /// Return the element type of the array/vector.
625 Type *getElementType() const;
626
627 /// Return the number of elements in the array or vector.
628 unsigned getNumElements() const;
629
630 /// Return the size (in bytes) of each element in the array/vector.
631 /// The size of the elements is known to be a multiple of one byte.
632 uint64_t getElementByteSize() const;
633
634 /// This method returns true if this is an array of \p CharSize integers.
635 bool isString(unsigned CharSize = 8) const;
636
637 /// This method returns true if the array "isString", ends with a null byte,
638 /// and does not contains any other null bytes.
639 bool isCString() const;
640
641 /// If this array is isString(), then this method returns the array as a
642 /// StringRef. Otherwise, it asserts out.
643 StringRef getAsString() const {
644 assert(isString() && "Not a string")((isString() && "Not a string") ? static_cast<void
> (0) : __assert_fail ("isString() && \"Not a string\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 644, __PRETTY_FUNCTION__))
;
645 return getRawDataValues();
646 }
647
648 /// If this array is isCString(), then this method returns the array (without
649 /// the trailing null byte) as a StringRef. Otherwise, it asserts out.
650 StringRef getAsCString() const {
651 assert(isCString() && "Isn't a C string")((isCString() && "Isn't a C string") ? static_cast<
void> (0) : __assert_fail ("isCString() && \"Isn't a C string\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 651, __PRETTY_FUNCTION__))
;
652 StringRef Str = getAsString();
653 return Str.substr(0, Str.size() - 1);
654 }
655
656 /// Return the raw, underlying, bytes of this data. Note that this is an
657 /// extremely tricky thing to work with, as it exposes the host endianness of
658 /// the data elements.
659 StringRef getRawDataValues() const;
660
661 /// Methods for support type inquiry through isa, cast, and dyn_cast:
662 static bool classof(const Value *V) {
663 return V->getValueID() == ConstantDataArrayVal ||
664 V->getValueID() == ConstantDataVectorVal;
665 }
666
667private:
668 const char *getElementPointer(unsigned Elt) const;
669};
670
671//===----------------------------------------------------------------------===//
672/// An array constant whose element type is a simple 1/2/4/8-byte integer or
673/// float/double, and whose elements are just simple data values
674/// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
675/// stores all of the elements of the constant as densely packed data, instead
676/// of as Value*'s.
677class ConstantDataArray final : public ConstantDataSequential {
678 friend class ConstantDataSequential;
679
680 explicit ConstantDataArray(Type *ty, const char *Data)
681 : ConstantDataSequential(ty, ConstantDataArrayVal, Data) {}
682
683public:
684 ConstantDataArray(const ConstantDataArray &) = delete;
685
686 /// get() constructor - Return a constant with array type with an element
687 /// count and element type matching the ArrayRef passed in. Note that this
688 /// can return a ConstantAggregateZero object.
689 template <typename ElementTy>
690 static Constant *get(LLVMContext &Context, ArrayRef<ElementTy> Elts) {
691 const char *Data = reinterpret_cast<const char *>(Elts.data());
692 return getRaw(StringRef(Data, Elts.size() * sizeof(ElementTy)), Elts.size(),
693 Type::getScalarTy<ElementTy>(Context));
694 }
695
696 /// get() constructor - ArrayTy needs to be compatible with
697 /// ArrayRef<ElementTy>. Calls get(LLVMContext, ArrayRef<ElementTy>).
698 template <typename ArrayTy>
699 static Constant *get(LLVMContext &Context, ArrayTy &Elts) {
700 return ConstantDataArray::get(Context, makeArrayRef(Elts));
701 }
702
703 /// getRaw() constructor - Return a constant with array type with an element
704 /// count and element type matching the NumElements and ElementTy parameters
705 /// passed in. Note that this can return a ConstantAggregateZero object.
706 /// ElementTy must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is
707 /// the buffer containing the elements. Be careful to make sure Data uses the
708 /// right endianness, the buffer will be used as-is.
709 static Constant *getRaw(StringRef Data, uint64_t NumElements,
710 Type *ElementTy) {
711 Type *Ty = ArrayType::get(ElementTy, NumElements);
712 return getImpl(Data, Ty);
713 }
714
715 /// getFP() constructors - Return a constant of array type with a float
716 /// element type taken from argument `ElementType', and count taken from
717 /// argument `Elts'. The amount of bits of the contained type must match the
718 /// number of bits of the type contained in the passed in ArrayRef.
719 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
720 /// that this can return a ConstantAggregateZero object.
721 static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts);
722 static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts);
723 static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts);
724
725 /// This method constructs a CDS and initializes it with a text string.
726 /// The default behavior (AddNull==true) causes a null terminator to
727 /// be placed at the end of the array (increasing the length of the string by
728 /// one more than the StringRef would normally indicate. Pass AddNull=false
729 /// to disable this behavior.
730 static Constant *getString(LLVMContext &Context, StringRef Initializer,
731 bool AddNull = true);
732
733 /// Specialize the getType() method to always return an ArrayType,
734 /// which reduces the amount of casting needed in parts of the compiler.
735 inline ArrayType *getType() const {
736 return cast<ArrayType>(Value::getType());
737 }
738
739 /// Methods for support type inquiry through isa, cast, and dyn_cast:
740 static bool classof(const Value *V) {
741 return V->getValueID() == ConstantDataArrayVal;
742 }
743};
744
745//===----------------------------------------------------------------------===//
746/// A vector constant whose element type is a simple 1/2/4/8-byte integer or
747/// float/double, and whose elements are just simple data values
748/// (i.e. ConstantInt/ConstantFP). This Constant node has no operands because it
749/// stores all of the elements of the constant as densely packed data, instead
750/// of as Value*'s.
751class ConstantDataVector final : public ConstantDataSequential {
752 friend class ConstantDataSequential;
753
754 explicit ConstantDataVector(Type *ty, const char *Data)
755 : ConstantDataSequential(ty, ConstantDataVectorVal, Data),
756 IsSplatSet(false) {}
757 // Cache whether or not the constant is a splat.
758 mutable bool IsSplatSet : 1;
759 mutable bool IsSplat : 1;
760 bool isSplatData() const;
761
762public:
763 ConstantDataVector(const ConstantDataVector &) = delete;
764
765 /// get() constructors - Return a constant with vector type with an element
766 /// count and element type matching the ArrayRef passed in. Note that this
767 /// can return a ConstantAggregateZero object.
768 static Constant *get(LLVMContext &Context, ArrayRef<uint8_t> Elts);
769 static Constant *get(LLVMContext &Context, ArrayRef<uint16_t> Elts);
770 static Constant *get(LLVMContext &Context, ArrayRef<uint32_t> Elts);
771 static Constant *get(LLVMContext &Context, ArrayRef<uint64_t> Elts);
772 static Constant *get(LLVMContext &Context, ArrayRef<float> Elts);
773 static Constant *get(LLVMContext &Context, ArrayRef<double> Elts);
774
775 /// getRaw() constructor - Return a constant with vector type with an element
776 /// count and element type matching the NumElements and ElementTy parameters
777 /// passed in. Note that this can return a ConstantAggregateZero object.
778 /// ElementTy must be one of i8/i16/i32/i64/half/bfloat/float/double. Data is
779 /// the buffer containing the elements. Be careful to make sure Data uses the
780 /// right endianness, the buffer will be used as-is.
781 static Constant *getRaw(StringRef Data, uint64_t NumElements,
782 Type *ElementTy) {
783 Type *Ty = VectorType::get(ElementTy, ElementCount::getFixed(NumElements));
784 return getImpl(Data, Ty);
785 }
786
787 /// getFP() constructors - Return a constant of vector type with a float
788 /// element type taken from argument `ElementType', and count taken from
789 /// argument `Elts'. The amount of bits of the contained type must match the
790 /// number of bits of the type contained in the passed in ArrayRef.
791 /// (i.e. half or bfloat for 16bits, float for 32bits, double for 64bits) Note
792 /// that this can return a ConstantAggregateZero object.
793 static Constant *getFP(Type *ElementType, ArrayRef<uint16_t> Elts);
794 static Constant *getFP(Type *ElementType, ArrayRef<uint32_t> Elts);
795 static Constant *getFP(Type *ElementType, ArrayRef<uint64_t> Elts);
796
797 /// Return a ConstantVector with the specified constant in each element.
798 /// The specified constant has to be a of a compatible type (i8/i16/
799 /// i32/i64/half/bfloat/float/double) and must be a ConstantFP or ConstantInt.
800 static Constant *getSplat(unsigned NumElts, Constant *Elt);
801
802 /// Returns true if this is a splat constant, meaning that all elements have
803 /// the same value.
804 bool isSplat() const;
805
806 /// If this is a splat constant, meaning that all of the elements have the
807 /// same value, return that value. Otherwise return NULL.
808 Constant *getSplatValue() const;
809
810 /// Specialize the getType() method to always return a FixedVectorType,
811 /// which reduces the amount of casting needed in parts of the compiler.
812 inline FixedVectorType *getType() const {
813 return cast<FixedVectorType>(Value::getType());
814 }
815
816 /// Methods for support type inquiry through isa, cast, and dyn_cast:
817 static bool classof(const Value *V) {
818 return V->getValueID() == ConstantDataVectorVal;
819 }
820};
821
822//===----------------------------------------------------------------------===//
823/// A constant token which is empty
824///
825class ConstantTokenNone final : public ConstantData {
826 friend class Constant;
827
828 explicit ConstantTokenNone(LLVMContext &Context)
829 : ConstantData(Type::getTokenTy(Context), ConstantTokenNoneVal) {}
830
831 void destroyConstantImpl();
832
833public:
834 ConstantTokenNone(const ConstantTokenNone &) = delete;
835
836 /// Return the ConstantTokenNone.
837 static ConstantTokenNone *get(LLVMContext &Context);
838
839 /// Methods to support type inquiry through isa, cast, and dyn_cast.
840 static bool classof(const Value *V) {
841 return V->getValueID() == ConstantTokenNoneVal;
842 }
843};
844
845/// The address of a basic block.
846///
847class BlockAddress final : public Constant {
848 friend class Constant;
849
850 BlockAddress(Function *F, BasicBlock *BB);
851
852 void *operator new(size_t s) { return User::operator new(s, 2); }
853
854 void destroyConstantImpl();
855 Value *handleOperandChangeImpl(Value *From, Value *To);
856
857public:
858 /// Return a BlockAddress for the specified function and basic block.
859 static BlockAddress *get(Function *F, BasicBlock *BB);
860
861 /// Return a BlockAddress for the specified basic block. The basic
862 /// block must be embedded into a function.
863 static BlockAddress *get(BasicBlock *BB);
864
865 /// Lookup an existing \c BlockAddress constant for the given BasicBlock.
866 ///
867 /// \returns 0 if \c !BB->hasAddressTaken(), otherwise the \c BlockAddress.
868 static BlockAddress *lookup(const BasicBlock *BB);
869
870 /// Transparently provide more efficient getOperand methods.
871 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
872
873 Function *getFunction() const { return (Function *)Op<0>().get(); }
874 BasicBlock *getBasicBlock() const { return (BasicBlock *)Op<1>().get(); }
875
876 /// Methods for support type inquiry through isa, cast, and dyn_cast:
877 static bool classof(const Value *V) {
878 return V->getValueID() == BlockAddressVal;
879 }
880};
881
882template <>
883struct OperandTraits<BlockAddress>
884 : public FixedNumOperandTraits<BlockAddress, 2> {};
885
886DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BlockAddress, Value)BlockAddress::op_iterator BlockAddress::op_begin() { return OperandTraits
<BlockAddress>::op_begin(this); } BlockAddress::const_op_iterator
BlockAddress::op_begin() const { return OperandTraits<BlockAddress
>::op_begin(const_cast<BlockAddress*>(this)); } BlockAddress
::op_iterator BlockAddress::op_end() { return OperandTraits<
BlockAddress>::op_end(this); } BlockAddress::const_op_iterator
BlockAddress::op_end() const { return OperandTraits<BlockAddress
>::op_end(const_cast<BlockAddress*>(this)); } Value *
BlockAddress::getOperand(unsigned i_nocapture) const { ((i_nocapture
< OperandTraits<BlockAddress>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<BlockAddress>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 886, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<BlockAddress>::op_begin(const_cast<BlockAddress
*>(this))[i_nocapture].get()); } void BlockAddress::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<BlockAddress>::operands(this) &&
"setOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<BlockAddress>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 886, __PRETTY_FUNCTION__)); OperandTraits<BlockAddress>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned BlockAddress
::getNumOperands() const { return OperandTraits<BlockAddress
>::operands(this); } template <int Idx_nocapture> Use
&BlockAddress::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
BlockAddress::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
887
888/// Wrapper for a function that represents a value that
889/// functionally represents the original function. This can be a function,
890/// global alias to a function, or an ifunc.
891class DSOLocalEquivalent final : public Constant {
892 friend class Constant;
893
894 DSOLocalEquivalent(GlobalValue *GV);
895
896 void *operator new(size_t s) { return User::operator new(s, 1); }
897
898 void destroyConstantImpl();
899 Value *handleOperandChangeImpl(Value *From, Value *To);
900
901public:
902 /// Return a DSOLocalEquivalent for the specified global value.
903 static DSOLocalEquivalent *get(GlobalValue *GV);
904
905 /// Transparently provide more efficient getOperand methods.
906 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value)public: inline Value *getOperand(unsigned) const; inline void
setOperand(unsigned, Value*); inline op_iterator op_begin();
inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
907
908 GlobalValue *getGlobalValue() const {
909 return cast<GlobalValue>(Op<0>().get());
910 }
911
912 /// Methods for support type inquiry through isa, cast, and dyn_cast:
913 static bool classof(const Value *V) {
914 return V->getValueID() == DSOLocalEquivalentVal;
915 }
916};
917
918template <>
919struct OperandTraits<DSOLocalEquivalent>
920 : public FixedNumOperandTraits<DSOLocalEquivalent, 1> {};
921
922DEFINE_TRANSPARENT_OPERAND_ACCESSORS(DSOLocalEquivalent, Value)DSOLocalEquivalent::op_iterator DSOLocalEquivalent::op_begin(
) { return OperandTraits<DSOLocalEquivalent>::op_begin(
this); } DSOLocalEquivalent::const_op_iterator DSOLocalEquivalent
::op_begin() const { return OperandTraits<DSOLocalEquivalent
>::op_begin(const_cast<DSOLocalEquivalent*>(this)); }
DSOLocalEquivalent::op_iterator DSOLocalEquivalent::op_end()
{ return OperandTraits<DSOLocalEquivalent>::op_end(this
); } DSOLocalEquivalent::const_op_iterator DSOLocalEquivalent
::op_end() const { return OperandTraits<DSOLocalEquivalent
>::op_end(const_cast<DSOLocalEquivalent*>(this)); } Value
*DSOLocalEquivalent::getOperand(unsigned i_nocapture) const {
((i_nocapture < OperandTraits<DSOLocalEquivalent>::
operands(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<DSOLocalEquivalent>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 922, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<DSOLocalEquivalent>::op_begin(const_cast
<DSOLocalEquivalent*>(this))[i_nocapture].get()); } void
DSOLocalEquivalent::setOperand(unsigned i_nocapture, Value *
Val_nocapture) { ((i_nocapture < OperandTraits<DSOLocalEquivalent
>::operands(this) && "setOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<DSOLocalEquivalent>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 922, __PRETTY_FUNCTION__)); OperandTraits<DSOLocalEquivalent
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
DSOLocalEquivalent::getNumOperands() const { return OperandTraits
<DSOLocalEquivalent>::operands(this); } template <int
Idx_nocapture> Use &DSOLocalEquivalent::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &DSOLocalEquivalent::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
923
924//===----------------------------------------------------------------------===//
925/// A constant value that is initialized with an expression using
926/// other constant values.
927///
928/// This class uses the standard Instruction opcodes to define the various
929/// constant expressions. The Opcode field for the ConstantExpr class is
930/// maintained in the Value::SubclassData field.
931class ConstantExpr : public Constant {
932 friend struct ConstantExprKeyType;
933 friend class Constant;
934
935 void destroyConstantImpl();
936 Value *handleOperandChangeImpl(Value *From, Value *To);
937
938protected:
939 ConstantExpr(Type *ty, unsigned Opcode, Use *Ops, unsigned NumOps)
940 : Constant(ty, ConstantExprVal, Ops, NumOps) {
941 // Operation type (an Instruction opcode) is stored as the SubclassData.
942 setValueSubclassData(Opcode);
943 }
944
945 ~ConstantExpr() = default;
946
947public:
948 // Static methods to construct a ConstantExpr of different kinds. Note that
949 // these methods may return a object that is not an instance of the
950 // ConstantExpr class, because they will attempt to fold the constant
951 // expression into something simpler if possible.
952
953 /// getAlignOf constant expr - computes the alignment of a type in a target
954 /// independent way (Note: the return type is an i64).
955 static Constant *getAlignOf(Type *Ty);
956
957 /// getSizeOf constant expr - computes the (alloc) size of a type (in
958 /// address-units, not bits) in a target independent way (Note: the return
959 /// type is an i64).
960 ///
961 static Constant *getSizeOf(Type *Ty);
962
963 /// getOffsetOf constant expr - computes the offset of a struct field in a
964 /// target independent way (Note: the return type is an i64).
965 ///
966 static Constant *getOffsetOf(StructType *STy, unsigned FieldNo);
967
968 /// getOffsetOf constant expr - This is a generalized form of getOffsetOf,
969 /// which supports any aggregate type, and any Constant index.
970 ///
971 static Constant *getOffsetOf(Type *Ty, Constant *FieldNo);
972
973 static Constant *getNeg(Constant *C, bool HasNUW = false,
974 bool HasNSW = false);
975 static Constant *getFNeg(Constant *C);
976 static Constant *getNot(Constant *C);
977 static Constant *getAdd(Constant *C1, Constant *C2, bool HasNUW = false,
978 bool HasNSW = false);
979 static Constant *getFAdd(Constant *C1, Constant *C2);
980 static Constant *getSub(Constant *C1, Constant *C2, bool HasNUW = false,
981 bool HasNSW = false);
982 static Constant *getFSub(Constant *C1, Constant *C2);
983 static Constant *getMul(Constant *C1, Constant *C2, bool HasNUW = false,
984 bool HasNSW = false);
985 static Constant *getFMul(Constant *C1, Constant *C2);
986 static Constant *getUDiv(Constant *C1, Constant *C2, bool isExact = false);
987 static Constant *getSDiv(Constant *C1, Constant *C2, bool isExact = false);
988 static Constant *getFDiv(Constant *C1, Constant *C2);
989 static Constant *getURem(Constant *C1, Constant *C2);
990 static Constant *getSRem(Constant *C1, Constant *C2);
991 static Constant *getFRem(Constant *C1, Constant *C2);
992 static Constant *getAnd(Constant *C1, Constant *C2);
993 static Constant *getOr(Constant *C1, Constant *C2);
994 static Constant *getXor(Constant *C1, Constant *C2);
995 static Constant *getUMin(Constant *C1, Constant *C2);
996 static Constant *getShl(Constant *C1, Constant *C2, bool HasNUW = false,
997 bool HasNSW = false);
998 static Constant *getLShr(Constant *C1, Constant *C2, bool isExact = false);
999 static Constant *getAShr(Constant *C1, Constant *C2, bool isExact = false);
1000 static Constant *getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1001 static Constant *getSExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1002 static Constant *getZExt(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1003 static Constant *getFPTrunc(Constant *C, Type *Ty,
1004 bool OnlyIfReduced = false);
1005 static Constant *getFPExtend(Constant *C, Type *Ty,
1006 bool OnlyIfReduced = false);
1007 static Constant *getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1008 static Constant *getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1009 static Constant *getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1010 static Constant *getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced = false);
1011 static Constant *getPtrToInt(Constant *C, Type *Ty,
1012 bool OnlyIfReduced = false);
1013 static Constant *getIntToPtr(Constant *C, Type *Ty,
1014 bool OnlyIfReduced = false);
1015 static Constant *getBitCast(Constant *C, Type *Ty,
1016 bool OnlyIfReduced = false);
1017 static Constant *getAddrSpaceCast(Constant *C, Type *Ty,
1018 bool OnlyIfReduced = false);
1019
1020 static Constant *getNSWNeg(Constant *C) { return getNeg(C, false, true); }
1021 static Constant *getNUWNeg(Constant *C) { return getNeg(C, true, false); }
1022
1023 static Constant *getNSWAdd(Constant *C1, Constant *C2) {
1024 return getAdd(C1, C2, false, true);
1025 }
1026
1027 static Constant *getNUWAdd(Constant *C1, Constant *C2) {
1028 return getAdd(C1, C2, true, false);
1029 }
1030
1031 static Constant *getNSWSub(Constant *C1, Constant *C2) {
1032 return getSub(C1, C2, false, true);
1033 }
1034
1035 static Constant *getNUWSub(Constant *C1, Constant *C2) {
1036 return getSub(C1, C2, true, false);
1037 }
1038
1039 static Constant *getNSWMul(Constant *C1, Constant *C2) {
1040 return getMul(C1, C2, false, true);
1041 }
1042
1043 static Constant *getNUWMul(Constant *C1, Constant *C2) {
1044 return getMul(C1, C2, true, false);
1045 }
1046
1047 static Constant *getNSWShl(Constant *C1, Constant *C2) {
1048 return getShl(C1, C2, false, true);
1049 }
1050
1051 static Constant *getNUWShl(Constant *C1, Constant *C2) {
1052 return getShl(C1, C2, true, false);
1053 }
1054
1055 static Constant *getExactSDiv(Constant *C1, Constant *C2) {
1056 return getSDiv(C1, C2, true);
1057 }
1058
1059 static Constant *getExactUDiv(Constant *C1, Constant *C2) {
1060 return getUDiv(C1, C2, true);
1061 }
1062
1063 static Constant *getExactAShr(Constant *C1, Constant *C2) {
1064 return getAShr(C1, C2, true);
1065 }
1066
1067 static Constant *getExactLShr(Constant *C1, Constant *C2) {
1068 return getLShr(C1, C2, true);
1069 }
1070
1071 /// If C is a scalar/fixed width vector of known powers of 2, then this
1072 /// function returns a new scalar/fixed width vector obtained from logBase2
1073 /// of C. Undef vector elements are set to zero.
1074 /// Return a null pointer otherwise.
1075 static Constant *getExactLogBase2(Constant *C);
1076
1077 /// Return the identity constant for a binary opcode.
1078 /// The identity constant C is defined as X op C = X and C op X = X for every
1079 /// X when the binary operation is commutative. If the binop is not
1080 /// commutative, callers can acquire the operand 1 identity constant by
1081 /// setting AllowRHSConstant to true. For example, any shift has a zero
1082 /// identity constant for operand 1: X shift 0 = X.
1083 /// Return nullptr if the operator does not have an identity constant.
1084 static Constant *getBinOpIdentity(unsigned Opcode, Type *Ty,
1085 bool AllowRHSConstant = false);
1086
1087 /// Return the absorbing element for the given binary
1088 /// operation, i.e. a constant C such that X op C = C and C op X = C for
1089 /// every X. For example, this returns zero for integer multiplication.
1090 /// It returns null if the operator doesn't have an absorbing element.
1091 static Constant *getBinOpAbsorber(unsigned Opcode, Type *Ty);
1092
1093 /// Transparently provide more efficient getOperand methods.
1094 DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Constant)public: inline Constant *getOperand(unsigned) const; inline void
setOperand(unsigned, Constant*); inline op_iterator op_begin
(); inline const_op_iterator op_begin() const; inline op_iterator
op_end(); inline const_op_iterator op_end() const; protected
: template <int> inline Use &Op(); template <int
> inline const Use &Op() const; public: inline unsigned
getNumOperands() const
;
1095
1096 /// Convenience function for getting a Cast operation.
1097 ///
1098 /// \param ops The opcode for the conversion
1099 /// \param C The constant to be converted
1100 /// \param Ty The type to which the constant is converted
1101 /// \param OnlyIfReduced see \a getWithOperands() docs.
1102 static Constant *getCast(unsigned ops, Constant *C, Type *Ty,
1103 bool OnlyIfReduced = false);
1104
1105 // Create a ZExt or BitCast cast constant expression
1106 static Constant *
1107 getZExtOrBitCast(Constant *C, ///< The constant to zext or bitcast
1108 Type *Ty ///< The type to zext or bitcast C to
1109 );
1110
1111 // Create a SExt or BitCast cast constant expression
1112 static Constant *
1113 getSExtOrBitCast(Constant *C, ///< The constant to sext or bitcast
1114 Type *Ty ///< The type to sext or bitcast C to
1115 );
1116
1117 // Create a Trunc or BitCast cast constant expression
1118 static Constant *
1119 getTruncOrBitCast(Constant *C, ///< The constant to trunc or bitcast
1120 Type *Ty ///< The type to trunc or bitcast C to
1121 );
1122
1123 /// Create a BitCast, AddrSpaceCast, or a PtrToInt cast constant
1124 /// expression.
1125 static Constant *
1126 getPointerCast(Constant *C, ///< The pointer value to be casted (operand 0)
1127 Type *Ty ///< The type to which cast should be made
1128 );
1129
1130 /// Create a BitCast or AddrSpaceCast for a pointer type depending on
1131 /// the address space.
1132 static Constant *getPointerBitCastOrAddrSpaceCast(
1133 Constant *C, ///< The constant to addrspacecast or bitcast
1134 Type *Ty ///< The type to bitcast or addrspacecast C to
1135 );
1136
1137 /// Create a ZExt, Bitcast or Trunc for integer -> integer casts
1138 static Constant *
1139 getIntegerCast(Constant *C, ///< The integer constant to be casted
1140 Type *Ty, ///< The integer type to cast to
1141 bool IsSigned ///< Whether C should be treated as signed or not
1142 );
1143
1144 /// Create a FPExt, Bitcast or FPTrunc for fp -> fp casts
1145 static Constant *getFPCast(Constant *C, ///< The integer constant to be casted
1146 Type *Ty ///< The integer type to cast to
1147 );
1148
1149 /// Return true if this is a convert constant expression
1150 bool isCast() const;
1151
1152 /// Return true if this is a compare constant expression
1153 bool isCompare() const;
1154
1155 /// Return true if this is an insertvalue or extractvalue expression,
1156 /// and the getIndices() method may be used.
1157 bool hasIndices() const;
1158
1159 /// Return true if this is a getelementptr expression and all
1160 /// the index operands are compile-time known integers within the
1161 /// corresponding notional static array extents. Note that this is
1162 /// not equivalant to, a subset of, or a superset of the "inbounds"
1163 /// property.
1164 bool isGEPWithNoNotionalOverIndexing() const;
1165
1166 /// Select constant expr
1167 ///
1168 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1169 static Constant *getSelect(Constant *C, Constant *V1, Constant *V2,
1170 Type *OnlyIfReducedTy = nullptr);
1171
1172 /// get - Return a unary operator constant expression,
1173 /// folding if possible.
1174 ///
1175 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1176 static Constant *get(unsigned Opcode, Constant *C1, unsigned Flags = 0,
1177 Type *OnlyIfReducedTy = nullptr);
1178
1179 /// get - Return a binary or shift operator constant expression,
1180 /// folding if possible.
1181 ///
1182 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1183 static Constant *get(unsigned Opcode, Constant *C1, Constant *C2,
1184 unsigned Flags = 0, Type *OnlyIfReducedTy = nullptr);
1185
1186 /// Return an ICmp or FCmp comparison operator constant expression.
1187 ///
1188 /// \param OnlyIfReduced see \a getWithOperands() docs.
1189 static Constant *getCompare(unsigned short pred, Constant *C1, Constant *C2,
1190 bool OnlyIfReduced = false);
1191
1192 /// get* - Return some common constants without having to
1193 /// specify the full Instruction::OPCODE identifier.
1194 ///
1195 static Constant *getICmp(unsigned short pred, Constant *LHS, Constant *RHS,
1196 bool OnlyIfReduced = false);
1197 static Constant *getFCmp(unsigned short pred, Constant *LHS, Constant *RHS,
1198 bool OnlyIfReduced = false);
1199
1200 /// Getelementptr form. Value* is only accepted for convenience;
1201 /// all elements must be Constants.
1202 ///
1203 /// \param InRangeIndex the inrange index if present or None.
1204 /// \param OnlyIfReducedTy see \a getWithOperands() docs.
1205 static Constant *getGetElementPtr(Type *Ty, Constant *C,
1206 ArrayRef<Constant *> IdxList,
1207 bool InBounds = false,
1208 Optional<unsigned> InRangeIndex = None,
1209 Type *OnlyIfReducedTy = nullptr) {
1210 return getGetElementPtr(
1211 Ty, C, makeArrayRef((Value *const *)IdxList.data(), IdxList.size()),
1212 InBounds, InRangeIndex, OnlyIfReducedTy);
1213 }
1214 static Constant *getGetElementPtr(Type *Ty, Constant *C, Constant *Idx,
1215 bool InBounds = false,
1216 Optional<unsigned> InRangeIndex = None,
1217 Type *OnlyIfReducedTy = nullptr) {
1218 // This form of the function only exists to avoid ambiguous overload
1219 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1220 // ArrayRef<Value *>.
1221 return getGetElementPtr(Ty, C, cast<Value>(Idx), InBounds, InRangeIndex,
1222 OnlyIfReducedTy);
1223 }
1224 static Constant *getGetElementPtr(Type *Ty, Constant *C,
1225 ArrayRef<Value *> IdxList,
1226 bool InBounds = false,
1227 Optional<unsigned> InRangeIndex = None,
1228 Type *OnlyIfReducedTy = nullptr);
1229
1230 /// Create an "inbounds" getelementptr. See the documentation for the
1231 /// "inbounds" flag in LangRef.html for details.
1232 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1233 ArrayRef<Constant *> IdxList) {
1234 return getGetElementPtr(Ty, C, IdxList, true);
1235 }
1236 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1237 Constant *Idx) {
1238 // This form of the function only exists to avoid ambiguous overload
1239 // warnings about whether to convert Idx to ArrayRef<Constant *> or
1240 // ArrayRef<Value *>.
1241 return getGetElementPtr(Ty, C, Idx, true);
1242 }
1243 static Constant *getInBoundsGetElementPtr(Type *Ty, Constant *C,
1244 ArrayRef<Value *> IdxList) {
1245 return getGetElementPtr(Ty, C, IdxList, true);
1246 }
1247
1248 static Constant *getExtractElement(Constant *Vec, Constant *Idx,
1249 Type *OnlyIfReducedTy = nullptr);
1250 static Constant *getInsertElement(Constant *Vec, Constant *Elt, Constant *Idx,
1251 Type *OnlyIfReducedTy = nullptr);
1252 static Constant *getShuffleVector(Constant *V1, Constant *V2,
1253 ArrayRef<int> Mask,
1254 Type *OnlyIfReducedTy = nullptr);
1255 static Constant *getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
1256 Type *OnlyIfReducedTy = nullptr);
1257 static Constant *getInsertValue(Constant *Agg, Constant *Val,
1258 ArrayRef<unsigned> Idxs,
1259 Type *OnlyIfReducedTy = nullptr);
1260
1261 /// Return the opcode at the root of this constant expression
1262 unsigned getOpcode() const { return getSubclassDataFromValue(); }
1263
1264 /// Return the ICMP or FCMP predicate value. Assert if this is not an ICMP or
1265 /// FCMP constant expression.
1266 unsigned getPredicate() const;
1267
1268 /// Assert that this is an insertvalue or exactvalue
1269 /// expression and return the list of indices.
1270 ArrayRef<unsigned> getIndices() const;
1271
1272 /// Assert that this is a shufflevector and return the mask. See class
1273 /// ShuffleVectorInst for a description of the mask representation.
1274 ArrayRef<int> getShuffleMask() const;
1275
1276 /// Assert that this is a shufflevector and return the mask.
1277 ///
1278 /// TODO: This is a temporary hack until we update the bitcode format for
1279 /// shufflevector.
1280 Constant *getShuffleMaskForBitcode() const;
1281
1282 /// Return a string representation for an opcode.
1283 const char *getOpcodeName() const;
1284
1285 /// Return a constant expression identical to this one, but with the specified
1286 /// operand set to the specified value.
1287 Constant *getWithOperandReplaced(unsigned OpNo, Constant *Op) const;
1288
1289 /// This returns the current constant expression with the operands replaced
1290 /// with the specified values. The specified array must have the same number
1291 /// of operands as our current one.
1292 Constant *getWithOperands(ArrayRef<Constant *> Ops) const {
1293 return getWithOperands(Ops, getType());
1294 }
1295
1296 /// Get the current expression with the operands replaced.
1297 ///
1298 /// Return the current constant expression with the operands replaced with \c
1299 /// Ops and the type with \c Ty. The new operands must have the same number
1300 /// as the current ones.
1301 ///
1302 /// If \c OnlyIfReduced is \c true, nullptr will be returned unless something
1303 /// gets constant-folded, the type changes, or the expression is otherwise
1304 /// canonicalized. This parameter should almost always be \c false.
1305 Constant *getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
1306 bool OnlyIfReduced = false,
1307 Type *SrcTy = nullptr) const;
1308
1309 /// Returns an Instruction which implements the same operation as this
1310 /// ConstantExpr. The instruction is not linked to any basic block.
1311 ///
1312 /// A better approach to this could be to have a constructor for Instruction
1313 /// which would take a ConstantExpr parameter, but that would have spread
1314 /// implementation details of ConstantExpr outside of Constants.cpp, which
1315 /// would make it harder to remove ConstantExprs altogether.
1316 Instruction *getAsInstruction() const;
1317
1318 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1319 static bool classof(const Value *V) {
1320 return V->getValueID() == ConstantExprVal;
1321 }
1322
1323private:
1324 // Shadow Value::setValueSubclassData with a private forwarding method so that
1325 // subclasses cannot accidentally use it.
1326 void setValueSubclassData(unsigned short D) {
1327 Value::setValueSubclassData(D);
1328 }
1329};
1330
1331template <>
1332struct OperandTraits<ConstantExpr>
1333 : public VariadicOperandTraits<ConstantExpr, 1> {};
1334
1335DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantExpr, Constant)ConstantExpr::op_iterator ConstantExpr::op_begin() { return OperandTraits
<ConstantExpr>::op_begin(this); } ConstantExpr::const_op_iterator
ConstantExpr::op_begin() const { return OperandTraits<ConstantExpr
>::op_begin(const_cast<ConstantExpr*>(this)); } ConstantExpr
::op_iterator ConstantExpr::op_end() { return OperandTraits<
ConstantExpr>::op_end(this); } ConstantExpr::const_op_iterator
ConstantExpr::op_end() const { return OperandTraits<ConstantExpr
>::op_end(const_cast<ConstantExpr*>(this)); } Constant
*ConstantExpr::getOperand(unsigned i_nocapture) const { ((i_nocapture
< OperandTraits<ConstantExpr>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<ConstantExpr>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 1335, __PRETTY_FUNCTION__)); return cast_or_null<Constant
>( OperandTraits<ConstantExpr>::op_begin(const_cast<
ConstantExpr*>(this))[i_nocapture].get()); } void ConstantExpr
::setOperand(unsigned i_nocapture, Constant *Val_nocapture) {
((i_nocapture < OperandTraits<ConstantExpr>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ConstantExpr>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/IR/Constants.h"
, 1335, __PRETTY_FUNCTION__)); OperandTraits<ConstantExpr>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ConstantExpr
::getNumOperands() const { return OperandTraits<ConstantExpr
>::operands(this); } template <int Idx_nocapture> Use
&ConstantExpr::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
ConstantExpr::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
1336
1337//===----------------------------------------------------------------------===//
1338/// 'undef' values are things that do not have specified contents.
1339/// These are used for a variety of purposes, including global variable
1340/// initializers and operands to instructions. 'undef' values can occur with
1341/// any first-class type.
1342///
1343/// Undef values aren't exactly constants; if they have multiple uses, they
1344/// can appear to have different bit patterns at each use. See
1345/// LangRef.html#undefvalues for details.
1346///
1347class UndefValue : public ConstantData {
1348 friend class Constant;
1349
1350 explicit UndefValue(Type *T) : ConstantData(T, UndefValueVal) {}
1351
1352 void destroyConstantImpl();
1353
1354protected:
1355 explicit UndefValue(Type *T, ValueTy vty) : ConstantData(T, vty) {}
1356
1357public:
1358 UndefValue(const UndefValue &) = delete;
1359
1360 /// Static factory methods - Return an 'undef' object of the specified type.
1361 static UndefValue *get(Type *T);
1362
1363 /// If this Undef has array or vector type, return a undef with the right
1364 /// element type.
1365 UndefValue *getSequentialElement() const;
1366
1367 /// If this undef has struct type, return a undef with the right element type
1368 /// for the specified element.
1369 UndefValue *getStructElement(unsigned Elt) const;
1370
1371 /// Return an undef of the right value for the specified GEP index if we can,
1372 /// otherwise return null (e.g. if C is a ConstantExpr).
1373 UndefValue *getElementValue(Constant *C) const;
1374
1375 /// Return an undef of the right value for the specified GEP index.
1376 UndefValue *getElementValue(unsigned Idx) const;
1377
1378 /// Return the number of elements in the array, vector, or struct.
1379 unsigned getNumElements() const;
1380
1381 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1382 static bool classof(const Value *V) {
1383 return V->getValueID() == UndefValueVal ||
1384 V->getValueID() == PoisonValueVal;
1385 }
1386};
1387
1388//===----------------------------------------------------------------------===//
1389/// In order to facilitate speculative execution, many instructions do not
1390/// invoke immediate undefined behavior when provided with illegal operands,
1391/// and return a poison value instead.
1392///
1393/// see LangRef.html#poisonvalues for details.
1394///
1395class PoisonValue final : public UndefValue {
1396 friend class Constant;
1397
1398 explicit PoisonValue(Type *T) : UndefValue(T, PoisonValueVal) {}
1399
1400 void destroyConstantImpl();
1401
1402public:
1403 PoisonValue(const PoisonValue &) = delete;
1404
1405 /// Static factory methods - Return an 'poison' object of the specified type.
1406 static PoisonValue *get(Type *T);
1407
1408 /// If this poison has array or vector type, return a poison with the right
1409 /// element type.
1410 PoisonValue *getSequentialElement() const;
1411
1412 /// If this poison has struct type, return a poison with the right element
1413 /// type for the specified element.
1414 PoisonValue *getStructElement(unsigned Elt) const;
1415
1416 /// Return an poison of the right value for the specified GEP index if we can,
1417 /// otherwise return null (e.g. if C is a ConstantExpr).
1418 PoisonValue *getElementValue(Constant *C) const;
1419
1420 /// Return an poison of the right value for the specified GEP index.
1421 PoisonValue *getElementValue(unsigned Idx) const;
1422
1423 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1424 static bool classof(const Value *V) {
1425 return V->getValueID() == PoisonValueVal;
1426 }
1427};
1428
1429} // end namespace llvm
1430
1431#endif // LLVM_IR_CONSTANTS_H

/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h

1//===-- llvm/ADT/APInt.h - For Arbitrary Precision Integer -----*- C++ -*--===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements a class to represent arbitrary precision
11/// integral constant values and operations on them.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_APINT_H
16#define LLVM_ADT_APINT_H
17
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/MathExtras.h"
20#include <cassert>
21#include <climits>
22#include <cstring>
23#include <string>
24
25namespace llvm {
26class FoldingSetNodeID;
27class StringRef;
28class hash_code;
29class raw_ostream;
30
31template <typename T> class SmallVectorImpl;
32template <typename T> class ArrayRef;
33template <typename T> class Optional;
34template <typename T> struct DenseMapInfo;
35
36class APInt;
37
38inline APInt operator-(APInt);
39
40//===----------------------------------------------------------------------===//
41// APInt Class
42//===----------------------------------------------------------------------===//
43
44/// Class for arbitrary precision integers.
45///
46/// APInt is a functional replacement for common case unsigned integer type like
47/// "unsigned", "unsigned long" or "uint64_t", but also allows non-byte-width
48/// integer sizes and large integer value types such as 3-bits, 15-bits, or more
49/// than 64-bits of precision. APInt provides a variety of arithmetic operators
50/// and methods to manipulate integer values of any bit-width. It supports both
51/// the typical integer arithmetic and comparison operations as well as bitwise
52/// manipulation.
53///
54/// The class has several invariants worth noting:
55/// * All bit, byte, and word positions are zero-based.
56/// * Once the bit width is set, it doesn't change except by the Truncate,
57/// SignExtend, or ZeroExtend operations.
58/// * All binary operators must be on APInt instances of the same bit width.
59/// Attempting to use these operators on instances with different bit
60/// widths will yield an assertion.
61/// * The value is stored canonically as an unsigned value. For operations
62/// where it makes a difference, there are both signed and unsigned variants
63/// of the operation. For example, sdiv and udiv. However, because the bit
64/// widths must be the same, operations such as Mul and Add produce the same
65/// results regardless of whether the values are interpreted as signed or
66/// not.
67/// * In general, the class tries to follow the style of computation that LLVM
68/// uses in its IR. This simplifies its use for LLVM.
69///
70class LLVM_NODISCARD[[clang::warn_unused_result]] APInt {
71public:
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
90private:
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 <= APINT_BITS_PER_WORD; }
32
Assuming field 'BitWidth' is > APINT_BITS_PER_WORD
33
Returning zero, which participates in a condition later
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
264public:
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-13~++20210413100635+64c24f493e5f/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; }
30
Calling 'APInt::operator!'
38
Returning from 'APInt::operator!'
39
Returning the value 1, which participates in a condition later
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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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())
31
Calling 'APInt::isSingleWord'
34
Returning from 'APInt::isSingleWord'
35
Taking false branch
743 return U.VAL == 0;
744 return countLeadingZerosSlowCase() == BitWidth;
36
Assuming the condition is true
37
Returning the value 1, which participates in a condition later
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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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-13~++20210413100635+64c24f493e5f/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 /// Truncate to width
1407 ///
1408 /// Make this APInt have the bit width given by \p width. The value is
1409 /// truncated or left alone to make it that width.
1410 APInt truncOrSelf(unsigned width) const;
1411
1412 /// Sign extend or truncate to width
1413 ///
1414 /// Make this APInt have the bit width given by \p width. The value is sign
1415 /// extended, or left alone to make it that width.
1416 APInt sextOrSelf(unsigned width) const;
1417
1418 /// Zero extend or truncate to width
1419 ///
1420 /// Make this APInt have the bit width given by \p width. The value is zero
1421 /// extended, or left alone to make it that width.
1422 APInt zextOrSelf(unsigned width) const;
1423
1424 /// @}
1425 /// \name Bit Manipulation Operators
1426 /// @{
1427
1428 /// Set every bit to 1.
1429 void setAllBits() {
1430 if (isSingleWord())
1431 U.VAL = WORDTYPE_MAX;
1432 else
1433 // Set all the bits in all the words.
1434 memset(U.pVal, -1, getNumWords() * APINT_WORD_SIZE);
1435 // Clear the unused ones
1436 clearUnusedBits();
1437 }
1438
1439 /// Set a given bit to 1.
1440 ///
1441 /// Set the given bit to 1 whose position is given as "bitPosition".
1442 void setBit(unsigned BitPosition) {
1443 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1443, __PRETTY_FUNCTION__))
;
1444 WordType Mask = maskBit(BitPosition);
1445 if (isSingleWord())
1446 U.VAL |= Mask;
1447 else
1448 U.pVal[whichWord(BitPosition)] |= Mask;
1449 }
1450
1451 /// Set the sign bit to 1.
1452 void setSignBit() {
1453 setBit(BitWidth - 1);
1454 }
1455
1456 /// Set a given bit to a given value.
1457 void setBitVal(unsigned BitPosition, bool BitValue) {
1458 if (BitValue)
1459 setBit(BitPosition);
1460 else
1461 clearBit(BitPosition);
1462 }
1463
1464 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1465 /// This function handles "wrap" case when \p loBit >= \p hiBit, and calls
1466 /// setBits when \p loBit < \p hiBit.
1467 /// For \p loBit == \p hiBit wrap case, set every bit to 1.
1468 void setBitsWithWrap(unsigned loBit, unsigned hiBit) {
1469 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1469, __PRETTY_FUNCTION__))
;
1470 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1470, __PRETTY_FUNCTION__))
;
1471 if (loBit < hiBit) {
1472 setBits(loBit, hiBit);
1473 return;
1474 }
1475 setLowBits(hiBit);
1476 setHighBits(BitWidth - loBit);
1477 }
1478
1479 /// Set the bits from loBit (inclusive) to hiBit (exclusive) to 1.
1480 /// This function handles case when \p loBit <= \p hiBit.
1481 void setBits(unsigned loBit, unsigned hiBit) {
1482 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1482, __PRETTY_FUNCTION__))
;
1483 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1483, __PRETTY_FUNCTION__))
;
1484 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1484, __PRETTY_FUNCTION__))
;
1485 if (loBit == hiBit)
1486 return;
1487 if (loBit < APINT_BITS_PER_WORD && hiBit <= APINT_BITS_PER_WORD) {
1488 uint64_t mask = WORDTYPE_MAX >> (APINT_BITS_PER_WORD - (hiBit - loBit));
1489 mask <<= loBit;
1490 if (isSingleWord())
1491 U.VAL |= mask;
1492 else
1493 U.pVal[0] |= mask;
1494 } else {
1495 setBitsSlowCase(loBit, hiBit);
1496 }
1497 }
1498
1499 /// Set the top bits starting from loBit.
1500 void setBitsFrom(unsigned loBit) {
1501 return setBits(loBit, BitWidth);
1502 }
1503
1504 /// Set the bottom loBits bits.
1505 void setLowBits(unsigned loBits) {
1506 return setBits(0, loBits);
1507 }
1508
1509 /// Set the top hiBits bits.
1510 void setHighBits(unsigned hiBits) {
1511 return setBits(BitWidth - hiBits, BitWidth);
1512 }
1513
1514 /// Set every bit to 0.
1515 void clearAllBits() {
1516 if (isSingleWord())
1517 U.VAL = 0;
1518 else
1519 memset(U.pVal, 0, getNumWords() * APINT_WORD_SIZE);
1520 }
1521
1522 /// Set a given bit to 0.
1523 ///
1524 /// Set the given bit to 0 whose position is given as "bitPosition".
1525 void clearBit(unsigned BitPosition) {
1526 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1526, __PRETTY_FUNCTION__))
;
1527 WordType Mask = ~maskBit(BitPosition);
1528 if (isSingleWord())
1529 U.VAL &= Mask;
1530 else
1531 U.pVal[whichWord(BitPosition)] &= Mask;
1532 }
1533
1534 /// Set bottom loBits bits to 0.
1535 void clearLowBits(unsigned loBits) {
1536 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1536, __PRETTY_FUNCTION__))
;
1537 APInt Keep = getHighBitsSet(BitWidth, BitWidth - loBits);
1538 *this &= Keep;
1539 }
1540
1541 /// Set the sign bit to 0.
1542 void clearSignBit() {
1543 clearBit(BitWidth - 1);
1544 }
1545
1546 /// Toggle every bit to its opposite value.
1547 void flipAllBits() {
1548 if (isSingleWord()) {
1549 U.VAL ^= WORDTYPE_MAX;
1550 clearUnusedBits();
1551 } else {
1552 flipAllBitsSlowCase();
1553 }
1554 }
1555
1556 /// Toggles a given bit to its opposite value.
1557 ///
1558 /// Toggle a given bit to its opposite value whose position is given
1559 /// as "bitPosition".
1560 void flipBit(unsigned bitPosition);
1561
1562 /// Negate this APInt in place.
1563 void negate() {
1564 flipAllBits();
1565 ++(*this);
1566 }
1567
1568 /// Insert the bits from a smaller APInt starting at bitPosition.
1569 void insertBits(const APInt &SubBits, unsigned bitPosition);
1570 void insertBits(uint64_t SubBits, unsigned bitPosition, unsigned numBits);
1571
1572 /// Return an APInt with the extracted bits [bitPosition,bitPosition+numBits).
1573 APInt extractBits(unsigned numBits, unsigned bitPosition) const;
1574 uint64_t extractBitsAsZExtValue(unsigned numBits, unsigned bitPosition) const;
1575
1576 /// @}
1577 /// \name Value Characterization Functions
1578 /// @{
1579
1580 /// Return the number of bits in the APInt.
1581 unsigned getBitWidth() const { return BitWidth; }
1582
1583 /// Get the number of words.
1584 ///
1585 /// Here one word's bitwidth equals to that of uint64_t.
1586 ///
1587 /// \returns the number of words to hold the integer value of this APInt.
1588 unsigned getNumWords() const { return getNumWords(BitWidth); }
1589
1590 /// Get the number of words.
1591 ///
1592 /// *NOTE* Here one word's bitwidth equals to that of uint64_t.
1593 ///
1594 /// \returns the number of words to hold the integer value with a given bit
1595 /// width.
1596 static unsigned getNumWords(unsigned BitWidth) {
1597 return ((uint64_t)BitWidth + APINT_BITS_PER_WORD - 1) / APINT_BITS_PER_WORD;
1598 }
1599
1600 /// Compute the number of active bits in the value
1601 ///
1602 /// This function returns the number of active bits which is defined as the
1603 /// bit width minus the number of leading zeros. This is used in several
1604 /// computations to see how "wide" the value is.
1605 unsigned getActiveBits() const { return BitWidth - countLeadingZeros(); }
1606
1607 /// Compute the number of active words in the value of this APInt.
1608 ///
1609 /// This is used in conjunction with getActiveData to extract the raw value of
1610 /// the APInt.
1611 unsigned getActiveWords() const {
1612 unsigned numActiveBits = getActiveBits();
1613 return numActiveBits ? whichWord(numActiveBits - 1) + 1 : 1;
1614 }
1615
1616 /// Get the minimum bit size for this signed APInt
1617 ///
1618 /// Computes the minimum bit width for this APInt while considering it to be a
1619 /// signed (and probably negative) value. If the value is not negative, this
1620 /// function returns the same value as getActiveBits()+1. Otherwise, it
1621 /// returns the smallest bit width that will retain the negative value. For
1622 /// example, -1 can be written as 0b1 or 0xFFFFFFFFFF. 0b1 is shorter and so
1623 /// for -1, this function will always return 1.
1624 unsigned getMinSignedBits() const { return BitWidth - getNumSignBits() + 1; }
1625
1626 /// Get zero extended value
1627 ///
1628 /// This method attempts to return the value of this APInt as a zero extended
1629 /// uint64_t. The bitwidth must be <= 64 or the value must fit within a
1630 /// uint64_t. Otherwise an assertion will result.
1631 uint64_t getZExtValue() const {
1632 if (isSingleWord())
1633 return U.VAL;
1634 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1634, __PRETTY_FUNCTION__))
;
1635 return U.pVal[0];
1636 }
1637
1638 /// Get sign extended value
1639 ///
1640 /// This method attempts to return the value of this APInt as a sign extended
1641 /// int64_t. The bit width must be <= 64 or the value must fit within an
1642 /// int64_t. Otherwise an assertion will result.
1643 int64_t getSExtValue() const {
1644 if (isSingleWord())
1645 return SignExtend64(U.VAL, BitWidth);
1646 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-13~++20210413100635+64c24f493e5f/llvm/include/llvm/ADT/APInt.h"
, 1646, __PRETTY_FUNCTION__))
;
1647 return int64_t(U.pVal[0]);
1648 }
1649
1650 /// Get bits required for string value.
1651 ///
1652 /// This method determines how many bits are required to hold the APInt
1653 /// equivalent of the string given by \p str.
1654 static unsigned getBitsNeeded(StringRef str, uint8_t radix);
1655
1656 /// The APInt version of the countLeadingZeros functions in
1657 /// MathExtras.h.
1658 ///
1659 /// It counts the number of zeros from the most significant bit to the first
1660 /// one bit.
1661 ///
1662 /// \returns BitWidth if the value is zero, otherwise returns the number of
1663 /// zeros from the most significant bit to the first one bits.
1664 unsigned countLeadingZeros() const {
1665 if (isSingleWord()) {
1666 unsigned unusedBits = APINT_BITS_PER_WORD - BitWidth;
1667 return llvm::countLeadingZeros(U.VAL) - unusedBits;
1668 }
1669 return countLeadingZerosSlowCase();
1670 }
1671
1672 /// Count the number of leading one bits.
1673 ///
1674 /// This function is an APInt version of the countLeadingOnes
1675 /// functions in MathExtras.h. It counts the number of ones from the most
1676 /// significant bit to the first zero bit.
1677 ///
1678 /// \returns 0 if the high order bit is not set, otherwise returns the number
1679 /// of 1 bits from the most significant to the least
1680 unsigned countLeadingOnes() const {
1681 if (isSingleWord())
1682 return llvm::countLeadingOnes(U.VAL << (APINT_BITS_PER_WORD - BitWidth));
1683 return countLeadingOnesSlowCase();
1684 }
1685
1686 /// Computes the number of leading bits of this APInt that are equal to its
1687 /// sign bit.
1688 unsigned getNumSignBits() const {
1689 return isNegative() ? countLeadingOnes() : countLeadingZeros();
1690 }
1691
1692 /// Count the number of trailing zero bits.
1693 ///
1694 /// This function is an APInt version of the countTrailingZeros
1695 /// functions in MathExtras.h. It counts the number of zeros from the least
1696 /// significant bit to the first set bit.
1697 ///
1698 /// \returns BitWidth if the value is zero, otherwise returns the number of
1699 /// zeros from the least significant bit to the first one bit.
1700 unsigned countTrailingZeros() const {
1701 if (isSingleWord())
1702 return std::min(unsigned(llvm::countTrailingZeros(U.VAL)), BitWidth);
1703 return countTrailingZerosSlowCase();
1704 }
1705
1706 /// Count the number of trailing one bits.
1707 ///
1708 /// This function is an APInt version of the countTrailingOnes
1709 /// functions in MathExtras.h. It counts the number of ones from the least
1710 /// significant bit to the first zero bit.
1711 ///
1712 /// \returns BitWidth if the value is all ones, otherwise returns the number
1713 /// of ones from the least significant bit to the first zero bit.
1714 unsigned countTrailingOnes() const {
1715 if (isSingleWord())
1716 return llvm::countTrailingOnes(U.VAL);
1717 return countTrailingOnesSlowCase();
1718 }
1719
1720 /// Count the number of bits set.
1721 ///
1722 /// This function is an APInt version of the countPopulation functions
1723 /// in MathExtras.h. It counts the number of 1 bits in the APInt value.
1724 ///
1725 /// \returns 0 if the value is zero, otherwise returns the number of set bits.
1726 unsigned countPopulation() const {
1727 if (isSingleWord())
1728 return llvm::countPopulation(U.VAL);
1729 return countPopulationSlowCase();
1730 }
1731
1732 /// @}
1733 /// \name Conversion Functions
1734 /// @{
1735 void print(raw_ostream &OS, bool isSigned) const;
1736
1737 /// Converts an APInt to a string and append it to Str. Str is commonly a
1738 /// SmallString.
1739 void toString(SmallVectorImpl<char> &Str, unsigned Radix, bool Signed,
1740 bool formatAsCLiteral = false) const;
1741
1742 /// Considers the APInt to be unsigned and converts it into a string in the
1743 /// radix given. The radix can be 2, 8, 10 16, or 36.
1744 void toStringUnsigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1745 toString(Str, Radix, false, false);
1746 }
1747
1748 /// Considers the APInt to be signed and converts it into a string in the
1749 /// radix given. The radix can be 2, 8, 10, 16, or 36.
1750 void toStringSigned(SmallVectorImpl<char> &Str, unsigned Radix = 10) const {
1751 toString(Str, Radix, true, false);
1752 }
1753
1754 /// Return the APInt as a std::string.
1755 ///
1756 /// Note that this is an inefficient method. It is better to pass in a
1757 /// SmallVector/SmallString to the methods above to avoid thrashing the heap
1758 /// for the string.
1759 std::string toString(unsigned Radix, bool Signed) const;
1760
1761 /// \returns a byte-swapped representation of this APInt Value.
1762 APInt byteSwap() const;
1763
1764 /// \returns the value with the bit representation reversed of this APInt
1765 /// Value.
1766 APInt reverseBits() const;
1767
1768 /// Converts this APInt to a double value.
1769 double roundToDouble(bool isSigned) const;
1770
1771 /// Converts this unsigned APInt to a double value.
1772 double roundToDouble() const { return roundToDouble(false); }
1773
1774 /// Converts this signed APInt to a double value.
1775 double signedRoundToDouble() const { return roundToDouble(true); }
1776
1777 /// Converts APInt bits to a double
1778 ///
1779 /// The conversion does not do a translation from integer to double, it just
1780 /// re-interprets the bits as a double. Note that it is valid to do this on
1781 /// any bit width. Exactly 64 bits will be translated.
1782 double bitsToDouble() const {
1783 return BitsToDouble(getWord(0));
1784 }
1785
1786 /// Converts APInt bits to a float
1787 ///
1788 /// The conversion does not do a translation from integer to float, it just
1789 /// re-interprets the bits as a float. Note that it is valid to do this on
1790 /// any bit width. Exactly 32 bits will be translated.
1791 float bitsToFloat() const {
1792 return BitsToFloat(static_cast<uint32_t>(getWord(0)));
1793 }
1794
1795 /// Converts a double to APInt bits.
1796 ///
1797 /// The conversion does not do a translation from double to integer, it just
1798 /// re-interprets the bits of the double.
1799 static APInt doubleToBits(double V) {
1800 return APInt(sizeof(double) * CHAR_BIT8, DoubleToBits(V));
1801 }
1802
1803 /// Converts a float to APInt bits.
1804 ///
1805 /// The conversion does not do a translation from float to integer, it just
1806 /// re-interprets the bits of the float.
1807 static APInt floatToBits(float V) {
1808 return APInt(sizeof(float) * CHAR_BIT8, FloatToBits(V));
1809 }
1810
1811 /// @}
1812 /// \name Mathematics Operations
1813 /// @{
1814
1815 /// \returns the floor log base 2 of this APInt.
1816 unsigned logBase2() const { return getActiveBits() - 1; }
1817
1818 /// \returns the ceil log base 2 of this APInt.
1819 unsigned ceilLogBase2() const {
1820 APInt temp(*this);
1821 --temp;
1822 return temp.getActiveBits();
1823 }
1824
1825 /// \returns the nearest log base 2 of this APInt. Ties round up.
1826 ///
1827 /// NOTE: When we have a BitWidth of 1, we define:
1828 ///
1829 /// log2(0) = UINT32_MAX
1830 /// log2(1) = 0
1831 ///
1832 /// to get around any mathematical concerns resulting from
1833 /// referencing 2 in a space where 2 does no exist.
1834 unsigned nearestLogBase2() const {
1835 // Special case when we have a bitwidth of 1. If VAL is 1, then we
1836 // get 0. If VAL is 0, we get WORDTYPE_MAX which gets truncated to
1837 // UINT32_MAX.
1838 if (BitWidth == 1)
1839 return U.VAL - 1;
1840
1841 // Handle the zero case.
1842 if (isNullValue())
1843 return UINT32_MAX(4294967295U);
1844
1845 // The non-zero case is handled by computing:
1846 //
1847 // nearestLogBase2(x) = logBase2(x) + x[logBase2(x)-1].
1848 //
1849 // where x[i] is referring to the value of the ith bit of x.
1850 unsigned lg = logBase2();
1851 return lg + unsigned((*this)[lg - 1]);
1852 }
1853
1854 /// \returns the log base 2 of this APInt if its an exact power of two, -1
1855 /// otherwise
1856 int32_t exactLogBase2() const {
1857 if (!isPowerOf2())
1858 return -1;
1859 return logBase2();
1860 }
1861
1862 /// Compute the square root
1863 APInt sqrt() const;
1864
1865 /// Get the absolute value;
1866 ///
1867 /// If *this is < 0 then return -(*this), otherwise *this;
1868 APInt abs() const {
1869 if (isNegative())
1870 return -(*this);
1871 return *this;
1872 }
1873
1874 /// \returns the multiplicative inverse for a given modulo.
1875 APInt multiplicativeInverse(const APInt &modulo) const;
1876
1877 /// @}
1878 /// \name Support for division by constant
1879 /// @{
1880
1881 /// Calculate the magic number for signed division by a constant.
1882 struct ms;
1883 ms magic() const;
1884
1885 /// Calculate the magic number for unsigned division by a constant.
1886 struct mu;
1887 mu magicu(unsigned LeadingZeros = 0) const;
1888
1889 /// @}
1890 /// \name Building-block Operations for APInt and APFloat
1891 /// @{
1892
1893 // These building block operations operate on a representation of arbitrary
1894 // precision, two's-complement, bignum integer values. They should be
1895 // sufficient to implement APInt and APFloat bignum requirements. Inputs are
1896 // generally a pointer to the base of an array of integer parts, representing
1897 // an unsigned bignum, and a count of how many parts there are.
1898
1899 /// Sets the least significant part of a bignum to the input value, and zeroes
1900 /// out higher parts.
1901 static void tcSet(WordType *, WordType, unsigned);
1902
1903 /// Assign one bignum to another.
1904 static void tcAssign(WordType *, const WordType *, unsigned);
1905
1906 /// Returns true if a bignum is zero, false otherwise.
1907 static bool tcIsZero(const WordType *, unsigned);
1908
1909 /// Extract the given bit of a bignum; returns 0 or 1. Zero-based.
1910 static int tcExtractBit(const WordType *, unsigned bit);
1911
1912 /// Copy the bit vector of width srcBITS from SRC, starting at bit srcLSB, to
1913 /// DST, of dstCOUNT parts, such that the bit srcLSB becomes the least
1914 /// significant bit of DST. All high bits above srcBITS in DST are
1915 /// zero-filled.
1916 static void tcExtract(WordType *, unsigned dstCount,
1917 const WordType *, unsigned srcBits,
1918 unsigned srcLSB);
1919
1920 /// Set the given bit of a bignum. Zero-based.
1921 static void tcSetBit(WordType *, unsigned bit);
1922
1923 /// Clear the given bit of a bignum. Zero-based.
1924 static void tcClearBit(WordType *, unsigned bit);
1925
1926 /// Returns the bit number of the least or most significant set bit of a
1927 /// number. If the input number has no bits set -1U is returned.
1928 static unsigned tcLSB(const WordType *, unsigned n);
1929 static unsigned tcMSB(const WordType *parts, unsigned n);
1930
1931 /// Negate a bignum in-place.
1932 static void tcNegate(WordType *, unsigned);
1933
1934 /// DST += RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1935 static WordType tcAdd(WordType *, const WordType *,
1936 WordType carry, unsigned);
1937 /// DST += RHS. Returns the carry flag.
1938 static WordType tcAddPart(WordType *, WordType, unsigned);
1939
1940 /// DST -= RHS + CARRY where CARRY is zero or one. Returns the carry flag.
1941 static WordType tcSubtract(WordType *, const WordType *,
1942 WordType carry, unsigned);
1943 /// DST -= RHS. Returns the carry flag.
1944 static WordType tcSubtractPart(WordType *, WordType, unsigned);
1945
1946 /// DST += SRC * MULTIPLIER + PART if add is true
1947 /// DST = SRC * MULTIPLIER + PART if add is false
1948 ///
1949 /// Requires 0 <= DSTPARTS <= SRCPARTS + 1. If DST overlaps SRC they must
1950 /// start at the same point, i.e. DST == SRC.
1951 ///
1952 /// If DSTPARTS == SRC_PARTS + 1 no overflow occurs and zero is returned.
1953 /// Otherwise DST is filled with the least significant DSTPARTS parts of the
1954 /// result, and if all of the omitted higher parts were zero return zero,
1955 /// otherwise overflow occurred and return one.
1956 static int tcMultiplyPart(WordType *dst, const WordType *src,
1957 WordType multiplier, WordType carry,
1958 unsigned srcParts, unsigned dstParts,
1959 bool add);
1960
1961 /// DST = LHS * RHS, where DST has the same width as the operands and is
1962 /// filled with the least significant parts of the result. Returns one if
1963 /// overflow occurred, otherwise zero. DST must be disjoint from both
1964 /// operands.
1965 static int tcMultiply(WordType *, const WordType *, const WordType *,
1966 unsigned);
1967
1968 /// DST = LHS * RHS, where DST has width the sum of the widths of the
1969 /// operands. No overflow occurs. DST must be disjoint from both operands.
1970 static void tcFullMultiply(WordType *, const WordType *,
1971 const WordType *, unsigned, unsigned);
1972
1973 /// If RHS is zero LHS and REMAINDER are left unchanged, return one.
1974 /// Otherwise set LHS to LHS / RHS with the fractional part discarded, set
1975 /// REMAINDER to the remainder, return zero. i.e.
1976 ///
1977 /// OLD_LHS = RHS * LHS + REMAINDER
1978 ///
1979 /// SCRATCH is a bignum of the same size as the operands and result for use by
1980 /// the routine; its contents need not be initialized and are destroyed. LHS,
1981 /// REMAINDER and SCRATCH must be distinct.
1982 static int tcDivide(WordType *lhs, const WordType *rhs,
1983 WordType *remainder, WordType *scratch,
1984 unsigned parts);
1985
1986 /// Shift a bignum left Count bits. Shifted in bits are zero. There are no
1987 /// restrictions on Count.
1988 static void tcShiftLeft(WordType *, unsigned Words, unsigned Count);
1989
1990 /// Shift a bignum right Count bits. Shifted in bits are zero. There are no
1991 /// restrictions on Count.
1992 static void tcShiftRight(WordType *, unsigned Words, unsigned Count);
1993
1994 /// The obvious AND, OR and XOR and complement operations.
1995 static void tcAnd(WordType *, const WordType *, unsigned);
1996 static void tcOr(WordType *, const WordType *, unsigned);
1997 static void tcXor(WordType *, const WordType *, unsigned);
1998 static void tcComplement(WordType *, unsigned);
1999
2000 /// Comparison (unsigned) of two bignums.
2001 static int tcCompare(const WordType *, const WordType *, unsigned);
2002
2003 /// Increment a bignum in-place. Return the carry flag.
2004 static WordType tcIncrement(WordType *dst, unsigned parts) {
2005 return tcAddPart(dst, 1, parts);
2006 }
2007
2008 /// Decrement a bignum in-place. Return the borrow flag.
2009 static WordType tcDecrement(WordType *dst, unsigned parts) {
2010 return tcSubtractPart(dst, 1, parts);
2011 }
2012
2013 /// Set the least significant BITS and clear the rest.
2014 static void tcSetLeastSignificantBits(WordType *, unsigned, unsigned bits);
2015
2016 /// debug method
2017 void dump() const;
2018
2019 /// @}
2020};
2021
2022/// Magic data for optimising signed division by a constant.
2023struct APInt::ms {
2024 APInt m; ///< magic number
2025 unsigned s; ///< shift amount
2026};
2027
2028/// Magic data for optimising unsigned division by a constant.
2029struct APInt::mu {
2030 APInt m; ///< magic number
2031 bool a; ///< add indicator
2032 unsigned s; ///< shift amount
2033};
2034
2035inline bool operator==(uint64_t V1, const APInt &V2) { return V2 == V1; }
2036
2037inline bool operator!=(uint64_t V1, const APInt &V2) { return V2 != V1; }
2038
2039/// Unary bitwise complement operator.
2040///
2041/// \returns an APInt that is the bitwise complement of \p v.
2042inline APInt operator~(APInt v) {
2043 v.flipAllBits();
2044 return v;
2045}
2046
2047inline APInt operator&(APInt a, const APInt &b) {
2048 a &= b;
2049 return a;
2050}
2051
2052inline APInt operator&(const APInt &a, APInt &&b) {
2053 b &= a;
2054 return std::move(b);
2055}
2056
2057inline APInt operator&(APInt a, uint64_t RHS) {
2058 a &= RHS;
2059 return a;
2060}
2061
2062inline APInt operator&(uint64_t LHS, APInt b) {
2063 b &= LHS;
2064 return b;
2065}
2066
2067inline APInt operator|(APInt a, const APInt &b) {
2068 a |= b;
2069 return a;
2070}
2071
2072inline APInt operator|(const APInt &a, APInt &&b) {
2073 b |= a;
2074 return std::move(b);
2075}
2076
2077inline APInt operator|(APInt a, uint64_t RHS) {
2078 a |= RHS;
2079 return a;
2080}
2081
2082inline APInt operator|(uint64_t LHS, APInt b) {
2083 b |= LHS;
2084 return b;
2085}
2086
2087inline APInt operator^(APInt a, const APInt &b) {
2088 a ^= b;
2089 return a;
2090}
2091
2092inline APInt operator^(const APInt &a, APInt &&b) {
2093 b ^= a;
2094 return std::move(b);
2095}
2096
2097inline APInt operator^(APInt a, uint64_t RHS) {
2098 a ^= RHS;
2099 return a;
2100}
2101
2102inline APInt operator^(uint64_t LHS, APInt b) {
2103 b ^= LHS;
2104 return b;
2105}
2106
2107inline raw_ostream &operator<<(raw_ostream &OS, const APInt &I) {
2108 I.print(OS, true);
2109 return OS;
2110}
2111
2112inline APInt operator-(APInt v) {
2113 v.negate();
2114 return v;
2115}
2116
2117inline APInt operator+(APInt a, const APInt &b) {
2118 a += b;
2119 return a;
2120}
2121
2122inline APInt operator+(const APInt &a, APInt &&b) {
2123 b += a;
2124 return std::move(b);
2125}
2126
2127inline APInt operator+(APInt a, uint64_t RHS) {
2128 a += RHS;
2129 return a;
2130}
2131
2132inline APInt operator+(uint64_t LHS, APInt b) {
2133 b += LHS;
2134 return b;
2135}
2136
2137inline APInt operator-(APInt a, const APInt &b) {
2138 a -= b;
2139 return a;
2140}
2141
2142inline APInt operator-(const APInt &a, APInt &&b) {
2143 b.negate();
2144 b += a;
2145 return std::move(b);
2146}
2147
2148inline APInt operator-(APInt a, uint64_t RHS) {
2149 a -= RHS;
2150 return a;
2151}
2152
2153inline APInt operator-(uint64_t LHS, APInt b) {
2154 b.negate();
2155 b += LHS;
2156 return b;
2157}
2158
2159inline APInt operator*(APInt a, uint64_t RHS) {
2160 a *= RHS;
2161 return a;
2162}
2163
2164inline APInt operator*(uint64_t LHS, APInt b) {
2165 b *= LHS;
2166 return b;
2167}
2168
2169
2170namespace APIntOps {
2171
2172/// Determine the smaller of two APInts considered to be signed.
2173inline const APInt &smin(const APInt &A, const APInt &B) {
2174 return A.slt(B) ? A : B;
2175}
2176
2177/// Determine the larger of two APInts considered to be signed.
2178inline const APInt &smax(const APInt &A, const APInt &B) {
2179 return A.sgt(B) ? A : B;
2180}
2181
2182/// Determine the smaller of two APInts considered to be signed.
2183inline const APInt &umin(const APInt &A, const APInt &B) {
2184 return A.ult(B) ? A : B;
2185}
2186
2187/// Determine the larger of two APInts considered to be unsigned.
2188inline const APInt &umax(const APInt &A, const APInt &B) {
2189 return A.ugt(B) ? A : B;
2190}
2191
2192/// Compute GCD of two unsigned APInt values.
2193///
2194/// This function returns the greatest common divisor of the two APInt values
2195/// using Stein's algorithm.
2196///
2197/// \returns the greatest common divisor of A and B.
2198APInt GreatestCommonDivisor(APInt A, APInt B);
2199
2200/// Converts the given APInt to a double value.
2201///
2202/// Treats the APInt as an unsigned value for conversion purposes.
2203inline double RoundAPIntToDouble(const APInt &APIVal) {
2204 return APIVal.roundToDouble();
2205}
2206
2207/// Converts the given APInt to a double value.
2208///
2209/// Treats the APInt as a signed value for conversion purposes.
2210inline double RoundSignedAPIntToDouble(const APInt &APIVal) {
2211 return APIVal.signedRoundToDouble();
2212}
2213
2214/// Converts the given APInt to a float vlalue.
2215inline float RoundAPIntToFloat(const APInt &APIVal) {
2216 return float(RoundAPIntToDouble(APIVal));
2217}
2218
2219/// Converts the given APInt to a float value.
2220///
2221/// Treats the APInt as a signed value for conversion purposes.
2222inline float RoundSignedAPIntToFloat(const APInt &APIVal) {
2223 return float(APIVal.signedRoundToDouble());
2224}
2225
2226/// Converts the given double value into a APInt.
2227///
2228/// This function convert a double value to an APInt value.
2229APInt RoundDoubleToAPInt(double Double, unsigned width);
2230
2231/// Converts a float value into a APInt.
2232///
2233/// Converts a float value into an APInt value.
2234inline APInt RoundFloatToAPInt(float Float, unsigned width) {
2235 return RoundDoubleToAPInt(double(Float), width);
2236}
2237
2238/// Return A unsign-divided by B, rounded by the given rounding mode.
2239APInt RoundingUDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2240
2241/// Return A sign-divided by B, rounded by the given rounding mode.
2242APInt RoundingSDiv(const APInt &A, const APInt &B, APInt::Rounding RM);
2243
2244/// Let q(n) = An^2 + Bn + C, and BW = bit width of the value range
2245/// (e.g. 32 for i32).
2246/// This function finds the smallest number n, such that
2247/// (a) n >= 0 and q(n) = 0, or
2248/// (b) n >= 1 and q(n-1) and q(n), when evaluated in the set of all
2249/// integers, belong to two different intervals [Rk, Rk+R),
2250/// where R = 2^BW, and k is an integer.
2251/// The idea here is to find when q(n) "overflows" 2^BW, while at the
2252/// same time "allowing" subtraction. In unsigned modulo arithmetic a
2253/// subtraction (treated as addition of negated numbers) would always
2254/// count as an overflow, but here we want to allow values to decrease
2255/// and increase as long as they are within the same interval.
2256/// Specifically, adding of two negative numbers should not cause an
2257/// overflow (as long as the magnitude does not exceed the bit width).
2258/// On the other hand, given a positive number, adding a negative
2259/// number to it can give a negative result, which would cause the
2260/// value to go from [-2^BW, 0) to [0, 2^BW). In that sense, zero is
2261/// treated as a special case of an overflow.
2262///
2263/// This function returns None if after finding k that minimizes the
2264/// positive solution to q(n) = kR, both solutions are contained between
2265/// two consecutive integers.
2266///
2267/// There are cases where q(n) > T, and q(n+1) < T (assuming evaluation
2268/// in arithmetic modulo 2^BW, and treating the values as signed) by the
2269/// virtue of *signed* overflow. This function will *not* find such an n,
2270/// however it may find a value of n satisfying the inequalities due to
2271/// an *unsigned* overflow (if the values are treated as unsigned).
2272/// To find a solution for a signed overflow, treat it as a problem of
2273/// finding an unsigned overflow with a range with of BW-1.
2274///
2275/// The returned value may have a different bit width from the input
2276/// coefficients.
2277Optional<APInt> SolveQuadraticEquationWrap(APInt A, APInt B, APInt C,
2278 unsigned RangeWidth);
2279
2280/// Compare two values, and if they are different, return the position of the
2281/// most significant bit that is different in the values.
2282Optional<unsigned> GetMostSignificantDifferentBit(const APInt &A,
2283 const APInt &B);
2284
2285} // End of APIntOps namespace
2286
2287// See friend declaration above. This additional declaration is required in
2288// order to compile LLVM with IBM xlC compiler.
2289hash_code hash_value(const APInt &Arg);
2290
2291/// StoreIntToMemory - Fills the StoreBytes bytes of memory starting from Dst
2292/// with the integer held in IntVal.
2293void StoreIntToMemory(const APInt &IntVal, uint8_t *Dst, unsigned StoreBytes);
2294
2295/// LoadIntFromMemory - Loads the integer stored in the LoadBytes bytes starting
2296/// from Src into IntVal, which is assumed to be wide enough and to hold zero.
2297void LoadIntFromMemory(APInt &IntVal, const uint8_t *Src, unsigned LoadBytes);
2298
2299} // namespace llvm
2300
2301#endif