Bug Summary

File:lib/Transforms/Utils/LoopUnroll.cpp
Warning:line 538, 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 LoopUnroll.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~svn374877/build-llvm/lib/Transforms/Utils -I /build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/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~svn374877/build-llvm/lib/Transforms/Utils -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -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-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp

/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp

1//===-- UnrollLoop.cpp - Loop unrolling utilities -------------------------===//
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 implements some loop unrolling utilities. It does not define any
10// actual pass or policy, but provides a single function to perform loop
11// unrolling.
12//
13// The process of unrolling can produce extraneous basic blocks linked with
14// unconditional branches. This will be corrected in the future.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/SmallPtrSet.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/Analysis/AssumptionCache.h"
21#include "llvm/Analysis/InstructionSimplify.h"
22#include "llvm/Analysis/LoopIterator.h"
23#include "llvm/Analysis/OptimizationRemarkEmitter.h"
24#include "llvm/Analysis/ScalarEvolution.h"
25#include "llvm/Transforms/Utils/Local.h"
26#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DebugInfoMetadata.h"
29#include "llvm/IR/Dominators.h"
30#include "llvm/IR/IntrinsicInst.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/raw_ostream.h"
34#include "llvm/Transforms/Utils/BasicBlockUtils.h"
35#include "llvm/Transforms/Utils/Cloning.h"
36#include "llvm/Transforms/Utils/LoopSimplify.h"
37#include "llvm/Transforms/Utils/LoopUtils.h"
38#include "llvm/Transforms/Utils/SimplifyIndVar.h"
39#include "llvm/Transforms/Utils/UnrollLoop.h"
40using namespace llvm;
41
42#define DEBUG_TYPE"loop-unroll" "loop-unroll"
43
44// TODO: Should these be here or in LoopUnroll?
45STATISTIC(NumCompletelyUnrolled, "Number of loops completely unrolled")static llvm::Statistic NumCompletelyUnrolled = {"loop-unroll"
, "NumCompletelyUnrolled", "Number of loops completely unrolled"
}
;
46STATISTIC(NumUnrolled, "Number of loops unrolled (completely or otherwise)")static llvm::Statistic NumUnrolled = {"loop-unroll", "NumUnrolled"
, "Number of loops unrolled (completely or otherwise)"}
;
47STATISTIC(NumUnrolledWithHeader, "Number of loops unrolled without a "static llvm::Statistic NumUnrolledWithHeader = {"loop-unroll"
, "NumUnrolledWithHeader", "Number of loops unrolled without a "
"conditional latch (completely or otherwise)"}
48 "conditional latch (completely or otherwise)")static llvm::Statistic NumUnrolledWithHeader = {"loop-unroll"
, "NumUnrolledWithHeader", "Number of loops unrolled without a "
"conditional latch (completely or otherwise)"}
;
49
50static cl::opt<bool>
51UnrollRuntimeEpilog("unroll-runtime-epilog", cl::init(false), cl::Hidden,
52 cl::desc("Allow runtime unrolled loops to be unrolled "
53 "with epilog instead of prolog."));
54
55static cl::opt<bool>
56UnrollVerifyDomtree("unroll-verify-domtree", cl::Hidden,
57 cl::desc("Verify domtree after unrolling"),
58#ifdef EXPENSIVE_CHECKS
59 cl::init(true)
60#else
61 cl::init(false)
62#endif
63 );
64
65/// Convert the instruction operands from referencing the current values into
66/// those specified by VMap.
67void llvm::remapInstruction(Instruction *I, ValueToValueMapTy &VMap) {
68 for (unsigned op = 0, E = I->getNumOperands(); op != E; ++op) {
69 Value *Op = I->getOperand(op);
70
71 // Unwrap arguments of dbg.value intrinsics.
72 bool Wrapped = false;
73 if (auto *V = dyn_cast<MetadataAsValue>(Op))
74 if (auto *Unwrapped = dyn_cast<ValueAsMetadata>(V->getMetadata())) {
75 Op = Unwrapped->getValue();
76 Wrapped = true;
77 }
78
79 auto wrap = [&](Value *V) {
80 auto &C = I->getContext();
81 return Wrapped ? MetadataAsValue::get(C, ValueAsMetadata::get(V)) : V;
82 };
83
84 ValueToValueMapTy::iterator It = VMap.find(Op);
85 if (It != VMap.end())
86 I->setOperand(op, wrap(It->second));
87 }
88
89 if (PHINode *PN = dyn_cast<PHINode>(I)) {
90 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
91 ValueToValueMapTy::iterator It = VMap.find(PN->getIncomingBlock(i));
92 if (It != VMap.end())
93 PN->setIncomingBlock(i, cast<BasicBlock>(It->second));
94 }
95 }
96}
97
98/// Check if unrolling created a situation where we need to insert phi nodes to
99/// preserve LCSSA form.
100/// \param Blocks is a vector of basic blocks representing unrolled loop.
101/// \param L is the outer loop.
102/// It's possible that some of the blocks are in L, and some are not. In this
103/// case, if there is a use is outside L, and definition is inside L, we need to
104/// insert a phi-node, otherwise LCSSA will be broken.
105/// The function is just a helper function for llvm::UnrollLoop that returns
106/// true if this situation occurs, indicating that LCSSA needs to be fixed.
107static bool needToInsertPhisForLCSSA(Loop *L, std::vector<BasicBlock *> Blocks,
108 LoopInfo *LI) {
109 for (BasicBlock *BB : Blocks) {
110 if (LI->getLoopFor(BB) == L)
111 continue;
112 for (Instruction &I : *BB) {
113 for (Use &U : I.operands()) {
114 if (auto Def = dyn_cast<Instruction>(U)) {
115 Loop *DefLoop = LI->getLoopFor(Def->getParent());
116 if (!DefLoop)
117 continue;
118 if (DefLoop->contains(L))
119 return true;
120 }
121 }
122 }
123 }
124 return false;
125}
126
127/// Adds ClonedBB to LoopInfo, creates a new loop for ClonedBB if necessary
128/// and adds a mapping from the original loop to the new loop to NewLoops.
129/// Returns nullptr if no new loop was created and a pointer to the
130/// original loop OriginalBB was part of otherwise.
131const Loop* llvm::addClonedBlockToLoopInfo(BasicBlock *OriginalBB,
132 BasicBlock *ClonedBB, LoopInfo *LI,
133 NewLoopsMap &NewLoops) {
134 // Figure out which loop New is in.
135 const Loop *OldLoop = LI->getLoopFor(OriginalBB);
136 assert(OldLoop && "Should (at least) be in the loop being unrolled!")((OldLoop && "Should (at least) be in the loop being unrolled!"
) ? static_cast<void> (0) : __assert_fail ("OldLoop && \"Should (at least) be in the loop being unrolled!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 136, __PRETTY_FUNCTION__))
;
137
138 Loop *&NewLoop = NewLoops[OldLoop];
139 if (!NewLoop) {
140 // Found a new sub-loop.
141 assert(OriginalBB == OldLoop->getHeader() &&((OriginalBB == OldLoop->getHeader() && "Header should be first in RPO"
) ? static_cast<void> (0) : __assert_fail ("OriginalBB == OldLoop->getHeader() && \"Header should be first in RPO\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 142, __PRETTY_FUNCTION__))
142 "Header should be first in RPO")((OriginalBB == OldLoop->getHeader() && "Header should be first in RPO"
) ? static_cast<void> (0) : __assert_fail ("OriginalBB == OldLoop->getHeader() && \"Header should be first in RPO\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 142, __PRETTY_FUNCTION__))
;
143
144 NewLoop = LI->AllocateLoop();
145 Loop *NewLoopParent = NewLoops.lookup(OldLoop->getParentLoop());
146
147 if (NewLoopParent)
148 NewLoopParent->addChildLoop(NewLoop);
149 else
150 LI->addTopLevelLoop(NewLoop);
151
152 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
153 return OldLoop;
154 } else {
155 NewLoop->addBasicBlockToLoop(ClonedBB, *LI);
156 return nullptr;
157 }
158}
159
160/// The function chooses which type of unroll (epilog or prolog) is more
161/// profitabale.
162/// Epilog unroll is more profitable when there is PHI that starts from
163/// constant. In this case epilog will leave PHI start from constant,
164/// but prolog will convert it to non-constant.
165///
166/// loop:
167/// PN = PHI [I, Latch], [CI, PreHeader]
168/// I = foo(PN)
169/// ...
170///
171/// Epilog unroll case.
172/// loop:
173/// PN = PHI [I2, Latch], [CI, PreHeader]
174/// I1 = foo(PN)
175/// I2 = foo(I1)
176/// ...
177/// Prolog unroll case.
178/// NewPN = PHI [PrologI, Prolog], [CI, PreHeader]
179/// loop:
180/// PN = PHI [I2, Latch], [NewPN, PreHeader]
181/// I1 = foo(PN)
182/// I2 = foo(I1)
183/// ...
184///
185static bool isEpilogProfitable(Loop *L) {
186 BasicBlock *PreHeader = L->getLoopPreheader();
187 BasicBlock *Header = L->getHeader();
188 assert(PreHeader && Header)((PreHeader && Header) ? static_cast<void> (0) :
__assert_fail ("PreHeader && Header", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 188, __PRETTY_FUNCTION__))
;
189 for (const PHINode &PN : Header->phis()) {
190 if (isa<ConstantInt>(PN.getIncomingValueForBlock(PreHeader)))
191 return true;
192 }
193 return false;
194}
195
196/// Perform some cleanup and simplifications on loops after unrolling. It is
197/// useful to simplify the IV's in the new loop, as well as do a quick
198/// simplify/dce pass of the instructions.
199void llvm::simplifyLoopAfterUnroll(Loop *L, bool SimplifyIVs, LoopInfo *LI,
200 ScalarEvolution *SE, DominatorTree *DT,
201 AssumptionCache *AC) {
202 // Simplify any new induction variables in the partially unrolled loop.
203 if (SE && SimplifyIVs) {
204 SmallVector<WeakTrackingVH, 16> DeadInsts;
205 simplifyLoopIVs(L, SE, DT, LI, DeadInsts);
206
207 // Aggressively clean up dead instructions that simplifyLoopIVs already
208 // identified. Any remaining should be cleaned up below.
209 while (!DeadInsts.empty())
210 if (Instruction *Inst =
211 dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
212 RecursivelyDeleteTriviallyDeadInstructions(Inst);
213 }
214
215 // At this point, the code is well formed. We now do a quick sweep over the
216 // inserted code, doing constant propagation and dead code elimination as we
217 // go.
218 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
219 for (BasicBlock *BB : L->getBlocks()) {
220 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
221 Instruction *Inst = &*I++;
222
223 if (Value *V = SimplifyInstruction(Inst, {DL, nullptr, DT, AC}))
224 if (LI->replacementPreservesLCSSAForm(Inst, V))
225 Inst->replaceAllUsesWith(V);
226 if (isInstructionTriviallyDead(Inst))
227 BB->getInstList().erase(Inst);
228 }
229 }
230
231 // TODO: after peeling or unrolling, previously loop variant conditions are
232 // likely to fold to constants, eagerly propagating those here will require
233 // fewer cleanup passes to be run. Alternatively, a LoopEarlyCSE might be
234 // appropriate.
235}
236
237/// Unroll the given loop by Count. The loop must be in LCSSA form. Unrolling
238/// can only fail when the loop's latch block is not terminated by a conditional
239/// branch instruction. However, if the trip count (and multiple) are not known,
240/// loop unrolling will mostly produce more code that is no faster.
241///
242/// TripCount is the upper bound of the iteration on which control exits
243/// LatchBlock. Control may exit the loop prior to TripCount iterations either
244/// via an early branch in other loop block or via LatchBlock terminator. This
245/// is relaxed from the general definition of trip count which is the number of
246/// times the loop header executes. Note that UnrollLoop assumes that the loop
247/// counter test is in LatchBlock in order to remove unnecesssary instances of
248/// the test. If control can exit the loop from the LatchBlock's terminator
249/// prior to TripCount iterations, flag PreserveCondBr needs to be set.
250///
251/// PreserveCondBr indicates whether the conditional branch of the LatchBlock
252/// needs to be preserved. It is needed when we use trip count upper bound to
253/// fully unroll the loop. If PreserveOnlyFirst is also set then only the first
254/// conditional branch needs to be preserved.
255///
256/// Similarly, TripMultiple divides the number of times that the LatchBlock may
257/// execute without exiting the loop.
258///
259/// If AllowRuntime is true then UnrollLoop will consider unrolling loops that
260/// have a runtime (i.e. not compile time constant) trip count. Unrolling these
261/// loops require a unroll "prologue" that runs "RuntimeTripCount % Count"
262/// iterations before branching into the unrolled loop. UnrollLoop will not
263/// runtime-unroll the loop if computing RuntimeTripCount will be expensive and
264/// AllowExpensiveTripCount is false.
265///
266/// If we want to perform PGO-based loop peeling, PeelCount is set to the
267/// number of iterations we want to peel off.
268///
269/// The LoopInfo Analysis that is passed will be kept consistent.
270///
271/// This utility preserves LoopInfo. It will also preserve ScalarEvolution and
272/// DominatorTree if they are non-null.
273///
274/// If RemainderLoop is non-null, it will receive the remainder loop (if
275/// required and not fully unrolled).
276LoopUnrollResult llvm::UnrollLoop(Loop *L, UnrollLoopOptions ULO, LoopInfo *LI,
277 ScalarEvolution *SE, DominatorTree *DT,
278 AssumptionCache *AC,
279 OptimizationRemarkEmitter *ORE,
280 bool PreserveLCSSA, Loop **RemainderLoop) {
281
282 BasicBlock *Preheader = L->getLoopPreheader();
283 if (!Preheader) {
1
Assuming 'Preheader' is non-null
2
Taking false branch
284 LLVM_DEBUG(dbgs() << " Can't unroll; loop preheader-insertion failed.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " Can't unroll; loop preheader-insertion failed.\n"
; } } while (false)
;
285 return LoopUnrollResult::Unmodified;
286 }
287
288 BasicBlock *LatchBlock = L->getLoopLatch();
289 if (!LatchBlock) {
3
Assuming 'LatchBlock' is non-null
4
Taking false branch
290 LLVM_DEBUG(dbgs() << " Can't unroll; loop exit-block-insertion failed.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " Can't unroll; loop exit-block-insertion failed.\n"
; } } while (false)
;
291 return LoopUnrollResult::Unmodified;
292 }
293
294 // Loops with indirectbr cannot be cloned.
295 if (!L->isSafeToClone()) {
5
Assuming the condition is false
6
Taking false branch
296 LLVM_DEBUG(dbgs() << " Can't unroll; Loop body cannot be cloned.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " Can't unroll; Loop body cannot be cloned.\n"
; } } while (false)
;
297 return LoopUnrollResult::Unmodified;
298 }
299
300 // The current loop unroll pass can unroll loops with a single latch or header
301 // that's a conditional branch exiting the loop.
302 // FIXME: The implementation can be extended to work with more complicated
303 // cases, e.g. loops with multiple latches.
304 BasicBlock *Header = L->getHeader();
305 BranchInst *HeaderBI = dyn_cast<BranchInst>(Header->getTerminator());
7
Assuming the object is not a 'BranchInst'
8
'HeaderBI' initialized to a null pointer value
306 BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator());
9
Assuming the object is a 'BranchInst'
307
308 // FIXME: Support loops without conditional latch and multiple exiting blocks.
309 if (!BI
9.1
'BI' is non-null
9.1
'BI' is non-null
||
310 (BI->isUnconditional() && (!HeaderBI || HeaderBI->isUnconditional() ||
10
Calling 'BranchInst::isUnconditional'
13
Returning from 'BranchInst::isUnconditional'
311 L->getExitingBlock() != Header))) {
312 LLVM_DEBUG(dbgs() << " Can't unroll; loop not terminated by a conditional "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " Can't unroll; loop not terminated by a conditional "
"branch in the latch or header.\n"; } } while (false)
313 "branch in the latch or header.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " Can't unroll; loop not terminated by a conditional "
"branch in the latch or header.\n"; } } while (false)
;
314 return LoopUnrollResult::Unmodified;
315 }
316
317 auto CheckLatchSuccessors = [&](unsigned S1, unsigned S2) {
318 return BI->isConditional() && BI->getSuccessor(S1) == Header &&
319 !L->contains(BI->getSuccessor(S2));
320 };
321
322 // If we have a conditional latch, it must exit the loop.
323 if (BI
13.1
'BI' is non-null
13.1
'BI' is non-null
&& BI->isConditional() && !CheckLatchSuccessors(0, 1) &&
14
Calling 'BranchInst::isConditional'
17
Returning from 'BranchInst::isConditional'
324 !CheckLatchSuccessors(1, 0)) {
325 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "Can't unroll; a conditional latch must exit the loop"
; } } while (false)
326 dbgs() << "Can't unroll; a conditional latch must exit the loop")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "Can't unroll; a conditional latch must exit the loop"
; } } while (false)
;
327 return LoopUnrollResult::Unmodified;
328 }
329
330 auto CheckHeaderSuccessors = [&](unsigned S1, unsigned S2) {
331 return HeaderBI && HeaderBI->isConditional() &&
332 L->contains(HeaderBI->getSuccessor(S1)) &&
333 !L->contains(HeaderBI->getSuccessor(S2));
334 };
335
336 // If we do not have a conditional latch, the header must exit the loop.
337 if (BI
17.1
'BI' is non-null
17.1
'BI' is non-null
&& !BI->isConditional() && HeaderBI
20.1
'HeaderBI' is null
20.1
'HeaderBI' is null
&& HeaderBI->isConditional() &&
18
Calling 'BranchInst::isConditional'
20
Returning from 'BranchInst::isConditional'
338 !CheckHeaderSuccessors(0, 1) && !CheckHeaderSuccessors(1, 0)) {
339 LLVM_DEBUG(dbgs() << "Can't unroll; conditional header must exit the loop")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "Can't unroll; conditional header must exit the loop"
; } } while (false)
;
340 return LoopUnrollResult::Unmodified;
341 }
342
343 if (Header->hasAddressTaken()) {
21
Assuming the condition is false
22
Taking false branch
344 // The loop-rotate pass can be helpful to avoid this in many cases.
345 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " Won't unroll loop: address of header block is taken.\n"
; } } while (false)
346 dbgs() << " Won't unroll loop: address of header block is taken.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " Won't unroll loop: address of header block is taken.\n"
; } } while (false)
;
347 return LoopUnrollResult::Unmodified;
348 }
349
350 if (ULO.TripCount != 0)
23
Assuming field 'TripCount' is equal to 0
24
Taking false branch
351 LLVM_DEBUG(dbgs() << " Trip Count = " << ULO.TripCount << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " Trip Count = " <<
ULO.TripCount << "\n"; } } while (false)
;
352 if (ULO.TripMultiple != 1)
25
Assuming field 'TripMultiple' is equal to 1
26
Taking false branch
353 LLVM_DEBUG(dbgs() << " Trip Multiple = " << ULO.TripMultiple << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " Trip Multiple = " <<
ULO.TripMultiple << "\n"; } } while (false)
;
354
355 // Effectively "DCE" unrolled iterations that are beyond the tripcount
356 // and will never be executed.
357 if (ULO.TripCount
26.1
Field 'TripCount' is equal to 0
26.1
Field 'TripCount' is equal to 0
!= 0 && ULO.Count > ULO.TripCount)
358 ULO.Count = ULO.TripCount;
359
360 // Don't enter the unroll code if there is nothing to do.
361 if (ULO.TripCount
26.2
Field 'TripCount' is equal to 0
26.2
Field 'TripCount' is equal to 0
== 0 && ULO.Count < 2 && ULO.PeelCount == 0) {
27
Assuming field 'Count' is >= 2
362 LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "Won't unroll; almost nothing to do\n"
; } } while (false)
;
363 return LoopUnrollResult::Unmodified;
364 }
365
366 assert
27.1
Field 'Count' is > 0
27.1
Field 'Count' is > 0
(ULO.Count > 0)((ULO.Count > 0) ? static_cast<void> (0) : __assert_fail
("ULO.Count > 0", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 366, __PRETTY_FUNCTION__))
;
28
'?' condition is true
367 assert
28.1
Field 'TripMultiple' is > 0
28.1
Field 'TripMultiple' is > 0
(ULO.TripMultiple > 0)((ULO.TripMultiple > 0) ? static_cast<void> (0) : __assert_fail
("ULO.TripMultiple > 0", "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 367, __PRETTY_FUNCTION__))
;
29
'?' condition is true
368 assert
29.1
Field 'TripCount' is equal to 0
29.1
Field 'TripCount' is equal to 0
(ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0)((ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0
) ? static_cast<void> (0) : __assert_fail ("ULO.TripCount == 0 || ULO.TripCount % ULO.TripMultiple == 0"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 368, __PRETTY_FUNCTION__))
;
369
370 // Are we eliminating the loop control altogether?
371 bool CompletelyUnroll = ULO.Count
29.2
Field 'Count' is not equal to field 'TripCount'
29.2
Field 'Count' is not equal to field 'TripCount'
== ULO.TripCount;
372 SmallVector<BasicBlock *, 4> ExitBlocks;
373 L->getExitBlocks(ExitBlocks);
374 std::vector<BasicBlock*> OriginalLoopBlocks = L->getBlocks();
375
376 // Go through all exits of L and see if there are any phi-nodes there. We just
377 // conservatively assume that they're inserted to preserve LCSSA form, which
378 // means that complete unrolling might break this form. We need to either fix
379 // it in-place after the transformation, or entirely rebuild LCSSA. TODO: For
380 // now we just recompute LCSSA for the outer loop, but it should be possible
381 // to fix it in-place.
382 bool NeedToFixLCSSA = PreserveLCSSA && CompletelyUnroll &&
30
Assuming 'PreserveLCSSA' is false
383 any_of(ExitBlocks, [](const BasicBlock *BB) {
384 return isa<PHINode>(BB->begin());
385 });
386
387 // We assume a run-time trip count if the compiler cannot
388 // figure out the loop trip count and the unroll-runtime
389 // flag is specified.
390 bool RuntimeTripCount =
391 (ULO.TripCount
30.1
Field 'TripCount' is equal to 0
30.1
Field 'TripCount' is equal to 0
== 0 && ULO.Count
30.2
Field 'Count' is > 0
30.2
Field 'Count' is > 0
> 0 && ULO.AllowRuntime);
392
393 assert((!RuntimeTripCount || !ULO.PeelCount) &&(((!RuntimeTripCount || !ULO.PeelCount) && "Did not expect runtime trip-count unrolling "
"and peeling for the same loop") ? static_cast<void> (
0) : __assert_fail ("(!RuntimeTripCount || !ULO.PeelCount) && \"Did not expect runtime trip-count unrolling \" \"and peeling for the same loop\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 395, __PRETTY_FUNCTION__))
31
Assuming 'RuntimeTripCount' is true
32
Assuming field 'PeelCount' is 0
33
'?' condition is true
394 "Did not expect runtime trip-count unrolling "(((!RuntimeTripCount || !ULO.PeelCount) && "Did not expect runtime trip-count unrolling "
"and peeling for the same loop") ? static_cast<void> (
0) : __assert_fail ("(!RuntimeTripCount || !ULO.PeelCount) && \"Did not expect runtime trip-count unrolling \" \"and peeling for the same loop\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 395, __PRETTY_FUNCTION__))
395 "and peeling for the same loop")(((!RuntimeTripCount || !ULO.PeelCount) && "Did not expect runtime trip-count unrolling "
"and peeling for the same loop") ? static_cast<void> (
0) : __assert_fail ("(!RuntimeTripCount || !ULO.PeelCount) && \"Did not expect runtime trip-count unrolling \" \"and peeling for the same loop\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 395, __PRETTY_FUNCTION__))
;
396
397 bool Peeled = false;
398 if (ULO.PeelCount
33.1
Field 'PeelCount' is 0
33.1
Field 'PeelCount' is 0
) {
34
Taking false branch
399 Peeled = peelLoop(L, ULO.PeelCount, LI, SE, DT, AC, PreserveLCSSA);
400
401 // Successful peeling may result in a change in the loop preheader/trip
402 // counts. If we later unroll the loop, we want these to be updated.
403 if (Peeled) {
404 // According to our guards and profitability checks the only
405 // meaningful exit should be latch block. Other exits go to deopt,
406 // so we do not worry about them.
407 BasicBlock *ExitingBlock = L->getLoopLatch();
408 assert(ExitingBlock && "Loop without exiting block?")((ExitingBlock && "Loop without exiting block?") ? static_cast
<void> (0) : __assert_fail ("ExitingBlock && \"Loop without exiting block?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 408, __PRETTY_FUNCTION__))
;
409 assert(L->isLoopExiting(ExitingBlock) && "Latch is not exiting?")((L->isLoopExiting(ExitingBlock) && "Latch is not exiting?"
) ? static_cast<void> (0) : __assert_fail ("L->isLoopExiting(ExitingBlock) && \"Latch is not exiting?\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 409, __PRETTY_FUNCTION__))
;
410 Preheader = L->getLoopPreheader();
411 ULO.TripCount = SE->getSmallConstantTripCount(L, ExitingBlock);
412 ULO.TripMultiple = SE->getSmallConstantTripMultiple(L, ExitingBlock);
413 }
414 }
415
416 // Loops containing convergent instructions must have a count that divides
417 // their TripMultiple.
418 LLVM_DEBUG(do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
35
Assuming 'DebugFlag' is true
36
Assuming the condition is false
37
Taking false branch
38
Loop condition is false. Exiting loop
419 {do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
420 bool HasConvergent = false;do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
421 for (auto &BB : L->blocks())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
422 for (auto &I : *BB)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
423 if (auto CS = CallSite(&I))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
424 HasConvergent |= CS.isConvergent();do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
425 assert((!HasConvergent || ULO.TripMultiple % ULO.Count == 0) &&do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
426 "Unroll count must divide trip multiple if loop contains a "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
427 "convergent operation.");do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
428 })do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { { bool HasConvergent = false; for (auto &
BB : L->blocks()) for (auto &I : *BB) if (auto CS = CallSite
(&I)) HasConvergent |= CS.isConvergent(); (((!HasConvergent
|| ULO.TripMultiple % ULO.Count == 0) && "Unroll count must divide trip multiple if loop contains a "
"convergent operation.") ? static_cast<void> (0) : __assert_fail
("(!HasConvergent || ULO.TripMultiple % ULO.Count == 0) && \"Unroll count must divide trip multiple if loop contains a \" \"convergent operation.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 427, __PRETTY_FUNCTION__)); }; } } while (false)
;
429
430 bool EpilogProfitability =
431 UnrollRuntimeEpilog.getNumOccurrences() ? UnrollRuntimeEpilog
39
Assuming the condition is true
40
'?' condition is true
432 : isEpilogProfitable(L);
433
434 if (RuntimeTripCount
40.1
'RuntimeTripCount' is true
40.1
'RuntimeTripCount' is true
&& ULO.TripMultiple % ULO.Count != 0 &&
41
Assuming the condition is false
435 !UnrollRuntimeLoopRemainder(L, ULO.Count, ULO.AllowExpensiveTripCount,
436 EpilogProfitability, ULO.UnrollRemainder,
437 ULO.ForgetAllSCEV, LI, SE, DT, AC,
438 PreserveLCSSA, RemainderLoop)) {
439 if (ULO.Force)
440 RuntimeTripCount = false;
441 else {
442 LLVM_DEBUG(dbgs() << "Won't unroll; remainder loop could not be "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "Won't unroll; remainder loop could not be "
"generated when assuming runtime trip count\n"; } } while (false
)
443 "generated when assuming runtime trip count\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "Won't unroll; remainder loop could not be "
"generated when assuming runtime trip count\n"; } } while (false
)
;
444 return LoopUnrollResult::Unmodified;
445 }
446 }
447
448 // If we know the trip count, we know the multiple...
449 unsigned BreakoutTrip = 0;
450 if (ULO.TripCount
41.1
Field 'TripCount' is equal to 0
41.1
Field 'TripCount' is equal to 0
!= 0) {
42
Taking false branch
451 BreakoutTrip = ULO.TripCount % ULO.Count;
452 ULO.TripMultiple = 0;
453 } else {
454 // Figure out what multiple to use.
455 BreakoutTrip = ULO.TripMultiple =
456 (unsigned)GreatestCommonDivisor64(ULO.Count, ULO.TripMultiple);
457 }
458
459 using namespace ore;
460 // Report the unrolling decision.
461 if (CompletelyUnroll
42.1
'CompletelyUnroll' is false
42.1
'CompletelyUnroll' is false
) {
43
Taking false branch
462 LLVM_DEBUG(dbgs() << "COMPLETELY UNROLLING loop %" << Header->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "COMPLETELY UNROLLING loop %"
<< Header->getName() << " with trip count " <<
ULO.TripCount << "!\n"; } } while (false)
463 << " with trip count " << ULO.TripCount << "!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "COMPLETELY UNROLLING loop %"
<< Header->getName() << " with trip count " <<
ULO.TripCount << "!\n"; } } while (false)
;
464 if (ORE)
465 ORE->emit([&]() {
466 return OptimizationRemark(DEBUG_TYPE"loop-unroll", "FullyUnrolled", L->getStartLoc(),
467 L->getHeader())
468 << "completely unrolled loop with "
469 << NV("UnrollCount", ULO.TripCount) << " iterations";
470 });
471 } else if (ULO.PeelCount
43.1
Field 'PeelCount' is 0
43.1
Field 'PeelCount' is 0
) {
44
Taking false branch
472 LLVM_DEBUG(dbgs() << "PEELING loop %" << Header->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "PEELING loop %" << Header
->getName() << " with iteration count " << ULO
.PeelCount << "!\n"; } } while (false)
473 << " with iteration count " << ULO.PeelCount << "!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "PEELING loop %" << Header
->getName() << " with iteration count " << ULO
.PeelCount << "!\n"; } } while (false)
;
474 if (ORE)
475 ORE->emit([&]() {
476 return OptimizationRemark(DEBUG_TYPE"loop-unroll", "Peeled", L->getStartLoc(),
477 L->getHeader())
478 << " peeled loop by " << NV("PeelCount", ULO.PeelCount)
479 << " iterations";
480 });
481 } else {
482 auto DiagBuilder = [&]() {
483 OptimizationRemark Diag(DEBUG_TYPE"loop-unroll", "PartialUnrolled", L->getStartLoc(),
484 L->getHeader());
485 return Diag << "unrolled loop by a factor of "
486 << NV("UnrollCount", ULO.Count);
487 };
488
489 LLVM_DEBUG(dbgs() << "UNROLLING loop %" << Header->getName() << " by "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "UNROLLING loop %" <<
Header->getName() << " by " << ULO.Count; } }
while (false)
45
Assuming 'DebugFlag' is true
46
Assuming the condition is false
47
Taking false branch
48
Loop condition is false. Exiting loop
490 << ULO.Count)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "UNROLLING loop %" <<
Header->getName() << " by " << ULO.Count; } }
while (false)
;
491 if (ULO.TripMultiple
48.1
Field 'TripMultiple' is not equal to 0
48.1
Field 'TripMultiple' is not equal to 0
== 0 || BreakoutTrip
48.2
'BreakoutTrip' is equal to field 'TripMultiple'
48.2
'BreakoutTrip' is equal to field 'TripMultiple'
!= ULO.TripMultiple) {
49
Taking false branch
492 LLVM_DEBUG(dbgs() << " with a breakout at trip " << BreakoutTrip)do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " with a breakout at trip "
<< BreakoutTrip; } } while (false)
;
493 if (ORE)
494 ORE->emit([&]() {
495 return DiagBuilder() << " with a breakout at trip "
496 << NV("BreakoutTrip", BreakoutTrip);
497 });
498 } else if (ULO.TripMultiple
49.1
Field 'TripMultiple' is equal to 1
49.1
Field 'TripMultiple' is equal to 1
!= 1) {
50
Taking false branch
499 LLVM_DEBUG(dbgs() << " with " << ULO.TripMultiple << " trips per branch")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " with " << ULO.TripMultiple
<< " trips per branch"; } } while (false)
;
500 if (ORE)
501 ORE->emit([&]() {
502 return DiagBuilder()
503 << " with " << NV("TripMultiple", ULO.TripMultiple)
504 << " trips per branch";
505 });
506 } else if (RuntimeTripCount
50.1
'RuntimeTripCount' is true
50.1
'RuntimeTripCount' is true
) {
51
Taking true branch
507 LLVM_DEBUG(dbgs() << " with run-time trip count")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << " with run-time trip count"
; } } while (false)
;
52
Assuming 'DebugFlag' is false
53
Loop condition is false. Exiting loop
508 if (ORE)
54
Assuming 'ORE' is null
55
Taking false branch
509 ORE->emit(
510 [&]() { return DiagBuilder() << " with run-time trip count"; });
511 }
512 LLVM_DEBUG
55.1
'DebugFlag' is false
55.1
'DebugFlag' is false
(dbgs() << "!\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "!\n"; } } while (false)
;
56
Loop condition is false. Exiting loop
513 }
514
515 // We are going to make changes to this loop. SCEV may be keeping cached info
516 // about it, in particular about backedge taken count. The changes we make
517 // are guaranteed to invalidate this information for our loop. It is tempting
518 // to only invalidate the loop being unrolled, but it is incorrect as long as
519 // all exiting branches from all inner loops have impact on the outer loops,
520 // and if something changes inside them then any of outer loops may also
521 // change. When we forget outermost loop, we also forget all contained loops
522 // and this is what we need here.
523 if (SE) {
57
Assuming 'SE' is null
58
Taking false branch
524 if (ULO.ForgetAllSCEV)
525 SE->forgetAllLoops();
526 else
527 SE->forgetTopmostLoop(L);
528 }
529
530 bool ContinueOnTrue;
531 bool LatchIsExiting = BI->isConditional();
59
Calling 'BranchInst::isConditional'
61
Returning from 'BranchInst::isConditional'
532 BasicBlock *LoopExit = nullptr;
533 if (LatchIsExiting
61.1
'LatchIsExiting' is false
61.1
'LatchIsExiting' is false
) {
62
Taking false branch
534 ContinueOnTrue = L->contains(BI->getSuccessor(0));
535 LoopExit = BI->getSuccessor(ContinueOnTrue);
536 } else {
537 NumUnrolledWithHeader++;
538 ContinueOnTrue = L->contains(HeaderBI->getSuccessor(0));
63
Called C++ object pointer is null
539 LoopExit = HeaderBI->getSuccessor(ContinueOnTrue);
540 }
541
542 // For the first iteration of the loop, we should use the precloned values for
543 // PHI nodes. Insert associations now.
544 ValueToValueMapTy LastValueMap;
545 std::vector<PHINode*> OrigPHINode;
546 for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
547 OrigPHINode.push_back(cast<PHINode>(I));
548 }
549
550 std::vector<BasicBlock *> Headers;
551 std::vector<BasicBlock *> HeaderSucc;
552 std::vector<BasicBlock *> Latches;
553 Headers.push_back(Header);
554 Latches.push_back(LatchBlock);
555
556 if (!LatchIsExiting) {
557 auto *Term = cast<BranchInst>(Header->getTerminator());
558 if (Term->isUnconditional() || L->contains(Term->getSuccessor(0))) {
559 assert(L->contains(Term->getSuccessor(0)))((L->contains(Term->getSuccessor(0))) ? static_cast<
void> (0) : __assert_fail ("L->contains(Term->getSuccessor(0))"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 559, __PRETTY_FUNCTION__))
;
560 HeaderSucc.push_back(Term->getSuccessor(0));
561 } else {
562 assert(L->contains(Term->getSuccessor(1)))((L->contains(Term->getSuccessor(1))) ? static_cast<
void> (0) : __assert_fail ("L->contains(Term->getSuccessor(1))"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 562, __PRETTY_FUNCTION__))
;
563 HeaderSucc.push_back(Term->getSuccessor(1));
564 }
565 }
566
567 // The current on-the-fly SSA update requires blocks to be processed in
568 // reverse postorder so that LastValueMap contains the correct value at each
569 // exit.
570 LoopBlocksDFS DFS(L);
571 DFS.perform(LI);
572
573 // Stash the DFS iterators before adding blocks to the loop.
574 LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO();
575 LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO();
576
577 std::vector<BasicBlock*> UnrolledLoopBlocks = L->getBlocks();
578
579 // Loop Unrolling might create new loops. While we do preserve LoopInfo, we
580 // might break loop-simplified form for these loops (as they, e.g., would
581 // share the same exit blocks). We'll keep track of loops for which we can
582 // break this so that later we can re-simplify them.
583 SmallSetVector<Loop *, 4> LoopsToSimplify;
584 for (Loop *SubLoop : *L)
585 LoopsToSimplify.insert(SubLoop);
586
587 if (Header->getParent()->isDebugInfoForProfiling())
588 for (BasicBlock *BB : L->getBlocks())
589 for (Instruction &I : *BB)
590 if (!isa<DbgInfoIntrinsic>(&I))
591 if (const DILocation *DIL = I.getDebugLoc()) {
592 auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(ULO.Count);
593 if (NewDIL)
594 I.setDebugLoc(NewDIL.getValue());
595 else
596 LLVM_DEBUG(dbgs()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "Failed to create new discriminator: "
<< DIL->getFilename() << " Line: " << DIL
->getLine(); } } while (false)
597 << "Failed to create new discriminator: "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "Failed to create new discriminator: "
<< DIL->getFilename() << " Line: " << DIL
->getLine(); } } while (false)
598 << DIL->getFilename() << " Line: " << DIL->getLine())do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("loop-unroll")) { dbgs() << "Failed to create new discriminator: "
<< DIL->getFilename() << " Line: " << DIL
->getLine(); } } while (false)
;
599 }
600
601 for (unsigned It = 1; It != ULO.Count; ++It) {
602 std::vector<BasicBlock*> NewBlocks;
603 SmallDenseMap<const Loop *, Loop *, 4> NewLoops;
604 NewLoops[L] = L;
605
606 for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) {
607 ValueToValueMapTy VMap;
608 BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It));
609 Header->getParent()->getBasicBlockList().push_back(New);
610
611 assert((*BB != Header || LI->getLoopFor(*BB) == L) &&(((*BB != Header || LI->getLoopFor(*BB) == L) && "Header should not be in a sub-loop"
) ? static_cast<void> (0) : __assert_fail ("(*BB != Header || LI->getLoopFor(*BB) == L) && \"Header should not be in a sub-loop\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 612, __PRETTY_FUNCTION__))
612 "Header should not be in a sub-loop")(((*BB != Header || LI->getLoopFor(*BB) == L) && "Header should not be in a sub-loop"
) ? static_cast<void> (0) : __assert_fail ("(*BB != Header || LI->getLoopFor(*BB) == L) && \"Header should not be in a sub-loop\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 612, __PRETTY_FUNCTION__))
;
613 // Tell LI about New.
614 const Loop *OldLoop = addClonedBlockToLoopInfo(*BB, New, LI, NewLoops);
615 if (OldLoop)
616 LoopsToSimplify.insert(NewLoops[OldLoop]);
617
618 if (*BB == Header)
619 // Loop over all of the PHI nodes in the block, changing them to use
620 // the incoming values from the previous block.
621 for (PHINode *OrigPHI : OrigPHINode) {
622 PHINode *NewPHI = cast<PHINode>(VMap[OrigPHI]);
623 Value *InVal = NewPHI->getIncomingValueForBlock(LatchBlock);
624 if (Instruction *InValI = dyn_cast<Instruction>(InVal))
625 if (It > 1 && L->contains(InValI))
626 InVal = LastValueMap[InValI];
627 VMap[OrigPHI] = InVal;
628 New->getInstList().erase(NewPHI);
629 }
630
631 // Update our running map of newest clones
632 LastValueMap[*BB] = New;
633 for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end();
634 VI != VE; ++VI)
635 LastValueMap[VI->first] = VI->second;
636
637 // Add phi entries for newly created values to all exit blocks.
638 for (BasicBlock *Succ : successors(*BB)) {
639 if (L->contains(Succ))
640 continue;
641 for (PHINode &PHI : Succ->phis()) {
642 Value *Incoming = PHI.getIncomingValueForBlock(*BB);
643 ValueToValueMapTy::iterator It = LastValueMap.find(Incoming);
644 if (It != LastValueMap.end())
645 Incoming = It->second;
646 PHI.addIncoming(Incoming, New);
647 }
648 }
649 // Keep track of new headers and latches as we create them, so that
650 // we can insert the proper branches later.
651 if (*BB == Header)
652 Headers.push_back(New);
653 if (*BB == LatchBlock)
654 Latches.push_back(New);
655
656 // Keep track of the successor of the new header in the current iteration.
657 for (auto *Pred : predecessors(*BB))
658 if (Pred == Header) {
659 HeaderSucc.push_back(New);
660 break;
661 }
662
663 NewBlocks.push_back(New);
664 UnrolledLoopBlocks.push_back(New);
665
666 // Update DomTree: since we just copy the loop body, and each copy has a
667 // dedicated entry block (copy of the header block), this header's copy
668 // dominates all copied blocks. That means, dominance relations in the
669 // copied body are the same as in the original body.
670 if (DT) {
671 if (*BB == Header)
672 DT->addNewBlock(New, Latches[It - 1]);
673 else {
674 auto BBDomNode = DT->getNode(*BB);
675 auto BBIDom = BBDomNode->getIDom();
676 BasicBlock *OriginalBBIDom = BBIDom->getBlock();
677 DT->addNewBlock(
678 New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)]));
679 }
680 }
681 }
682
683 // Remap all instructions in the most recent iteration
684 for (BasicBlock *NewBlock : NewBlocks) {
685 for (Instruction &I : *NewBlock) {
686 ::remapInstruction(&I, LastValueMap);
687 if (auto *II = dyn_cast<IntrinsicInst>(&I))
688 if (II->getIntrinsicID() == Intrinsic::assume)
689 AC->registerAssumption(II);
690 }
691 }
692 }
693
694 // Loop over the PHI nodes in the original block, setting incoming values.
695 for (PHINode *PN : OrigPHINode) {
696 if (CompletelyUnroll) {
697 PN->replaceAllUsesWith(PN->getIncomingValueForBlock(Preheader));
698 Header->getInstList().erase(PN);
699 } else if (ULO.Count > 1) {
700 Value *InVal = PN->removeIncomingValue(LatchBlock, false);
701 // If this value was defined in the loop, take the value defined by the
702 // last iteration of the loop.
703 if (Instruction *InValI = dyn_cast<Instruction>(InVal)) {
704 if (L->contains(InValI))
705 InVal = LastValueMap[InVal];
706 }
707 assert(Latches.back() == LastValueMap[LatchBlock] && "bad last latch")((Latches.back() == LastValueMap[LatchBlock] && "bad last latch"
) ? static_cast<void> (0) : __assert_fail ("Latches.back() == LastValueMap[LatchBlock] && \"bad last latch\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 707, __PRETTY_FUNCTION__))
;
708 PN->addIncoming(InVal, Latches.back());
709 }
710 }
711
712 auto setDest = [LoopExit, ContinueOnTrue](BasicBlock *Src, BasicBlock *Dest,
713 ArrayRef<BasicBlock *> NextBlocks,
714 BasicBlock *BlockInLoop,
715 bool NeedConditional) {
716 auto *Term = cast<BranchInst>(Src->getTerminator());
717 if (NeedConditional) {
718 // Update the conditional branch's successor for the following
719 // iteration.
720 Term->setSuccessor(!ContinueOnTrue, Dest);
721 } else {
722 // Remove phi operands at this loop exit
723 if (Dest != LoopExit) {
724 BasicBlock *BB = Src;
725 for (BasicBlock *Succ : successors(BB)) {
726 // Preserve the incoming value from BB if we are jumping to the block
727 // in the current loop.
728 if (Succ == BlockInLoop)
729 continue;
730 for (PHINode &Phi : Succ->phis())
731 Phi.removeIncomingValue(BB, false);
732 }
733 }
734 // Replace the conditional branch with an unconditional one.
735 BranchInst::Create(Dest, Term);
736 Term->eraseFromParent();
737 }
738 };
739
740 // Now that all the basic blocks for the unrolled iterations are in place,
741 // set up the branches to connect them.
742 if (LatchIsExiting) {
743 // Set up latches to branch to the new header in the unrolled iterations or
744 // the loop exit for the last latch in a fully unrolled loop.
745 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
746 // The branch destination.
747 unsigned j = (i + 1) % e;
748 BasicBlock *Dest = Headers[j];
749 bool NeedConditional = true;
750
751 if (RuntimeTripCount && j != 0) {
752 NeedConditional = false;
753 }
754
755 // For a complete unroll, make the last iteration end with a branch
756 // to the exit block.
757 if (CompletelyUnroll) {
758 if (j == 0)
759 Dest = LoopExit;
760 // If using trip count upper bound to completely unroll, we need to keep
761 // the conditional branch except the last one because the loop may exit
762 // after any iteration.
763 assert(NeedConditional &&((NeedConditional && "NeedCondition cannot be modified by both complete "
"unrolling and runtime unrolling") ? static_cast<void>
(0) : __assert_fail ("NeedConditional && \"NeedCondition cannot be modified by both complete \" \"unrolling and runtime unrolling\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 765, __PRETTY_FUNCTION__))
764 "NeedCondition cannot be modified by both complete "((NeedConditional && "NeedCondition cannot be modified by both complete "
"unrolling and runtime unrolling") ? static_cast<void>
(0) : __assert_fail ("NeedConditional && \"NeedCondition cannot be modified by both complete \" \"unrolling and runtime unrolling\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 765, __PRETTY_FUNCTION__))
765 "unrolling and runtime unrolling")((NeedConditional && "NeedCondition cannot be modified by both complete "
"unrolling and runtime unrolling") ? static_cast<void>
(0) : __assert_fail ("NeedConditional && \"NeedCondition cannot be modified by both complete \" \"unrolling and runtime unrolling\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 765, __PRETTY_FUNCTION__))
;
766 NeedConditional =
767 (ULO.PreserveCondBr && j && !(ULO.PreserveOnlyFirst && i != 0));
768 } else if (j != BreakoutTrip &&
769 (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0)) {
770 // If we know the trip count or a multiple of it, we can safely use an
771 // unconditional branch for some iterations.
772 NeedConditional = false;
773 }
774
775 setDest(Latches[i], Dest, Headers, Headers[i], NeedConditional);
776 }
777 } else {
778 // Setup headers to branch to their new successors in the unrolled
779 // iterations.
780 for (unsigned i = 0, e = Headers.size(); i != e; ++i) {
781 // The branch destination.
782 unsigned j = (i + 1) % e;
783 BasicBlock *Dest = HeaderSucc[i];
784 bool NeedConditional = true;
785
786 if (RuntimeTripCount && j != 0)
787 NeedConditional = false;
788
789 if (CompletelyUnroll)
790 // We cannot drop the conditional branch for the last condition, as we
791 // may have to execute the loop body depending on the condition.
792 NeedConditional = j == 0 || ULO.PreserveCondBr;
793 else if (j != BreakoutTrip &&
794 (ULO.TripMultiple == 0 || j % ULO.TripMultiple != 0))
795 // If we know the trip count or a multiple of it, we can safely use an
796 // unconditional branch for some iterations.
797 NeedConditional = false;
798
799 setDest(Headers[i], Dest, Headers, HeaderSucc[i], NeedConditional);
800 }
801
802 // Set up latches to branch to the new header in the unrolled iterations or
803 // the loop exit for the last latch in a fully unrolled loop.
804
805 for (unsigned i = 0, e = Latches.size(); i != e; ++i) {
806 // The original branch was replicated in each unrolled iteration.
807 BranchInst *Term = cast<BranchInst>(Latches[i]->getTerminator());
808
809 // The branch destination.
810 unsigned j = (i + 1) % e;
811 BasicBlock *Dest = Headers[j];
812
813 // When completely unrolling, the last latch becomes unreachable.
814 if (CompletelyUnroll && j == 0)
815 new UnreachableInst(Term->getContext(), Term);
816 else
817 // Replace the conditional branch with an unconditional one.
818 BranchInst::Create(Dest, Term);
819
820 Term->eraseFromParent();
821 }
822 }
823
824 // Update dominators of blocks we might reach through exits.
825 // Immediate dominator of such block might change, because we add more
826 // routes which can lead to the exit: we can now reach it from the copied
827 // iterations too.
828 if (DT && ULO.Count > 1) {
829 for (auto *BB : OriginalLoopBlocks) {
830 auto *BBDomNode = DT->getNode(BB);
831 SmallVector<BasicBlock *, 16> ChildrenToUpdate;
832 for (auto *ChildDomNode : BBDomNode->getChildren()) {
833 auto *ChildBB = ChildDomNode->getBlock();
834 if (!L->contains(ChildBB))
835 ChildrenToUpdate.push_back(ChildBB);
836 }
837 BasicBlock *NewIDom;
838 BasicBlock *&TermBlock = LatchIsExiting ? LatchBlock : Header;
839 auto &TermBlocks = LatchIsExiting ? Latches : Headers;
840 if (BB == TermBlock) {
841 // The latch is special because we emit unconditional branches in
842 // some cases where the original loop contained a conditional branch.
843 // Since the latch is always at the bottom of the loop, if the latch
844 // dominated an exit before unrolling, the new dominator of that exit
845 // must also be a latch. Specifically, the dominator is the first
846 // latch which ends in a conditional branch, or the last latch if
847 // there is no such latch.
848 // For loops exiting from the header, we limit the supported loops
849 // to have a single exiting block.
850 NewIDom = TermBlocks.back();
851 for (BasicBlock *Iter : TermBlocks) {
852 Instruction *Term = Iter->getTerminator();
853 if (isa<BranchInst>(Term) && cast<BranchInst>(Term)->isConditional()) {
854 NewIDom = Iter;
855 break;
856 }
857 }
858 } else {
859 // The new idom of the block will be the nearest common dominator
860 // of all copies of the previous idom. This is equivalent to the
861 // nearest common dominator of the previous idom and the first latch,
862 // which dominates all copies of the previous idom.
863 NewIDom = DT->findNearestCommonDominator(BB, LatchBlock);
864 }
865 for (auto *ChildBB : ChildrenToUpdate)
866 DT->changeImmediateDominator(ChildBB, NewIDom);
867 }
868 }
869
870 assert(!DT || !UnrollVerifyDomtree ||((!DT || !UnrollVerifyDomtree || DT->verify(DominatorTree::
VerificationLevel::Fast)) ? static_cast<void> (0) : __assert_fail
("!DT || !UnrollVerifyDomtree || DT->verify(DominatorTree::VerificationLevel::Fast)"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 871, __PRETTY_FUNCTION__))
871 DT->verify(DominatorTree::VerificationLevel::Fast))((!DT || !UnrollVerifyDomtree || DT->verify(DominatorTree::
VerificationLevel::Fast)) ? static_cast<void> (0) : __assert_fail
("!DT || !UnrollVerifyDomtree || DT->verify(DominatorTree::VerificationLevel::Fast)"
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 871, __PRETTY_FUNCTION__))
;
872
873 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy);
874 // Merge adjacent basic blocks, if possible.
875 for (BasicBlock *Latch : Latches) {
876 BranchInst *Term = dyn_cast<BranchInst>(Latch->getTerminator());
877 assert((Term ||(((Term || (CompletelyUnroll && !LatchIsExiting &&
Latch == Latches.back())) && "Need a branch as terminator, except when fully unrolling with "
"unconditional latch") ? static_cast<void> (0) : __assert_fail
("(Term || (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) && \"Need a branch as terminator, except when fully unrolling with \" \"unconditional latch\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 880, __PRETTY_FUNCTION__))
878 (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) &&(((Term || (CompletelyUnroll && !LatchIsExiting &&
Latch == Latches.back())) && "Need a branch as terminator, except when fully unrolling with "
"unconditional latch") ? static_cast<void> (0) : __assert_fail
("(Term || (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) && \"Need a branch as terminator, except when fully unrolling with \" \"unconditional latch\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 880, __PRETTY_FUNCTION__))
879 "Need a branch as terminator, except when fully unrolling with "(((Term || (CompletelyUnroll && !LatchIsExiting &&
Latch == Latches.back())) && "Need a branch as terminator, except when fully unrolling with "
"unconditional latch") ? static_cast<void> (0) : __assert_fail
("(Term || (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) && \"Need a branch as terminator, except when fully unrolling with \" \"unconditional latch\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 880, __PRETTY_FUNCTION__))
880 "unconditional latch")(((Term || (CompletelyUnroll && !LatchIsExiting &&
Latch == Latches.back())) && "Need a branch as terminator, except when fully unrolling with "
"unconditional latch") ? static_cast<void> (0) : __assert_fail
("(Term || (CompletelyUnroll && !LatchIsExiting && Latch == Latches.back())) && \"Need a branch as terminator, except when fully unrolling with \" \"unconditional latch\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 880, __PRETTY_FUNCTION__))
;
881 if (Term && Term->isUnconditional()) {
882 BasicBlock *Dest = Term->getSuccessor(0);
883 BasicBlock *Fold = Dest->getUniquePredecessor();
884 if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) {
885 // Dest has been folded into Fold. Update our worklists accordingly.
886 std::replace(Latches.begin(), Latches.end(), Dest, Fold);
887 UnrolledLoopBlocks.erase(std::remove(UnrolledLoopBlocks.begin(),
888 UnrolledLoopBlocks.end(), Dest),
889 UnrolledLoopBlocks.end());
890 }
891 }
892 }
893 // Apply updates to the DomTree.
894 DT = &DTU.getDomTree();
895
896 // At this point, the code is well formed. We now simplify the unrolled loop,
897 // doing constant propagation and dead code elimination as we go.
898 simplifyLoopAfterUnroll(L, !CompletelyUnroll && (ULO.Count > 1 || Peeled), LI,
899 SE, DT, AC);
900
901 NumCompletelyUnrolled += CompletelyUnroll;
902 ++NumUnrolled;
903
904 Loop *OuterL = L->getParentLoop();
905 // Update LoopInfo if the loop is completely removed.
906 if (CompletelyUnroll)
907 LI->erase(L);
908
909 // After complete unrolling most of the blocks should be contained in OuterL.
910 // However, some of them might happen to be out of OuterL (e.g. if they
911 // precede a loop exit). In this case we might need to insert PHI nodes in
912 // order to preserve LCSSA form.
913 // We don't need to check this if we already know that we need to fix LCSSA
914 // form.
915 // TODO: For now we just recompute LCSSA for the outer loop in this case, but
916 // it should be possible to fix it in-place.
917 if (PreserveLCSSA && OuterL && CompletelyUnroll && !NeedToFixLCSSA)
918 NeedToFixLCSSA |= ::needToInsertPhisForLCSSA(OuterL, UnrolledLoopBlocks, LI);
919
920 // If we have a pass and a DominatorTree we should re-simplify impacted loops
921 // to ensure subsequent analyses can rely on this form. We want to simplify
922 // at least one layer outside of the loop that was unrolled so that any
923 // changes to the parent loop exposed by the unrolling are considered.
924 if (DT) {
925 if (OuterL) {
926 // OuterL includes all loops for which we can break loop-simplify, so
927 // it's sufficient to simplify only it (it'll recursively simplify inner
928 // loops too).
929 if (NeedToFixLCSSA) {
930 // LCSSA must be performed on the outermost affected loop. The unrolled
931 // loop's last loop latch is guaranteed to be in the outermost loop
932 // after LoopInfo's been updated by LoopInfo::erase.
933 Loop *LatchLoop = LI->getLoopFor(Latches.back());
934 Loop *FixLCSSALoop = OuterL;
935 if (!FixLCSSALoop->contains(LatchLoop))
936 while (FixLCSSALoop->getParentLoop() != LatchLoop)
937 FixLCSSALoop = FixLCSSALoop->getParentLoop();
938
939 formLCSSARecursively(*FixLCSSALoop, *DT, LI, SE);
940 } else if (PreserveLCSSA) {
941 assert(OuterL->isLCSSAForm(*DT) &&((OuterL->isLCSSAForm(*DT) && "Loops should be in LCSSA form after loop-unroll."
) ? static_cast<void> (0) : __assert_fail ("OuterL->isLCSSAForm(*DT) && \"Loops should be in LCSSA form after loop-unroll.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 942, __PRETTY_FUNCTION__))
942 "Loops should be in LCSSA form after loop-unroll.")((OuterL->isLCSSAForm(*DT) && "Loops should be in LCSSA form after loop-unroll."
) ? static_cast<void> (0) : __assert_fail ("OuterL->isLCSSAForm(*DT) && \"Loops should be in LCSSA form after loop-unroll.\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 942, __PRETTY_FUNCTION__))
;
943 }
944
945 // TODO: That potentially might be compile-time expensive. We should try
946 // to fix the loop-simplified form incrementally.
947 simplifyLoop(OuterL, DT, LI, SE, AC, nullptr, PreserveLCSSA);
948 } else {
949 // Simplify loops for which we might've broken loop-simplify form.
950 for (Loop *SubLoop : LoopsToSimplify)
951 simplifyLoop(SubLoop, DT, LI, SE, AC, nullptr, PreserveLCSSA);
952 }
953 }
954
955 return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled
956 : LoopUnrollResult::PartiallyUnrolled;
957}
958
959/// Given an llvm.loop loop id metadata node, returns the loop hint metadata
960/// node with the given name (for example, "llvm.loop.unroll.count"). If no
961/// such metadata node exists, then nullptr is returned.
962MDNode *llvm::GetUnrollMetadata(MDNode *LoopID, StringRef Name) {
963 // First operand should refer to the loop id itself.
964 assert(LoopID->getNumOperands() > 0 && "requires at least one operand")((LoopID->getNumOperands() > 0 && "requires at least one operand"
) ? static_cast<void> (0) : __assert_fail ("LoopID->getNumOperands() > 0 && \"requires at least one operand\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 964, __PRETTY_FUNCTION__))
;
965 assert(LoopID->getOperand(0) == LoopID && "invalid loop id")((LoopID->getOperand(0) == LoopID && "invalid loop id"
) ? static_cast<void> (0) : __assert_fail ("LoopID->getOperand(0) == LoopID && \"invalid loop id\""
, "/build/llvm-toolchain-snapshot-10~svn374877/lib/Transforms/Utils/LoopUnroll.cpp"
, 965, __PRETTY_FUNCTION__))
;
966
967 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
968 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
969 if (!MD)
970 continue;
971
972 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
973 if (!S)
974 continue;
975
976 if (Name.equals(S->getString()))
977 return MD;
978 }
979 return nullptr;
980}

/build/llvm-toolchain-snapshot-10~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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; }
11
Assuming the condition is false
12
Returning zero, which participates in a condition later
3056 bool isConditional() const { return getNumOperands() == 3; }
15
Assuming the condition is false
16
Returning zero, which participates in a condition later
19
Returning zero, which participates in a condition later
60
Returning zero, 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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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~svn374877/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
3431 /// Add an entry to the switch instruction.
3432 /// Note:
3433 /// This action invalidates case_end(). Old case_end() iterator will
3434 /// point to the added case.
3435 void addCase(ConstantInt *OnVal, BasicBlock *Dest);
3436
3437 /// This method removes the specified case and its successor from the switch
3438 /// instruction. Note that this operation may reorder the remaining cases at
3439 /// index idx and above.
3440 /// Note:
3441 /// This action invalidates iterators for all cases following the one removed,
3442 /// including the case_end() iterator. It returns an iterator for the next
3443 /// case.
3444 CaseIt removeCase(CaseIt I);
3445
3446 unsigned getNumSuccessors() const { return getNumOperands()/2; }
3447 BasicBlock *getSuccessor(unsigned idx) const {
3448 assert(idx < getNumSuccessors() &&"Successor idx out of range for switch!")((idx < getNumSuccessors() &&"Successor idx out of range for switch!"
) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() &&\"Successor idx out of range for switch!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 3448, __PRETTY_FUNCTION__))
;
3449 return cast<BasicBlock>(getOperand(idx*2+1));
3450 }
3451 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
3452 assert(idx < getNumSuccessors() && "Successor # out of range for switch!")((idx < getNumSuccessors() && "Successor # out of range for switch!"
) ? static_cast<void> (0) : __assert_fail ("idx < getNumSuccessors() && \"Successor # out of range for switch!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 3452, __PRETTY_FUNCTION__))
;
3453 setOperand(idx * 2 + 1, NewSucc);
3454 }
3455
3456 // Methods for support type inquiry through isa, cast, and dyn_cast:
3457 static bool classof(const Instruction *I) {
3458 return I->getOpcode() == Instruction::Switch;
3459 }
3460 static bool classof(const Value *V) {
3461 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3462 }
3463};
3464
3465/// A wrapper class to simplify modification of SwitchInst cases along with
3466/// their prof branch_weights metadata.
3467class SwitchInstProfUpdateWrapper {
3468 SwitchInst &SI;
3469 Optional<SmallVector<uint32_t, 8> > Weights = None;
3470 bool Changed = false;
3471
3472protected:
3473 static MDNode *getProfBranchWeightsMD(const SwitchInst &SI);
3474
3475 MDNode *buildProfBranchWeightsMD();
3476
3477 void init();
3478
3479public:
3480 using CaseWeightOpt = Optional<uint32_t>;
3481 SwitchInst *operator->() { return &SI; }
3482 SwitchInst &operator*() { return SI; }
3483 operator SwitchInst *() { return &SI; }
3484
3485 SwitchInstProfUpdateWrapper(SwitchInst &SI) : SI(SI) { init(); }
3486
3487 ~SwitchInstProfUpdateWrapper() {
3488 if (Changed)
3489 SI.setMetadata(LLVMContext::MD_prof, buildProfBranchWeightsMD());
3490 }
3491
3492 /// Delegate the call to the underlying SwitchInst::removeCase() and remove
3493 /// correspondent branch weight.
3494 SwitchInst::CaseIt removeCase(SwitchInst::CaseIt I);
3495
3496 /// Delegate the call to the underlying SwitchInst::addCase() and set the
3497 /// specified branch weight for the added case.
3498 void addCase(ConstantInt *OnVal, BasicBlock *Dest, CaseWeightOpt W);
3499
3500 /// Delegate the call to the underlying SwitchInst::eraseFromParent() and mark
3501 /// this object to not touch the underlying SwitchInst in destructor.
3502 SymbolTableList<Instruction>::iterator eraseFromParent();
3503
3504 void setSuccessorWeight(unsigned idx, CaseWeightOpt W);
3505 CaseWeightOpt getSuccessorWeight(unsigned idx);
3506
3507 static CaseWeightOpt getSuccessorWeight(const SwitchInst &SI, unsigned idx);
3508};
3509
3510template <>
3511struct OperandTraits<SwitchInst> : public HungoffOperandTraits<2> {
3512};
3513
3514DEFINE_TRANSPARENT_OPERAND_ACCESSORS(SwitchInst, Value)SwitchInst::op_iterator SwitchInst::op_begin() { return OperandTraits
<SwitchInst>::op_begin(this); } SwitchInst::const_op_iterator
SwitchInst::op_begin() const { return OperandTraits<SwitchInst
>::op_begin(const_cast<SwitchInst*>(this)); } SwitchInst
::op_iterator SwitchInst::op_end() { return OperandTraits<
SwitchInst>::op_end(this); } SwitchInst::const_op_iterator
SwitchInst::op_end() const { return OperandTraits<SwitchInst
>::op_end(const_cast<SwitchInst*>(this)); } Value *SwitchInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<SwitchInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 3514, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<SwitchInst>::op_begin(const_cast<SwitchInst
*>(this))[i_nocapture].get()); } void SwitchInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<SwitchInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<SwitchInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 3514, __PRETTY_FUNCTION__)); OperandTraits<SwitchInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned SwitchInst
::getNumOperands() const { return OperandTraits<SwitchInst
>::operands(this); } template <int Idx_nocapture> Use
&SwitchInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
SwitchInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
3515
3516//===----------------------------------------------------------------------===//
3517// IndirectBrInst Class
3518//===----------------------------------------------------------------------===//
3519
3520//===---------------------------------------------------------------------------
3521/// Indirect Branch Instruction.
3522///
3523class IndirectBrInst : public Instruction {
3524 unsigned ReservedSpace;
3525
3526 // Operand[0] = Address to jump to
3527 // Operand[n+1] = n-th destination
3528 IndirectBrInst(const IndirectBrInst &IBI);
3529
3530 /// Create a new indirectbr instruction, specifying an
3531 /// Address to jump to. The number of expected destinations can be specified
3532 /// here to make memory allocation more efficient. This constructor can also
3533 /// autoinsert before another instruction.
3534 IndirectBrInst(Value *Address, unsigned NumDests, Instruction *InsertBefore);
3535
3536 /// Create a new indirectbr instruction, specifying an
3537 /// Address to jump to. The number of expected destinations can be specified
3538 /// here to make memory allocation more efficient. This constructor also
3539 /// autoinserts at the end of the specified BasicBlock.
3540 IndirectBrInst(Value *Address, unsigned NumDests, BasicBlock *InsertAtEnd);
3541
3542 // allocate space for exactly zero operands
3543 void *operator new(size_t s) {
3544 return User::operator new(s);
3545 }
3546
3547 void init(Value *Address, unsigned NumDests);
3548 void growOperands();
3549
3550protected:
3551 // Note: Instruction needs to be a friend here to call cloneImpl.
3552 friend class Instruction;
3553
3554 IndirectBrInst *cloneImpl() const;
3555
3556public:
3557 /// Iterator type that casts an operand to a basic block.
3558 ///
3559 /// This only makes sense because the successors are stored as adjacent
3560 /// operands for indirectbr instructions.
3561 struct succ_op_iterator
3562 : iterator_adaptor_base<succ_op_iterator, value_op_iterator,
3563 std::random_access_iterator_tag, BasicBlock *,
3564 ptrdiff_t, BasicBlock *, BasicBlock *> {
3565 explicit succ_op_iterator(value_op_iterator I) : iterator_adaptor_base(I) {}
3566
3567 BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3568 BasicBlock *operator->() const { return operator*(); }
3569 };
3570
3571 /// The const version of `succ_op_iterator`.
3572 struct const_succ_op_iterator
3573 : iterator_adaptor_base<const_succ_op_iterator, const_value_op_iterator,
3574 std::random_access_iterator_tag,
3575 const BasicBlock *, ptrdiff_t, const BasicBlock *,
3576 const BasicBlock *> {
3577 explicit const_succ_op_iterator(const_value_op_iterator I)
3578 : iterator_adaptor_base(I) {}
3579
3580 const BasicBlock *operator*() const { return cast<BasicBlock>(*I); }
3581 const BasicBlock *operator->() const { return operator*(); }
3582 };
3583
3584 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3585 Instruction *InsertBefore = nullptr) {
3586 return new IndirectBrInst(Address, NumDests, InsertBefore);
3587 }
3588
3589 static IndirectBrInst *Create(Value *Address, unsigned NumDests,
3590 BasicBlock *InsertAtEnd) {
3591 return new IndirectBrInst(Address, NumDests, InsertAtEnd);
3592 }
3593
3594 /// Provide fast operand accessors.
3595 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
;
3596
3597 // Accessor Methods for IndirectBrInst instruction.
3598 Value *getAddress() { return getOperand(0); }
3599 const Value *getAddress() const { return getOperand(0); }
3600 void setAddress(Value *V) { setOperand(0, V); }
3601
3602 /// return the number of possible destinations in this
3603 /// indirectbr instruction.
3604 unsigned getNumDestinations() const { return getNumOperands()-1; }
3605
3606 /// Return the specified destination.
3607 BasicBlock *getDestination(unsigned i) { return getSuccessor(i); }
3608 const BasicBlock *getDestination(unsigned i) const { return getSuccessor(i); }
3609
3610 /// Add a destination.
3611 ///
3612 void addDestination(BasicBlock *Dest);
3613
3614 /// This method removes the specified successor from the
3615 /// indirectbr instruction.
3616 void removeDestination(unsigned i);
3617
3618 unsigned getNumSuccessors() const { return getNumOperands()-1; }
3619 BasicBlock *getSuccessor(unsigned i) const {
3620 return cast<BasicBlock>(getOperand(i+1));
3621 }
3622 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3623 setOperand(i + 1, NewSucc);
3624 }
3625
3626 iterator_range<succ_op_iterator> successors() {
3627 return make_range(succ_op_iterator(std::next(value_op_begin())),
3628 succ_op_iterator(value_op_end()));
3629 }
3630
3631 iterator_range<const_succ_op_iterator> successors() const {
3632 return make_range(const_succ_op_iterator(std::next(value_op_begin())),
3633 const_succ_op_iterator(value_op_end()));
3634 }
3635
3636 // Methods for support type inquiry through isa, cast, and dyn_cast:
3637 static bool classof(const Instruction *I) {
3638 return I->getOpcode() == Instruction::IndirectBr;
3639 }
3640 static bool classof(const Value *V) {
3641 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3642 }
3643};
3644
3645template <>
3646struct OperandTraits<IndirectBrInst> : public HungoffOperandTraits<1> {
3647};
3648
3649DEFINE_TRANSPARENT_OPERAND_ACCESSORS(IndirectBrInst, Value)IndirectBrInst::op_iterator IndirectBrInst::op_begin() { return
OperandTraits<IndirectBrInst>::op_begin(this); } IndirectBrInst
::const_op_iterator IndirectBrInst::op_begin() const { return
OperandTraits<IndirectBrInst>::op_begin(const_cast<
IndirectBrInst*>(this)); } IndirectBrInst::op_iterator IndirectBrInst
::op_end() { return OperandTraits<IndirectBrInst>::op_end
(this); } IndirectBrInst::const_op_iterator IndirectBrInst::op_end
() const { return OperandTraits<IndirectBrInst>::op_end
(const_cast<IndirectBrInst*>(this)); } Value *IndirectBrInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<IndirectBrInst>::operands(this) &&
"getOperand() out of range!") ? static_cast<void> (0) :
__assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 3649, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<IndirectBrInst>::op_begin(const_cast<
IndirectBrInst*>(this))[i_nocapture].get()); } void IndirectBrInst
::setOperand(unsigned i_nocapture, Value *Val_nocapture) { ((
i_nocapture < OperandTraits<IndirectBrInst>::operands
(this) && "setOperand() out of range!") ? static_cast
<void> (0) : __assert_fail ("i_nocapture < OperandTraits<IndirectBrInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 3649, __PRETTY_FUNCTION__)); OperandTraits<IndirectBrInst
>::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned
IndirectBrInst::getNumOperands() const { return OperandTraits
<IndirectBrInst>::operands(this); } template <int Idx_nocapture
> Use &IndirectBrInst::Op() { return this->OpFrom<
Idx_nocapture>(this); } template <int Idx_nocapture>
const Use &IndirectBrInst::Op() const { return this->
OpFrom<Idx_nocapture>(this); }
3650
3651//===----------------------------------------------------------------------===//
3652// InvokeInst Class
3653//===----------------------------------------------------------------------===//
3654
3655/// Invoke instruction. The SubclassData field is used to hold the
3656/// calling convention of the call.
3657///
3658class InvokeInst : public CallBase {
3659 /// The number of operands for this call beyond the called function,
3660 /// arguments, and operand bundles.
3661 static constexpr int NumExtraOperands = 2;
3662
3663 /// The index from the end of the operand array to the normal destination.
3664 static constexpr int NormalDestOpEndIdx = -3;
3665
3666 /// The index from the end of the operand array to the unwind destination.
3667 static constexpr int UnwindDestOpEndIdx = -2;
3668
3669 InvokeInst(const InvokeInst &BI);
3670
3671 /// Construct an InvokeInst given a range of arguments.
3672 ///
3673 /// Construct an InvokeInst from a range of arguments
3674 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3675 BasicBlock *IfException, ArrayRef<Value *> Args,
3676 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3677 const Twine &NameStr, Instruction *InsertBefore);
3678
3679 inline InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3680 BasicBlock *IfException, ArrayRef<Value *> Args,
3681 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3682 const Twine &NameStr, BasicBlock *InsertAtEnd);
3683
3684 void init(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3685 BasicBlock *IfException, ArrayRef<Value *> Args,
3686 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3687
3688 /// Compute the number of operands to allocate.
3689 static int ComputeNumOperands(int NumArgs, int NumBundleInputs = 0) {
3690 // We need one operand for the called function, plus our extra operands and
3691 // the input operand counts provided.
3692 return 1 + NumExtraOperands + NumArgs + NumBundleInputs;
3693 }
3694
3695protected:
3696 // Note: Instruction needs to be a friend here to call cloneImpl.
3697 friend class Instruction;
3698
3699 InvokeInst *cloneImpl() const;
3700
3701public:
3702 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3703 BasicBlock *IfException, ArrayRef<Value *> Args,
3704 const Twine &NameStr,
3705 Instruction *InsertBefore = nullptr) {
3706 int NumOperands = ComputeNumOperands(Args.size());
3707 return new (NumOperands)
3708 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3709 NameStr, InsertBefore);
3710 }
3711
3712 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3713 BasicBlock *IfException, ArrayRef<Value *> Args,
3714 ArrayRef<OperandBundleDef> Bundles = None,
3715 const Twine &NameStr = "",
3716 Instruction *InsertBefore = nullptr) {
3717 int NumOperands =
3718 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3719 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3720
3721 return new (NumOperands, DescriptorBytes)
3722 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3723 NameStr, InsertBefore);
3724 }
3725
3726 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3727 BasicBlock *IfException, ArrayRef<Value *> Args,
3728 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3729 int NumOperands = ComputeNumOperands(Args.size());
3730 return new (NumOperands)
3731 InvokeInst(Ty, Func, IfNormal, IfException, Args, None, NumOperands,
3732 NameStr, InsertAtEnd);
3733 }
3734
3735 static InvokeInst *Create(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3736 BasicBlock *IfException, ArrayRef<Value *> Args,
3737 ArrayRef<OperandBundleDef> Bundles,
3738 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3739 int NumOperands =
3740 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles));
3741 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3742
3743 return new (NumOperands, DescriptorBytes)
3744 InvokeInst(Ty, Func, IfNormal, IfException, Args, Bundles, NumOperands,
3745 NameStr, InsertAtEnd);
3746 }
3747
3748 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3749 BasicBlock *IfException, ArrayRef<Value *> Args,
3750 const Twine &NameStr,
3751 Instruction *InsertBefore = nullptr) {
3752 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3753 IfException, Args, None, NameStr, InsertBefore);
3754 }
3755
3756 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3757 BasicBlock *IfException, ArrayRef<Value *> Args,
3758 ArrayRef<OperandBundleDef> Bundles = None,
3759 const Twine &NameStr = "",
3760 Instruction *InsertBefore = nullptr) {
3761 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3762 IfException, Args, Bundles, NameStr, InsertBefore);
3763 }
3764
3765 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3766 BasicBlock *IfException, ArrayRef<Value *> Args,
3767 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3768 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3769 IfException, Args, NameStr, InsertAtEnd);
3770 }
3771
3772 static InvokeInst *Create(FunctionCallee Func, BasicBlock *IfNormal,
3773 BasicBlock *IfException, ArrayRef<Value *> Args,
3774 ArrayRef<OperandBundleDef> Bundles,
3775 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3776 return Create(Func.getFunctionType(), Func.getCallee(), IfNormal,
3777 IfException, Args, Bundles, NameStr, InsertAtEnd);
3778 }
3779
3780 // Deprecated [opaque pointer types]
3781 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3782 BasicBlock *IfException, ArrayRef<Value *> Args,
3783 const Twine &NameStr,
3784 Instruction *InsertBefore = nullptr) {
3785 return Create(cast<FunctionType>(
3786 cast<PointerType>(Func->getType())->getElementType()),
3787 Func, IfNormal, IfException, Args, None, NameStr,
3788 InsertBefore);
3789 }
3790
3791 // Deprecated [opaque pointer types]
3792 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3793 BasicBlock *IfException, ArrayRef<Value *> Args,
3794 ArrayRef<OperandBundleDef> Bundles = None,
3795 const Twine &NameStr = "",
3796 Instruction *InsertBefore = nullptr) {
3797 return Create(cast<FunctionType>(
3798 cast<PointerType>(Func->getType())->getElementType()),
3799 Func, IfNormal, IfException, Args, Bundles, NameStr,
3800 InsertBefore);
3801 }
3802
3803 // Deprecated [opaque pointer types]
3804 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3805 BasicBlock *IfException, ArrayRef<Value *> Args,
3806 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3807 return Create(cast<FunctionType>(
3808 cast<PointerType>(Func->getType())->getElementType()),
3809 Func, IfNormal, IfException, Args, NameStr, InsertAtEnd);
3810 }
3811
3812 // Deprecated [opaque pointer types]
3813 static InvokeInst *Create(Value *Func, BasicBlock *IfNormal,
3814 BasicBlock *IfException, ArrayRef<Value *> Args,
3815 ArrayRef<OperandBundleDef> Bundles,
3816 const Twine &NameStr, BasicBlock *InsertAtEnd) {
3817 return Create(cast<FunctionType>(
3818 cast<PointerType>(Func->getType())->getElementType()),
3819 Func, IfNormal, IfException, Args, Bundles, NameStr,
3820 InsertAtEnd);
3821 }
3822
3823 /// Create a clone of \p II with a different set of operand bundles and
3824 /// insert it before \p InsertPt.
3825 ///
3826 /// The returned invoke instruction is identical to \p II in every way except
3827 /// that the operand bundles for the new instruction are set to the operand
3828 /// bundles in \p Bundles.
3829 static InvokeInst *Create(InvokeInst *II, ArrayRef<OperandBundleDef> Bundles,
3830 Instruction *InsertPt = nullptr);
3831
3832 /// Determine if the call should not perform indirect branch tracking.
3833 bool doesNoCfCheck() const { return hasFnAttr(Attribute::NoCfCheck); }
3834
3835 /// Determine if the call cannot unwind.
3836 bool doesNotThrow() const { return hasFnAttr(Attribute::NoUnwind); }
3837 void setDoesNotThrow() {
3838 addAttribute(AttributeList::FunctionIndex, Attribute::NoUnwind);
3839 }
3840
3841 // get*Dest - Return the destination basic blocks...
3842 BasicBlock *getNormalDest() const {
3843 return cast<BasicBlock>(Op<NormalDestOpEndIdx>());
3844 }
3845 BasicBlock *getUnwindDest() const {
3846 return cast<BasicBlock>(Op<UnwindDestOpEndIdx>());
3847 }
3848 void setNormalDest(BasicBlock *B) {
3849 Op<NormalDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3850 }
3851 void setUnwindDest(BasicBlock *B) {
3852 Op<UnwindDestOpEndIdx>() = reinterpret_cast<Value *>(B);
3853 }
3854
3855 /// Get the landingpad instruction from the landing pad
3856 /// block (the unwind destination).
3857 LandingPadInst *getLandingPadInst() const;
3858
3859 BasicBlock *getSuccessor(unsigned i) const {
3860 assert(i < 2 && "Successor # out of range for invoke!")((i < 2 && "Successor # out of range for invoke!")
? static_cast<void> (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 3860, __PRETTY_FUNCTION__))
;
3861 return i == 0 ? getNormalDest() : getUnwindDest();
3862 }
3863
3864 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
3865 assert(i < 2 && "Successor # out of range for invoke!")((i < 2 && "Successor # out of range for invoke!")
? static_cast<void> (0) : __assert_fail ("i < 2 && \"Successor # out of range for invoke!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 3865, __PRETTY_FUNCTION__))
;
3866 if (i == 0)
3867 setNormalDest(NewSucc);
3868 else
3869 setUnwindDest(NewSucc);
3870 }
3871
3872 unsigned getNumSuccessors() const { return 2; }
3873
3874 // Methods for support type inquiry through isa, cast, and dyn_cast:
3875 static bool classof(const Instruction *I) {
3876 return (I->getOpcode() == Instruction::Invoke);
3877 }
3878 static bool classof(const Value *V) {
3879 return isa<Instruction>(V) && classof(cast<Instruction>(V));
3880 }
3881
3882private:
3883
3884 // Shadow Instruction::setInstructionSubclassData with a private forwarding
3885 // method so that subclasses cannot accidentally use it.
3886 void setInstructionSubclassData(unsigned short D) {
3887 Instruction::setInstructionSubclassData(D);
3888 }
3889};
3890
3891InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3892 BasicBlock *IfException, ArrayRef<Value *> Args,
3893 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3894 const Twine &NameStr, Instruction *InsertBefore)
3895 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3896 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3897 InsertBefore) {
3898 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3899}
3900
3901InvokeInst::InvokeInst(FunctionType *Ty, Value *Func, BasicBlock *IfNormal,
3902 BasicBlock *IfException, ArrayRef<Value *> Args,
3903 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3904 const Twine &NameStr, BasicBlock *InsertAtEnd)
3905 : CallBase(Ty->getReturnType(), Instruction::Invoke,
3906 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
3907 InsertAtEnd) {
3908 init(Ty, Func, IfNormal, IfException, Args, Bundles, NameStr);
3909}
3910
3911//===----------------------------------------------------------------------===//
3912// CallBrInst Class
3913//===----------------------------------------------------------------------===//
3914
3915/// CallBr instruction, tracking function calls that may not return control but
3916/// instead transfer it to a third location. The SubclassData field is used to
3917/// hold the calling convention of the call.
3918///
3919class CallBrInst : public CallBase {
3920
3921 unsigned NumIndirectDests;
3922
3923 CallBrInst(const CallBrInst &BI);
3924
3925 /// Construct a CallBrInst given a range of arguments.
3926 ///
3927 /// Construct a CallBrInst from a range of arguments
3928 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3929 ArrayRef<BasicBlock *> IndirectDests,
3930 ArrayRef<Value *> Args,
3931 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3932 const Twine &NameStr, Instruction *InsertBefore);
3933
3934 inline CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
3935 ArrayRef<BasicBlock *> IndirectDests,
3936 ArrayRef<Value *> Args,
3937 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
3938 const Twine &NameStr, BasicBlock *InsertAtEnd);
3939
3940 void init(FunctionType *FTy, Value *Func, BasicBlock *DefaultDest,
3941 ArrayRef<BasicBlock *> IndirectDests, ArrayRef<Value *> Args,
3942 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr);
3943
3944 /// Should the Indirect Destinations change, scan + update the Arg list.
3945 void updateArgBlockAddresses(unsigned i, BasicBlock *B);
3946
3947 /// Compute the number of operands to allocate.
3948 static int ComputeNumOperands(int NumArgs, int NumIndirectDests,
3949 int NumBundleInputs = 0) {
3950 // We need one operand for the called function, plus our extra operands and
3951 // the input operand counts provided.
3952 return 2 + NumIndirectDests + NumArgs + NumBundleInputs;
3953 }
3954
3955protected:
3956 // Note: Instruction needs to be a friend here to call cloneImpl.
3957 friend class Instruction;
3958
3959 CallBrInst *cloneImpl() const;
3960
3961public:
3962 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3963 BasicBlock *DefaultDest,
3964 ArrayRef<BasicBlock *> IndirectDests,
3965 ArrayRef<Value *> Args, const Twine &NameStr,
3966 Instruction *InsertBefore = nullptr) {
3967 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3968 return new (NumOperands)
3969 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3970 NumOperands, NameStr, InsertBefore);
3971 }
3972
3973 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3974 BasicBlock *DefaultDest,
3975 ArrayRef<BasicBlock *> IndirectDests,
3976 ArrayRef<Value *> Args,
3977 ArrayRef<OperandBundleDef> Bundles = None,
3978 const Twine &NameStr = "",
3979 Instruction *InsertBefore = nullptr) {
3980 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
3981 CountBundleInputs(Bundles));
3982 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
3983
3984 return new (NumOperands, DescriptorBytes)
3985 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
3986 NumOperands, NameStr, InsertBefore);
3987 }
3988
3989 static CallBrInst *Create(FunctionType *Ty, Value *Func,
3990 BasicBlock *DefaultDest,
3991 ArrayRef<BasicBlock *> IndirectDests,
3992 ArrayRef<Value *> Args, const Twine &NameStr,
3993 BasicBlock *InsertAtEnd) {
3994 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size());
3995 return new (NumOperands)
3996 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, None,
3997 NumOperands, NameStr, InsertAtEnd);
3998 }
3999
4000 static CallBrInst *Create(FunctionType *Ty, Value *Func,
4001 BasicBlock *DefaultDest,
4002 ArrayRef<BasicBlock *> IndirectDests,
4003 ArrayRef<Value *> Args,
4004 ArrayRef<OperandBundleDef> Bundles,
4005 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4006 int NumOperands = ComputeNumOperands(Args.size(), IndirectDests.size(),
4007 CountBundleInputs(Bundles));
4008 unsigned DescriptorBytes = Bundles.size() * sizeof(BundleOpInfo);
4009
4010 return new (NumOperands, DescriptorBytes)
4011 CallBrInst(Ty, Func, DefaultDest, IndirectDests, Args, Bundles,
4012 NumOperands, NameStr, InsertAtEnd);
4013 }
4014
4015 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4016 ArrayRef<BasicBlock *> IndirectDests,
4017 ArrayRef<Value *> Args, const Twine &NameStr,
4018 Instruction *InsertBefore = nullptr) {
4019 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4020 IndirectDests, Args, NameStr, InsertBefore);
4021 }
4022
4023 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4024 ArrayRef<BasicBlock *> IndirectDests,
4025 ArrayRef<Value *> Args,
4026 ArrayRef<OperandBundleDef> Bundles = None,
4027 const Twine &NameStr = "",
4028 Instruction *InsertBefore = nullptr) {
4029 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4030 IndirectDests, Args, Bundles, NameStr, InsertBefore);
4031 }
4032
4033 static CallBrInst *Create(FunctionCallee Func, BasicBlock *DefaultDest,
4034 ArrayRef<BasicBlock *> IndirectDests,
4035 ArrayRef<Value *> Args, const Twine &NameStr,
4036 BasicBlock *InsertAtEnd) {
4037 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4038 IndirectDests, Args, NameStr, InsertAtEnd);
4039 }
4040
4041 static CallBrInst *Create(FunctionCallee Func,
4042 BasicBlock *DefaultDest,
4043 ArrayRef<BasicBlock *> IndirectDests,
4044 ArrayRef<Value *> Args,
4045 ArrayRef<OperandBundleDef> Bundles,
4046 const Twine &NameStr, BasicBlock *InsertAtEnd) {
4047 return Create(Func.getFunctionType(), Func.getCallee(), DefaultDest,
4048 IndirectDests, Args, Bundles, NameStr, InsertAtEnd);
4049 }
4050
4051 /// Create a clone of \p CBI with a different set of operand bundles and
4052 /// insert it before \p InsertPt.
4053 ///
4054 /// The returned callbr instruction is identical to \p CBI in every way
4055 /// except that the operand bundles for the new instruction are set to the
4056 /// operand bundles in \p Bundles.
4057 static CallBrInst *Create(CallBrInst *CBI,
4058 ArrayRef<OperandBundleDef> Bundles,
4059 Instruction *InsertPt = nullptr);
4060
4061 /// Return the number of callbr indirect dest labels.
4062 ///
4063 unsigned getNumIndirectDests() const { return NumIndirectDests; }
4064
4065 /// getIndirectDestLabel - Return the i-th indirect dest label.
4066 ///
4067 Value *getIndirectDestLabel(unsigned i) const {
4068 assert(i < getNumIndirectDests() && "Out of bounds!")((i < getNumIndirectDests() && "Out of bounds!") ?
static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4068, __PRETTY_FUNCTION__))
;
4069 return getOperand(i + getNumArgOperands() + getNumTotalBundleOperands() +
4070 1);
4071 }
4072
4073 Value *getIndirectDestLabelUse(unsigned i) const {
4074 assert(i < getNumIndirectDests() && "Out of bounds!")((i < getNumIndirectDests() && "Out of bounds!") ?
static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() && \"Out of bounds!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4074, __PRETTY_FUNCTION__))
;
4075 return getOperandUse(i + getNumArgOperands() + getNumTotalBundleOperands() +
4076 1);
4077 }
4078
4079 // Return the destination basic blocks...
4080 BasicBlock *getDefaultDest() const {
4081 return cast<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() - 1));
4082 }
4083 BasicBlock *getIndirectDest(unsigned i) const {
4084 return cast_or_null<BasicBlock>(*(&Op<-1>() - getNumIndirectDests() + i));
4085 }
4086 SmallVector<BasicBlock *, 16> getIndirectDests() const {
4087 SmallVector<BasicBlock *, 16> IndirectDests;
4088 for (unsigned i = 0, e = getNumIndirectDests(); i < e; ++i)
4089 IndirectDests.push_back(getIndirectDest(i));
4090 return IndirectDests;
4091 }
4092 void setDefaultDest(BasicBlock *B) {
4093 *(&Op<-1>() - getNumIndirectDests() - 1) = reinterpret_cast<Value *>(B);
4094 }
4095 void setIndirectDest(unsigned i, BasicBlock *B) {
4096 updateArgBlockAddresses(i, B);
4097 *(&Op<-1>() - getNumIndirectDests() + i) = reinterpret_cast<Value *>(B);
4098 }
4099
4100 BasicBlock *getSuccessor(unsigned i) const {
4101 assert(i < getNumSuccessors() + 1 &&((i < getNumSuccessors() + 1 && "Successor # out of range for callbr!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4102, __PRETTY_FUNCTION__))
4102 "Successor # out of range for callbr!")((i < getNumSuccessors() + 1 && "Successor # out of range for callbr!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumSuccessors() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4102, __PRETTY_FUNCTION__))
;
4103 return i == 0 ? getDefaultDest() : getIndirectDest(i - 1);
4104 }
4105
4106 void setSuccessor(unsigned i, BasicBlock *NewSucc) {
4107 assert(i < getNumIndirectDests() + 1 &&((i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4108, __PRETTY_FUNCTION__))
4108 "Successor # out of range for callbr!")((i < getNumIndirectDests() + 1 && "Successor # out of range for callbr!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumIndirectDests() + 1 && \"Successor # out of range for callbr!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4108, __PRETTY_FUNCTION__))
;
4109 return i == 0 ? setDefaultDest(NewSucc) : setIndirectDest(i - 1, NewSucc);
4110 }
4111
4112 unsigned getNumSuccessors() const { return getNumIndirectDests() + 1; }
4113
4114 // Methods for support type inquiry through isa, cast, and dyn_cast:
4115 static bool classof(const Instruction *I) {
4116 return (I->getOpcode() == Instruction::CallBr);
4117 }
4118 static bool classof(const Value *V) {
4119 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4120 }
4121
4122private:
4123
4124 // Shadow Instruction::setInstructionSubclassData with a private forwarding
4125 // method so that subclasses cannot accidentally use it.
4126 void setInstructionSubclassData(unsigned short D) {
4127 Instruction::setInstructionSubclassData(D);
4128 }
4129};
4130
4131CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4132 ArrayRef<BasicBlock *> IndirectDests,
4133 ArrayRef<Value *> Args,
4134 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4135 const Twine &NameStr, Instruction *InsertBefore)
4136 : CallBase(Ty->getReturnType(), Instruction::CallBr,
4137 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4138 InsertBefore) {
4139 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4140}
4141
4142CallBrInst::CallBrInst(FunctionType *Ty, Value *Func, BasicBlock *DefaultDest,
4143 ArrayRef<BasicBlock *> IndirectDests,
4144 ArrayRef<Value *> Args,
4145 ArrayRef<OperandBundleDef> Bundles, int NumOperands,
4146 const Twine &NameStr, BasicBlock *InsertAtEnd)
4147 : CallBase(
4148 cast<FunctionType>(
4149 cast<PointerType>(Func->getType())->getElementType())
4150 ->getReturnType(),
4151 Instruction::CallBr,
4152 OperandTraits<CallBase>::op_end(this) - NumOperands, NumOperands,
4153 InsertAtEnd) {
4154 init(Ty, Func, DefaultDest, IndirectDests, Args, Bundles, NameStr);
4155}
4156
4157//===----------------------------------------------------------------------===//
4158// ResumeInst Class
4159//===----------------------------------------------------------------------===//
4160
4161//===---------------------------------------------------------------------------
4162/// Resume the propagation of an exception.
4163///
4164class ResumeInst : public Instruction {
4165 ResumeInst(const ResumeInst &RI);
4166
4167 explicit ResumeInst(Value *Exn, Instruction *InsertBefore=nullptr);
4168 ResumeInst(Value *Exn, BasicBlock *InsertAtEnd);
4169
4170protected:
4171 // Note: Instruction needs to be a friend here to call cloneImpl.
4172 friend class Instruction;
4173
4174 ResumeInst *cloneImpl() const;
4175
4176public:
4177 static ResumeInst *Create(Value *Exn, Instruction *InsertBefore = nullptr) {
4178 return new(1) ResumeInst(Exn, InsertBefore);
4179 }
4180
4181 static ResumeInst *Create(Value *Exn, BasicBlock *InsertAtEnd) {
4182 return new(1) ResumeInst(Exn, InsertAtEnd);
4183 }
4184
4185 /// Provide fast operand accessors
4186 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
;
4187
4188 /// Convenience accessor.
4189 Value *getValue() const { return Op<0>(); }
4190
4191 unsigned getNumSuccessors() const { return 0; }
4192
4193 // Methods for support type inquiry through isa, cast, and dyn_cast:
4194 static bool classof(const Instruction *I) {
4195 return I->getOpcode() == Instruction::Resume;
4196 }
4197 static bool classof(const Value *V) {
4198 return isa<Instruction>(V) && classof(cast<Instruction>(V));
4199 }
4200
4201private:
4202 BasicBlock *getSuccessor(unsigned idx) const {
4203 llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!"
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4203)
;
4204 }
4205
4206 void setSuccessor(unsigned idx, BasicBlock *NewSucc) {
4207 llvm_unreachable("ResumeInst has no successors!")::llvm::llvm_unreachable_internal("ResumeInst has no successors!"
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4207)
;
4208 }
4209};
4210
4211template <>
4212struct OperandTraits<ResumeInst> :
4213 public FixedNumOperandTraits<ResumeInst, 1> {
4214};
4215
4216DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ResumeInst, Value)ResumeInst::op_iterator ResumeInst::op_begin() { return OperandTraits
<ResumeInst>::op_begin(this); } ResumeInst::const_op_iterator
ResumeInst::op_begin() const { return OperandTraits<ResumeInst
>::op_begin(const_cast<ResumeInst*>(this)); } ResumeInst
::op_iterator ResumeInst::op_end() { return OperandTraits<
ResumeInst>::op_end(this); } ResumeInst::const_op_iterator
ResumeInst::op_end() const { return OperandTraits<ResumeInst
>::op_end(const_cast<ResumeInst*>(this)); } Value *ResumeInst
::getOperand(unsigned i_nocapture) const { ((i_nocapture <
OperandTraits<ResumeInst>::operands(this) && "getOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"getOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4216, __PRETTY_FUNCTION__)); return cast_or_null<Value>
( OperandTraits<ResumeInst>::op_begin(const_cast<ResumeInst
*>(this))[i_nocapture].get()); } void ResumeInst::setOperand
(unsigned i_nocapture, Value *Val_nocapture) { ((i_nocapture <
OperandTraits<ResumeInst>::operands(this) && "setOperand() out of range!"
) ? static_cast<void> (0) : __assert_fail ("i_nocapture < OperandTraits<ResumeInst>::operands(this) && \"setOperand() out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn374877/include/llvm/IR/Instructions.h"
, 4216, __PRETTY_FUNCTION__)); OperandTraits<ResumeInst>
::op_begin(this)[i_nocapture] = Val_nocapture; } unsigned ResumeInst
::getNumOperands() const { return OperandTraits<ResumeInst
>::operands(this); } template <int Idx_nocapture> Use
&ResumeInst::Op() { return this->OpFrom<Idx_nocapture
>(this); } template <int Idx_nocapture> const Use &
ResumeInst::Op() const { return this->OpFrom<Idx_nocapture
>(this); }
4217
4218//===----------------------------------------------------------------------===//
4219// CatchSwitchInst Class
4220//===----------------------------------------------------------------------===//
4221class CatchSwitchInst : public Instruction {
4222 /// The number of operands actually allocated. NumOperands is
4223 /// the number actually in use.
4224 unsigned ReservedSpace;
4225
4226 // Operand[0] = Outer scope
4227 // Operand[1] = Unwind block destination
4228 // Operand[n] = BasicBlock to go to on match
4229 CatchSwitchInst(const CatchSwitchInst &CSI);
4230
4231 /// Create a new switch instruction, specifying a
4232 /// default destination. The number of additional handlers can be specified
4233 /// here to make memory allocation more efficient.
4234 /// This constructor can also autoinsert before another instruction.
4235 CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
4236 unsigned NumHandlers, const Twine &NameStr,
4237 Instruction *InsertBefore);
4238
4239 /// Create a new switch instruction, specifying a
4240 /// default destination. The number of additional handlers can be specified
4241 /// here to make memory allocation more efficient.
4242 /// This constructor also autoinserts at the end of the specified BasicBl