Bug Summary

File:lib/Analysis/LazyValueInfo.cpp
Warning:line 1388, column 34
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name LazyValueInfo.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn374814/build-llvm/lib/Analysis -I /build/llvm-toolchain-snapshot-10~svn374814/lib/Analysis -I /build/llvm-toolchain-snapshot-10~svn374814/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374814/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/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/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/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-10~svn374814/build-llvm/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374814=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-15-035155-28452-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374814/lib/Analysis/LazyValueInfo.cpp

/build/llvm-toolchain-snapshot-10~svn374814/lib/Analysis/LazyValueInfo.cpp

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

/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h

1//===- llvm/Instructions.h - Instruction 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// This file exposes the class definitions of all of the subclasses of the
10// Instruction class. This is meant to be an easy way to get access to all
11// instruction subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_INSTRUCTIONS_H
16#define LLVM_IR_INSTRUCTIONS_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/None.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringRef.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/ADT/iterator.h"
25#include "llvm/ADT/iterator_range.h"
26#include "llvm/IR/Attributes.h"
27#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/CallingConv.h"
29#include "llvm/IR/Constant.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/OperandTraits.h"
35#include "llvm/IR/Type.h"
36#include "llvm/IR/Use.h"
37#include "llvm/IR/User.h"
38#include "llvm/IR/Value.h"
39#include "llvm/Support/AtomicOrdering.h"
40#include "llvm/Support/Casting.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <cassert>
43#include <cstddef>
44#include <cstdint>
45#include <iterator>
46
47namespace llvm {
48
49class APInt;
50class ConstantInt;
51class DataLayout;
52class LLVMContext;
53
54//===----------------------------------------------------------------------===//
55// AllocaInst Class
56//===----------------------------------------------------------------------===//
57
58/// an instruction to allocate memory on the stack
59class AllocaInst : public UnaryInstruction {
60 Type *AllocatedType;
61
62protected:
63 // Note: Instruction needs to be a friend here to call cloneImpl.
64 friend class Instruction;
65
66 AllocaInst *cloneImpl() const;
67
68public:
69 explicit AllocaInst(Type *Ty, unsigned AddrSpace,
70 Value *ArraySize = nullptr,
71 const Twine &Name = "",
72 Instruction *InsertBefore = nullptr);
73 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
74 const Twine &Name, BasicBlock *InsertAtEnd);
75
76 AllocaInst(Type *Ty, unsigned AddrSpace,
77 const Twine &Name, Instruction *InsertBefore = nullptr);
78 AllocaInst(Type *Ty, unsigned AddrSpace,
79 const Twine &Name, BasicBlock *InsertAtEnd);
80
81 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
82 const Twine &Name = "", Instruction *InsertBefore = nullptr);
83 AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize, unsigned Align,
84 const Twine &Name, BasicBlock *InsertAtEnd);
85
86 /// Return true if there is an allocation size parameter to the allocation
87 /// instruction that is not 1.
88 bool isArrayAllocation() const;
89
90 /// Get the number of elements allocated. For a simple allocation of a single
91 /// element, this will return a constant 1 value.
92 const Value *getArraySize() const { return getOperand(0); }
93 Value *getArraySize() { return getOperand(0); }
94
95 /// Overload to return most specific pointer type.
96 PointerType *getType() const {
97 return cast<PointerType>(Instruction::getType());
98 }
99
100 /// Get allocation size in bits. Returns None if size can't be determined,
101 /// e.g. in case of a VLA.
102 Optional<uint64_t> getAllocationSizeInBits(const DataLayout &DL) const;
103
104 /// Return the type that is being allocated by the instruction.
105 Type *getAllocatedType() const { return AllocatedType; }
106 /// for use only in special circumstances that need to generically
107 /// transform a whole instruction (eg: IR linking and vectorization).
108 void setAllocatedType(Type *Ty) { AllocatedType = Ty; }
109
110 /// Return the alignment of the memory that is being allocated by the
111 /// instruction.
112 unsigned getAlignment() const {
113 if (const auto MA = decodeMaybeAlign(getSubclassDataFromInstruction() & 31))
114 return MA->value();
115 return 0;
116 }
117 void setAlignment(MaybeAlign Align);
118
119 /// Return true if this alloca is in the entry block of the function and is a
120 /// constant size. If so, the code generator will fold it into the
121 /// prolog/epilog code, so it is basically free.
122 bool isStaticAlloca() const;
123
124 /// Return true if this alloca is used as an inalloca argument to a call. Such
125 /// allocas are never considered static even if they are in the entry block.
126 bool isUsedWithInAlloca() const {
127 return getSubclassDataFromInstruction() & 32;
128 }
129
130 /// Specify whether this alloca is used to represent the arguments to a call.
131 void setUsedWithInAlloca(bool V) {
132 setInstructionSubclassData((getSubclassDataFromInstruction() & ~32) |
133 (V ? 32 : 0));
134 }
135
136 /// Return true if this alloca is used as a swifterror argument to a call.
137 bool isSwiftError() const {
138 return getSubclassDataFromInstruction() & 64;
139 }
140
141 /// Specify whether this alloca is used to represent a swifterror.
142 void setSwiftError(bool V) {
143 setInstructionSubclassData((getSubclassDataFromInstruction() & ~64) |
144 (V ? 64 : 0));
145 }
146
147 // Methods for support type inquiry through isa, cast, and dyn_cast:
148 static bool classof(const Instruction *I) {
149 return (I->getOpcode() == Instruction::Alloca);
150 }
151 static bool classof(const Value *V) {
152 return isa<Instruction>(V) && classof(cast<Instruction>(V));
153 }
154
155private:
156 // Shadow Instruction::setInstructionSubclassData with a private forwarding
157 // method so that subclasses cannot accidentally use it.
158 void setInstructionSubclassData(unsigned short D) {
159 Instruction::setInstructionSubclassData(D);
160 }
161};
162
163//===----------------------------------------------------------------------===//
164// LoadInst Class
165//===----------------------------------------------------------------------===//
166
167/// An instruction for reading from memory. This uses the SubclassData field in
168/// Value to store whether or not the load is volatile.
169class LoadInst : public UnaryInstruction {
170 void AssertOK();
171
172protected:
173 // Note: Instruction needs to be a friend here to call cloneImpl.
174 friend class Instruction;
175
176 LoadInst *cloneImpl() const;
177
178public:
179 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr = "",
180 Instruction *InsertBefore = nullptr);
181 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd);
182 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
183 Instruction *InsertBefore = nullptr);
184 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
185 BasicBlock *InsertAtEnd);
186 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
187 unsigned Align, Instruction *InsertBefore = nullptr);
188 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
189 unsigned Align, BasicBlock *InsertAtEnd);
190 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
191 unsigned Align, AtomicOrdering Order,
192 SyncScope::ID SSID = SyncScope::System,
193 Instruction *InsertBefore = nullptr);
194 LoadInst(Type *Ty, Value *Ptr, const Twine &NameStr, bool isVolatile,
195 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
196 BasicBlock *InsertAtEnd);
197
198 // Deprecated [opaque pointer types]
199 explicit LoadInst(Value *Ptr, const Twine &NameStr = "",
200 Instruction *InsertBefore = nullptr)
201 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
202 InsertBefore) {}
203 LoadInst(Value *Ptr, const Twine &NameStr, BasicBlock *InsertAtEnd)
204 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
205 InsertAtEnd) {}
206 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
207 Instruction *InsertBefore = nullptr)
208 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
209 isVolatile, InsertBefore) {}
210 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile,
211 BasicBlock *InsertAtEnd)
212 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
213 isVolatile, InsertAtEnd) {}
214 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
215 Instruction *InsertBefore = nullptr)
216 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
217 isVolatile, Align, InsertBefore) {}
218 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
219 BasicBlock *InsertAtEnd)
220 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
221 isVolatile, Align, InsertAtEnd) {}
222 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
223 AtomicOrdering Order, SyncScope::ID SSID = SyncScope::System,
224 Instruction *InsertBefore = nullptr)
225 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
226 isVolatile, Align, Order, SSID, InsertBefore) {}
227 LoadInst(Value *Ptr, const Twine &NameStr, bool isVolatile, unsigned Align,
228 AtomicOrdering Order, SyncScope::ID SSID, BasicBlock *InsertAtEnd)
229 : LoadInst(Ptr->getType()->getPointerElementType(), Ptr, NameStr,
230 isVolatile, Align, Order, SSID, InsertAtEnd) {}
231
232 /// Return true if this is a load from a volatile memory location.
233 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
234
235 /// Specify whether this is a volatile load or not.
236 void setVolatile(bool V) {
237 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
238 (V ? 1 : 0));
239 }
240
241 /// Return the alignment of the access that is being performed.
242 unsigned getAlignment() const {
243 if (const auto MA =
244 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
245 return MA->value();
246 return 0;
247 }
248
249 void setAlignment(MaybeAlign Align);
250
251 /// Returns the ordering constraint of this load instruction.
252 AtomicOrdering getOrdering() const {
253 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
254 }
255
256 /// Sets the ordering constraint of this load instruction. May not be Release
257 /// or AcquireRelease.
258 void setOrdering(AtomicOrdering Ordering) {
259 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
260 ((unsigned)Ordering << 7));
261 }
262
263 /// Returns the synchronization scope ID of this load instruction.
264 SyncScope::ID getSyncScopeID() const {
265 return SSID;
266 }
267
268 /// Sets the synchronization scope ID of this load instruction.
269 void setSyncScopeID(SyncScope::ID SSID) {
270 this->SSID = SSID;
271 }
272
273 /// Sets the ordering constraint and the synchronization scope ID of this load
274 /// instruction.
275 void setAtomic(AtomicOrdering Ordering,
276 SyncScope::ID SSID = SyncScope::System) {
277 setOrdering(Ordering);
278 setSyncScopeID(SSID);
279 }
280
281 bool isSimple() const { return !isAtomic() && !isVolatile(); }
282
283 bool isUnordered() const {
284 return (getOrdering() == AtomicOrdering::NotAtomic ||
285 getOrdering() == AtomicOrdering::Unordered) &&
286 !isVolatile();
287 }
288
289 Value *getPointerOperand() { return getOperand(0); }
290 const Value *getPointerOperand() const { return getOperand(0); }
291 static unsigned getPointerOperandIndex() { return 0U; }
292 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
293
294 /// Returns the address space of the pointer operand.
295 unsigned getPointerAddressSpace() const {
296 return getPointerOperandType()->getPointerAddressSpace();
297 }
298
299 // Methods for support type inquiry through isa, cast, and dyn_cast:
300 static bool classof(const Instruction *I) {
301 return I->getOpcode() == Instruction::Load;
302 }
303 static bool classof(const Value *V) {
304 return isa<Instruction>(V) && classof(cast<Instruction>(V));
305 }
306
307private:
308 // Shadow Instruction::setInstructionSubclassData with a private forwarding
309 // method so that subclasses cannot accidentally use it.
310 void setInstructionSubclassData(unsigned short D) {
311 Instruction::setInstructionSubclassData(D);
312 }
313
314 /// The synchronization scope ID of this load instruction. Not quite enough
315 /// room in SubClassData for everything, so synchronization scope ID gets its
316 /// own field.
317 SyncScope::ID SSID;
318};
319
320//===----------------------------------------------------------------------===//
321// StoreInst Class
322//===----------------------------------------------------------------------===//
323
324/// An instruction for storing to memory.
325class StoreInst : public Instruction {
326 void AssertOK();
327
328protected:
329 // Note: Instruction needs to be a friend here to call cloneImpl.
330 friend class Instruction;
331
332 StoreInst *cloneImpl() const;
333
334public:
335 StoreInst(Value *Val, Value *Ptr, Instruction *InsertBefore);
336 StoreInst(Value *Val, Value *Ptr, BasicBlock *InsertAtEnd);
337 StoreInst(Value *Val, Value *Ptr, bool isVolatile = false,
338 Instruction *InsertBefore = nullptr);
339 StoreInst(Value *Val, Value *Ptr, bool isVolatile, BasicBlock *InsertAtEnd);
340 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
341 unsigned Align, Instruction *InsertBefore = nullptr);
342 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
343 unsigned Align, BasicBlock *InsertAtEnd);
344 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
345 unsigned Align, AtomicOrdering Order,
346 SyncScope::ID SSID = SyncScope::System,
347 Instruction *InsertBefore = nullptr);
348 StoreInst(Value *Val, Value *Ptr, bool isVolatile,
349 unsigned Align, AtomicOrdering Order, SyncScope::ID SSID,
350 BasicBlock *InsertAtEnd);
351
352 // allocate space for exactly two operands
353 void *operator new(size_t s) {
354 return User::operator new(s, 2);
355 }
356
357 /// Return true if this is a store to a volatile memory location.
358 bool isVolatile() const { return getSubclassDataFromInstruction() & 1; }
359
360 /// Specify whether this is a volatile store or not.
361 void setVolatile(bool V) {
362 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
363 (V ? 1 : 0));
364 }
365
366 /// Transparently provide more efficient getOperand methods.
367 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
;
368
369 /// Return the alignment of the access that is being performed
370 unsigned getAlignment() const {
371 if (const auto MA =
372 decodeMaybeAlign((getSubclassDataFromInstruction() >> 1) & 31))
373 return MA->value();
374 return 0;
375 }
376
377 void setAlignment(MaybeAlign Align);
378
379 /// Returns the ordering constraint of this store instruction.
380 AtomicOrdering getOrdering() const {
381 return AtomicOrdering((getSubclassDataFromInstruction() >> 7) & 7);
382 }
383
384 /// Sets the ordering constraint of this store instruction. May not be
385 /// Acquire or AcquireRelease.
386 void setOrdering(AtomicOrdering Ordering) {
387 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 7)) |
388 ((unsigned)Ordering << 7));
389 }
390
391 /// Returns the synchronization scope ID of this store instruction.
392 SyncScope::ID getSyncScopeID() const {
393 return SSID;
394 }
395
396 /// Sets the synchronization scope ID of this store instruction.
397 void setSyncScopeID(SyncScope::ID SSID) {
398 this->SSID = SSID;
399 }
400
401 /// Sets the ordering constraint and the synchronization scope ID of this
402 /// store instruction.
403 void setAtomic(AtomicOrdering Ordering,
404 SyncScope::ID SSID = SyncScope::System) {
405 setOrdering(Ordering);
406 setSyncScopeID(SSID);
407 }
408
409 bool isSimple() const { return !isAtomic() && !isVolatile(); }
410
411 bool isUnordered() const {
412 return (getOrdering() == AtomicOrdering::NotAtomic ||
413 getOrdering() == AtomicOrdering::Unordered) &&
414 !isVolatile();
415 }
416
417 Value *getValueOperand() { return getOperand(0); }
418 const Value *getValueOperand() const { return getOperand(0); }
419
420 Value *getPointerOperand() { return getOperand(1); }
421 const Value *getPointerOperand() const { return getOperand(1); }
422 static unsigned getPointerOperandIndex() { return 1U; }
423 Type *getPointerOperandType() const { return getPointerOperand()->getType(); }
424
425 /// Returns the address space of the pointer operand.
426 unsigned getPointerAddressSpace() const {
427 return getPointerOperandType()->getPointerAddressSpace();
428 }
429
430 // Methods for support type inquiry through isa, cast, and dyn_cast:
431 static bool classof(const Instruction *I) {
432 return I->getOpcode() == Instruction::Store;
433 }
434 static bool classof(const Value *V) {
435 return isa<Instruction>(V) && classof(cast<Instruction>(V));
436 }
437
438private:
439 // Shadow Instruction::setInstructionSubclassData with a private forwarding
440 // method so that subclasses cannot accidentally use it.
441 void setInstructionSubclassData(unsigned short D) {
442 Instruction::setInstructionSubclassData(D);
443 }
444
445 /// The synchronization scope ID of this store instruction. Not quite enough
446 /// room in SubClassData for everything, so synchronization scope ID gets its
447 /// own field.
448 SyncScope::ID SSID;
449};
450
451template <>
452struct OperandTraits<StoreInst> : public FixedNumOperandTraits<StoreInst, 2> {
453};
454
455DEFINE_TRANSPARENT_OPERAND_ACCESSORS(StoreInst, Value)StoreInst::op_iterator StoreInst::op_begin() { return OperandTraits
<StoreInst>::op_begin(this); } StoreInst::const_op_iterator
StoreInst::op_begin() const { return OperandTraits<StoreInst
>::op_begin(const_cast<StoreInst*>(this)); } StoreInst
::op_iterator StoreInst::op_end() { return OperandTraits<StoreInst
>::op_end(this); } StoreInst::const_op_iterator StoreInst::
op_end() const { return OperandTraits<StoreInst>::op_end
(const_cast<StoreInst*>(this)); } Value *StoreInst::getOperand
(unsigned i_nocapture) const { ((i_nocapture < OperandTraits
<StoreInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 455, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<StoreInst>::op_begin(const_cast<StoreInst
*>(this))[i_nocapture].get()); } void StoreInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<StoreInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<StoreInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 455, __PRETTY_FUNCTION__)); OperandTraits<StoreInst>::
op_begin(this)[i_nocapture] = Val_nocapture; } unsigned StoreInst
::getNumOperands() const { return OperandTraits<StoreInst>
::operands(this); } template <int Idx_nocapture> Use &
StoreInst::Op() { return this->OpFrom<Idx_nocapture>
(this); } template <int Idx_nocapture> const Use &StoreInst
::Op() const { return this->OpFrom<Idx_nocapture>(this
); }
456
457//===----------------------------------------------------------------------===//
458// FenceInst Class
459//===----------------------------------------------------------------------===//
460
461/// An instruction for ordering other memory operations.
462class FenceInst : public Instruction {
463 void Init(AtomicOrdering Ordering, SyncScope::ID SSID);
464
465protected:
466 // Note: Instruction needs to be a friend here to call cloneImpl.
467 friend class Instruction;
468
469 FenceInst *cloneImpl() const;
470
471public:
472 // Ordering may only be Acquire, Release, AcquireRelease, or
473 // SequentiallyConsistent.
474 FenceInst(LLVMContext &C, AtomicOrdering Ordering,
475 SyncScope::ID SSID = SyncScope::System,
476 Instruction *InsertBefore = nullptr);
477 FenceInst(LLVMContext &C, AtomicOrdering Ordering, SyncScope::ID SSID,
478 BasicBlock *InsertAtEnd);
479
480 // allocate space for exactly zero operands
481 void *operator new(size_t s) {
482 return User::operator new(s, 0);
483 }
484
485 /// Returns the ordering constraint of this fence instruction.
486 AtomicOrdering getOrdering() const {
487 return AtomicOrdering(getSubclassDataFromInstruction() >> 1);
488 }
489
490 /// Sets the ordering constraint of this fence instruction. May only be
491 /// Acquire, Release, AcquireRelease, or SequentiallyConsistent.
492 void setOrdering(AtomicOrdering Ordering) {
493 setInstructionSubclassData((getSubclassDataFromInstruction() & 1) |
494 ((unsigned)Ordering << 1));
495 }
496
497 /// Returns the synchronization scope ID of this fence instruction.
498 SyncScope::ID getSyncScopeID() const {
499 return SSID;
500 }
501
502 /// Sets the synchronization scope ID of this fence instruction.
503 void setSyncScopeID(SyncScope::ID SSID) {
504 this->SSID = SSID;
505 }
506
507 // Methods for support type inquiry through isa, cast, and dyn_cast:
508 static bool classof(const Instruction *I) {
509 return I->getOpcode() == Instruction::Fence;
510 }
511 static bool classof(const Value *V) {
512 return isa<Instruction>(V) && classof(cast<Instruction>(V));
513 }
514
515private:
516 // Shadow Instruction::setInstructionSubclassData with a private forwarding
517 // method so that subclasses cannot accidentally use it.
518 void setInstructionSubclassData(unsigned short D) {
519 Instruction::setInstructionSubclassData(D);
520 }
521
522 /// The synchronization scope ID of this fence instruction. Not quite enough
523 /// room in SubClassData for everything, so synchronization scope ID gets its
524 /// own field.
525 SyncScope::ID SSID;
526};
527
528//===----------------------------------------------------------------------===//
529// AtomicCmpXchgInst Class
530//===----------------------------------------------------------------------===//
531
532/// An instruction that atomically checks whether a
533/// specified value is in a memory location, and, if it is, stores a new value
534/// there. The value returned by this instruction is a pair containing the
535/// original value as first element, and an i1 indicating success (true) or
536/// failure (false) as second element.
537///
538class AtomicCmpXchgInst : public Instruction {
539 void Init(Value *Ptr, Value *Cmp, Value *NewVal,
540 AtomicOrdering SuccessOrdering, AtomicOrdering FailureOrdering,
541 SyncScope::ID SSID);
542
543protected:
544 // Note: Instruction needs to be a friend here to call cloneImpl.
545 friend class Instruction;
546
547 AtomicCmpXchgInst *cloneImpl() const;
548
549public:
550 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
551 AtomicOrdering SuccessOrdering,
552 AtomicOrdering FailureOrdering,
553 SyncScope::ID SSID, Instruction *InsertBefore = nullptr);
554 AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
555 AtomicOrdering SuccessOrdering,
556 AtomicOrdering FailureOrdering,
557 SyncScope::ID SSID, BasicBlock *InsertAtEnd);
558
559 // allocate space for exactly three operands
560 void *operator new(size_t s) {
561 return User::operator new(s, 3);
562 }
563
564 /// Return true if this is a cmpxchg from a volatile memory
565 /// location.
566 ///
567 bool isVolatile() const {
568 return getSubclassDataFromInstruction() & 1;
569 }
570
571 /// Specify whether this is a volatile cmpxchg.
572 ///
573 void setVolatile(bool V) {
574 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
575 (unsigned)V);
576 }
577
578 /// Return true if this cmpxchg may spuriously fail.
579 bool isWeak() const {
580 return getSubclassDataFromInstruction() & 0x100;
581 }
582
583 void setWeak(bool IsWeak) {
584 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x100) |
585 (IsWeak << 8));
586 }
587
588 /// Transparently provide more efficient getOperand methods.
589 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
;
590
591 /// Returns the success ordering constraint of this cmpxchg instruction.
592 AtomicOrdering getSuccessOrdering() const {
593 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
594 }
595
596 /// Sets the success ordering constraint of this cmpxchg instruction.
597 void setSuccessOrdering(AtomicOrdering Ordering) {
598 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 599, __PRETTY_FUNCTION__))
599 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 599, __PRETTY_FUNCTION__))
;
600 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0x1c) |
601 ((unsigned)Ordering << 2));
602 }
603
604 /// Returns the failure ordering constraint of this cmpxchg instruction.
605 AtomicOrdering getFailureOrdering() const {
606 return AtomicOrdering((getSubclassDataFromInstruction() >> 5) & 7);
607 }
608
609 /// Sets the failure ordering constraint of this cmpxchg instruction.
610 void setFailureOrdering(AtomicOrdering Ordering) {
611 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 612, __PRETTY_FUNCTION__))
612 "CmpXchg instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "CmpXchg instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"CmpXchg instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 612, __PRETTY_FUNCTION__))
;
613 setInstructionSubclassData((getSubclassDataFromInstruction() & ~0xe0) |
614 ((unsigned)Ordering << 5));
615 }
616
617 /// Returns the synchronization scope ID of this cmpxchg instruction.
618 SyncScope::ID getSyncScopeID() const {
619 return SSID;
620 }
621
622 /// Sets the synchronization scope ID of this cmpxchg instruction.
623 void setSyncScopeID(SyncScope::ID SSID) {
624 this->SSID = SSID;
625 }
626
627 Value *getPointerOperand() { return getOperand(0); }
628 const Value *getPointerOperand() const { return getOperand(0); }
629 static unsigned getPointerOperandIndex() { return 0U; }
630
631 Value *getCompareOperand() { return getOperand(1); }
632 const Value *getCompareOperand() const { return getOperand(1); }
633
634 Value *getNewValOperand() { return getOperand(2); }
635 const Value *getNewValOperand() const { return getOperand(2); }
636
637 /// Returns the address space of the pointer operand.
638 unsigned getPointerAddressSpace() const {
639 return getPointerOperand()->getType()->getPointerAddressSpace();
640 }
641
642 /// Returns the strongest permitted ordering on failure, given the
643 /// desired ordering on success.
644 ///
645 /// If the comparison in a cmpxchg operation fails, there is no atomic store
646 /// so release semantics cannot be provided. So this function drops explicit
647 /// Release requests from the AtomicOrdering. A SequentiallyConsistent
648 /// operation would remain SequentiallyConsistent.
649 static AtomicOrdering
650 getStrongestFailureOrdering(AtomicOrdering SuccessOrdering) {
651 switch (SuccessOrdering) {
652 default:
653 llvm_unreachable("invalid cmpxchg success ordering")::llvm::llvm_unreachable_internal("invalid cmpxchg success ordering"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 653)
;
654 case AtomicOrdering::Release:
655 case AtomicOrdering::Monotonic:
656 return AtomicOrdering::Monotonic;
657 case AtomicOrdering::AcquireRelease:
658 case AtomicOrdering::Acquire:
659 return AtomicOrdering::Acquire;
660 case AtomicOrdering::SequentiallyConsistent:
661 return AtomicOrdering::SequentiallyConsistent;
662 }
663 }
664
665 // Methods for support type inquiry through isa, cast, and dyn_cast:
666 static bool classof(const Instruction *I) {
667 return I->getOpcode() == Instruction::AtomicCmpXchg;
668 }
669 static bool classof(const Value *V) {
670 return isa<Instruction>(V) && classof(cast<Instruction>(V));
671 }
672
673private:
674 // Shadow Instruction::setInstructionSubclassData with a private forwarding
675 // method so that subclasses cannot accidentally use it.
676 void setInstructionSubclassData(unsigned short D) {
677 Instruction::setInstructionSubclassData(D);
678 }
679
680 /// The synchronization scope ID of this cmpxchg instruction. Not quite
681 /// enough room in SubClassData for everything, so synchronization scope ID
682 /// gets its own field.
683 SyncScope::ID SSID;
684};
685
686template <>
687struct OperandTraits<AtomicCmpXchgInst> :
688 public FixedNumOperandTraits<AtomicCmpXchgInst, 3> {
689};
690
691DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicCmpXchgInst, Value)AtomicCmpXchgInst::op_iterator AtomicCmpXchgInst::op_begin() {
return OperandTraits<AtomicCmpXchgInst>::op_begin(this
); } AtomicCmpXchgInst::const_op_iterator AtomicCmpXchgInst::
op_begin() const { return OperandTraits<AtomicCmpXchgInst>
::op_begin(const_cast<AtomicCmpXchgInst*>(this)); } AtomicCmpXchgInst
::op_iterator AtomicCmpXchgInst::op_end() { return OperandTraits
<AtomicCmpXchgInst>::op_end(this); } AtomicCmpXchgInst::
const_op_iterator AtomicCmpXchgInst::op_end() const { return OperandTraits
<AtomicCmpXchgInst>::op_end(const_cast<AtomicCmpXchgInst
*>(this)); } Value *AtomicCmpXchgInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<AtomicCmpXchgInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 691, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<AtomicCmpXchgInst>::op_begin(const_cast
<AtomicCmpXchgInst*>(this))[i_nocapture].get()); } void
AtomicCmpXchgInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<AtomicCmpXchgInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicCmpXchgInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 691, __PRETTY_FUNCTION__)); OperandTraits<AtomicCmpXchgInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
AtomicCmpXchgInst::getNumOperands() const { return OperandTraits
<AtomicCmpXchgInst>::operands(this); } template <int
Idx_nocapture> Use &AtomicCmpXchgInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &AtomicCmpXchgInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
692
693//===----------------------------------------------------------------------===//
694// AtomicRMWInst Class
695//===----------------------------------------------------------------------===//
696
697/// an instruction that atomically reads a memory location,
698/// combines it with another value, and then stores the result back. Returns
699/// the old value.
700///
701class AtomicRMWInst : public Instruction {
702protected:
703 // Note: Instruction needs to be a friend here to call cloneImpl.
704 friend class Instruction;
705
706 AtomicRMWInst *cloneImpl() const;
707
708public:
709 /// This enumeration lists the possible modifications atomicrmw can make. In
710 /// the descriptions, 'p' is the pointer to the instruction's memory location,
711 /// 'old' is the initial value of *p, and 'v' is the other value passed to the
712 /// instruction. These instructions always return 'old'.
713 enum BinOp {
714 /// *p = v
715 Xchg,
716 /// *p = old + v
717 Add,
718 /// *p = old - v
719 Sub,
720 /// *p = old & v
721 And,
722 /// *p = ~(old & v)
723 Nand,
724 /// *p = old | v
725 Or,
726 /// *p = old ^ v
727 Xor,
728 /// *p = old >signed v ? old : v
729 Max,
730 /// *p = old <signed v ? old : v
731 Min,
732 /// *p = old >unsigned v ? old : v
733 UMax,
734 /// *p = old <unsigned v ? old : v
735 UMin,
736
737 /// *p = old + v
738 FAdd,
739
740 /// *p = old - v
741 FSub,
742
743 FIRST_BINOP = Xchg,
744 LAST_BINOP = FSub,
745 BAD_BINOP
746 };
747
748 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
749 AtomicOrdering Ordering, SyncScope::ID SSID,
750 Instruction *InsertBefore = nullptr);
751 AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
752 AtomicOrdering Ordering, SyncScope::ID SSID,
753 BasicBlock *InsertAtEnd);
754
755 // allocate space for exactly two operands
756 void *operator new(size_t s) {
757 return User::operator new(s, 2);
758 }
759
760 BinOp getOperation() const {
761 return static_cast<BinOp>(getSubclassDataFromInstruction() >> 5);
762 }
763
764 static StringRef getOperationName(BinOp Op);
765
766 static bool isFPOperation(BinOp Op) {
767 switch (Op) {
768 case AtomicRMWInst::FAdd:
769 case AtomicRMWInst::FSub:
770 return true;
771 default:
772 return false;
773 }
774 }
775
776 void setOperation(BinOp Operation) {
777 unsigned short SubclassData = getSubclassDataFromInstruction();
778 setInstructionSubclassData((SubclassData & 31) |
779 (Operation << 5));
780 }
781
782 /// Return true if this is a RMW on a volatile memory location.
783 ///
784 bool isVolatile() const {
785 return getSubclassDataFromInstruction() & 1;
786 }
787
788 /// Specify whether this is a volatile RMW or not.
789 ///
790 void setVolatile(bool V) {
791 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
792 (unsigned)V);
793 }
794
795 /// Transparently provide more efficient getOperand methods.
796 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
;
797
798 /// Returns the ordering constraint of this rmw instruction.
799 AtomicOrdering getOrdering() const {
800 return AtomicOrdering((getSubclassDataFromInstruction() >> 2) & 7);
801 }
802
803 /// Sets the ordering constraint of this rmw instruction.
804 void setOrdering(AtomicOrdering Ordering) {
805 assert(Ordering != AtomicOrdering::NotAtomic &&((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 806, __PRETTY_FUNCTION__))
806 "atomicrmw instructions can only be atomic.")((Ordering != AtomicOrdering::NotAtomic && "atomicrmw instructions can only be atomic."
) ? static_cast<void> (0) : __assert_fail ("Ordering != AtomicOrdering::NotAtomic && \"atomicrmw instructions can only be atomic.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 806, __PRETTY_FUNCTION__))
;
807 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(7 << 2)) |
808 ((unsigned)Ordering << 2));
809 }
810
811 /// Returns the synchronization scope ID of this rmw instruction.
812 SyncScope::ID getSyncScopeID() const {
813 return SSID;
814 }
815
816 /// Sets the synchronization scope ID of this rmw instruction.
817 void setSyncScopeID(SyncScope::ID SSID) {
818 this->SSID = SSID;
819 }
820
821 Value *getPointerOperand() { return getOperand(0); }
822 const Value *getPointerOperand() const { return getOperand(0); }
823 static unsigned getPointerOperandIndex() { return 0U; }
824
825 Value *getValOperand() { return getOperand(1); }
826 const Value *getValOperand() const { return getOperand(1); }
827
828 /// Returns the address space of the pointer operand.
829 unsigned getPointerAddressSpace() const {
830 return getPointerOperand()->getType()->getPointerAddressSpace();
831 }
832
833 bool isFloatingPointOperation() const {
834 return isFPOperation(getOperation());
835 }
836
837 // Methods for support type inquiry through isa, cast, and dyn_cast:
838 static bool classof(const Instruction *I) {
839 return I->getOpcode() == Instruction::AtomicRMW;
840 }
841 static bool classof(const Value *V) {
842 return isa<Instruction>(V) && classof(cast<Instruction>(V));
843 }
844
845private:
846 void Init(BinOp Operation, Value *Ptr, Value *Val,
847 AtomicOrdering Ordering, SyncScope::ID SSID);
848
849 // Shadow Instruction::setInstructionSubclassData with a private forwarding
850 // method so that subclasses cannot accidentally use it.
851 void setInstructionSubclassData(unsigned short D) {
852 Instruction::setInstructionSubclassData(D);
853 }
854
855 /// The synchronization scope ID of this rmw instruction. Not quite enough
856 /// room in SubClassData for everything, so synchronization scope ID gets its
857 /// own field.
858 SyncScope::ID SSID;
859};
860
861template <>
862struct OperandTraits<AtomicRMWInst>
863 : public FixedNumOperandTraits<AtomicRMWInst,2> {
864};
865
866DEFINE_TRANSPARENT_OPERAND_ACCESSORS(AtomicRMWInst, Value)AtomicRMWInst::op_iterator AtomicRMWInst::op_begin() { return
OperandTraits<AtomicRMWInst>::op_begin(this); } AtomicRMWInst
::const_op_iterator AtomicRMWInst::op_begin() const { return OperandTraits
<AtomicRMWInst>::op_begin(const_cast<AtomicRMWInst*>
(this)); } AtomicRMWInst::op_iterator AtomicRMWInst::op_end()
{ return OperandTraits<AtomicRMWInst>::op_end(this); }
AtomicRMWInst::const_op_iterator AtomicRMWInst::op_end() const
{ return OperandTraits<AtomicRMWInst>::op_end(const_cast
<AtomicRMWInst*>(this)); } Value *AtomicRMWInst::getOperand
(unsigned i_nocapture) const { ((i_nocapture < OperandTraits
<AtomicRMWInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 866, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<AtomicRMWInst>::op_begin(const_cast<
AtomicRMWInst*>(this))[i_nocapture].get()); } void AtomicRMWInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<AtomicRMWInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<AtomicRMWInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 866, __PRETTY_FUNCTION__)); OperandTraits<AtomicRMWInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned AtomicRMWInst
::getNumOperands() const { return OperandTraits<AtomicRMWInst
>::operands(this); } template <int Idx_nocapture> Use
&AtomicRMWInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
AtomicRMWInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
867
868//===----------------------------------------------------------------------===//
869// GetElementPtrInst Class
870//===----------------------------------------------------------------------===//
871
872// checkGEPType - Simple wrapper function to give a better assertion failure
873// message on bad indexes for a gep instruction.
874//
875inline Type *checkGEPType(Type *Ty) {
876 assert(Ty && "Invalid GetElementPtrInst indices for type!")((Ty && "Invalid GetElementPtrInst indices for type!"
) ? static_cast<void> (0) : __assert_fail ("Ty && \"Invalid GetElementPtrInst indices for type!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 876, __PRETTY_FUNCTION__))
;
877 return Ty;
878}
879
880/// an instruction for type-safe pointer arithmetic to
881/// access elements of arrays and structs
882///
883class GetElementPtrInst : public Instruction {
884 Type *SourceElementType;
885 Type *ResultElementType;
886
887 GetElementPtrInst(const GetElementPtrInst &GEPI);
888
889 /// Constructors - Create a getelementptr instruction with a base pointer an
890 /// list of indices. The first ctor can optionally insert before an existing
891 /// instruction, the second appends the new instruction to the specified
892 /// BasicBlock.
893 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
894 ArrayRef<Value *> IdxList, unsigned Values,
895 const Twine &NameStr, Instruction *InsertBefore);
896 inline GetElementPtrInst(Type *PointeeType, Value *Ptr,
897 ArrayRef<Value *> IdxList, unsigned Values,
898 const Twine &NameStr, BasicBlock *InsertAtEnd);
899
900 void init(Value *Ptr, ArrayRef<Value *> IdxList, const Twine &NameStr);
901
902protected:
903 // Note: Instruction needs to be a friend here to call cloneImpl.
904 friend class Instruction;
905
906 GetElementPtrInst *cloneImpl() const;
907
908public:
909 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
910 ArrayRef<Value *> IdxList,
911 const Twine &NameStr = "",
912 Instruction *InsertBefore = nullptr) {
913 unsigned Values = 1 + unsigned(IdxList.size());
914 if (!PointeeType)
915 PointeeType =
916 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
917 else
918 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 920, __PRETTY_FUNCTION__))
919 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 920, __PRETTY_FUNCTION__))
920 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 920, __PRETTY_FUNCTION__))
;
921 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
922 NameStr, InsertBefore);
923 }
924
925 static GetElementPtrInst *Create(Type *PointeeType, Value *Ptr,
926 ArrayRef<Value *> IdxList,
927 const Twine &NameStr,
928 BasicBlock *InsertAtEnd) {
929 unsigned Values = 1 + unsigned(IdxList.size());
930 if (!PointeeType)
931 PointeeType =
932 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType();
933 else
934 assert(((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 936, __PRETTY_FUNCTION__))
935 PointeeType ==((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 936, __PRETTY_FUNCTION__))
936 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType())((PointeeType == cast<PointerType>(Ptr->getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("PointeeType == cast<PointerType>(Ptr->getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 936, __PRETTY_FUNCTION__))
;
937 return new (Values) GetElementPtrInst(PointeeType, Ptr, IdxList, Values,
938 NameStr, InsertAtEnd);
939 }
940
941 /// Create an "inbounds" getelementptr. See the documentation for the
942 /// "inbounds" flag in LangRef.html for details.
943 static GetElementPtrInst *CreateInBounds(Value *Ptr,
944 ArrayRef<Value *> IdxList,
945 const Twine &NameStr = "",
946 Instruction *InsertBefore = nullptr){
947 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertBefore);
948 }
949
950 static GetElementPtrInst *
951 CreateInBounds(Type *PointeeType, Value *Ptr, ArrayRef<Value *> IdxList,
952 const Twine &NameStr = "",
953 Instruction *InsertBefore = nullptr) {
954 GetElementPtrInst *GEP =
955 Create(PointeeType, Ptr, IdxList, NameStr, InsertBefore);
956 GEP->setIsInBounds(true);
957 return GEP;
958 }
959
960 static GetElementPtrInst *CreateInBounds(Value *Ptr,
961 ArrayRef<Value *> IdxList,
962 const Twine &NameStr,
963 BasicBlock *InsertAtEnd) {
964 return CreateInBounds(nullptr, Ptr, IdxList, NameStr, InsertAtEnd);
965 }
966
967 static GetElementPtrInst *CreateInBounds(Type *PointeeType, Value *Ptr,
968 ArrayRef<Value *> IdxList,
969 const Twine &NameStr,
970 BasicBlock *InsertAtEnd) {
971 GetElementPtrInst *GEP =
972 Create(PointeeType, Ptr, IdxList, NameStr, InsertAtEnd);
973 GEP->setIsInBounds(true);
974 return GEP;
975 }
976
977 /// Transparently provide more efficient getOperand methods.
978 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
;
979
980 Type *getSourceElementType() const { return SourceElementType; }
981
982 void setSourceElementType(Type *Ty) { SourceElementType = Ty; }
983 void setResultElementType(Type *Ty) { ResultElementType = Ty; }
984
985 Type *getResultElementType() const {
986 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 987, __PRETTY_FUNCTION__))
987 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 987, __PRETTY_FUNCTION__))
;
988 return ResultElementType;
989 }
990
991 /// Returns the address space of this instruction's pointer type.
992 unsigned getAddressSpace() const {
993 // Note that this is always the same as the pointer operand's address space
994 // and that is cheaper to compute, so cheat here.
995 return getPointerAddressSpace();
996 }
997
998 /// Returns the type of the element that would be loaded with
999 /// a load instruction with the specified parameters.
1000 ///
1001 /// Null is returned if the indices are invalid for the specified
1002 /// pointer type.
1003 ///
1004 static Type *getIndexedType(Type *Ty, ArrayRef<Value *> IdxList);
1005 static Type *getIndexedType(Type *Ty, ArrayRef<Constant *> IdxList);
1006 static Type *getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList);
1007
1008 inline op_iterator idx_begin() { return op_begin()+1; }
1009 inline const_op_iterator idx_begin() const { return op_begin()+1; }
1010 inline op_iterator idx_end() { return op_end(); }
1011 inline const_op_iterator idx_end() const { return op_end(); }
1012
1013 inline iterator_range<op_iterator> indices() {
1014 return make_range(idx_begin(), idx_end());
1015 }
1016
1017 inline iterator_range<const_op_iterator> indices() const {
1018 return make_range(idx_begin(), idx_end());
1019 }
1020
1021 Value *getPointerOperand() {
1022 return getOperand(0);
1023 }
1024 const Value *getPointerOperand() const {
1025 return getOperand(0);
1026 }
1027 static unsigned getPointerOperandIndex() {
1028 return 0U; // get index for modifying correct operand.
1029 }
1030
1031 /// Method to return the pointer operand as a
1032 /// PointerType.
1033 Type *getPointerOperandType() const {
1034 return getPointerOperand()->getType();
1035 }
1036
1037 /// Returns the address space of the pointer operand.
1038 unsigned getPointerAddressSpace() const {
1039 return getPointerOperandType()->getPointerAddressSpace();
1040 }
1041
1042 /// Returns the pointer type returned by the GEP
1043 /// instruction, which may be a vector of pointers.
1044 static Type *getGEPReturnType(Value *Ptr, ArrayRef<Value *> IdxList) {
1045 return getGEPReturnType(
1046 cast<PointerType>(Ptr->getType()->getScalarType())->getElementType(),
1047 Ptr, IdxList);
1048 }
1049 static Type *getGEPReturnType(Type *ElTy, Value *Ptr,
1050 ArrayRef<Value *> IdxList) {
1051 Type *PtrTy = PointerType::get(checkGEPType(getIndexedType(ElTy, IdxList)),
1052 Ptr->getType()->getPointerAddressSpace());
1053 // Vector GEP
1054 if (Ptr->getType()->isVectorTy()) {
1055 unsigned NumElem = Ptr->getType()->getVectorNumElements();
1056 return VectorType::get(PtrTy, NumElem);
1057 }
1058 for (Value *Index : IdxList)
1059 if (Index->getType()->isVectorTy()) {
1060 unsigned NumElem = Index->getType()->getVectorNumElements();
1061 return VectorType::get(PtrTy, NumElem);
1062 }
1063 // Scalar GEP
1064 return PtrTy;
1065 }
1066
1067 unsigned getNumIndices() const { // Note: always non-negative
1068 return getNumOperands() - 1;
1069 }
1070
1071 bool hasIndices() const {
1072 return getNumOperands() > 1;
1073 }
1074
1075 /// Return true if all of the indices of this GEP are
1076 /// zeros. If so, the result pointer and the first operand have the same
1077 /// value, just potentially different types.
1078 bool hasAllZeroIndices() const;
1079
1080 /// Return true if all of the indices of this GEP are
1081 /// constant integers. If so, the result pointer and the first operand have
1082 /// a constant offset between them.
1083 bool hasAllConstantIndices() const;
1084
1085 /// Set or clear the inbounds flag on this GEP instruction.
1086 /// See LangRef.html for the meaning of inbounds on a getelementptr.
1087 void setIsInBounds(bool b = true);
1088
1089 /// Determine whether the GEP has the inbounds flag.
1090 bool isInBounds() const;
1091
1092 /// Accumulate the constant address offset of this GEP if possible.
1093 ///
1094 /// This routine accepts an APInt into which it will accumulate the constant
1095 /// offset of this GEP if the GEP is in fact constant. If the GEP is not
1096 /// all-constant, it returns false and the value of the offset APInt is
1097 /// undefined (it is *not* preserved!). The APInt passed into this routine
1098 /// must be at least as wide as the IntPtr type for the address space of
1099 /// the base GEP pointer.
1100 bool accumulateConstantOffset(const DataLayout &DL, APInt &Offset) const;
1101
1102 // Methods for support type inquiry through isa, cast, and dyn_cast:
1103 static bool classof(const Instruction *I) {
1104 return (I->getOpcode() == Instruction::GetElementPtr);
1105 }
1106 static bool classof(const Value *V) {
1107 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1108 }
1109};
1110
1111template <>
1112struct OperandTraits<GetElementPtrInst> :
1113 public VariadicOperandTraits<GetElementPtrInst, 1> {
1114};
1115
1116GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1117 ArrayRef<Value *> IdxList, unsigned Values,
1118 const Twine &NameStr,
1119 Instruction *InsertBefore)
1120 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1121 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1122 Values, InsertBefore),
1123 SourceElementType(PointeeType),
1124 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1125 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1126, __PRETTY_FUNCTION__))
1126 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1126, __PRETTY_FUNCTION__))
;
1127 init(Ptr, IdxList, NameStr);
1128}
1129
1130GetElementPtrInst::GetElementPtrInst(Type *PointeeType, Value *Ptr,
1131 ArrayRef<Value *> IdxList, unsigned Values,
1132 const Twine &NameStr,
1133 BasicBlock *InsertAtEnd)
1134 : Instruction(getGEPReturnType(PointeeType, Ptr, IdxList), GetElementPtr,
1135 OperandTraits<GetElementPtrInst>::op_end(this) - Values,
1136 Values, InsertAtEnd),
1137 SourceElementType(PointeeType),
1138 ResultElementType(getIndexedType(PointeeType, IdxList)) {
1139 assert(ResultElementType ==((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1140, __PRETTY_FUNCTION__))
1140 cast<PointerType>(getType()->getScalarType())->getElementType())((ResultElementType == cast<PointerType>(getType()->
getScalarType())->getElementType()) ? static_cast<void>
(0) : __assert_fail ("ResultElementType == cast<PointerType>(getType()->getScalarType())->getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1140, __PRETTY_FUNCTION__))
;
1141 init(Ptr, IdxList, NameStr);
1142}
1143
1144DEFINE_TRANSPARENT_OPERAND_ACCESSORS(GetElementPtrInst, Value)GetElementPtrInst::op_iterator GetElementPtrInst::op_begin() {
return OperandTraits<GetElementPtrInst>::op_begin(this
); } GetElementPtrInst::const_op_iterator GetElementPtrInst::
op_begin() const { return OperandTraits<GetElementPtrInst>
::op_begin(const_cast<GetElementPtrInst*>(this)); } GetElementPtrInst
::op_iterator GetElementPtrInst::op_end() { return OperandTraits
<GetElementPtrInst>::op_end(this); } GetElementPtrInst::
const_op_iterator GetElementPtrInst::op_end() const { return OperandTraits
<GetElementPtrInst>::op_end(const_cast<GetElementPtrInst
*>(this)); } Value *GetElementPtrInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<GetElementPtrInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1144, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<GetElementPtrInst>::op_begin(const_cast
<GetElementPtrInst*>(this))[i_nocapture].get()); } void
GetElementPtrInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<GetElementPtrInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<GetElementPtrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1144, __PRETTY_FUNCTION__)); OperandTraits<GetElementPtrInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
GetElementPtrInst::getNumOperands() const { return OperandTraits
<GetElementPtrInst>::operands(this); } template <int
Idx_nocapture> Use &GetElementPtrInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &GetElementPtrInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
1145
1146//===----------------------------------------------------------------------===//
1147// ICmpInst Class
1148//===----------------------------------------------------------------------===//
1149
1150/// This instruction compares its operands according to the predicate given
1151/// to the constructor. It only operates on integers or pointers. The operands
1152/// must be identical types.
1153/// Represent an integer comparison operator.
1154class ICmpInst: public CmpInst {
1155 void AssertOK() {
1156 assert(isIntPredicate() &&((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1157, __PRETTY_FUNCTION__))
1157 "Invalid ICmp predicate value")((isIntPredicate() && "Invalid ICmp predicate value")
? static_cast<void> (0) : __assert_fail ("isIntPredicate() && \"Invalid ICmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1157, __PRETTY_FUNCTION__))
;
1158 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1159, __PRETTY_FUNCTION__))
1159 "Both operands to ICmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to ICmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to ICmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1159, __PRETTY_FUNCTION__))
;
1160 // Check that the operands are the right type
1161 assert((getOperand(0)->getType()->isIntOrIntVectorTy() ||(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1163, __PRETTY_FUNCTION__))
1162 getOperand(0)->getType()->isPtrOrPtrVectorTy()) &&(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1163, __PRETTY_FUNCTION__))
1163 "Invalid operand types for ICmp instruction")(((getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand
(0)->getType()->isPtrOrPtrVectorTy()) && "Invalid operand types for ICmp instruction"
) ? static_cast<void> (0) : __assert_fail ("(getOperand(0)->getType()->isIntOrIntVectorTy() || getOperand(0)->getType()->isPtrOrPtrVectorTy()) && \"Invalid operand types for ICmp instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1163, __PRETTY_FUNCTION__))
;
1164 }
1165
1166protected:
1167 // Note: Instruction needs to be a friend here to call cloneImpl.
1168 friend class Instruction;
1169
1170 /// Clone an identical ICmpInst
1171 ICmpInst *cloneImpl() const;
1172
1173public:
1174 /// Constructor with insert-before-instruction semantics.
1175 ICmpInst(
1176 Instruction *InsertBefore, ///< Where to insert
1177 Predicate pred, ///< The predicate to use for the comparison
1178 Value *LHS, ///< The left-hand-side of the expression
1179 Value *RHS, ///< The right-hand-side of the expression
1180 const Twine &NameStr = "" ///< Name of the instruction
1181 ) : CmpInst(makeCmpResultType(LHS->getType()),
1182 Instruction::ICmp, pred, LHS, RHS, NameStr,
1183 InsertBefore) {
1184#ifndef NDEBUG
1185 AssertOK();
1186#endif
1187 }
1188
1189 /// Constructor with insert-at-end semantics.
1190 ICmpInst(
1191 BasicBlock &InsertAtEnd, ///< Block to insert into.
1192 Predicate pred, ///< The predicate to use for the comparison
1193 Value *LHS, ///< The left-hand-side of the expression
1194 Value *RHS, ///< The right-hand-side of the expression
1195 const Twine &NameStr = "" ///< Name of the instruction
1196 ) : CmpInst(makeCmpResultType(LHS->getType()),
1197 Instruction::ICmp, pred, LHS, RHS, NameStr,
1198 &InsertAtEnd) {
1199#ifndef NDEBUG
1200 AssertOK();
1201#endif
1202 }
1203
1204 /// Constructor with no-insertion semantics
1205 ICmpInst(
1206 Predicate pred, ///< The predicate to use for the comparison
1207 Value *LHS, ///< The left-hand-side of the expression
1208 Value *RHS, ///< The right-hand-side of the expression
1209 const Twine &NameStr = "" ///< Name of the instruction
1210 ) : CmpInst(makeCmpResultType(LHS->getType()),
1211 Instruction::ICmp, pred, LHS, RHS, NameStr) {
1212#ifndef NDEBUG
1213 AssertOK();
1214#endif
1215 }
1216
1217 /// For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
1218 /// @returns the predicate that would be the result if the operand were
1219 /// regarded as signed.
1220 /// Return the signed version of the predicate
1221 Predicate getSignedPredicate() const {
1222 return getSignedPredicate(getPredicate());
1223 }
1224
1225 /// This is a static version that you can use without an instruction.
1226 /// Return the signed version of the predicate.
1227 static Predicate getSignedPredicate(Predicate pred);
1228
1229 /// For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
1230 /// @returns the predicate that would be the result if the operand were
1231 /// regarded as unsigned.
1232 /// Return the unsigned version of the predicate
1233 Predicate getUnsignedPredicate() const {
1234 return getUnsignedPredicate(getPredicate());
1235 }
1236
1237 /// This is a static version that you can use without an instruction.
1238 /// Return the unsigned version of the predicate.
1239 static Predicate getUnsignedPredicate(Predicate pred);
1240
1241 /// Return true if this predicate is either EQ or NE. This also
1242 /// tests for commutativity.
1243 static bool isEquality(Predicate P) {
1244 return P == ICMP_EQ || P == ICMP_NE;
1245 }
1246
1247 /// Return true if this predicate is either EQ or NE. This also
1248 /// tests for commutativity.
1249 bool isEquality() const {
1250 return isEquality(getPredicate());
1251 }
1252
1253 /// @returns true if the predicate of this ICmpInst is commutative
1254 /// Determine if this relation is commutative.
1255 bool isCommutative() const { return isEquality(); }
1256
1257 /// Return true if the predicate is relational (not EQ or NE).
1258 ///
1259 bool isRelational() const {
1260 return !isEquality();
1261 }
1262
1263 /// Return true if the predicate is relational (not EQ or NE).
1264 ///
1265 static bool isRelational(Predicate P) {
1266 return !isEquality(P);
1267 }
1268
1269 /// Exchange the two operands to this instruction in such a way that it does
1270 /// not modify the semantics of the instruction. The predicate value may be
1271 /// changed to retain the same result if the predicate is order dependent
1272 /// (e.g. ult).
1273 /// Swap operands and adjust predicate.
1274 void swapOperands() {
1275 setPredicate(getSwappedPredicate());
1276 Op<0>().swap(Op<1>());
1277 }
1278
1279 // Methods for support type inquiry through isa, cast, and dyn_cast:
1280 static bool classof(const Instruction *I) {
1281 return I->getOpcode() == Instruction::ICmp;
1282 }
1283 static bool classof(const Value *V) {
1284 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1285 }
1286};
1287
1288//===----------------------------------------------------------------------===//
1289// FCmpInst Class
1290//===----------------------------------------------------------------------===//
1291
1292/// This instruction compares its operands according to the predicate given
1293/// to the constructor. It only operates on floating point values or packed
1294/// vectors of floating point values. The operands must be identical types.
1295/// Represents a floating point comparison operator.
1296class FCmpInst: public CmpInst {
1297 void AssertOK() {
1298 assert(isFPPredicate() && "Invalid FCmp predicate value")((isFPPredicate() && "Invalid FCmp predicate value") ?
static_cast<void> (0) : __assert_fail ("isFPPredicate() && \"Invalid FCmp predicate value\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1298, __PRETTY_FUNCTION__))
;
1299 assert(getOperand(0)->getType() == getOperand(1)->getType() &&((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1300, __PRETTY_FUNCTION__))
1300 "Both operands to FCmp instruction are not of the same type!")((getOperand(0)->getType() == getOperand(1)->getType() &&
"Both operands to FCmp instruction are not of the same type!"
) ? static_cast<void> (0) : __assert_fail ("getOperand(0)->getType() == getOperand(1)->getType() && \"Both operands to FCmp instruction are not of the same type!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1300, __PRETTY_FUNCTION__))
;
1301 // Check that the operands are the right type
1302 assert(getOperand(0)->getType()->isFPOrFPVectorTy() &&((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1303, __PRETTY_FUNCTION__))
1303 "Invalid operand types for FCmp instruction")((getOperand(0)->getType()->isFPOrFPVectorTy() &&
"Invalid operand types for FCmp instruction") ? static_cast<
void> (0) : __assert_fail ("getOperand(0)->getType()->isFPOrFPVectorTy() && \"Invalid operand types for FCmp instruction\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1303, __PRETTY_FUNCTION__))
;
1304 }
1305
1306protected:
1307 // Note: Instruction needs to be a friend here to call cloneImpl.
1308 friend class Instruction;
1309
1310 /// Clone an identical FCmpInst
1311 FCmpInst *cloneImpl() const;
1312
1313public:
1314 /// Constructor with insert-before-instruction semantics.
1315 FCmpInst(
1316 Instruction *InsertBefore, ///< Where to insert
1317 Predicate pred, ///< The predicate to use for the comparison
1318 Value *LHS, ///< The left-hand-side of the expression
1319 Value *RHS, ///< The right-hand-side of the expression
1320 const Twine &NameStr = "" ///< Name of the instruction
1321 ) : CmpInst(makeCmpResultType(LHS->getType()),
1322 Instruction::FCmp, pred, LHS, RHS, NameStr,
1323 InsertBefore) {
1324 AssertOK();
1325 }
1326
1327 /// Constructor with insert-at-end semantics.
1328 FCmpInst(
1329 BasicBlock &InsertAtEnd, ///< Block to insert into.
1330 Predicate pred, ///< The predicate to use for the comparison
1331 Value *LHS, ///< The left-hand-side of the expression
1332 Value *RHS, ///< The right-hand-side of the expression
1333 const Twine &NameStr = "" ///< Name of the instruction
1334 ) : CmpInst(makeCmpResultType(LHS->getType()),
1335 Instruction::FCmp, pred, LHS, RHS, NameStr,
1336 &InsertAtEnd) {
1337 AssertOK();
1338 }
1339
1340 /// Constructor with no-insertion semantics
1341 FCmpInst(
1342 Predicate Pred, ///< The predicate to use for the comparison
1343 Value *LHS, ///< The left-hand-side of the expression
1344 Value *RHS, ///< The right-hand-side of the expression
1345 const Twine &NameStr = "", ///< Name of the instruction
1346 Instruction *FlagsSource = nullptr
1347 ) : CmpInst(makeCmpResultType(LHS->getType()), Instruction::FCmp, Pred, LHS,
1348 RHS, NameStr, nullptr, FlagsSource) {
1349 AssertOK();
1350 }
1351
1352 /// @returns true if the predicate of this instruction is EQ or NE.
1353 /// Determine if this is an equality predicate.
1354 static bool isEquality(Predicate Pred) {
1355 return Pred == FCMP_OEQ || Pred == FCMP_ONE || Pred == FCMP_UEQ ||
1356 Pred == FCMP_UNE;
1357 }
1358
1359 /// @returns true if the predicate of this instruction is EQ or NE.
1360 /// Determine if this is an equality predicate.
1361 bool isEquality() const { return isEquality(getPredicate()); }
1362
1363 /// @returns true if the predicate of this instruction is commutative.
1364 /// Determine if this is a commutative predicate.
1365 bool isCommutative() const {
1366 return isEquality() ||
1367 getPredicate() == FCMP_FALSE ||
1368 getPredicate() == FCMP_TRUE ||
1369 getPredicate() == FCMP_ORD ||
1370 getPredicate() == FCMP_UNO;
1371 }
1372
1373 /// @returns true if the predicate is relational (not EQ or NE).
1374 /// Determine if this a relational predicate.
1375 bool isRelational() const { return !isEquality(); }
1376
1377 /// Exchange the two operands to this instruction in such a way that it does
1378 /// not modify the semantics of the instruction. The predicate value may be
1379 /// changed to retain the same result if the predicate is order dependent
1380 /// (e.g. ult).
1381 /// Swap operands and adjust predicate.
1382 void swapOperands() {
1383 setPredicate(getSwappedPredicate());
1384 Op<0>().swap(Op<1>());
1385 }
1386
1387 /// Methods for support type inquiry through isa, cast, and dyn_cast:
1388 static bool classof(const Instruction *I) {
1389 return I->getOpcode() == Instruction::FCmp;
1390 }
1391 static bool classof(const Value *V) {
1392 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1393 }
1394};
1395
1396//===----------------------------------------------------------------------===//
1397/// This class represents a function call, abstracting a target
1398/// machine's calling convention. This class uses low bit of the SubClassData
1399/// field to indicate whether or not this is a tail call. The rest of the bits
1400/// hold the calling convention of the call.
1401///
1402class CallInst : public CallBase {
1403 CallInst(const CallInst &CI);
1404
1405 /// Construct a CallInst given a range of arguments.
1406 /// Construct a CallInst from a range of arguments
1407 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1408 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1409 Instruction *InsertBefore);
1410
1411 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1412 const Twine &NameStr, Instruction *InsertBefore)
1413 : CallInst(Ty, Func, Args, None, NameStr, InsertBefore) {}
1414
1415 /// Construct a CallInst given a range of arguments.
1416 /// Construct a CallInst from a range of arguments
1417 inline CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1418 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1419 BasicBlock *InsertAtEnd);
1420
1421 explicit CallInst(FunctionType *Ty, Value *F, const Twine &NameStr,
1422 Instruction *InsertBefore);
1423
1424 CallInst(FunctionType *ty, Value *F, const Twine &NameStr,
1425 BasicBlock *InsertAtEnd);
1426
1427 void init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
1428 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
1429 void init(FunctionType *FTy, Value *Func, const Twine &NameStr);
1430
1431 /// Compute the number of operands to allocate.
1432 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
1433 // We need one operand for the called function, plus the input operand
1434 // counts provided.
1435 return 1 + NumArgs + NumBundleInputs;
1436 }
1437
1438protected:
1439 // Note: Instruction needs to be a friend here to call cloneImpl.
1440 friend class Instruction;
1441
1442 CallInst *cloneImpl() const;
1443
1444public:
1445 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr = "",
1446 Instruction *InsertBefore = nullptr) {
1447 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertBefore);
1448 }
1449
1450 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1451 const Twine &NameStr,
1452 Instruction *InsertBefore = nullptr) {
1453 return new (ComputeNumOperands(Args.size()))
1454 CallInst(Ty, Func, Args, None, NameStr, InsertBefore);
1455 }
1456
1457 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1458 ArrayRef<OperandBundleDef> Bundles = None,
1459 const Twine &NameStr = "",
1460 Instruction *InsertBefore = nullptr) {
1461 const int NumOperands =
1462 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1463 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1464
1465 return new (NumOperands, DescriptorBytes)
1466 CallInst(Ty, Func, Args, Bundles, NameStr, InsertBefore);
1467 }
1468
1469 static CallInst *Create(FunctionType *Ty, Value *F, const Twine &NameStr,
1470 BasicBlock *InsertAtEnd) {
1471 return new (ComputeNumOperands(0)) CallInst(Ty, F, NameStr, InsertAtEnd);
1472 }
1473
1474 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1475 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1476 return new (ComputeNumOperands(Args.size()))
1477 CallInst(Ty, Func, Args, None, NameStr, InsertAtEnd);
1478 }
1479
1480 static CallInst *Create(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1481 ArrayRef<OperandBundleDef> Bundles,
1482 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1483 const int NumOperands =
1484 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
1485 const unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
1486
1487 return new (NumOperands, DescriptorBytes)
1488 CallInst(Ty, Func, Args, Bundles, NameStr, InsertAtEnd);
1489 }
1490
1491 static CallInst *Create(FunctionCallee Func, const Twine &NameStr = "",
1492 Instruction *InsertBefore = nullptr) {
1493 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1494 InsertBefore);
1495 }
1496
1497 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1498 ArrayRef<OperandBundleDef> Bundles = None,
1499 const Twine &NameStr = "",
1500 Instruction *InsertBefore = nullptr) {
1501 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1502 NameStr, InsertBefore);
1503 }
1504
1505 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1506 const Twine &NameStr,
1507 Instruction *InsertBefore = nullptr) {
1508 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1509 InsertBefore);
1510 }
1511
1512 static CallInst *Create(FunctionCallee Func, const Twine &NameStr,
1513 BasicBlock *InsertAtEnd) {
1514 return Create(Func.getFunctionType(), Func.getCallee(), NameStr,
1515 InsertAtEnd);
1516 }
1517
1518 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1519 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1520 return Create(Func.getFunctionType(), Func.getCallee(), Args, NameStr,
1521 InsertAtEnd);
1522 }
1523
1524 static CallInst *Create(FunctionCallee Func, ArrayRef<Value *> Args,
1525 ArrayRef<OperandBundleDef> Bundles,
1526 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1527 return Create(Func.getFunctionType(), Func.getCallee(), Args, Bundles,
1528 NameStr, InsertAtEnd);
1529 }
1530
1531 // Deprecated [opaque pointer types]
1532 static CallInst *Create(Value *Func, const Twine &NameStr = "",
1533 Instruction *InsertBefore = nullptr) {
1534 return Create(cast<FunctionType>(
1535 cast<PointerType>(Func->getType())->getElementType()),
1536 Func, NameStr, InsertBefore);
1537 }
1538
1539 // Deprecated [opaque pointer types]
1540 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1541 const Twine &NameStr,
1542 Instruction *InsertBefore = nullptr) {
1543 return Create(cast<FunctionType>(
1544 cast<PointerType>(Func->getType())->getElementType()),
1545 Func, Args, NameStr, InsertBefore);
1546 }
1547
1548 // Deprecated [opaque pointer types]
1549 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1550 ArrayRef<OperandBundleDef> Bundles = None,
1551 const Twine &NameStr = "",
1552 Instruction *InsertBefore = nullptr) {
1553 return Create(cast<FunctionType>(
1554 cast<PointerType>(Func->getType())->getElementType()),
1555 Func, Args, Bundles, NameStr, InsertBefore);
1556 }
1557
1558 // Deprecated [opaque pointer types]
1559 static CallInst *Create(Value *Func, const Twine &NameStr,
1560 BasicBlock *InsertAtEnd) {
1561 return Create(cast<FunctionType>(
1562 cast<PointerType>(Func->getType())->getElementType()),
1563 Func, NameStr, InsertAtEnd);
1564 }
1565
1566 // Deprecated [opaque pointer types]
1567 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1568 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1569 return Create(cast<FunctionType>(
1570 cast<PointerType>(Func->getType())->getElementType()),
1571 Func, Args, NameStr, InsertAtEnd);
1572 }
1573
1574 // Deprecated [opaque pointer types]
1575 static CallInst *Create(Value *Func, ArrayRef<Value *> Args,
1576 ArrayRef<OperandBundleDef> Bundles,
1577 const Twine &NameStr, BasicBlock *InsertAtEnd) {
1578 return Create(cast<FunctionType>(
1579 cast<PointerType>(Func->getType())->getElementType()),
1580 Func, Args, Bundles, NameStr, InsertAtEnd);
1581 }
1582
1583 /// Create a clone of \p CI with a different set of operand bundles and
1584 /// insert it before \p InsertPt.
1585 ///
1586 /// The returned call instruction is identical \p CI in every way except that
1587 /// the operand bundles for the new instruction are set to the operand bundles
1588 /// in \p Bundles.
1589 static CallInst *Create(CallInst *CI, ArrayRef<OperandBundleDef> Bundles,
1590 Instruction *InsertPt = nullptr);
1591
1592 /// Generate the IR for a call to malloc:
1593 /// 1. Compute the malloc call's argument as the specified type's size,
1594 /// possibly multiplied by the array size if the array size is not
1595 /// constant 1.
1596 /// 2. Call malloc with that argument.
1597 /// 3. Bitcast the result of the malloc call to the specified type.
1598 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1599 Type *AllocTy, Value *AllocSize,
1600 Value *ArraySize = nullptr,
1601 Function *MallocF = nullptr,
1602 const Twine &Name = "");
1603 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1604 Type *AllocTy, Value *AllocSize,
1605 Value *ArraySize = nullptr,
1606 Function *MallocF = nullptr,
1607 const Twine &Name = "");
1608 static Instruction *CreateMalloc(Instruction *InsertBefore, Type *IntPtrTy,
1609 Type *AllocTy, Value *AllocSize,
1610 Value *ArraySize = nullptr,
1611 ArrayRef<OperandBundleDef> Bundles = None,
1612 Function *MallocF = nullptr,
1613 const Twine &Name = "");
1614 static Instruction *CreateMalloc(BasicBlock *InsertAtEnd, Type *IntPtrTy,
1615 Type *AllocTy, Value *AllocSize,
1616 Value *ArraySize = nullptr,
1617 ArrayRef<OperandBundleDef> Bundles = None,
1618 Function *MallocF = nullptr,
1619 const Twine &Name = "");
1620 /// Generate the IR for a call to the builtin free function.
1621 static Instruction *CreateFree(Value *Source, Instruction *InsertBefore);
1622 static Instruction *CreateFree(Value *Source, BasicBlock *InsertAtEnd);
1623 static Instruction *CreateFree(Value *Source,
1624 ArrayRef<OperandBundleDef> Bundles,
1625 Instruction *InsertBefore);
1626 static Instruction *CreateFree(Value *Source,
1627 ArrayRef<OperandBundleDef> Bundles,
1628 BasicBlock *InsertAtEnd);
1629
1630 // Note that 'musttail' implies 'tail'.
1631 enum TailCallKind {
1632 TCK_None = 0,
1633 TCK_Tail = 1,
1634 TCK_MustTail = 2,
1635 TCK_NoTail = 3
1636 };
1637 TailCallKind getTailCallKind() const {
1638 return TailCallKind(getSubclassDataFromInstruction() & 3);
1639 }
1640
1641 bool isTailCall() const {
1642 unsigned Kind = getSubclassDataFromInstruction() & 3;
1643 return Kind == TCK_Tail || Kind == TCK_MustTail;
1644 }
1645
1646 bool isMustTailCall() const {
1647 return (getSubclassDataFromInstruction() & 3) == TCK_MustTail;
1648 }
1649
1650 bool isNoTailCall() const {
1651 return (getSubclassDataFromInstruction() & 3) == TCK_NoTail;
1652 }
1653
1654 void setTailCall(bool isTC = true) {
1655 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1656 unsigned(isTC ? TCK_Tail : TCK_None));
1657 }
1658
1659 void setTailCallKind(TailCallKind TCK) {
1660 setInstructionSubclassData((getSubclassDataFromInstruction() & ~3) |
1661 unsigned(TCK));
1662 }
1663
1664 /// Return true if the call can return twice
1665 bool canReturnTwice() const { return hasFnAttr(Attribute::ReturnsTwice); }
1666 void setCanReturnTwice() {
1667 addAttribute(AttributeList::FunctionIndex, Attribute::ReturnsTwice);
1668 }
1669
1670 // Methods for support type inquiry through isa, cast, and dyn_cast:
1671 static bool classof(const Instruction *I) {
1672 return I->getOpcode() == Instruction::Call;
1673 }
1674 static bool classof(const Value *V) {
1675 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1676 }
1677
1678 /// Updates profile metadata by scaling it by \p S / \p T.
1679 void updateProfWeight(uint64_t S, uint64_t T);
1680
1681private:
1682 // Shadow Instruction::setInstructionSubclassData with a private forwarding
1683 // method so that subclasses cannot accidentally use it.
1684 void setInstructionSubclassData(unsigned short D) {
1685 Instruction::setInstructionSubclassData(D);
1686 }
1687};
1688
1689CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1690 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1691 BasicBlock *InsertAtEnd)
1692 : CallBase(Ty->getReturnType(), Instruction::Call,
1693 OperandTraits<CallBase>::op_end(this) -
1694 (Args.size() + CountBundleInputs(Bundles) + 1),
1695 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1696 InsertAtEnd) {
1697 init(Ty, Func, Args, Bundles, NameStr);
1698}
1699
1700CallInst::CallInst(FunctionType *Ty, Value *Func, ArrayRef<Value *> Args,
1701 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr,
1702 Instruction *InsertBefore)
1703 : CallBase(Ty->getReturnType(), Instruction::Call,
1704 OperandTraits<CallBase>::op_end(this) -
1705 (Args.size() + CountBundleInputs(Bundles) + 1),
1706 unsigned(Args.size() + CountBundleInputs(Bundles) + 1),
1707 InsertBefore) {
1708 init(Ty, Func, Args, Bundles, NameStr);
1709}
1710
1711//===----------------------------------------------------------------------===//
1712// SelectInst Class
1713//===----------------------------------------------------------------------===//
1714
1715/// This class represents the LLVM 'select' instruction.
1716///
1717class SelectInst : public Instruction {
1718 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1719 Instruction *InsertBefore)
1720 : Instruction(S1->getType(), Instruction::Select,
1721 &Op<0>(), 3, InsertBefore) {
1722 init(C, S1, S2);
1723 setName(NameStr);
1724 }
1725
1726 SelectInst(Value *C, Value *S1, Value *S2, const Twine &NameStr,
1727 BasicBlock *InsertAtEnd)
1728 : Instruction(S1->getType(), Instruction::Select,
1729 &Op<0>(), 3, InsertAtEnd) {
1730 init(C, S1, S2);
1731 setName(NameStr);
1732 }
1733
1734 void init(Value *C, Value *S1, Value *S2) {
1735 assert(!areInvalidOperands(C, S1, S2) && "Invalid operands for select")((!areInvalidOperands(C, S1, S2) && "Invalid operands for select"
) ? static_cast<void> (0) : __assert_fail ("!areInvalidOperands(C, S1, S2) && \"Invalid operands for select\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1735, __PRETTY_FUNCTION__))
;
1736 Op<0>() = C;
1737 Op<1>() = S1;
1738 Op<2>() = S2;
1739 }
1740
1741protected:
1742 // Note: Instruction needs to be a friend here to call cloneImpl.
1743 friend class Instruction;
1744
1745 SelectInst *cloneImpl() const;
1746
1747public:
1748 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1749 const Twine &NameStr = "",
1750 Instruction *InsertBefore = nullptr,
1751 Instruction *MDFrom = nullptr) {
1752 SelectInst *Sel = new(3) SelectInst(C, S1, S2, NameStr, InsertBefore);
1753 if (MDFrom)
1754 Sel->copyMetadata(*MDFrom);
1755 return Sel;
1756 }
1757
1758 static SelectInst *Create(Value *C, Value *S1, Value *S2,
1759 const Twine &NameStr,
1760 BasicBlock *InsertAtEnd) {
1761 return new(3) SelectInst(C, S1, S2, NameStr, InsertAtEnd);
1762 }
1763
1764 const Value *getCondition() const { return Op<0>(); }
1765 const Value *getTrueValue() const { return Op<1>(); }
1766 const Value *getFalseValue() const { return Op<2>(); }
1767 Value *getCondition() { return Op<0>(); }
1768 Value *getTrueValue() { return Op<1>(); }
1769 Value *getFalseValue() { return Op<2>(); }
1770
1771 void setCondition(Value *V) { Op<0>() = V; }
1772 void setTrueValue(Value *V) { Op<1>() = V; }
1773 void setFalseValue(Value *V) { Op<2>() = V; }
1774
1775 /// Swap the true and false values of the select instruction.
1776 /// This doesn't swap prof metadata.
1777 void swapValues() { Op<1>().swap(Op<2>()); }
1778
1779 /// Return a string if the specified operands are invalid
1780 /// for a select operation, otherwise return null.
1781 static const char *areInvalidOperands(Value *Cond, Value *True, Value *False);
1782
1783 /// Transparently provide more efficient getOperand methods.
1784 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
;
1785
1786 OtherOps getOpcode() const {
1787 return static_cast<OtherOps>(Instruction::getOpcode());
1788 }
1789
1790 // Methods for support type inquiry through isa, cast, and dyn_cast:
1791 static bool classof(const Instruction *I) {
1792 return I->getOpcode() == Instruction::Select;
1793 }
1794 static bool classof(const Value *V) {
1795 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1796 }
1797};
1798
1799template <>
1800struct OperandTraits<SelectInst> : public FixedNumOperandTraits<SelectInst, 3> {
1801};
1802
1803DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SelectInst, Value)SelectInst::op_iterator SelectInst::op_begin() { return OperandTraits
<SelectInst>::op_begin(this); } SelectInst::const_op_iterator
SelectInst::op_begin() const { return OperandTraits<SelectInst
>::op_begin(const_cast<SelectInst*>(this)); } SelectInst
::op_iterator SelectInst::op_end() { return OperandTraits<
SelectInst>::op_end(this); } SelectInst::const_op_iterator
SelectInst::op_end() const { return OperandTraits<SelectInst
>::op_end(const_cast<SelectInst*>(this)); } Value *SelectInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1803, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<SelectInst>::op_begin(const_cast<SelectInst
*>(this))[i_nocapture].get()); } void SelectInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<SelectInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SelectInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1803, __PRETTY_FUNCTION__)); OperandTraits<SelectInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SelectInst
::getNumOperands() const { return OperandTraits<SelectInst
>::operands(this); } template <int Idx_nocapture> Use
&SelectInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
SelectInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
1804
1805//===----------------------------------------------------------------------===//
1806// VAArgInst Class
1807//===----------------------------------------------------------------------===//
1808
1809/// This class represents the va_arg llvm instruction, which returns
1810/// an argument of the specified type given a va_list and increments that list
1811///
1812class VAArgInst : public UnaryInstruction {
1813protected:
1814 // Note: Instruction needs to be a friend here to call cloneImpl.
1815 friend class Instruction;
1816
1817 VAArgInst *cloneImpl() const;
1818
1819public:
1820 VAArgInst(Value *List, Type *Ty, const Twine &NameStr = "",
1821 Instruction *InsertBefore = nullptr)
1822 : UnaryInstruction(Ty, VAArg, List, InsertBefore) {
1823 setName(NameStr);
1824 }
1825
1826 VAArgInst(Value *List, Type *Ty, const Twine &NameStr,
1827 BasicBlock *InsertAtEnd)
1828 : UnaryInstruction(Ty, VAArg, List, InsertAtEnd) {
1829 setName(NameStr);
1830 }
1831
1832 Value *getPointerOperand() { return getOperand(0); }
1833 const Value *getPointerOperand() const { return getOperand(0); }
1834 static unsigned getPointerOperandIndex() { return 0U; }
1835
1836 // Methods for support type inquiry through isa, cast, and dyn_cast:
1837 static bool classof(const Instruction *I) {
1838 return I->getOpcode() == VAArg;
1839 }
1840 static bool classof(const Value *V) {
1841 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1842 }
1843};
1844
1845//===----------------------------------------------------------------------===//
1846// ExtractElementInst Class
1847//===----------------------------------------------------------------------===//
1848
1849/// This instruction extracts a single (scalar)
1850/// element from a VectorType value
1851///
1852class ExtractElementInst : public Instruction {
1853 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr = "",
1854 Instruction *InsertBefore = nullptr);
1855 ExtractElementInst(Value *Vec, Value *Idx, const Twine &NameStr,
1856 BasicBlock *InsertAtEnd);
1857
1858protected:
1859 // Note: Instruction needs to be a friend here to call cloneImpl.
1860 friend class Instruction;
1861
1862 ExtractElementInst *cloneImpl() const;
1863
1864public:
1865 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1866 const Twine &NameStr = "",
1867 Instruction *InsertBefore = nullptr) {
1868 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertBefore);
1869 }
1870
1871 static ExtractElementInst *Create(Value *Vec, Value *Idx,
1872 const Twine &NameStr,
1873 BasicBlock *InsertAtEnd) {
1874 return new(2) ExtractElementInst(Vec, Idx, NameStr, InsertAtEnd);
1875 }
1876
1877 /// Return true if an extractelement instruction can be
1878 /// formed with the specified operands.
1879 static bool isValidOperands(const Value *Vec, const Value *Idx);
1880
1881 Value *getVectorOperand() { return Op<0>(); }
1882 Value *getIndexOperand() { return Op<1>(); }
1883 const Value *getVectorOperand() const { return Op<0>(); }
1884 const Value *getIndexOperand() const { return Op<1>(); }
1885
1886 VectorType *getVectorOperandType() const {
1887 return cast<VectorType>(getVectorOperand()->getType());
1888 }
1889
1890 /// Transparently provide more efficient getOperand methods.
1891 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
;
1892
1893 // Methods for support type inquiry through isa, cast, and dyn_cast:
1894 static bool classof(const Instruction *I) {
1895 return I->getOpcode() == Instruction::ExtractElement;
1896 }
1897 static bool classof(const Value *V) {
1898 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1899 }
1900};
1901
1902template <>
1903struct OperandTraits<ExtractElementInst> :
1904 public FixedNumOperandTraits<ExtractElementInst, 2> {
1905};
1906
1907DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ExtractElementInst, Value)ExtractElementInst::op_iterator ExtractElementInst::op_begin(
) { return OperandTraits<ExtractElementInst>::op_begin(
this); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_begin() const { return OperandTraits<ExtractElementInst
>::op_begin(const_cast<ExtractElementInst*>(this)); }
ExtractElementInst::op_iterator ExtractElementInst::op_end()
{ return OperandTraits<ExtractElementInst>::op_end(this
); } ExtractElementInst::const_op_iterator ExtractElementInst
::op_end() const { return OperandTraits<ExtractElementInst
>::op_end(const_cast<ExtractElementInst*>(this)); } Value
*ExtractElementInst::getOperand(unsigned i_nocapture) const {
((i_nocapture < OperandTraits<ExtractElementInst>::
operands(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1907, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ExtractElementInst>::op_begin(const_cast
<ExtractElementInst*>(this))[i_nocapture].get()); } void
ExtractElementInst::setOperand(unsigned i_nocapture, Value *
Val_nocapture) { ((i_nocapture < OperandTraits<ExtractElementInst
>::operands(this) && "setOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ExtractElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1907, __PRETTY_FUNCTION__)); OperandTraits<ExtractElementInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
ExtractElementInst::getNumOperands() const { return OperandTraits
<ExtractElementInst>::operands(this); } template <int
Idx_nocapture> Use &ExtractElementInst::Op() { return
this->OpFrom<Idx_nocapture>(this); } template <int
Idx_nocapture> const Use &ExtractElementInst::Op() const
{ return this->OpFrom<Idx_nocapture>(this); }
1908
1909//===----------------------------------------------------------------------===//
1910// InsertElementInst Class
1911//===----------------------------------------------------------------------===//
1912
1913/// This instruction inserts a single (scalar)
1914/// element into a VectorType value
1915///
1916class InsertElementInst : public Instruction {
1917 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx,
1918 const Twine &NameStr = "",
1919 Instruction *InsertBefore = nullptr);
1920 InsertElementInst(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr,
1921 BasicBlock *InsertAtEnd);
1922
1923protected:
1924 // Note: Instruction needs to be a friend here to call cloneImpl.
1925 friend class Instruction;
1926
1927 InsertElementInst *cloneImpl() const;
1928
1929public:
1930 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1931 const Twine &NameStr = "",
1932 Instruction *InsertBefore = nullptr) {
1933 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertBefore);
1934 }
1935
1936 static InsertElementInst *Create(Value *Vec, Value *NewElt, Value *Idx,
1937 const Twine &NameStr,
1938 BasicBlock *InsertAtEnd) {
1939 return new(3) InsertElementInst(Vec, NewElt, Idx, NameStr, InsertAtEnd);
1940 }
1941
1942 /// Return true if an insertelement instruction can be
1943 /// formed with the specified operands.
1944 static bool isValidOperands(const Value *Vec, const Value *NewElt,
1945 const Value *Idx);
1946
1947 /// Overload to return most specific vector type.
1948 ///
1949 VectorType *getType() const {
1950 return cast<VectorType>(Instruction::getType());
1951 }
1952
1953 /// Transparently provide more efficient getOperand methods.
1954 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
;
1955
1956 // Methods for support type inquiry through isa, cast, and dyn_cast:
1957 static bool classof(const Instruction *I) {
1958 return I->getOpcode() == Instruction::InsertElement;
1959 }
1960 static bool classof(const Value *V) {
1961 return isa<Instruction>(V) && classof(cast<Instruction>(V));
1962 }
1963};
1964
1965template <>
1966struct OperandTraits<InsertElementInst> :
1967 public FixedNumOperandTraits<InsertElementInst, 3> {
1968};
1969
1970DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertElementInst, Value)InsertElementInst::op_iterator InsertElementInst::op_begin() {
return OperandTraits<InsertElementInst>::op_begin(this
); } InsertElementInst::const_op_iterator InsertElementInst::
op_begin() const { return OperandTraits<InsertElementInst>
::op_begin(const_cast<InsertElementInst*>(this)); } InsertElementInst
::op_iterator InsertElementInst::op_end() { return OperandTraits
<InsertElementInst>::op_end(this); } InsertElementInst::
const_op_iterator InsertElementInst::op_end() const { return OperandTraits
<InsertElementInst>::op_end(const_cast<InsertElementInst
*>(this)); } Value *InsertElementInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<InsertElementInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1970, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<InsertElementInst>::op_begin(const_cast
<InsertElementInst*>(this))[i_nocapture].get()); } void
InsertElementInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<InsertElementInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertElementInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 1970, __PRETTY_FUNCTION__)); OperandTraits<InsertElementInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
InsertElementInst::getNumOperands() const { return OperandTraits
<InsertElementInst>::operands(this); } template <int
Idx_nocapture> Use &InsertElementInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &InsertElementInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
1971
1972//===----------------------------------------------------------------------===//
1973// ShuffleVectorInst Class
1974//===----------------------------------------------------------------------===//
1975
1976/// This instruction constructs a fixed permutation of two
1977/// input vectors.
1978///
1979class ShuffleVectorInst : public Instruction {
1980protected:
1981 // Note: Instruction needs to be a friend here to call cloneImpl.
1982 friend class Instruction;
1983
1984 ShuffleVectorInst *cloneImpl() const;
1985
1986public:
1987 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1988 const Twine &NameStr = "",
1989 Instruction *InsertBefor = nullptr);
1990 ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1991 const Twine &NameStr, BasicBlock *InsertAtEnd);
1992
1993 // allocate space for exactly three operands
1994 void *operator new(size_t s) {
1995 return User::operator new(s, 3);
1996 }
1997
1998 /// Swap the first 2 operands and adjust the mask to preserve the semantics
1999 /// of the instruction.
2000 void commute();
2001
2002 /// Return true if a shufflevector instruction can be
2003 /// formed with the specified operands.
2004 static bool isValidOperands(const Value *V1, const Value *V2,
2005 const Value *Mask);
2006
2007 /// Overload to return most specific vector type.
2008 ///
2009 VectorType *getType() const {
2010 return cast<VectorType>(Instruction::getType());
2011 }
2012
2013 /// Transparently provide more efficient getOperand methods.
2014 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
;
2015
2016 Constant *getMask() const {
2017 return cast<Constant>(getOperand(2));
2018 }
2019
2020 /// Return the shuffle mask value for the specified element of the mask.
2021 /// Return -1 if the element is undef.
2022 static int getMaskValue(const Constant *Mask, unsigned Elt);
2023
2024 /// Return the shuffle mask value of this instruction for the given element
2025 /// index. Return -1 if the element is undef.
2026 int getMaskValue(unsigned Elt) const {
2027 return getMaskValue(getMask(), Elt);
2028 }
2029
2030 /// Convert the input shuffle mask operand to a vector of integers. Undefined
2031 /// elements of the mask are returned as -1.
2032 static void getShuffleMask(const Constant *Mask,
2033 SmallVectorImpl<int> &Result);
2034
2035 /// Return the mask for this instruction as a vector of integers. Undefined
2036 /// elements of the mask are returned as -1.
2037 void getShuffleMask(SmallVectorImpl<int> &Result) const {
2038 return getShuffleMask(getMask(), Result);
2039 }
2040
2041 SmallVector<int, 16> getShuffleMask() const {
2042 SmallVector<int, 16> Mask;
2043 getShuffleMask(Mask);
2044 return Mask;
2045 }
2046
2047 /// Return true if this shuffle returns a vector with a different number of
2048 /// elements than its source vectors.
2049 /// Examples: shufflevector <4 x n> A, <4 x n> B, <1,2,3>
2050 /// shufflevector <4 x n> A, <4 x n> B, <1,2,3,4,5>
2051 bool changesLength() const {
2052 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2053 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2054 return NumSourceElts != NumMaskElts;
2055 }
2056
2057 /// Return true if this shuffle returns a vector with a greater number of
2058 /// elements than its source vectors.
2059 /// Example: shufflevector <2 x n> A, <2 x n> B, <1,2,3>
2060 bool increasesLength() const {
2061 unsigned NumSourceElts = Op<0>()->getType()->getVectorNumElements();
2062 unsigned NumMaskElts = getMask()->getType()->getVectorNumElements();
2063 return NumSourceElts < NumMaskElts;
2064 }
2065
2066 /// Return true if this shuffle mask chooses elements from exactly one source
2067 /// vector.
2068 /// Example: <7,5,undef,7>
2069 /// This assumes that vector operands are the same length as the mask.
2070 static bool isSingleSourceMask(ArrayRef<int> Mask);
2071 static bool isSingleSourceMask(const Constant *Mask) {
2072 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2072, __PRETTY_FUNCTION__))
;
2073 SmallVector<int, 16> MaskAsInts;
2074 getShuffleMask(Mask, MaskAsInts);
2075 return isSingleSourceMask(MaskAsInts);
2076 }
2077
2078 /// Return true if this shuffle chooses elements from exactly one source
2079 /// vector without changing the length of that vector.
2080 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,0,undef,3>
2081 /// TODO: Optionally allow length-changing shuffles.
2082 bool isSingleSource() const {
2083 return !changesLength() && isSingleSourceMask(getMask());
2084 }
2085
2086 /// Return true if this shuffle mask chooses elements from exactly one source
2087 /// vector without lane crossings. A shuffle using this mask is not
2088 /// necessarily a no-op because it may change the number of elements from its
2089 /// input vectors or it may provide demanded bits knowledge via undef lanes.
2090 /// Example: <undef,undef,2,3>
2091 static bool isIdentityMask(ArrayRef<int> Mask);
2092 static bool isIdentityMask(const Constant *Mask) {
2093 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2093, __PRETTY_FUNCTION__))
;
2094 SmallVector<int, 16> MaskAsInts;
2095 getShuffleMask(Mask, MaskAsInts);
2096 return isIdentityMask(MaskAsInts);
2097 }
2098
2099 /// Return true if this shuffle chooses elements from exactly one source
2100 /// vector without lane crossings and does not change the number of elements
2101 /// from its input vectors.
2102 /// Example: shufflevector <4 x n> A, <4 x n> B, <4,undef,6,undef>
2103 bool isIdentity() const {
2104 return !changesLength() && isIdentityMask(getShuffleMask());
2105 }
2106
2107 /// Return true if this shuffle lengthens exactly one source vector with
2108 /// undefs in the high elements.
2109 bool isIdentityWithPadding() const;
2110
2111 /// Return true if this shuffle extracts the first N elements of exactly one
2112 /// source vector.
2113 bool isIdentityWithExtract() const;
2114
2115 /// Return true if this shuffle concatenates its 2 source vectors. This
2116 /// returns false if either input is undefined. In that case, the shuffle is
2117 /// is better classified as an identity with padding operation.
2118 bool isConcat() const;
2119
2120 /// Return true if this shuffle mask chooses elements from its source vectors
2121 /// without lane crossings. A shuffle using this mask would be
2122 /// equivalent to a vector select with a constant condition operand.
2123 /// Example: <4,1,6,undef>
2124 /// This returns false if the mask does not choose from both input vectors.
2125 /// In that case, the shuffle is better classified as an identity shuffle.
2126 /// This assumes that vector operands are the same length as the mask
2127 /// (a length-changing shuffle can never be equivalent to a vector select).
2128 static bool isSelectMask(ArrayRef<int> Mask);
2129 static bool isSelectMask(const Constant *Mask) {
2130 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2130, __PRETTY_FUNCTION__))
;
2131 SmallVector<int, 16> MaskAsInts;
2132 getShuffleMask(Mask, MaskAsInts);
2133 return isSelectMask(MaskAsInts);
2134 }
2135
2136 /// Return true if this shuffle chooses elements from its source vectors
2137 /// without lane crossings and all operands have the same number of elements.
2138 /// In other words, this shuffle is equivalent to a vector select with a
2139 /// constant condition operand.
2140 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,1,6,3>
2141 /// This returns false if the mask does not choose from both input vectors.
2142 /// In that case, the shuffle is better classified as an identity shuffle.
2143 /// TODO: Optionally allow length-changing shuffles.
2144 bool isSelect() const {
2145 return !changesLength() && isSelectMask(getMask());
2146 }
2147
2148 /// Return true if this shuffle mask swaps the order of elements from exactly
2149 /// one source vector.
2150 /// Example: <7,6,undef,4>
2151 /// This assumes that vector operands are the same length as the mask.
2152 static bool isReverseMask(ArrayRef<int> Mask);
2153 static bool isReverseMask(const Constant *Mask) {
2154 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2154, __PRETTY_FUNCTION__))
;
2155 SmallVector<int, 16> MaskAsInts;
2156 getShuffleMask(Mask, MaskAsInts);
2157 return isReverseMask(MaskAsInts);
2158 }
2159
2160 /// Return true if this shuffle swaps the order of elements from exactly
2161 /// one source vector.
2162 /// Example: shufflevector <4 x n> A, <4 x n> B, <3,undef,1,undef>
2163 /// TODO: Optionally allow length-changing shuffles.
2164 bool isReverse() const {
2165 return !changesLength() && isReverseMask(getMask());
2166 }
2167
2168 /// Return true if this shuffle mask chooses all elements with the same value
2169 /// as the first element of exactly one source vector.
2170 /// Example: <4,undef,undef,4>
2171 /// This assumes that vector operands are the same length as the mask.
2172 static bool isZeroEltSplatMask(ArrayRef<int> Mask);
2173 static bool isZeroEltSplatMask(const Constant *Mask) {
2174 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2174, __PRETTY_FUNCTION__))
;
2175 SmallVector<int, 16> MaskAsInts;
2176 getShuffleMask(Mask, MaskAsInts);
2177 return isZeroEltSplatMask(MaskAsInts);
2178 }
2179
2180 /// Return true if all elements of this shuffle are the same value as the
2181 /// first element of exactly one source vector without changing the length
2182 /// of that vector.
2183 /// Example: shufflevector <4 x n> A, <4 x n> B, <undef,0,undef,0>
2184 /// TODO: Optionally allow length-changing shuffles.
2185 /// TODO: Optionally allow splats from other elements.
2186 bool isZeroEltSplat() const {
2187 return !changesLength() && isZeroEltSplatMask(getMask());
2188 }
2189
2190 /// Return true if this shuffle mask is a transpose mask.
2191 /// Transpose vector masks transpose a 2xn matrix. They read corresponding
2192 /// even- or odd-numbered vector elements from two n-dimensional source
2193 /// vectors and write each result into consecutive elements of an
2194 /// n-dimensional destination vector. Two shuffles are necessary to complete
2195 /// the transpose, one for the even elements and another for the odd elements.
2196 /// This description closely follows how the TRN1 and TRN2 AArch64
2197 /// instructions operate.
2198 ///
2199 /// For example, a simple 2x2 matrix can be transposed with:
2200 ///
2201 /// ; Original matrix
2202 /// m0 = < a, b >
2203 /// m1 = < c, d >
2204 ///
2205 /// ; Transposed matrix
2206 /// t0 = < a, c > = shufflevector m0, m1, < 0, 2 >
2207 /// t1 = < b, d > = shufflevector m0, m1, < 1, 3 >
2208 ///
2209 /// For matrices having greater than n columns, the resulting nx2 transposed
2210 /// matrix is stored in two result vectors such that one vector contains
2211 /// interleaved elements from all the even-numbered rows and the other vector
2212 /// contains interleaved elements from all the odd-numbered rows. For example,
2213 /// a 2x4 matrix can be transposed with:
2214 ///
2215 /// ; Original matrix
2216 /// m0 = < a, b, c, d >
2217 /// m1 = < e, f, g, h >
2218 ///
2219 /// ; Transposed matrix
2220 /// t0 = < a, e, c, g > = shufflevector m0, m1 < 0, 4, 2, 6 >
2221 /// t1 = < b, f, d, h > = shufflevector m0, m1 < 1, 5, 3, 7 >
2222 static bool isTransposeMask(ArrayRef<int> Mask);
2223 static bool isTransposeMask(const Constant *Mask) {
2224 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2224, __PRETTY_FUNCTION__))
;
2225 SmallVector<int, 16> MaskAsInts;
2226 getShuffleMask(Mask, MaskAsInts);
2227 return isTransposeMask(MaskAsInts);
2228 }
2229
2230 /// Return true if this shuffle transposes the elements of its inputs without
2231 /// changing the length of the vectors. This operation may also be known as a
2232 /// merge or interleave. See the description for isTransposeMask() for the
2233 /// exact specification.
2234 /// Example: shufflevector <4 x n> A, <4 x n> B, <0,4,2,6>
2235 bool isTranspose() const {
2236 return !changesLength() && isTransposeMask(getMask());
2237 }
2238
2239 /// Return true if this shuffle mask is an extract subvector mask.
2240 /// A valid extract subvector mask returns a smaller vector from a single
2241 /// source operand. The base extraction index is returned as well.
2242 static bool isExtractSubvectorMask(ArrayRef<int> Mask, int NumSrcElts,
2243 int &Index);
2244 static bool isExtractSubvectorMask(const Constant *Mask, int NumSrcElts,
2245 int &Index) {
2246 assert(Mask->getType()->isVectorTy() && "Shuffle needs vector constant.")((Mask->getType()->isVectorTy() && "Shuffle needs vector constant."
) ? static_cast<void> (0) : __assert_fail ("Mask->getType()->isVectorTy() && \"Shuffle needs vector constant.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2246, __PRETTY_FUNCTION__))
;
2247 SmallVector<int, 16> MaskAsInts;
2248 getShuffleMask(Mask, MaskAsInts);
2249 return isExtractSubvectorMask(MaskAsInts, NumSrcElts, Index);
2250 }
2251
2252 /// Return true if this shuffle mask is an extract subvector mask.
2253 bool isExtractSubvectorMask(int &Index) const {
2254 int NumSrcElts = Op<0>()->getType()->getVectorNumElements();
2255 return isExtractSubvectorMask(getMask(), NumSrcElts, Index);
2256 }
2257
2258 /// Change values in a shuffle permute mask assuming the two vector operands
2259 /// of length InVecNumElts have swapped position.
2260 static void commuteShuffleMask(MutableArrayRef<int> Mask,
2261 unsigned InVecNumElts) {
2262 for (int &Idx : Mask) {
2263 if (Idx == -1)
2264 continue;
2265 Idx = Idx < (int)InVecNumElts ? Idx + InVecNumElts : Idx - InVecNumElts;
2266 assert(Idx >= 0 && Idx < (int)InVecNumElts * 2 &&((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2267, __PRETTY_FUNCTION__))
2267 "shufflevector mask index out of range")((Idx >= 0 && Idx < (int)InVecNumElts * 2 &&
"shufflevector mask index out of range") ? static_cast<void
> (0) : __assert_fail ("Idx >= 0 && Idx < (int)InVecNumElts * 2 && \"shufflevector mask index out of range\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2267, __PRETTY_FUNCTION__))
;
2268 }
2269 }
2270
2271 // Methods for support type inquiry through isa, cast, and dyn_cast:
2272 static bool classof(const Instruction *I) {
2273 return I->getOpcode() == Instruction::ShuffleVector;
2274 }
2275 static bool classof(const Value *V) {
2276 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2277 }
2278};
2279
2280template <>
2281struct OperandTraits<ShuffleVectorInst> :
2282 public FixedNumOperandTraits<ShuffleVectorInst, 3> {
2283};
2284
2285DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ShuffleVectorInst, Value)ShuffleVectorInst::op_iterator ShuffleVectorInst::op_begin() {
return OperandTraits<ShuffleVectorInst>::op_begin(this
); } ShuffleVectorInst::const_op_iterator ShuffleVectorInst::
op_begin() const { return OperandTraits<ShuffleVectorInst>
::op_begin(const_cast<ShuffleVectorInst*>(this)); } ShuffleVectorInst
::op_iterator ShuffleVectorInst::op_end() { return OperandTraits
<ShuffleVectorInst>::op_end(this); } ShuffleVectorInst::
const_op_iterator ShuffleVectorInst::op_end() const { return OperandTraits
<ShuffleVectorInst>::op_end(const_cast<ShuffleVectorInst
*>(this)); } Value *ShuffleVectorInst::getOperand(unsigned
i_nocapture) const { ((i_nocapture < OperandTraits<ShuffleVectorInst
>::operands(this) && "getOperand() out of range!")
? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2285, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ShuffleVectorInst>::op_begin(const_cast
<ShuffleVectorInst*>(this))[i_nocapture].get()); } void
ShuffleVectorInst::setOperand(unsigned i_nocapture, Value *Val_nocapture
) { ((i_nocapture < OperandTraits<ShuffleVectorInst>
::operands(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ShuffleVectorInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2285, __PRETTY_FUNCTION__)); OperandTraits<ShuffleVectorInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
ShuffleVectorInst::getNumOperands() const { return OperandTraits
<ShuffleVectorInst>::operands(this); } template <int
Idx_nocapture> Use &ShuffleVectorInst::Op() { return this
->OpFrom<Idx_nocapture>(this); } template <int Idx_nocapture
> const Use &ShuffleVectorInst::Op() const { return this
->OpFrom<Idx_nocapture>(this); }
2286
2287//===----------------------------------------------------------------------===//
2288// ExtractValueInst Class
2289//===----------------------------------------------------------------------===//
2290
2291/// This instruction extracts a struct member or array
2292/// element value from an aggregate value.
2293///
2294class ExtractValueInst : public UnaryInstruction {
2295 SmallVector<unsigned, 4> Indices;
2296
2297 ExtractValueInst(const ExtractValueInst &EVI);
2298
2299 /// Constructors - Create a extractvalue instruction with a base aggregate
2300 /// value and a list of indices. The first ctor can optionally insert before
2301 /// an existing instruction, the second appends the new instruction to the
2302 /// specified BasicBlock.
2303 inline ExtractValueInst(Value *Agg,
2304 ArrayRef<unsigned> Idxs,
2305 const Twine &NameStr,
2306 Instruction *InsertBefore);
2307 inline ExtractValueInst(Value *Agg,
2308 ArrayRef<unsigned> Idxs,
2309 const Twine &NameStr, BasicBlock *InsertAtEnd);
2310
2311 void init(ArrayRef<unsigned> Idxs, const Twine &NameStr);
2312
2313protected:
2314 // Note: Instruction needs to be a friend here to call cloneImpl.
2315 friend class Instruction;
2316
2317 ExtractValueInst *cloneImpl() const;
2318
2319public:
2320 static ExtractValueInst *Create(Value *Agg,
2321 ArrayRef<unsigned> Idxs,
2322 const Twine &NameStr = "",
2323 Instruction *InsertBefore = nullptr) {
2324 return new
2325 ExtractValueInst(Agg, Idxs, NameStr, InsertBefore);
2326 }
2327
2328 static ExtractValueInst *Create(Value *Agg,
2329 ArrayRef<unsigned> Idxs,
2330 const Twine &NameStr,
2331 BasicBlock *InsertAtEnd) {
2332 return new ExtractValueInst(Agg, Idxs, NameStr, InsertAtEnd);
2333 }
2334
2335 /// Returns the type of the element that would be extracted
2336 /// with an extractvalue instruction with the specified parameters.
2337 ///
2338 /// Null is returned if the indices are invalid for the specified type.
2339 static Type *getIndexedType(Type *Agg, ArrayRef<unsigned> Idxs);
2340
2341 using idx_iterator = const unsigned*;
2342
2343 inline idx_iterator idx_begin() const { return Indices.begin(); }
2344 inline idx_iterator idx_end() const { return Indices.end(); }
2345 inline iterator_range<idx_iterator> indices() const {
2346 return make_range(idx_begin(), idx_end());
2347 }
2348
2349 Value *getAggregateOperand() {
2350 return getOperand(0);
2351 }
2352 const Value *getAggregateOperand() const {
2353 return getOperand(0);
2354 }
2355 static unsigned getAggregateOperandIndex() {
2356 return 0U; // get index for modifying correct operand
2357 }
2358
2359 ArrayRef<unsigned> getIndices() const {
2360 return Indices;
2361 }
2362
2363 unsigned getNumIndices() const {
2364 return (unsigned)Indices.size();
2365 }
2366
2367 bool hasIndices() const {
2368 return true;
2369 }
2370
2371 // Methods for support type inquiry through isa, cast, and dyn_cast:
2372 static bool classof(const Instruction *I) {
2373 return I->getOpcode() == Instruction::ExtractValue;
2374 }
2375 static bool classof(const Value *V) {
2376 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2377 }
2378};
2379
2380ExtractValueInst::ExtractValueInst(Value *Agg,
2381 ArrayRef<unsigned> Idxs,
2382 const Twine &NameStr,
2383 Instruction *InsertBefore)
2384 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2385 ExtractValue, Agg, InsertBefore) {
2386 init(Idxs, NameStr);
2387}
2388
2389ExtractValueInst::ExtractValueInst(Value *Agg,
2390 ArrayRef<unsigned> Idxs,
2391 const Twine &NameStr,
2392 BasicBlock *InsertAtEnd)
2393 : UnaryInstruction(checkGEPType(getIndexedType(Agg->getType(), Idxs)),
2394 ExtractValue, Agg, InsertAtEnd) {
2395 init(Idxs, NameStr);
2396}
2397
2398//===----------------------------------------------------------------------===//
2399// InsertValueInst Class
2400//===----------------------------------------------------------------------===//
2401
2402/// This instruction inserts a struct field of array element
2403/// value into an aggregate value.
2404///
2405class InsertValueInst : public Instruction {
2406 SmallVector<unsigned, 4> Indices;
2407
2408 InsertValueInst(const InsertValueInst &IVI);
2409
2410 /// Constructors - Create a insertvalue instruction with a base aggregate
2411 /// value, a value to insert, and a list of indices. The first ctor can
2412 /// optionally insert before an existing instruction, the second appends
2413 /// the new instruction to the specified BasicBlock.
2414 inline InsertValueInst(Value *Agg, Value *Val,
2415 ArrayRef<unsigned> Idxs,
2416 const Twine &NameStr,
2417 Instruction *InsertBefore);
2418 inline InsertValueInst(Value *Agg, Value *Val,
2419 ArrayRef<unsigned> Idxs,
2420 const Twine &NameStr, BasicBlock *InsertAtEnd);
2421
2422 /// Constructors - These two constructors are convenience methods because one
2423 /// and two index insertvalue instructions are so common.
2424 InsertValueInst(Value *Agg, Value *Val, unsigned Idx,
2425 const Twine &NameStr = "",
2426 Instruction *InsertBefore = nullptr);
2427 InsertValueInst(Value *Agg, Value *Val, unsigned Idx, const Twine &NameStr,
2428 BasicBlock *InsertAtEnd);
2429
2430 void init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2431 const Twine &NameStr);
2432
2433protected:
2434 // Note: Instruction needs to be a friend here to call cloneImpl.
2435 friend class Instruction;
2436
2437 InsertValueInst *cloneImpl() const;
2438
2439public:
2440 // allocate space for exactly two operands
2441 void *operator new(size_t s) {
2442 return User::operator new(s, 2);
2443 }
2444
2445 static InsertValueInst *Create(Value *Agg, Value *Val,
2446 ArrayRef<unsigned> Idxs,
2447 const Twine &NameStr = "",
2448 Instruction *InsertBefore = nullptr) {
2449 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertBefore);
2450 }
2451
2452 static InsertValueInst *Create(Value *Agg, Value *Val,
2453 ArrayRef<unsigned> Idxs,
2454 const Twine &NameStr,
2455 BasicBlock *InsertAtEnd) {
2456 return new InsertValueInst(Agg, Val, Idxs, NameStr, InsertAtEnd);
2457 }
2458
2459 /// Transparently provide more efficient getOperand methods.
2460 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
;
2461
2462 using idx_iterator = const unsigned*;
2463
2464 inline idx_iterator idx_begin() const { return Indices.begin(); }
2465 inline idx_iterator idx_end() const { return Indices.end(); }
2466 inline iterator_range<idx_iterator> indices() const {
2467 return make_range(idx_begin(), idx_end());
2468 }
2469
2470 Value *getAggregateOperand() {
2471 return getOperand(0);
2472 }
2473 const Value *getAggregateOperand() const {
2474 return getOperand(0);
2475 }
2476 static unsigned getAggregateOperandIndex() {
2477 return 0U; // get index for modifying correct operand
2478 }
2479
2480 Value *getInsertedValueOperand() {
2481 return getOperand(1);
2482 }
2483 const Value *getInsertedValueOperand() const {
2484 return getOperand(1);
2485 }
2486 static unsigned getInsertedValueOperandIndex() {
2487 return 1U; // get index for modifying correct operand
2488 }
2489
2490 ArrayRef<unsigned> getIndices() const {
2491 return Indices;
2492 }
2493
2494 unsigned getNumIndices() const {
2495 return (unsigned)Indices.size();
2496 }
2497
2498 bool hasIndices() const {
2499 return true;
2500 }
2501
2502 // Methods for support type inquiry through isa, cast, and dyn_cast:
2503 static bool classof(const Instruction *I) {
2504 return I->getOpcode() == Instruction::InsertValue;
2505 }
2506 static bool classof(const Value *V) {
2507 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2508 }
2509};
2510
2511template <>
2512struct OperandTraits<InsertValueInst> :
2513 public FixedNumOperandTraits<InsertValueInst, 2> {
2514};
2515
2516InsertValueInst::InsertValueInst(Value *Agg,
2517 Value *Val,
2518 ArrayRef<unsigned> Idxs,
2519 const Twine &NameStr,
2520 Instruction *InsertBefore)
2521 : Instruction(Agg->getType(), InsertValue,
2522 OperandTraits<InsertValueInst>::op_begin(this),
2523 2, InsertBefore) {
2524 init(Agg, Val, Idxs, NameStr);
2525}
2526
2527InsertValueInst::InsertValueInst(Value *Agg,
2528 Value *Val,
2529 ArrayRef<unsigned> Idxs,
2530 const Twine &NameStr,
2531 BasicBlock *InsertAtEnd)
2532 : Instruction(Agg->getType(), InsertValue,
2533 OperandTraits<InsertValueInst>::op_begin(this),
2534 2, InsertAtEnd) {
2535 init(Agg, Val, Idxs, NameStr);
2536}
2537
2538DEFINE_TRANSPARENT_OPERAND_ACCESSORS(InsertValueInst, Value)InsertValueInst::op_iterator InsertValueInst::op_begin() { return
OperandTraits<InsertValueInst>::op_begin(this); } InsertValueInst
::const_op_iterator InsertValueInst::op_begin() const { return
OperandTraits<InsertValueInst>::op_begin(const_cast<
InsertValueInst*>(this)); } InsertValueInst::op_iterator InsertValueInst
::op_end() { return OperandTraits<InsertValueInst>::op_end
(this); } InsertValueInst::const_op_iterator InsertValueInst::
op_end() const { return OperandTraits<InsertValueInst>::
op_end(const_cast<InsertValueInst*>(this)); } Value *InsertValueInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<InsertValueInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2538, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<InsertValueInst>::op_begin(const_cast<
InsertValueInst*>(this))[i_nocapture].get()); } void InsertValueInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<InsertValueInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<InsertValueInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2538, __PRETTY_FUNCTION__)); OperandTraits<InsertValueInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
InsertValueInst::getNumOperands() const { return OperandTraits
<InsertValueInst>::operands(this); } template <int Idx_nocapture
> Use &InsertValueInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &InsertValueInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
2539
2540//===----------------------------------------------------------------------===//
2541// PHINode Class
2542//===----------------------------------------------------------------------===//
2543
2544// PHINode - The PHINode class is used to represent the magical mystical PHI
2545// node, that can not exist in nature, but can be synthesized in a computer
2546// scientist's overactive imagination.
2547//
2548class PHINode : public Instruction {
2549 /// The number of operands actually allocated. NumOperands is
2550 /// the number actually in use.
2551 unsigned ReservedSpace;
2552
2553 PHINode(const PHINode &PN);
2554
2555 explicit PHINode(Type *Ty, unsigned NumReservedValues,
2556 const Twine &NameStr = "",
2557 Instruction *InsertBefore = nullptr)
2558 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertBefore),
2559 ReservedSpace(NumReservedValues) {
2560 setName(NameStr);
2561 allocHungoffUses(ReservedSpace);
2562 }
2563
2564 PHINode(Type *Ty, unsigned NumReservedValues, const Twine &NameStr,
2565 BasicBlock *InsertAtEnd)
2566 : Instruction(Ty, Instruction::PHI, nullptr, 0, InsertAtEnd),
2567 ReservedSpace(NumReservedValues) {
2568 setName(NameStr);
2569 allocHungoffUses(ReservedSpace);
2570 }
2571
2572protected:
2573 // Note: Instruction needs to be a friend here to call cloneImpl.
2574 friend class Instruction;
2575
2576 PHINode *cloneImpl() const;
2577
2578 // allocHungoffUses - this is more complicated than the generic
2579 // User::allocHungoffUses, because we have to allocate Uses for the incoming
2580 // values and pointers to the incoming blocks, all in one allocation.
2581 void allocHungoffUses(unsigned N) {
2582 User::allocHungoffUses(N, /* IsPhi */ true);
2583 }
2584
2585public:
2586 /// Constructors - NumReservedValues is a hint for the number of incoming
2587 /// edges that this phi node will have (use 0 if you really have no idea).
2588 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2589 const Twine &NameStr = "",
2590 Instruction *InsertBefore = nullptr) {
2591 return new PHINode(Ty, NumReservedValues, NameStr, InsertBefore);
2592 }
2593
2594 static PHINode *Create(Type *Ty, unsigned NumReservedValues,
2595 const Twine &NameStr, BasicBlock *InsertAtEnd) {
2596 return new PHINode(Ty, NumReservedValues, NameStr, InsertAtEnd);
2597 }
2598
2599 /// Provide fast operand accessors
2600 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
;
2601
2602 // Block iterator interface. This provides access to the list of incoming
2603 // basic blocks, which parallels the list of incoming values.
2604
2605 using block_iterator = BasicBlock **;
2606 using const_block_iterator = BasicBlock * const *;
2607
2608 block_iterator block_begin() {
2609 Use::UserRef *ref =
2610 reinterpret_cast<Use::UserRef*>(op_begin() + ReservedSpace);
2611 return reinterpret_cast<block_iterator>(ref + 1);
2612 }
2613
2614 const_block_iterator block_begin() const {
2615 const Use::UserRef *ref =
2616 reinterpret_cast<const Use::UserRef*>(op_begin() + ReservedSpace);
2617 return reinterpret_cast<const_block_iterator>(ref + 1);
2618 }
2619
2620 block_iterator block_end() {
2621 return block_begin() + getNumOperands();
2622 }
2623
2624 const_block_iterator block_end() const {
2625 return block_begin() + getNumOperands();
2626 }
2627
2628 iterator_range<block_iterator> blocks() {
2629 return make_range(block_begin(), block_end());
2630 }
2631
2632 iterator_range<const_block_iterator> blocks() const {
2633 return make_range(block_begin(), block_end());
2634 }
2635
2636 op_range incoming_values() { return operands(); }
2637
2638 const_op_range incoming_values() const { return operands(); }
2639
2640 /// Return the number of incoming edges
2641 ///
2642 unsigned getNumIncomingValues() const { return getNumOperands(); }
2643
2644 /// Return incoming value number x
2645 ///
2646 Value *getIncomingValue(unsigned i) const {
2647 return getOperand(i);
2648 }
2649 void setIncomingValue(unsigned i, Value *V) {
2650 assert(V && "PHI node got a null value!")((V && "PHI node got a null value!") ? static_cast<
void> (0) : __assert_fail ("V && \"PHI node got a null value!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2650, __PRETTY_FUNCTION__))
;
2651 assert(getType() == V->getType() &&((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!"
) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2652, __PRETTY_FUNCTION__))
2652 "All operands to PHI node must be the same type as the PHI node!")((getType() == V->getType() && "All operands to PHI node must be the same type as the PHI node!"
) ? static_cast<void> (0) : __assert_fail ("getType() == V->getType() && \"All operands to PHI node must be the same type as the PHI node!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2652, __PRETTY_FUNCTION__))
;
2653 setOperand(i, V);
2654 }
2655
2656 static unsigned getOperandNumForIncomingValue(unsigned i) {
2657 return i;
2658 }
2659
2660 static unsigned getIncomingValueNumForOperand(unsigned i) {
2661 return i;
2662 }
2663
2664 /// Return incoming basic block number @p i.
2665 ///
2666 BasicBlock *getIncomingBlock(unsigned i) const {
2667 return block_begin()[i];
2668 }
2669
2670 /// Return incoming basic block corresponding
2671 /// to an operand of the PHI.
2672 ///
2673 BasicBlock *getIncomingBlock(const Use &U) const {
2674 assert(this == U.getUser() && "Iterator doesn't point to PHI's Uses?")((this == U.getUser() && "Iterator doesn't point to PHI's Uses?"
) ? static_cast<void> (0) : __assert_fail ("this == U.getUser() && \"Iterator doesn't point to PHI's Uses?\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2674, __PRETTY_FUNCTION__))
;
2675 return getIncomingBlock(unsigned(&U - op_begin()));
2676 }
2677
2678 /// Return incoming basic block corresponding
2679 /// to value use iterator.
2680 ///
2681 BasicBlock *getIncomingBlock(Value::const_user_iterator I) const {
2682 return getIncomingBlock(I.getUse());
2683 }
2684
2685 void setIncomingBlock(unsigned i, BasicBlock *BB) {
2686 assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast
<void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2686, __PRETTY_FUNCTION__))
;
2687 block_begin()[i] = BB;
2688 }
2689
2690 /// Replace every incoming basic block \p Old to basic block \p New.
2691 void replaceIncomingBlockWith(const BasicBlock *Old, BasicBlock *New) {
2692 assert(New && Old && "PHI node got a null basic block!")((New && Old && "PHI node got a null basic block!"
) ? static_cast<void> (0) : __assert_fail ("New && Old && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2692, __PRETTY_FUNCTION__))
;
2693 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2694 if (getIncomingBlock(Op) == Old)
2695 setIncomingBlock(Op, New);
2696 }
2697
2698 /// Add an incoming value to the end of the PHI list
2699 ///
2700 void addIncoming(Value *V, BasicBlock *BB) {
2701 if (getNumOperands() == ReservedSpace)
2702 growOperands(); // Get more space!
2703 // Initialize some new operands.
2704 setNumHungOffUseOperands(getNumOperands() + 1);
2705 setIncomingValue(getNumOperands() - 1, V);
2706 setIncomingBlock(getNumOperands() - 1, BB);
2707 }
2708
2709 /// Remove an incoming value. This is useful if a
2710 /// predecessor basic block is deleted. The value removed is returned.
2711 ///
2712 /// If the last incoming value for a PHI node is removed (and DeletePHIIfEmpty
2713 /// is true), the PHI node is destroyed and any uses of it are replaced with
2714 /// dummy values. The only time there should be zero incoming values to a PHI
2715 /// node is when the block is dead, so this strategy is sound.
2716 ///
2717 Value *removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty = true);
2718
2719 Value *removeIncomingValue(const BasicBlock *BB, bool DeletePHIIfEmpty=true) {
2720 int Idx = getBasicBlockIndex(BB);
2721 assert(Idx >= 0 && "Invalid basic block argument to remove!")((Idx >= 0 && "Invalid basic block argument to remove!"
) ? static_cast<void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument to remove!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2721, __PRETTY_FUNCTION__))
;
2722 return removeIncomingValue(Idx, DeletePHIIfEmpty);
2723 }
2724
2725 /// Return the first index of the specified basic
2726 /// block in the value list for this PHI. Returns -1 if no instance.
2727 ///
2728 int getBasicBlockIndex(const BasicBlock *BB) const {
2729 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2730 if (block_begin()[i] == BB)
2731 return i;
2732 return -1;
2733 }
2734
2735 Value *getIncomingValueForBlock(const BasicBlock *BB) const {
2736 int Idx = getBasicBlockIndex(BB);
2737 assert(Idx >= 0 && "Invalid basic block argument!")((Idx >= 0 && "Invalid basic block argument!") ? static_cast
<void> (0) : __assert_fail ("Idx >= 0 && \"Invalid basic block argument!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2737, __PRETTY_FUNCTION__))
;
2738 return getIncomingValue(Idx);
2739 }
2740
2741 /// Set every incoming value(s) for block \p BB to \p V.
2742 void setIncomingValueForBlock(const BasicBlock *BB, Value *V) {
2743 assert(BB && "PHI node got a null basic block!")((BB && "PHI node got a null basic block!") ? static_cast
<void> (0) : __assert_fail ("BB && \"PHI node got a null basic block!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2743, __PRETTY_FUNCTION__))
;
2744 bool Found = false;
2745 for (unsigned Op = 0, NumOps = getNumOperands(); Op != NumOps; ++Op)
2746 if (getIncomingBlock(Op) == BB) {
2747 Found = true;
2748 setIncomingValue(Op, V);
2749 }
2750 (void)Found;
2751 assert(Found && "Invalid basic block argument to set!")((Found && "Invalid basic block argument to set!") ? static_cast
<void> (0) : __assert_fail ("Found && \"Invalid basic block argument to set!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2751, __PRETTY_FUNCTION__))
;
2752 }
2753
2754 /// If the specified PHI node always merges together the
2755 /// same value, return the value, otherwise return null.
2756 Value *hasConstantValue() const;
2757
2758 /// Whether the specified PHI node always merges
2759 /// together the same value, assuming undefs are equal to a unique
2760 /// non-undef value.
2761 bool hasConstantOrUndefValue() const;
2762
2763 /// Methods for support type inquiry through isa, cast, and dyn_cast:
2764 static bool classof(const Instruction *I) {
2765 return I->getOpcode() == Instruction::PHI;
2766 }
2767 static bool classof(const Value *V) {
2768 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2769 }
2770
2771private:
2772 void growOperands();
2773};
2774
2775template <>
2776struct OperandTraits<PHINode> : public HungoffOperandTraits<2> {
2777};
2778
2779DEFINE_TRANSPARENT_OPERAND_ACCESSORS(PHINode, Value)PHINode::op_iterator PHINode::op_begin() { return OperandTraits
<PHINode>::op_begin(this); } PHINode::const_op_iterator
PHINode::op_begin() const { return OperandTraits<PHINode>
::op_begin(const_cast<PHINode*>(this)); } PHINode::op_iterator
PHINode::op_end() { return OperandTraits<PHINode>::op_end
(this); } PHINode::const_op_iterator PHINode::op_end() const {
return OperandTraits<PHINode>::op_end(const_cast<PHINode
*>(this)); } Value *PHINode::getOperand(unsigned i_nocapture
) const { ((i_nocapture < OperandTraits<PHINode>::operands
(this) && "getOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2779, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<PHINode>::op_begin(const_cast<PHINode
*>(this))[i_nocapture].get()); } void PHINode::setOperand(
unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<PHINode>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<PHINode>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2779, __PRETTY_FUNCTION__)); OperandTraits<PHINode>::
op_begin(this)[i_nocapture] = Val_nocapture; } unsigned PHINode
::getNumOperands() const { return OperandTraits<PHINode>
::operands(this); } template <int Idx_nocapture> Use &
PHINode::Op() { return this->OpFrom<Idx_nocapture>(this
); } template <int Idx_nocapture> const Use &PHINode
::Op() const { return this->OpFrom<Idx_nocapture>(this
); }
2780
2781//===----------------------------------------------------------------------===//
2782// LandingPadInst Class
2783//===----------------------------------------------------------------------===//
2784
2785//===---------------------------------------------------------------------------
2786/// The landingpad instruction holds all of the information
2787/// necessary to generate correct exception handling. The landingpad instruction
2788/// cannot be moved from the top of a landing pad block, which itself is
2789/// accessible only from the 'unwind' edge of an invoke. This uses the
2790/// SubclassData field in Value to store whether or not the landingpad is a
2791/// cleanup.
2792///
2793class LandingPadInst : public Instruction {
2794 /// The number of operands actually allocated. NumOperands is
2795 /// the number actually in use.
2796 unsigned ReservedSpace;
2797
2798 LandingPadInst(const LandingPadInst &LP);
2799
2800public:
2801 enum ClauseType { Catch, Filter };
2802
2803private:
2804 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2805 const Twine &NameStr, Instruction *InsertBefore);
2806 explicit LandingPadInst(Type *RetTy, unsigned NumReservedValues,
2807 const Twine &NameStr, BasicBlock *InsertAtEnd);
2808
2809 // Allocate space for exactly zero operands.
2810 void *operator new(size_t s) {
2811 return User::operator new(s);
2812 }
2813
2814 void growOperands(unsigned Size);
2815 void init(unsigned NumReservedValues, const Twine &NameStr);
2816
2817protected:
2818 // Note: Instruction needs to be a friend here to call cloneImpl.
2819 friend class Instruction;
2820
2821 LandingPadInst *cloneImpl() const;
2822
2823public:
2824 /// Constructors - NumReservedClauses is a hint for the number of incoming
2825 /// clauses that this landingpad will have (use 0 if you really have no idea).
2826 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2827 const Twine &NameStr = "",
2828 Instruction *InsertBefore = nullptr);
2829 static LandingPadInst *Create(Type *RetTy, unsigned NumReservedClauses,
2830 const Twine &NameStr, BasicBlock *InsertAtEnd);
2831
2832 /// Provide fast operand accessors
2833 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
;
2834
2835 /// Return 'true' if this landingpad instruction is a
2836 /// cleanup. I.e., it should be run when unwinding even if its landing pad
2837 /// doesn't catch the exception.
2838 bool isCleanup() const { return getSubclassDataFromInstruction() & 1; }
2839
2840 /// Indicate that this landingpad instruction is a cleanup.
2841 void setCleanup(bool V) {
2842 setInstructionSubclassData((getSubclassDataFromInstruction() & ~1) |
2843 (V ? 1 : 0));
2844 }
2845
2846 /// Add a catch or filter clause to the landing pad.
2847 void addClause(Constant *ClauseVal);
2848
2849 /// Get the value of the clause at index Idx. Use isCatch/isFilter to
2850 /// determine what type of clause this is.
2851 Constant *getClause(unsigned Idx) const {
2852 return cast<Constant>(getOperandList()[Idx]);
2853 }
2854
2855 /// Return 'true' if the clause and index Idx is a catch clause.
2856 bool isCatch(unsigned Idx) const {
2857 return !isa<ArrayType>(getOperandList()[Idx]->getType());
2858 }
2859
2860 /// Return 'true' if the clause and index Idx is a filter clause.
2861 bool isFilter(unsigned Idx) const {
2862 return isa<ArrayType>(getOperandList()[Idx]->getType());
2863 }
2864
2865 /// Get the number of clauses for this landing pad.
2866 unsigned getNumClauses() const { return getNumOperands(); }
2867
2868 /// Grow the size of the operand list to accommodate the new
2869 /// number of clauses.
2870 void reserveClauses(unsigned Size) { growOperands(Size); }
2871
2872 // Methods for support type inquiry through isa, cast, and dyn_cast:
2873 static bool classof(const Instruction *I) {
2874 return I->getOpcode() == Instruction::LandingPad;
2875 }
2876 static bool classof(const Value *V) {
2877 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2878 }
2879};
2880
2881template <>
2882struct OperandTraits<LandingPadInst> : public HungoffOperandTraits<1> {
2883};
2884
2885DEFINE_TRANSPARENT_OPERAND_ACCESSORS(LandingPadInst, Value)LandingPadInst::op_iterator LandingPadInst::op_begin() { return
OperandTraits<LandingPadInst>::op_begin(this); } LandingPadInst
::const_op_iterator LandingPadInst::op_begin() const { return
OperandTraits<LandingPadInst>::op_begin(const_cast<
LandingPadInst*>(this)); } LandingPadInst::op_iterator LandingPadInst
::op_end() { return OperandTraits<LandingPadInst>::op_end
(this); } LandingPadInst::const_op_iterator LandingPadInst::op_end
() const { return OperandTraits<LandingPadInst>::op_end
(const_cast<LandingPadInst*>(this)); } Value *LandingPadInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<LandingPadInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2885, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<LandingPadInst>::op_begin(const_cast<
LandingPadInst*>(this))[i_nocapture].get()); } void LandingPadInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<LandingPadInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<LandingPadInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2885, __PRETTY_FUNCTION__)); OperandTraits<LandingPadInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
LandingPadInst::getNumOperands() const { return OperandTraits
<LandingPadInst>::operands(this); } template <int Idx_nocapture
> Use &LandingPadInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &LandingPadInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
2886
2887//===----------------------------------------------------------------------===//
2888// ReturnInst Class
2889//===----------------------------------------------------------------------===//
2890
2891//===---------------------------------------------------------------------------
2892/// Return a value (possibly void), from a function. Execution
2893/// does not continue in this function any longer.
2894///
2895class ReturnInst : public Instruction {
2896 ReturnInst(const ReturnInst &RI);
2897
2898private:
2899 // ReturnInst constructors:
2900 // ReturnInst() - 'ret void' instruction
2901 // ReturnInst( null) - 'ret void' instruction
2902 // ReturnInst(Value* X) - 'ret X' instruction
2903 // ReturnInst( null, Inst *I) - 'ret void' instruction, insert before I
2904 // ReturnInst(Value* X, Inst *I) - 'ret X' instruction, insert before I
2905 // ReturnInst( null, BB *B) - 'ret void' instruction, insert @ end of B
2906 // ReturnInst(Value* X, BB *B) - 'ret X' instruction, insert @ end of B
2907 //
2908 // NOTE: If the Value* passed is of type void then the constructor behaves as
2909 // if it was passed NULL.
2910 explicit ReturnInst(LLVMContext &C, Value *retVal = nullptr,
2911 Instruction *InsertBefore = nullptr);
2912 ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd);
2913 explicit ReturnInst(LLVMContext &C, BasicBlock *InsertAtEnd);
2914
2915protected:
2916 // Note: Instruction needs to be a friend here to call cloneImpl.
2917 friend class Instruction;
2918
2919 ReturnInst *cloneImpl() const;
2920
2921public:
2922 static ReturnInst* Create(LLVMContext &C, Value *retVal = nullptr,
2923 Instruction *InsertBefore = nullptr) {
2924 return new(!!retVal) ReturnInst(C, retVal, InsertBefore);
2925 }
2926
2927 static ReturnInst* Create(LLVMContext &C, Value *retVal,
2928 BasicBlock *InsertAtEnd) {
2929 return new(!!retVal) ReturnInst(C, retVal, InsertAtEnd);
2930 }
2931
2932 static ReturnInst* Create(LLVMContext &C, BasicBlock *InsertAtEnd) {
2933 return new(0) ReturnInst(C, InsertAtEnd);
2934 }
2935
2936 /// Provide fast operand accessors
2937 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
;
2938
2939 /// Convenience accessor. Returns null if there is no return value.
2940 Value *getReturnValue() const {
2941 return getNumOperands() != 0 ? getOperand(0) : nullptr;
2942 }
2943
2944 unsigned getNumSuccessors() const { return 0; }
2945
2946 // Methods for support type inquiry through isa, cast, and dyn_cast:
2947 static bool classof(const Instruction *I) {
2948 return (I->getOpcode() == Instruction::Ret);
2949 }
2950 static bool classof(const Value *V) {
2951 return isa<Instruction>(V) && classof(cast<Instruction>(V));
2952 }
2953
2954private:
2955 BasicBlock *getSuccessor(unsigned idx) const {
2956 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2956)
;
2957 }
2958
2959 void setSuccessor(unsigned idx, BasicBlock *B) {
2960 llvm_unreachable("ReturnInst has no successors!")::llvm::llvm_unreachable_internal("ReturnInst has no successors!"
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2960)
;
2961 }
2962};
2963
2964template <>
2965struct OperandTraits<ReturnInst> : public VariadicOperandTraits<ReturnInst> {
2966};
2967
2968DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ReturnInst, Value)ReturnInst::op_iterator ReturnInst::op_begin() { return OperandTraits
<ReturnInst>::op_begin(this); } ReturnInst::const_op_iterator
ReturnInst::op_begin() const { return OperandTraits<ReturnInst
>::op_begin(const_cast<ReturnInst*>(this)); } ReturnInst
::op_iterator ReturnInst::op_end() { return OperandTraits<
ReturnInst>::op_end(this); } ReturnInst::const_op_iterator
ReturnInst::op_end() const { return OperandTraits<ReturnInst
>::op_end(const_cast<ReturnInst*>(this)); } Value *ReturnInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<ReturnInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2968, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ReturnInst>::op_begin(const_cast<ReturnInst
*>(this))[i_nocapture].get()); } void ReturnInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<ReturnInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ReturnInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 2968, __PRETTY_FUNCTION__)); OperandTraits<ReturnInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ReturnInst
::getNumOperands() const { return OperandTraits<ReturnInst
>::operands(this); } template <int Idx_nocapture> Use
&ReturnInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
ReturnInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
2969
2970//===----------------------------------------------------------------------===//
2971// BranchInst Class
2972//===----------------------------------------------------------------------===//
2973
2974//===---------------------------------------------------------------------------
2975/// Conditional or Unconditional Branch instruction.
2976///
2977class BranchInst : public Instruction {
2978 /// Ops list - Branches are strange. The operands are ordered:
2979 /// [Cond, FalseDest,] TrueDest. This makes some accessors faster because
2980 /// they don't have to check for cond/uncond branchness. These are mostly
2981 /// accessed relative from op_end().
2982 BranchInst(const BranchInst &BI);
2983 // BranchInst constructors (where {B, T, F} are blocks, and C is a condition):
2984 // BranchInst(BB *B) - 'br B'
2985 // BranchInst(BB* T, BB *F, Value *C) - 'br C, T, F'
2986 // BranchInst(BB* B, Inst *I) - 'br B' insert before I
2987 // BranchInst(BB* T, BB *F, Value *C, Inst *I) - 'br C, T, F', insert before I
2988 // BranchInst(BB* B, BB *I) - 'br B' insert at end
2989 // BranchInst(BB* T, BB *F, Value *C, BB *I) - 'br C, T, F', insert at end
2990 explicit BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore = nullptr);
2991 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2992 Instruction *InsertBefore = nullptr);
2993 BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd);
2994 BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
2995 BasicBlock *InsertAtEnd);
2996
2997 void AssertOK();
2998
2999protected:
3000 // Note: Instruction needs to be a friend here to call cloneImpl.
3001 friend class Instruction;
3002
3003 BranchInst *cloneImpl() const;
3004
3005public:
3006 /// Iterator type that casts an operand to a basic block.
3007 ///
3008 /// This only makes sense because the successors are stored as adjacent
3009 /// operands for branch instructions.
3010 struct succ_op_iterator
3011 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3012 std::random_access_iterator_tag, BasicBlock *,
3013 ptrdiff_t, BasicBlock *, BasicBlock *> {
3014 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3015
3016 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3017 BasicBlock *operator->() const { return operator*(); }
3018 };
3019
3020 /// The const version of `succ_op_iterator`.
3021 struct const_succ_op_iterator
3022 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3023 std::random_access_iterator_tag,
3024 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3025 const BasicBlock *> {
3026 explicit const_succ_op_iterator(const_value_op_iterator I)
3027 : iterator_adaptor_base(I) {}
3028
3029 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3030 const BasicBlock *operator->() const { return operator*(); }
3031 };
3032
3033 static BranchInst *Create(BasicBlock *IfTrue,
3034 Instruction *InsertBefore = nullptr) {
3035 return new(1) BranchInst(IfTrue, InsertBefore);
3036 }
3037
3038 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3039 Value *Cond, Instruction *InsertBefore = nullptr) {
3040 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertBefore);
3041 }
3042
3043 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *InsertAtEnd) {
3044 return new(1) BranchInst(IfTrue, InsertAtEnd);
3045 }
3046
3047 static BranchInst *Create(BasicBlock *IfTrue, BasicBlock *IfFalse,
3048 Value *Cond, BasicBlock *InsertAtEnd) {
3049 return new(3) BranchInst(IfTrue, IfFalse, Cond, InsertAtEnd);
3050 }
3051
3052 /// Transparently provide more efficient getOperand methods.
3053 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
;
3054
3055 bool isUnconditional() const { return getNumOperands() == 1; }
3056 bool isConditional() const { return getNumOperands() == 3; }
14
Assuming the condition is true
15
Returning the value 1, which participates in a condition later
3057
3058 Value *getCondition() const {
3059 assert(isConditional() && "Cannot get condition of an uncond branch!")((isConditional() && "Cannot get condition of an uncond branch!"
) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot get condition of an uncond branch!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3059, __PRETTY_FUNCTION__))
;
3060 return Op<-3>();
3061 }
3062
3063 void setCondition(Value *V) {
3064 assert(isConditional() && "Cannot set condition of unconditional branch!")((isConditional() && "Cannot set condition of unconditional branch!"
) ? static_cast<void> (0) : __assert_fail ("isConditional() && \"Cannot set condition of unconditional branch!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3064, __PRETTY_FUNCTION__))
;
3065 Op<-3>() = V;
3066 }
3067
3068 unsigned getNumSuccessors() const { return 1+isConditional(); }
3069
3070 BasicBlock *getSuccessor(unsigned i) const {
3071 assert(i < getNumSuccessors() && "Successor # out of range for Branch!")((i < getNumSuccessors() && "Successor # out of range for Branch!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3071, __PRETTY_FUNCTION__))
;
3072 return cast_or_null<BasicBlock>((&Op<-1>() - i)->get());
3073 }
3074
3075 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3076 assert(idx < getNumSuccessors() && "Successor # out of range for Branch!")((idx < getNumSuccessors() && "Successor # out of range for Branch!"
) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for Branch!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3076, __PRETTY_FUNCTION__))
;
3077 *(&Op<-1>() - idx) = NewSucc;
3078 }
3079
3080 /// Swap the successors of this branch instruction.
3081 ///
3082 /// Swaps the successors of the branch instruction. This also swaps any
3083 /// branch weight metadata associated with the instruction so that it
3084 /// continues to map correctly to each operand.
3085 void swapSuccessors();
3086
3087 iterator_range<succ_op_iterator> successors() {
3088 return make_range(
3089 succ_op_iterator(std::next(value_op_begin(), isConditional() ? 1 : 0)),
3090 succ_op_iterator(value_op_end()));
3091 }
3092
3093 iterator_range<const_succ_op_iterator> successors() const {
3094 return make_range(const_succ_op_iterator(
3095 std::next(value_op_begin(), isConditional() ? 1 : 0)),
3096 const_succ_op_iterator(value_op_end()));
3097 }
3098
3099 // Methods for support type inquiry through isa, cast, and dyn_cast:
3100 static bool classof(const Instruction *I) {
3101 return (I->getOpcode() == Instruction::Br);
3102 }
3103 static bool classof(const Value *V) {
3104 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3105 }
3106};
3107
3108template <>
3109struct OperandTraits<BranchInst> : public VariadicOperandTraits<BranchInst, 1> {
3110};
3111
3112DEFINE_TRANSPARENT_OPERAND_ACCESSORS(BranchInst, Value)BranchInst::op_iterator BranchInst::op_begin() { return OperandTraits
<BranchInst>::op_begin(this); } BranchInst::const_op_iterator
BranchInst::op_begin() const { return OperandTraits<BranchInst
>::op_begin(const_cast<BranchInst*>(this)); } BranchInst
::op_iterator BranchInst::op_end() { return OperandTraits<
BranchInst>::op_end(this); } BranchInst::const_op_iterator
BranchInst::op_end() const { return OperandTraits<BranchInst
>::op_end(const_cast<BranchInst*>(this)); } Value *BranchInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<BranchInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3112, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<BranchInst>::op_begin(const_cast<BranchInst
*>(this))[i_nocapture].get()); } void BranchInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<BranchInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<BranchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3112, __PRETTY_FUNCTION__)); OperandTraits<BranchInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned BranchInst
::getNumOperands() const { return OperandTraits<BranchInst
>::operands(this); } template <int Idx_nocapture> Use
&BranchInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
BranchInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
3113
3114//===----------------------------------------------------------------------===//
3115// SwitchInst Class
3116//===----------------------------------------------------------------------===//
3117
3118//===---------------------------------------------------------------------------
3119/// Multiway switch
3120///
3121class SwitchInst : public Instruction {
3122 unsigned ReservedSpace;
3123
3124 // Operand[0] = Value to switch on
3125 // Operand[1] = Default basic block destination
3126 // Operand[2n ] = Value to match
3127 // Operand[2n+1] = BasicBlock to go to on match
3128 SwitchInst(const SwitchInst &SI);
3129
3130 /// Create a new switch instruction, specifying a value to switch on and a
3131 /// default destination. The number of additional cases can be specified here
3132 /// to make memory allocation more efficient. This constructor can also
3133 /// auto-insert before another instruction.
3134 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3135 Instruction *InsertBefore);
3136
3137 /// Create a new switch instruction, specifying a value to switch on and a
3138 /// default destination. The number of additional cases can be specified here
3139 /// to make memory allocation more efficient. This constructor also
3140 /// auto-inserts at the end of the specified BasicBlock.
3141 SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3142 BasicBlock *InsertAtEnd);
3143
3144 // allocate space for exactly zero operands
3145 void *operator new(size_t s) {
3146 return User::operator new(s);
3147 }
3148
3149 void init(Value *Value, BasicBlock *Default, unsigned NumReserved);
3150 void growOperands();
3151
3152protected:
3153 // Note: Instruction needs to be a friend here to call cloneImpl.
3154 friend class Instruction;
3155
3156 SwitchInst *cloneImpl() const;
3157
3158public:
3159 // -2
3160 static const unsigned DefaultPseudoIndex = static_cast<unsigned>(~0L-1);
3161
3162 template <typename CaseHandleT> class CaseIteratorImpl;
3163
3164 /// A handle to a particular switch case. It exposes a convenient interface
3165 /// to both the case value and the successor block.
3166 ///
3167 /// We define this as a template and instantiate it to form both a const and
3168 /// non-const handle.
3169 template <typename SwitchInstT, typename ConstantIntT, typename BasicBlockT>
3170 class CaseHandleImpl {
3171 // Directly befriend both const and non-const iterators.
3172 friend class SwitchInst::CaseIteratorImpl<
3173 CaseHandleImpl<SwitchInstT, ConstantIntT, BasicBlockT>>;
3174
3175 protected:
3176 // Expose the switch type we're parameterized with to the iterator.
3177 using SwitchInstType = SwitchInstT;
3178
3179 SwitchInstT *SI;
3180 ptrdiff_t Index;
3181
3182 CaseHandleImpl() = default;
3183 CaseHandleImpl(SwitchInstT *SI, ptrdiff_t Index) : SI(SI), Index(Index) {}
3184
3185 public:
3186 /// Resolves case value for current case.
3187 ConstantIntT *getCaseValue() const {
3188 assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3189, __PRETTY_FUNCTION__))
3189 "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3189, __PRETTY_FUNCTION__))
;
3190 return reinterpret_cast<ConstantIntT *>(SI->getOperand(2 + Index * 2));
3191 }
3192
3193 /// Resolves successor for current case.
3194 BasicBlockT *getCaseSuccessor() const {
3195 assert(((unsigned)Index < SI->getNumCases() ||((((unsigned)Index < SI->getNumCases() || (unsigned)Index
== DefaultPseudoIndex) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3197, __PRETTY_FUNCTION__))
3196 (unsigned)Index == DefaultPseudoIndex) &&((((unsigned)Index < SI->getNumCases() || (unsigned)Index
== DefaultPseudoIndex) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3197, __PRETTY_FUNCTION__))
3197 "Index out the number of cases.")((((unsigned)Index < SI->getNumCases() || (unsigned)Index
== DefaultPseudoIndex) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index < SI->getNumCases() || (unsigned)Index == DefaultPseudoIndex) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3197, __PRETTY_FUNCTION__))
;
3198 return SI->getSuccessor(getSuccessorIndex());
3199 }
3200
3201 /// Returns number of current case.
3202 unsigned getCaseIndex() const { return Index; }
3203
3204 /// Returns successor index for current case successor.
3205 unsigned getSuccessorIndex() const {
3206 assert(((unsigned)Index == DefaultPseudoIndex ||((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index <
SI->getNumCases()) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3208, __PRETTY_FUNCTION__))
3207 (unsigned)Index < SI->getNumCases()) &&((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index <
SI->getNumCases()) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3208, __PRETTY_FUNCTION__))
3208 "Index out the number of cases.")((((unsigned)Index == DefaultPseudoIndex || (unsigned)Index <
SI->getNumCases()) && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("((unsigned)Index == DefaultPseudoIndex || (unsigned)Index < SI->getNumCases()) && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3208, __PRETTY_FUNCTION__))
;
3209 return (unsigned)Index != DefaultPseudoIndex ? Index + 1 : 0;
3210 }
3211
3212 bool operator==(const CaseHandleImpl &RHS) const {
3213 assert(SI == RHS.SI && "Incompatible operators.")((SI == RHS.SI && "Incompatible operators.") ? static_cast
<void> (0) : __assert_fail ("SI == RHS.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3213, __PRETTY_FUNCTION__))
;
3214 return Index == RHS.Index;
3215 }
3216 };
3217
3218 using ConstCaseHandle =
3219 CaseHandleImpl<const SwitchInst, const ConstantInt, const BasicBlock>;
3220
3221 class CaseHandle
3222 : public CaseHandleImpl<SwitchInst, ConstantInt, BasicBlock> {
3223 friend class SwitchInst::CaseIteratorImpl<CaseHandle>;
3224
3225 public:
3226 CaseHandle(SwitchInst *SI, ptrdiff_t Index) : CaseHandleImpl(SI, Index) {}
3227
3228 /// Sets the new value for current case.
3229 void setValue(ConstantInt *V) {
3230 assert((unsigned)Index < SI->getNumCases() &&(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3231, __PRETTY_FUNCTION__))
3231 "Index out the number of cases.")(((unsigned)Index < SI->getNumCases() && "Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("(unsigned)Index < SI->getNumCases() && \"Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3231, __PRETTY_FUNCTION__))
;
3232 SI->setOperand(2 + Index*2, reinterpret_cast<Value*>(V));
3233 }
3234
3235 /// Sets the new successor for current case.
3236 void setSuccessor(BasicBlock *S) {
3237 SI->setSuccessor(getSuccessorIndex(), S);
3238 }
3239 };
3240
3241 template <typename CaseHandleT>
3242 class CaseIteratorImpl
3243 : public iterator_facade_base<CaseIteratorImpl<CaseHandleT>,
3244 std::random_access_iterator_tag,
3245 CaseHandleT> {
3246 using SwitchInstT = typename CaseHandleT::SwitchInstType;
3247
3248 CaseHandleT Case;
3249
3250 public:
3251 /// Default constructed iterator is in an invalid state until assigned to
3252 /// a case for a particular switch.
3253 CaseIteratorImpl() = default;
3254
3255 /// Initializes case iterator for given SwitchInst and for given
3256 /// case number.
3257 CaseIteratorImpl(SwitchInstT *SI, unsigned CaseNum) : Case(SI, CaseNum) {}
3258
3259 /// Initializes case iterator for given SwitchInst and for given
3260 /// successor index.
3261 static CaseIteratorImpl fromSuccessorIndex(SwitchInstT *SI,
3262 unsigned SuccessorIndex) {
3263 assert(SuccessorIndex < SI->getNumSuccessors() &&((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!"
) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3264, __PRETTY_FUNCTION__))
3264 "Successor index # out of range!")((SuccessorIndex < SI->getNumSuccessors() && "Successor index # out of range!"
) ? static_cast<void> (0) : __assert_fail ("SuccessorIndex < SI->getNumSuccessors() && \"Successor index # out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3264, __PRETTY_FUNCTION__))
;
3265 return SuccessorIndex != 0 ? CaseIteratorImpl(SI, SuccessorIndex - 1)
3266 : CaseIteratorImpl(SI, DefaultPseudoIndex);
3267 }
3268
3269 /// Support converting to the const variant. This will be a no-op for const
3270 /// variant.
3271 operator CaseIteratorImpl<ConstCaseHandle>() const {
3272 return CaseIteratorImpl<ConstCaseHandle>(Case.SI, Case.Index);
3273 }
3274
3275 CaseIteratorImpl &operator+=(ptrdiff_t N) {
3276 // Check index correctness after addition.
3277 // Note: Index == getNumCases() means end().
3278 assert(Case.Index + N >= 0 &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3280, __PRETTY_FUNCTION__))
3279 (unsigned)(Case.Index + N) <= Case.SI->getNumCases() &&((Case.Index + N >= 0 && (unsigned)(Case.Index + N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3280, __PRETTY_FUNCTION__))
3280 "Case.Index out the number of cases.")((Case.Index + N >= 0 && (unsigned)(Case.Index + N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index + N >= 0 && (unsigned)(Case.Index + N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3280, __PRETTY_FUNCTION__))
;
3281 Case.Index += N;
3282 return *this;
3283 }
3284 CaseIteratorImpl &operator-=(ptrdiff_t N) {
3285 // Check index correctness after subtraction.
3286 // Note: Case.Index == getNumCases() means end().
3287 assert(Case.Index - N >= 0 &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3289, __PRETTY_FUNCTION__))
3288 (unsigned)(Case.Index - N) <= Case.SI->getNumCases() &&((Case.Index - N >= 0 && (unsigned)(Case.Index - N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3289, __PRETTY_FUNCTION__))
3289 "Case.Index out the number of cases.")((Case.Index - N >= 0 && (unsigned)(Case.Index - N
) <= Case.SI->getNumCases() && "Case.Index out the number of cases."
) ? static_cast<void> (0) : __assert_fail ("Case.Index - N >= 0 && (unsigned)(Case.Index - N) <= Case.SI->getNumCases() && \"Case.Index out the number of cases.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3289, __PRETTY_FUNCTION__))
;
3290 Case.Index -= N;
3291 return *this;
3292 }
3293 ptrdiff_t operator-(const CaseIteratorImpl &RHS) const {
3294 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators."
) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3294, __PRETTY_FUNCTION__))
;
3295 return Case.Index - RHS.Case.Index;
3296 }
3297 bool operator==(const CaseIteratorImpl &RHS) const {
3298 return Case == RHS.Case;
3299 }
3300 bool operator<(const CaseIteratorImpl &RHS) const {
3301 assert(Case.SI == RHS.Case.SI && "Incompatible operators.")((Case.SI == RHS.Case.SI && "Incompatible operators."
) ? static_cast<void> (0) : __assert_fail ("Case.SI == RHS.Case.SI && \"Incompatible operators.\""
, "/build/llvm-toolchain-snapshot-10~svn374814/include/llvm/IR/Instructions.h"
, 3301, __PRETTY_FUNCTION__))
;
3302 return Case.Index < RHS.Case.Index;
3303 }
3304 CaseHandleT &operator*() { return Case; }
3305 const CaseHandleT &operator*() const { return Case; }
3306 };
3307
3308 using CaseIt = CaseIteratorImpl<CaseHandle>;
3309 using ConstCaseIt = CaseIteratorImpl<ConstCaseHandle>;
3310
3311 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3312 unsigned NumCases,
3313 Instruction *InsertBefore = nullptr) {
3314 return new SwitchInst(Value, Default, NumCases, InsertBefore);
3315 }
3316
3317 static SwitchInst *Create(Value *Value, BasicBlock *Default,
3318 unsigned NumCases, BasicBlock *InsertAtEnd) {
3319 return new SwitchInst(Value, Default, NumCases, InsertAtEnd);
3320 }
3321
3322 /// Provide fast operand accessors
3323 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
;
3324
3325 // Accessor Methods for Switch stmt
3326 Value *getCondition() const { return getOperand(0); }
3327 void setCondition(Value *V) { setOperand(0, V); }
3328
3329 BasicBlock *getDefaultDest() const {
3330 return cast<BasicBlock>(getOperand(1));
3331 }
3332
3333 void setDefaultDest(BasicBlock *DefaultCase) {
3334 setOperand(1, reinterpret_cast<Value*>(DefaultCase));
3335 }
3336
3337 /// Return the number of 'cases' in this switch instruction, excluding the
3338 /// default case.
3339 unsigned getNumCases() const {
3340 return getNumOperands()/2 - 1;
3341 }
3342
3343 /// Returns a read/write iterator that points to the first case in the
3344 /// SwitchInst.
3345 CaseIt case_begin() {
3346 return CaseIt(this, 0);
3347 }
3348
3349 /// Returns a read-only iterator that points to the first case in the
3350 /// SwitchInst.
3351 ConstCaseIt case_begin() const {
3352 return ConstCaseIt(this, 0);
3353 }
3354
3355 /// Returns a read/write iterator that points one past the last in the
3356 /// SwitchInst.
3357 CaseIt case_end() {
3358 return CaseIt(this, getNumCases());
3359 }
3360
3361 /// Returns a read-only iterator that points one past the last in the
3362 /// SwitchInst.
3363 ConstCaseIt case_end() const {
3364 return ConstCaseIt(this, getNumCases());
3365 }
3366
3367 /// Iteration adapter for range-for loops.
3368 iterator_range<CaseIt> cases() {
3369 return make_range(case_begin(), case_end());
3370 }
3371
3372 /// Constant iteration adapter for range-for loops.
3373 iterator_range<ConstCaseIt> cases() const {
3374 return make_range(case_begin(), case_end());
3375 }
3376
3377 /// Returns an iterator that points to the default case.
3378 /// Note: this iterator allows to resolve successor only. Attempt
3379 /// to resolve case value causes an assertion.
3380 /// Also note, that increment and decrement also causes an assertion and
3381 /// makes iterator invalid.
3382 CaseIt case_default() {
3383 return CaseIt(this, DefaultPseudoIndex);
3384 }
3385 ConstCaseIt case_default() const {
3386 return ConstCaseIt(this, DefaultPseudoIndex);
3387 }
3388
3389 /// Search all of the case values for the specified constant. If it is
3390 /// explicitly handled, return the case iterator of it, otherwise return
3391 /// default case iterator to indicate that it is handled by the default
3392 /// handler.
3393 CaseIt findCaseValue(const ConstantInt *C) {
3394 CaseIt I = llvm::find_if(
3395 cases(), [C](CaseHandle &Case) { return Case.getCaseValue() == C; });
3396 if (I != case_end())
3397 return I;
3398
3399 return case_default();
3400 }
3401 ConstCaseIt findCaseValue(const ConstantInt *C) const {
3402 ConstCaseIt I = llvm::find_if(cases(), [C](ConstCaseHandle &Case) {
3403 return Case.getCaseValue() == C;
3404 });
3405 if (I != case_end())
3406 return I;
3407
3408 return case_default();
3409 }
3410
3411 /// Finds the unique case value for a given successor. Returns null if the
3412 /// successor is not found, not unique, or is the default case.
3413 ConstantInt *findCaseDest(BasicBlock *BB) {
3414 if (BB == getDefaultDest())
3415 return nullptr;
3416
3417 ConstantInt *CI = nullptr;
3418 for (auto Case : cases()) {
3419 if (Case.getCaseSuccessor() != BB)
3420 continue;
3421
3422 if (CI)
3423 return nullptr; // Multiple cases lead to BB.
3424
3425 CI = Case.getCaseValue();
3426 }
3427
3428 return CI;
3429 }
3430