Bug Summary

File:lib/CodeGen/WinEHPrepare.cpp
Warning:line 210, column 30
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 WinEHPrepare.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen -I /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn338205/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/x86_64-linux-gnu/c++/8 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/8/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-class-memaccess -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn338205/build-llvm/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-29-043837-17923-1 -x c++ /build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp -faddrsig

/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp

1//===-- WinEHPrepare - Prepare exception handling for code generation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass lowers LLVM IR exception handling into something closer to what the
11// backend wants for functions using a personality function from a runtime
12// provided by MSVC. Functions with other personality functions are left alone
13// and may be prepared by other passes. In particular, all supported MSVC
14// personality functions require cleanup code to be outlined, and the C++
15// personality requires catch handler code to be outlined.
16//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/ADT/DenseMap.h"
20#include "llvm/ADT/MapVector.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/Analysis/CFG.h"
23#include "llvm/Analysis/EHPersonalities.h"
24#include "llvm/Transforms/Utils/Local.h"
25#include "llvm/CodeGen/MachineBasicBlock.h"
26#include "llvm/CodeGen/Passes.h"
27#include "llvm/CodeGen/WinEHFuncInfo.h"
28#include "llvm/IR/Verifier.h"
29#include "llvm/MC/MCSymbol.h"
30#include "llvm/Pass.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Transforms/Utils/BasicBlockUtils.h"
34#include "llvm/Transforms/Utils/Cloning.h"
35#include "llvm/Transforms/Utils/SSAUpdater.h"
36
37using namespace llvm;
38
39#define DEBUG_TYPE"winehprepare" "winehprepare"
40
41static cl::opt<bool> DisableDemotion(
42 "disable-demotion", cl::Hidden,
43 cl::desc(
44 "Clone multicolor basic blocks but do not demote cross scopes"),
45 cl::init(false));
46
47static cl::opt<bool> DisableCleanups(
48 "disable-cleanups", cl::Hidden,
49 cl::desc("Do not remove implausible terminators or other similar cleanups"),
50 cl::init(false));
51
52static cl::opt<bool> DemoteCatchSwitchPHIOnlyOpt(
53 "demote-catchswitch-only", cl::Hidden,
54 cl::desc("Demote catchswitch BBs only (for wasm EH)"), cl::init(false));
55
56namespace {
57
58class WinEHPrepare : public FunctionPass {
59public:
60 static char ID; // Pass identification, replacement for typeid.
61 WinEHPrepare(bool DemoteCatchSwitchPHIOnly = false)
62 : FunctionPass(ID), DemoteCatchSwitchPHIOnly(DemoteCatchSwitchPHIOnly) {}
63
64 bool runOnFunction(Function &Fn) override;
65
66 bool doFinalization(Module &M) override;
67
68 void getAnalysisUsage(AnalysisUsage &AU) const override;
69
70 StringRef getPassName() const override {
71 return "Windows exception handling preparation";
72 }
73
74private:
75 void insertPHIStores(PHINode *OriginalPHI, AllocaInst *SpillSlot);
76 void
77 insertPHIStore(BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
78 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist);
79 AllocaInst *insertPHILoads(PHINode *PN, Function &F);
80 void replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
81 DenseMap<BasicBlock *, Value *> &Loads, Function &F);
82 bool prepareExplicitEH(Function &F);
83 void colorFunclets(Function &F);
84
85 void demotePHIsOnFunclets(Function &F, bool DemoteCatchSwitchPHIOnly);
86 void cloneCommonBlocks(Function &F);
87 void removeImplausibleInstructions(Function &F);
88 void cleanupPreparedFunclets(Function &F);
89 void verifyPreparedFunclets(Function &F);
90
91 bool DemoteCatchSwitchPHIOnly;
92
93 // All fields are reset by runOnFunction.
94 EHPersonality Personality = EHPersonality::Unknown;
95
96 const DataLayout *DL = nullptr;
97 DenseMap<BasicBlock *, ColorVector> BlockColors;
98 MapVector<BasicBlock *, std::vector<BasicBlock *>> FuncletBlocks;
99};
100
101} // end anonymous namespace
102
103char WinEHPrepare::ID = 0;
104INITIALIZE_PASS(WinEHPrepare, DEBUG_TYPE, "Prepare Windows exceptions",static void *initializeWinEHPreparePassOnce(PassRegistry &
Registry) { PassInfo *PI = new PassInfo( "Prepare Windows exceptions"
, "winehprepare", &WinEHPrepare::ID, PassInfo::NormalCtor_t
(callDefaultCtor<WinEHPrepare>), false, false); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeWinEHPreparePassFlag; void llvm::initializeWinEHPreparePass
(PassRegistry &Registry) { llvm::call_once(InitializeWinEHPreparePassFlag
, initializeWinEHPreparePassOnce, std::ref(Registry)); }
105 false, false)static void *initializeWinEHPreparePassOnce(PassRegistry &
Registry) { PassInfo *PI = new PassInfo( "Prepare Windows exceptions"
, "winehprepare", &WinEHPrepare::ID, PassInfo::NormalCtor_t
(callDefaultCtor<WinEHPrepare>), false, false); Registry
.registerPass(*PI, true); return PI; } static llvm::once_flag
InitializeWinEHPreparePassFlag; void llvm::initializeWinEHPreparePass
(PassRegistry &Registry) { llvm::call_once(InitializeWinEHPreparePassFlag
, initializeWinEHPreparePassOnce, std::ref(Registry)); }
106
107FunctionPass *llvm::createWinEHPass(bool DemoteCatchSwitchPHIOnly) {
108 return new WinEHPrepare(DemoteCatchSwitchPHIOnly);
109}
110
111bool WinEHPrepare::runOnFunction(Function &Fn) {
112 if (!Fn.hasPersonalityFn())
113 return false;
114
115 // Classify the personality to see what kind of preparation we need.
116 Personality = classifyEHPersonality(Fn.getPersonalityFn());
117
118 // Do nothing if this is not a scope-based personality.
119 if (!isScopedEHPersonality(Personality))
120 return false;
121
122 DL = &Fn.getParent()->getDataLayout();
123 return prepareExplicitEH(Fn);
124}
125
126bool WinEHPrepare::doFinalization(Module &M) { return false; }
127
128void WinEHPrepare::getAnalysisUsage(AnalysisUsage &AU) const {}
129
130static int addUnwindMapEntry(WinEHFuncInfo &FuncInfo, int ToState,
131 const BasicBlock *BB) {
132 CxxUnwindMapEntry UME;
133 UME.ToState = ToState;
134 UME.Cleanup = BB;
135 FuncInfo.CxxUnwindMap.push_back(UME);
136 return FuncInfo.getLastStateNumber();
137}
138
139static void addTryBlockMapEntry(WinEHFuncInfo &FuncInfo, int TryLow,
140 int TryHigh, int CatchHigh,
141 ArrayRef<const CatchPadInst *> Handlers) {
142 WinEHTryBlockMapEntry TBME;
143 TBME.TryLow = TryLow;
144 TBME.TryHigh = TryHigh;
145 TBME.CatchHigh = CatchHigh;
146 assert(TBME.TryLow <= TBME.TryHigh)(static_cast <bool> (TBME.TryLow <= TBME.TryHigh) ? void
(0) : __assert_fail ("TBME.TryLow <= TBME.TryHigh", "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 146, __extension__ __PRETTY_FUNCTION__))
;
147 for (const CatchPadInst *CPI : Handlers) {
148 WinEHHandlerType HT;
149 Constant *TypeInfo = cast<Constant>(CPI->getArgOperand(0));
150 if (TypeInfo->isNullValue())
151 HT.TypeDescriptor = nullptr;
152 else
153 HT.TypeDescriptor = cast<GlobalVariable>(TypeInfo->stripPointerCasts());
154 HT.Adjectives = cast<ConstantInt>(CPI->getArgOperand(1))->getZExtValue();
155 HT.Handler = CPI->getParent();
156 if (auto *AI =
157 dyn_cast<AllocaInst>(CPI->getArgOperand(2)->stripPointerCasts()))
158 HT.CatchObj.Alloca = AI;
159 else
160 HT.CatchObj.Alloca = nullptr;
161 TBME.HandlerArray.push_back(HT);
162 }
163 FuncInfo.TryBlockMap.push_back(TBME);
164}
165
166static BasicBlock *getCleanupRetUnwindDest(const CleanupPadInst *CleanupPad) {
167 for (const User *U : CleanupPad->users())
168 if (const auto *CRI = dyn_cast<CleanupReturnInst>(U))
169 return CRI->getUnwindDest();
170 return nullptr;
171}
172
173static void calculateStateNumbersForInvokes(const Function *Fn,
174 WinEHFuncInfo &FuncInfo) {
175 auto *F = const_cast<Function *>(Fn);
176 DenseMap<BasicBlock *, ColorVector> BlockColors = colorEHFunclets(*F);
177 for (BasicBlock &BB : *F) {
178 auto *II = dyn_cast<InvokeInst>(BB.getTerminator());
179 if (!II)
3
Assuming 'II' is non-null
4
Taking false branch
180 continue;
181
182 auto &BBColors = BlockColors[&BB];
183 assert(BBColors.size() == 1 && "multi-color BB not removed by preparation")(static_cast <bool> (BBColors.size() == 1 && "multi-color BB not removed by preparation"
) ? void (0) : __assert_fail ("BBColors.size() == 1 && \"multi-color BB not removed by preparation\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 183, __extension__ __PRETTY_FUNCTION__))
;
184 BasicBlock *FuncletEntryBB = BBColors.front();
185
186 BasicBlock *FuncletUnwindDest;
187 auto *FuncletPad =
188 dyn_cast<FuncletPadInst>(FuncletEntryBB->getFirstNonPHI());
189 assert(FuncletPad || FuncletEntryBB == &Fn->getEntryBlock())(static_cast <bool> (FuncletPad || FuncletEntryBB == &
Fn->getEntryBlock()) ? void (0) : __assert_fail ("FuncletPad || FuncletEntryBB == &Fn->getEntryBlock()"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 189, __extension__ __PRETTY_FUNCTION__))
;
190 if (!FuncletPad)
5
Taking true branch
191 FuncletUnwindDest = nullptr;
192 else if (auto *CatchPad = dyn_cast<CatchPadInst>(FuncletPad))
193 FuncletUnwindDest = CatchPad->getCatchSwitch()->getUnwindDest();
194 else if (auto *CleanupPad = dyn_cast<CleanupPadInst>(FuncletPad))
195 FuncletUnwindDest = getCleanupRetUnwindDest(CleanupPad);
196 else
197 llvm_unreachable("unexpected funclet pad!")::llvm::llvm_unreachable_internal("unexpected funclet pad!", "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 197)
;
198
199 BasicBlock *InvokeUnwindDest = II->getUnwindDest();
6
Calling 'InvokeInst::getUnwindDest'
12
Returning from 'InvokeInst::getUnwindDest'
13
'InvokeUnwindDest' initialized here
200 int BaseState = -1;
201 if (FuncletUnwindDest == InvokeUnwindDest) {
14
Assuming 'FuncletUnwindDest' is equal to 'InvokeUnwindDest'
15
Taking true branch
202 auto BaseStateI = FuncInfo.FuncletBaseStateMap.find(FuncletPad);
203 if (BaseStateI != FuncInfo.FuncletBaseStateMap.end())
16
Assuming the condition is false
17
Taking false branch
204 BaseState = BaseStateI->second;
205 }
206
207 if (BaseState != -1) {
18
Taking false branch
208 FuncInfo.InvokeStateMap[II] = BaseState;
209 } else {
210 Instruction *PadInst = InvokeUnwindDest->getFirstNonPHI();
19
Called C++ object pointer is null
211 assert(FuncInfo.EHPadStateMap.count(PadInst) && "EH Pad has no state!")(static_cast <bool> (FuncInfo.EHPadStateMap.count(PadInst
) && "EH Pad has no state!") ? void (0) : __assert_fail
("FuncInfo.EHPadStateMap.count(PadInst) && \"EH Pad has no state!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 211, __extension__ __PRETTY_FUNCTION__))
;
212 FuncInfo.InvokeStateMap[II] = FuncInfo.EHPadStateMap[PadInst];
213 }
214 }
215}
216
217// Given BB which ends in an unwind edge, return the EHPad that this BB belongs
218// to. If the unwind edge came from an invoke, return null.
219static const BasicBlock *getEHPadFromPredecessor(const BasicBlock *BB,
220 Value *ParentPad) {
221 const TerminatorInst *TI = BB->getTerminator();
222 if (isa<InvokeInst>(TI))
223 return nullptr;
224 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(TI)) {
225 if (CatchSwitch->getParentPad() != ParentPad)
226 return nullptr;
227 return BB;
228 }
229 assert(!TI->isEHPad() && "unexpected EHPad!")(static_cast <bool> (!TI->isEHPad() && "unexpected EHPad!"
) ? void (0) : __assert_fail ("!TI->isEHPad() && \"unexpected EHPad!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 229, __extension__ __PRETTY_FUNCTION__))
;
230 auto *CleanupPad = cast<CleanupReturnInst>(TI)->getCleanupPad();
231 if (CleanupPad->getParentPad() != ParentPad)
232 return nullptr;
233 return CleanupPad->getParent();
234}
235
236static void calculateCXXStateNumbers(WinEHFuncInfo &FuncInfo,
237 const Instruction *FirstNonPHI,
238 int ParentState) {
239 const BasicBlock *BB = FirstNonPHI->getParent();
240 assert(BB->isEHPad() && "not a funclet!")(static_cast <bool> (BB->isEHPad() && "not a funclet!"
) ? void (0) : __assert_fail ("BB->isEHPad() && \"not a funclet!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 240, __extension__ __PRETTY_FUNCTION__))
;
241
242 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
243 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&(static_cast <bool> (FuncInfo.EHPadStateMap.count(CatchSwitch
) == 0 && "shouldn't revist catch funclets!") ? void (
0) : __assert_fail ("FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && \"shouldn't revist catch funclets!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 244, __extension__ __PRETTY_FUNCTION__))
244 "shouldn't revist catch funclets!")(static_cast <bool> (FuncInfo.EHPadStateMap.count(CatchSwitch
) == 0 && "shouldn't revist catch funclets!") ? void (
0) : __assert_fail ("FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && \"shouldn't revist catch funclets!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 244, __extension__ __PRETTY_FUNCTION__))
;
245
246 SmallVector<const CatchPadInst *, 2> Handlers;
247 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
248 auto *CatchPad = cast<CatchPadInst>(CatchPadBB->getFirstNonPHI());
249 Handlers.push_back(CatchPad);
250 }
251 int TryLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
252 FuncInfo.EHPadStateMap[CatchSwitch] = TryLow;
253 for (const BasicBlock *PredBlock : predecessors(BB))
254 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
255 CatchSwitch->getParentPad())))
256 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
257 TryLow);
258 int CatchLow = addUnwindMapEntry(FuncInfo, ParentState, nullptr);
259
260 // catchpads are separate funclets in C++ EH due to the way rethrow works.
261 int TryHigh = CatchLow - 1;
262 for (const auto *CatchPad : Handlers) {
263 FuncInfo.FuncletBaseStateMap[CatchPad] = CatchLow;
264 for (const User *U : CatchPad->users()) {
265 const auto *UserI = cast<Instruction>(U);
266 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
267 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
268 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
269 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
270 }
271 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
272 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
273 // If a nested cleanup pad reports a null unwind destination and the
274 // enclosing catch pad doesn't it must be post-dominated by an
275 // unreachable instruction.
276 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
277 calculateCXXStateNumbers(FuncInfo, UserI, CatchLow);
278 }
279 }
280 }
281 int CatchHigh = FuncInfo.getLastStateNumber();
282 addTryBlockMapEntry(FuncInfo, TryLow, TryHigh, CatchHigh, Handlers);
283 LLVM_DEBUG(dbgs() << "TryLow[" << BB->getName() << "]: " << TryLow << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "TryLow[" << BB->
getName() << "]: " << TryLow << '\n'; } } while
(false)
;
284 LLVM_DEBUG(dbgs() << "TryHigh[" << BB->getName() << "]: " << TryHighdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "TryHigh[" << BB->
getName() << "]: " << TryHigh << '\n'; } } while
(false)
285 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "TryHigh[" << BB->
getName() << "]: " << TryHigh << '\n'; } } while
(false)
;
286 LLVM_DEBUG(dbgs() << "CatchHigh[" << BB->getName() << "]: " << CatchHighdo { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "CatchHigh[" << BB->
getName() << "]: " << CatchHigh << '\n'; } }
while (false)
287 << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "CatchHigh[" << BB->
getName() << "]: " << CatchHigh << '\n'; } }
while (false)
;
288 } else {
289 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
290
291 // It's possible for a cleanup to be visited twice: it might have multiple
292 // cleanupret instructions.
293 if (FuncInfo.EHPadStateMap.count(CleanupPad))
294 return;
295
296 int CleanupState = addUnwindMapEntry(FuncInfo, ParentState, BB);
297 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
298 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
CleanupState << " to BB " << BB->getName() <<
'\n'; } } while (false)
299 << BB->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
CleanupState << " to BB " << BB->getName() <<
'\n'; } } while (false)
;
300 for (const BasicBlock *PredBlock : predecessors(BB)) {
301 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
302 CleanupPad->getParentPad()))) {
303 calculateCXXStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
304 CleanupState);
305 }
306 }
307 for (const User *U : CleanupPad->users()) {
308 const auto *UserI = cast<Instruction>(U);
309 if (UserI->isEHPad())
310 report_fatal_error("Cleanup funclets for the MSVC++ personality cannot "
311 "contain exceptional actions");
312 }
313 }
314}
315
316static int addSEHExcept(WinEHFuncInfo &FuncInfo, int ParentState,
317 const Function *Filter, const BasicBlock *Handler) {
318 SEHUnwindMapEntry Entry;
319 Entry.ToState = ParentState;
320 Entry.IsFinally = false;
321 Entry.Filter = Filter;
322 Entry.Handler = Handler;
323 FuncInfo.SEHUnwindMap.push_back(Entry);
324 return FuncInfo.SEHUnwindMap.size() - 1;
325}
326
327static int addSEHFinally(WinEHFuncInfo &FuncInfo, int ParentState,
328 const BasicBlock *Handler) {
329 SEHUnwindMapEntry Entry;
330 Entry.ToState = ParentState;
331 Entry.IsFinally = true;
332 Entry.Filter = nullptr;
333 Entry.Handler = Handler;
334 FuncInfo.SEHUnwindMap.push_back(Entry);
335 return FuncInfo.SEHUnwindMap.size() - 1;
336}
337
338static void calculateSEHStateNumbers(WinEHFuncInfo &FuncInfo,
339 const Instruction *FirstNonPHI,
340 int ParentState) {
341 const BasicBlock *BB = FirstNonPHI->getParent();
342 assert(BB->isEHPad() && "no a funclet!")(static_cast <bool> (BB->isEHPad() && "no a funclet!"
) ? void (0) : __assert_fail ("BB->isEHPad() && \"no a funclet!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 342, __extension__ __PRETTY_FUNCTION__))
;
343
344 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(FirstNonPHI)) {
345 assert(FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 &&(static_cast <bool> (FuncInfo.EHPadStateMap.count(CatchSwitch
) == 0 && "shouldn't revist catch funclets!") ? void (
0) : __assert_fail ("FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && \"shouldn't revist catch funclets!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 346, __extension__ __PRETTY_FUNCTION__))
346 "shouldn't revist catch funclets!")(static_cast <bool> (FuncInfo.EHPadStateMap.count(CatchSwitch
) == 0 && "shouldn't revist catch funclets!") ? void (
0) : __assert_fail ("FuncInfo.EHPadStateMap.count(CatchSwitch) == 0 && \"shouldn't revist catch funclets!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 346, __extension__ __PRETTY_FUNCTION__))
;
347
348 // Extract the filter function and the __except basic block and create a
349 // state for them.
350 assert(CatchSwitch->getNumHandlers() == 1 &&(static_cast <bool> (CatchSwitch->getNumHandlers() ==
1 && "SEH doesn't have multiple handlers per __try")
? void (0) : __assert_fail ("CatchSwitch->getNumHandlers() == 1 && \"SEH doesn't have multiple handlers per __try\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 351, __extension__ __PRETTY_FUNCTION__))
351 "SEH doesn't have multiple handlers per __try")(static_cast <bool> (CatchSwitch->getNumHandlers() ==
1 && "SEH doesn't have multiple handlers per __try")
? void (0) : __assert_fail ("CatchSwitch->getNumHandlers() == 1 && \"SEH doesn't have multiple handlers per __try\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 351, __extension__ __PRETTY_FUNCTION__))
;
352 const auto *CatchPad =
353 cast<CatchPadInst>((*CatchSwitch->handler_begin())->getFirstNonPHI());
354 const BasicBlock *CatchPadBB = CatchPad->getParent();
355 const Constant *FilterOrNull =
356 cast<Constant>(CatchPad->getArgOperand(0)->stripPointerCasts());
357 const Function *Filter = dyn_cast<Function>(FilterOrNull);
358 assert((Filter || FilterOrNull->isNullValue()) &&(static_cast <bool> ((Filter || FilterOrNull->isNullValue
()) && "unexpected filter value") ? void (0) : __assert_fail
("(Filter || FilterOrNull->isNullValue()) && \"unexpected filter value\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 359, __extension__ __PRETTY_FUNCTION__))
359 "unexpected filter value")(static_cast <bool> ((Filter || FilterOrNull->isNullValue
()) && "unexpected filter value") ? void (0) : __assert_fail
("(Filter || FilterOrNull->isNullValue()) && \"unexpected filter value\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 359, __extension__ __PRETTY_FUNCTION__))
;
360 int TryState = addSEHExcept(FuncInfo, ParentState, Filter, CatchPadBB);
361
362 // Everything in the __try block uses TryState as its parent state.
363 FuncInfo.EHPadStateMap[CatchSwitch] = TryState;
364 LLVM_DEBUG(dbgs() << "Assigning state #" << TryState << " to BB "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
TryState << " to BB " << CatchPadBB->getName(
) << '\n'; } } while (false)
365 << CatchPadBB->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
TryState << " to BB " << CatchPadBB->getName(
) << '\n'; } } while (false)
;
366 for (const BasicBlock *PredBlock : predecessors(BB))
367 if ((PredBlock = getEHPadFromPredecessor(PredBlock,
368 CatchSwitch->getParentPad())))
369 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
370 TryState);
371
372 // Everything in the __except block unwinds to ParentState, just like code
373 // outside the __try.
374 for (const User *U : CatchPad->users()) {
375 const auto *UserI = cast<Instruction>(U);
376 if (auto *InnerCatchSwitch = dyn_cast<CatchSwitchInst>(UserI)) {
377 BasicBlock *UnwindDest = InnerCatchSwitch->getUnwindDest();
378 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
379 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
380 }
381 if (auto *InnerCleanupPad = dyn_cast<CleanupPadInst>(UserI)) {
382 BasicBlock *UnwindDest = getCleanupRetUnwindDest(InnerCleanupPad);
383 // If a nested cleanup pad reports a null unwind destination and the
384 // enclosing catch pad doesn't it must be post-dominated by an
385 // unreachable instruction.
386 if (!UnwindDest || UnwindDest == CatchSwitch->getUnwindDest())
387 calculateSEHStateNumbers(FuncInfo, UserI, ParentState);
388 }
389 }
390 } else {
391 auto *CleanupPad = cast<CleanupPadInst>(FirstNonPHI);
392
393 // It's possible for a cleanup to be visited twice: it might have multiple
394 // cleanupret instructions.
395 if (FuncInfo.EHPadStateMap.count(CleanupPad))
396 return;
397
398 int CleanupState = addSEHFinally(FuncInfo, ParentState, BB);
399 FuncInfo.EHPadStateMap[CleanupPad] = CleanupState;
400 LLVM_DEBUG(dbgs() << "Assigning state #" << CleanupState << " to BB "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
CleanupState << " to BB " << BB->getName() <<
'\n'; } } while (false)
401 << BB->getName() << '\n')do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { dbgs() << "Assigning state #" <<
CleanupState << " to BB " << BB->getName() <<
'\n'; } } while (false)
;
402 for (const BasicBlock *PredBlock : predecessors(BB))
403 if ((PredBlock =
404 getEHPadFromPredecessor(PredBlock, CleanupPad->getParentPad())))
405 calculateSEHStateNumbers(FuncInfo, PredBlock->getFirstNonPHI(),
406 CleanupState);
407 for (const User *U : CleanupPad->users()) {
408 const auto *UserI = cast<Instruction>(U);
409 if (UserI->isEHPad())
410 report_fatal_error("Cleanup funclets for the SEH personality cannot "
411 "contain exceptional actions");
412 }
413 }
414}
415
416static bool isTopLevelPadForMSVC(const Instruction *EHPad) {
417 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(EHPad))
418 return isa<ConstantTokenNone>(CatchSwitch->getParentPad()) &&
419 CatchSwitch->unwindsToCaller();
420 if (auto *CleanupPad = dyn_cast<CleanupPadInst>(EHPad))
421 return isa<ConstantTokenNone>(CleanupPad->getParentPad()) &&
422 getCleanupRetUnwindDest(CleanupPad) == nullptr;
423 if (isa<CatchPadInst>(EHPad))
424 return false;
425 llvm_unreachable("unexpected EHPad!")::llvm::llvm_unreachable_internal("unexpected EHPad!", "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 425)
;
426}
427
428void llvm::calculateSEHStateNumbers(const Function *Fn,
429 WinEHFuncInfo &FuncInfo) {
430 // Don't compute state numbers twice.
431 if (!FuncInfo.SEHUnwindMap.empty())
1
Taking false branch
432 return;
433
434 for (const BasicBlock &BB : *Fn) {
435 if (!BB.isEHPad())
436 continue;
437 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
438 if (!isTopLevelPadForMSVC(FirstNonPHI))
439 continue;
440 ::calculateSEHStateNumbers(FuncInfo, FirstNonPHI, -1);
441 }
442
443 calculateStateNumbersForInvokes(Fn, FuncInfo);
2
Calling 'calculateStateNumbersForInvokes'
444}
445
446void llvm::calculateWinCXXEHStateNumbers(const Function *Fn,
447 WinEHFuncInfo &FuncInfo) {
448 // Return if it's already been done.
449 if (!FuncInfo.EHPadStateMap.empty())
450 return;
451
452 for (const BasicBlock &BB : *Fn) {
453 if (!BB.isEHPad())
454 continue;
455 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
456 if (!isTopLevelPadForMSVC(FirstNonPHI))
457 continue;
458 calculateCXXStateNumbers(FuncInfo, FirstNonPHI, -1);
459 }
460
461 calculateStateNumbersForInvokes(Fn, FuncInfo);
462}
463
464static int addClrEHHandler(WinEHFuncInfo &FuncInfo, int HandlerParentState,
465 int TryParentState, ClrHandlerType HandlerType,
466 uint32_t TypeToken, const BasicBlock *Handler) {
467 ClrEHUnwindMapEntry Entry;
468 Entry.HandlerParentState = HandlerParentState;
469 Entry.TryParentState = TryParentState;
470 Entry.Handler = Handler;
471 Entry.HandlerType = HandlerType;
472 Entry.TypeToken = TypeToken;
473 FuncInfo.ClrEHUnwindMap.push_back(Entry);
474 return FuncInfo.ClrEHUnwindMap.size() - 1;
475}
476
477void llvm::calculateClrEHStateNumbers(const Function *Fn,
478 WinEHFuncInfo &FuncInfo) {
479 // Return if it's already been done.
480 if (!FuncInfo.EHPadStateMap.empty())
481 return;
482
483 // This numbering assigns one state number to each catchpad and cleanuppad.
484 // It also computes two tree-like relations over states:
485 // 1) Each state has a "HandlerParentState", which is the state of the next
486 // outer handler enclosing this state's handler (same as nearest ancestor
487 // per the ParentPad linkage on EH pads, but skipping over catchswitches).
488 // 2) Each state has a "TryParentState", which:
489 // a) for a catchpad that's not the last handler on its catchswitch, is
490 // the state of the next catchpad on that catchswitch
491 // b) for all other pads, is the state of the pad whose try region is the
492 // next outer try region enclosing this state's try region. The "try
493 // regions are not present as such in the IR, but will be inferred
494 // based on the placement of invokes and pads which reach each other
495 // by exceptional exits
496 // Catchswitches do not get their own states, but each gets mapped to the
497 // state of its first catchpad.
498
499 // Step one: walk down from outermost to innermost funclets, assigning each
500 // catchpad and cleanuppad a state number. Add an entry to the
501 // ClrEHUnwindMap for each state, recording its HandlerParentState and
502 // handler attributes. Record the TryParentState as well for each catchpad
503 // that's not the last on its catchswitch, but initialize all other entries'
504 // TryParentStates to a sentinel -1 value that the next pass will update.
505
506 // Seed a worklist with pads that have no parent.
507 SmallVector<std::pair<const Instruction *, int>, 8> Worklist;
508 for (const BasicBlock &BB : *Fn) {
509 const Instruction *FirstNonPHI = BB.getFirstNonPHI();
510 const Value *ParentPad;
511 if (const auto *CPI = dyn_cast<CleanupPadInst>(FirstNonPHI))
512 ParentPad = CPI->getParentPad();
513 else if (const auto *CSI = dyn_cast<CatchSwitchInst>(FirstNonPHI))
514 ParentPad = CSI->getParentPad();
515 else
516 continue;
517 if (isa<ConstantTokenNone>(ParentPad))
518 Worklist.emplace_back(FirstNonPHI, -1);
519 }
520
521 // Use the worklist to visit all pads, from outer to inner. Record
522 // HandlerParentState for all pads. Record TryParentState only for catchpads
523 // that aren't the last on their catchswitch (setting all other entries'
524 // TryParentStates to an initial value of -1). This loop is also responsible
525 // for setting the EHPadStateMap entry for all catchpads, cleanuppads, and
526 // catchswitches.
527 while (!Worklist.empty()) {
528 const Instruction *Pad;
529 int HandlerParentState;
530 std::tie(Pad, HandlerParentState) = Worklist.pop_back_val();
531
532 if (const auto *Cleanup = dyn_cast<CleanupPadInst>(Pad)) {
533 // Create the entry for this cleanup with the appropriate handler
534 // properties. Finally and fault handlers are distinguished by arity.
535 ClrHandlerType HandlerType =
536 (Cleanup->getNumArgOperands() ? ClrHandlerType::Fault
537 : ClrHandlerType::Finally);
538 int CleanupState = addClrEHHandler(FuncInfo, HandlerParentState, -1,
539 HandlerType, 0, Pad->getParent());
540 // Queue any child EH pads on the worklist.
541 for (const User *U : Cleanup->users())
542 if (const auto *I = dyn_cast<Instruction>(U))
543 if (I->isEHPad())
544 Worklist.emplace_back(I, CleanupState);
545 // Remember this pad's state.
546 FuncInfo.EHPadStateMap[Cleanup] = CleanupState;
547 } else {
548 // Walk the handlers of this catchswitch in reverse order since all but
549 // the last need to set the following one as its TryParentState.
550 const auto *CatchSwitch = cast<CatchSwitchInst>(Pad);
551 int CatchState = -1, FollowerState = -1;
552 SmallVector<const BasicBlock *, 4> CatchBlocks(CatchSwitch->handlers());
553 for (auto CBI = CatchBlocks.rbegin(), CBE = CatchBlocks.rend();
554 CBI != CBE; ++CBI, FollowerState = CatchState) {
555 const BasicBlock *CatchBlock = *CBI;
556 // Create the entry for this catch with the appropriate handler
557 // properties.
558 const auto *Catch = cast<CatchPadInst>(CatchBlock->getFirstNonPHI());
559 uint32_t TypeToken = static_cast<uint32_t>(
560 cast<ConstantInt>(Catch->getArgOperand(0))->getZExtValue());
561 CatchState =
562 addClrEHHandler(FuncInfo, HandlerParentState, FollowerState,
563 ClrHandlerType::Catch, TypeToken, CatchBlock);
564 // Queue any child EH pads on the worklist.
565 for (const User *U : Catch->users())
566 if (const auto *I = dyn_cast<Instruction>(U))
567 if (I->isEHPad())
568 Worklist.emplace_back(I, CatchState);
569 // Remember this catch's state.
570 FuncInfo.EHPadStateMap[Catch] = CatchState;
571 }
572 // Associate the catchswitch with the state of its first catch.
573 assert(CatchSwitch->getNumHandlers())(static_cast <bool> (CatchSwitch->getNumHandlers()) ?
void (0) : __assert_fail ("CatchSwitch->getNumHandlers()"
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 573, __extension__ __PRETTY_FUNCTION__))
;
574 FuncInfo.EHPadStateMap[CatchSwitch] = CatchState;
575 }
576 }
577
578 // Step two: record the TryParentState of each state. For cleanuppads that
579 // don't have cleanuprets, we may need to infer this from their child pads,
580 // so visit pads in descendant-most to ancestor-most order.
581 for (auto Entry = FuncInfo.ClrEHUnwindMap.rbegin(),
582 End = FuncInfo.ClrEHUnwindMap.rend();
583 Entry != End; ++Entry) {
584 const Instruction *Pad =
585 Entry->Handler.get<const BasicBlock *>()->getFirstNonPHI();
586 // For most pads, the TryParentState is the state associated with the
587 // unwind dest of exceptional exits from it.
588 const BasicBlock *UnwindDest;
589 if (const auto *Catch = dyn_cast<CatchPadInst>(Pad)) {
590 // If a catch is not the last in its catchswitch, its TryParentState is
591 // the state associated with the next catch in the switch, even though
592 // that's not the unwind dest of exceptions escaping the catch. Those
593 // cases were already assigned a TryParentState in the first pass, so
594 // skip them.
595 if (Entry->TryParentState != -1)
596 continue;
597 // Otherwise, get the unwind dest from the catchswitch.
598 UnwindDest = Catch->getCatchSwitch()->getUnwindDest();
599 } else {
600 const auto *Cleanup = cast<CleanupPadInst>(Pad);
601 UnwindDest = nullptr;
602 for (const User *U : Cleanup->users()) {
603 if (auto *CleanupRet = dyn_cast<CleanupReturnInst>(U)) {
604 // Common and unambiguous case -- cleanupret indicates cleanup's
605 // unwind dest.
606 UnwindDest = CleanupRet->getUnwindDest();
607 break;
608 }
609
610 // Get an unwind dest for the user
611 const BasicBlock *UserUnwindDest = nullptr;
612 if (auto *Invoke = dyn_cast<InvokeInst>(U)) {
613 UserUnwindDest = Invoke->getUnwindDest();
614 } else if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(U)) {
615 UserUnwindDest = CatchSwitch->getUnwindDest();
616 } else if (auto *ChildCleanup = dyn_cast<CleanupPadInst>(U)) {
617 int UserState = FuncInfo.EHPadStateMap[ChildCleanup];
618 int UserUnwindState =
619 FuncInfo.ClrEHUnwindMap[UserState].TryParentState;
620 if (UserUnwindState != -1)
621 UserUnwindDest = FuncInfo.ClrEHUnwindMap[UserUnwindState]
622 .Handler.get<const BasicBlock *>();
623 }
624
625 // Not having an unwind dest for this user might indicate that it
626 // doesn't unwind, so can't be taken as proof that the cleanup itself
627 // may unwind to caller (see e.g. SimplifyUnreachable and
628 // RemoveUnwindEdge).
629 if (!UserUnwindDest)
630 continue;
631
632 // Now we have an unwind dest for the user, but we need to see if it
633 // unwinds all the way out of the cleanup or if it stays within it.
634 const Instruction *UserUnwindPad = UserUnwindDest->getFirstNonPHI();
635 const Value *UserUnwindParent;
636 if (auto *CSI = dyn_cast<CatchSwitchInst>(UserUnwindPad))
637 UserUnwindParent = CSI->getParentPad();
638 else
639 UserUnwindParent =
640 cast<CleanupPadInst>(UserUnwindPad)->getParentPad();
641
642 // The unwind stays within the cleanup iff it targets a child of the
643 // cleanup.
644 if (UserUnwindParent == Cleanup)
645 continue;
646
647 // This unwind exits the cleanup, so its dest is the cleanup's dest.
648 UnwindDest = UserUnwindDest;
649 break;
650 }
651 }
652
653 // Record the state of the unwind dest as the TryParentState.
654 int UnwindDestState;
655
656 // If UnwindDest is null at this point, either the pad in question can
657 // be exited by unwind to caller, or it cannot be exited by unwind. In
658 // either case, reporting such cases as unwinding to caller is correct.
659 // This can lead to EH tables that "look strange" -- if this pad's is in
660 // a parent funclet which has other children that do unwind to an enclosing
661 // pad, the try region for this pad will be missing the "duplicate" EH
662 // clause entries that you'd expect to see covering the whole parent. That
663 // should be benign, since the unwind never actually happens. If it were
664 // an issue, we could add a subsequent pass that pushes unwind dests down
665 // from parents that have them to children that appear to unwind to caller.
666 if (!UnwindDest) {
667 UnwindDestState = -1;
668 } else {
669 UnwindDestState = FuncInfo.EHPadStateMap[UnwindDest->getFirstNonPHI()];
670 }
671
672 Entry->TryParentState = UnwindDestState;
673 }
674
675 // Step three: transfer information from pads to invokes.
676 calculateStateNumbersForInvokes(Fn, FuncInfo);
677}
678
679void WinEHPrepare::colorFunclets(Function &F) {
680 BlockColors = colorEHFunclets(F);
681
682 // Invert the map from BB to colors to color to BBs.
683 for (BasicBlock &BB : F) {
684 ColorVector &Colors = BlockColors[&BB];
685 for (BasicBlock *Color : Colors)
686 FuncletBlocks[Color].push_back(&BB);
687 }
688}
689
690void WinEHPrepare::demotePHIsOnFunclets(Function &F,
691 bool DemoteCatchSwitchPHIOnly) {
692 // Strip PHI nodes off of EH pads.
693 SmallVector<PHINode *, 16> PHINodes;
694 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
695 BasicBlock *BB = &*FI++;
696 if (!BB->isEHPad())
697 continue;
698 if (DemoteCatchSwitchPHIOnly && !isa<CatchSwitchInst>(BB->getFirstNonPHI()))
699 continue;
700
701 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
702 Instruction *I = &*BI++;
703 auto *PN = dyn_cast<PHINode>(I);
704 // Stop at the first non-PHI.
705 if (!PN)
706 break;
707
708 AllocaInst *SpillSlot = insertPHILoads(PN, F);
709 if (SpillSlot)
710 insertPHIStores(PN, SpillSlot);
711
712 PHINodes.push_back(PN);
713 }
714 }
715
716 for (auto *PN : PHINodes) {
717 // There may be lingering uses on other EH PHIs being removed
718 PN->replaceAllUsesWith(UndefValue::get(PN->getType()));
719 PN->eraseFromParent();
720 }
721}
722
723void WinEHPrepare::cloneCommonBlocks(Function &F) {
724 // We need to clone all blocks which belong to multiple funclets. Values are
725 // remapped throughout the funclet to propagate both the new instructions
726 // *and* the new basic blocks themselves.
727 for (auto &Funclets : FuncletBlocks) {
728 BasicBlock *FuncletPadBB = Funclets.first;
729 std::vector<BasicBlock *> &BlocksInFunclet = Funclets.second;
730 Value *FuncletToken;
731 if (FuncletPadBB == &F.getEntryBlock())
732 FuncletToken = ConstantTokenNone::get(F.getContext());
733 else
734 FuncletToken = FuncletPadBB->getFirstNonPHI();
735
736 std::vector<std::pair<BasicBlock *, BasicBlock *>> Orig2Clone;
737 ValueToValueMapTy VMap;
738 for (BasicBlock *BB : BlocksInFunclet) {
739 ColorVector &ColorsForBB = BlockColors[BB];
740 // We don't need to do anything if the block is monochromatic.
741 size_t NumColorsForBB = ColorsForBB.size();
742 if (NumColorsForBB == 1)
743 continue;
744
745 DEBUG_WITH_TYPE("winehprepare-coloring",do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Cloning block \'"
<< BB->getName() << "\' for funclet \'" <<
FuncletPadBB->getName() << "\'.\n"; } } while (false
)
746 dbgs() << " Cloning block \'" << BB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Cloning block \'"
<< BB->getName() << "\' for funclet \'" <<
FuncletPadBB->getName() << "\'.\n"; } } while (false
)
747 << "\' for funclet \'" << FuncletPadBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Cloning block \'"
<< BB->getName() << "\' for funclet \'" <<
FuncletPadBB->getName() << "\'.\n"; } } while (false
)
748 << "\'.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Cloning block \'"
<< BB->getName() << "\' for funclet \'" <<
FuncletPadBB->getName() << "\'.\n"; } } while (false
)
;
749
750 // Create a new basic block and copy instructions into it!
751 BasicBlock *CBB =
752 CloneBasicBlock(BB, VMap, Twine(".for.", FuncletPadBB->getName()));
753 // Insert the clone immediately after the original to ensure determinism
754 // and to keep the same relative ordering of any funclet's blocks.
755 CBB->insertInto(&F, BB->getNextNode());
756
757 // Add basic block mapping.
758 VMap[BB] = CBB;
759
760 // Record delta operations that we need to perform to our color mappings.
761 Orig2Clone.emplace_back(BB, CBB);
762 }
763
764 // If nothing was cloned, we're done cloning in this funclet.
765 if (Orig2Clone.empty())
766 continue;
767
768 // Update our color mappings to reflect that one block has lost a color and
769 // another has gained a color.
770 for (auto &BBMapping : Orig2Clone) {
771 BasicBlock *OldBlock = BBMapping.first;
772 BasicBlock *NewBlock = BBMapping.second;
773
774 BlocksInFunclet.push_back(NewBlock);
775 ColorVector &NewColors = BlockColors[NewBlock];
776 assert(NewColors.empty() && "A new block should only have one color!")(static_cast <bool> (NewColors.empty() && "A new block should only have one color!"
) ? void (0) : __assert_fail ("NewColors.empty() && \"A new block should only have one color!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 776, __extension__ __PRETTY_FUNCTION__))
;
777 NewColors.push_back(FuncletPadBB);
778
779 DEBUG_WITH_TYPE("winehprepare-coloring",do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Assigned color \'"
<< FuncletPadBB->getName() << "\' to block \'"
<< NewBlock->getName() << "\'.\n"; } } while (
false)
780 dbgs() << " Assigned color \'" << FuncletPadBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Assigned color \'"
<< FuncletPadBB->getName() << "\' to block \'"
<< NewBlock->getName() << "\'.\n"; } } while (
false)
781 << "\' to block \'" << NewBlock->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Assigned color \'"
<< FuncletPadBB->getName() << "\' to block \'"
<< NewBlock->getName() << "\'.\n"; } } while (
false)
782 << "\'.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Assigned color \'"
<< FuncletPadBB->getName() << "\' to block \'"
<< NewBlock->getName() << "\'.\n"; } } while (
false)
;
783
784 BlocksInFunclet.erase(
785 std::remove(BlocksInFunclet.begin(), BlocksInFunclet.end(), OldBlock),
786 BlocksInFunclet.end());
787 ColorVector &OldColors = BlockColors[OldBlock];
788 OldColors.erase(
789 std::remove(OldColors.begin(), OldColors.end(), FuncletPadBB),
790 OldColors.end());
791
792 DEBUG_WITH_TYPE("winehprepare-coloring",do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Removed color \'"
<< FuncletPadBB->getName() << "\' from block \'"
<< OldBlock->getName() << "\'.\n"; } } while (
false)
793 dbgs() << " Removed color \'" << FuncletPadBB->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Removed color \'"
<< FuncletPadBB->getName() << "\' from block \'"
<< OldBlock->getName() << "\'.\n"; } } while (
false)
794 << "\' from block \'" << OldBlock->getName()do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Removed color \'"
<< FuncletPadBB->getName() << "\' from block \'"
<< OldBlock->getName() << "\'.\n"; } } while (
false)
795 << "\'.\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare-coloring")) { dbgs() << " Removed color \'"
<< FuncletPadBB->getName() << "\' from block \'"
<< OldBlock->getName() << "\'.\n"; } } while (
false)
;
796 }
797
798 // Loop over all of the instructions in this funclet, fixing up operand
799 // references as we go. This uses VMap to do all the hard work.
800 for (BasicBlock *BB : BlocksInFunclet)
801 // Loop over all instructions, fixing each one as we find it...
802 for (Instruction &I : *BB)
803 RemapInstruction(&I, VMap,
804 RF_IgnoreMissingLocals | RF_NoModuleLevelChanges);
805
806 // Catchrets targeting cloned blocks need to be updated separately from
807 // the loop above because they are not in the current funclet.
808 SmallVector<CatchReturnInst *, 2> FixupCatchrets;
809 for (auto &BBMapping : Orig2Clone) {
810 BasicBlock *OldBlock = BBMapping.first;
811 BasicBlock *NewBlock = BBMapping.second;
812
813 FixupCatchrets.clear();
814 for (BasicBlock *Pred : predecessors(OldBlock))
815 if (auto *CatchRet = dyn_cast<CatchReturnInst>(Pred->getTerminator()))
816 if (CatchRet->getCatchSwitchParentPad() == FuncletToken)
817 FixupCatchrets.push_back(CatchRet);
818
819 for (CatchReturnInst *CatchRet : FixupCatchrets)
820 CatchRet->setSuccessor(NewBlock);
821 }
822
823 auto UpdatePHIOnClonedBlock = [&](PHINode *PN, bool IsForOldBlock) {
824 unsigned NumPreds = PN->getNumIncomingValues();
825 for (unsigned PredIdx = 0, PredEnd = NumPreds; PredIdx != PredEnd;
826 ++PredIdx) {
827 BasicBlock *IncomingBlock = PN->getIncomingBlock(PredIdx);
828 bool EdgeTargetsFunclet;
829 if (auto *CRI =
830 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
831 EdgeTargetsFunclet = (CRI->getCatchSwitchParentPad() == FuncletToken);
832 } else {
833 ColorVector &IncomingColors = BlockColors[IncomingBlock];
834 assert(!IncomingColors.empty() && "Block not colored!")(static_cast <bool> (!IncomingColors.empty() &&
"Block not colored!") ? void (0) : __assert_fail ("!IncomingColors.empty() && \"Block not colored!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 834, __extension__ __PRETTY_FUNCTION__))
;
835 assert((IncomingColors.size() == 1 ||(static_cast <bool> ((IncomingColors.size() == 1 || llvm
::all_of(IncomingColors, [&](BasicBlock *Color) { return Color
!= FuncletPadBB; })) && "Cloning should leave this funclet's blocks monochromatic"
) ? void (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 840, __extension__ __PRETTY_FUNCTION__))
836 llvm::all_of(IncomingColors,(static_cast <bool> ((IncomingColors.size() == 1 || llvm
::all_of(IncomingColors, [&](BasicBlock *Color) { return Color
!= FuncletPadBB; })) && "Cloning should leave this funclet's blocks monochromatic"
) ? void (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 840, __extension__ __PRETTY_FUNCTION__))
837 [&](BasicBlock *Color) {(static_cast <bool> ((IncomingColors.size() == 1 || llvm
::all_of(IncomingColors, [&](BasicBlock *Color) { return Color
!= FuncletPadBB; })) && "Cloning should leave this funclet's blocks monochromatic"
) ? void (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 840, __extension__ __PRETTY_FUNCTION__))
838 return Color != FuncletPadBB;(static_cast <bool> ((IncomingColors.size() == 1 || llvm
::all_of(IncomingColors, [&](BasicBlock *Color) { return Color
!= FuncletPadBB; })) && "Cloning should leave this funclet's blocks monochromatic"
) ? void (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 840, __extension__ __PRETTY_FUNCTION__))
839 })) &&(static_cast <bool> ((IncomingColors.size() == 1 || llvm
::all_of(IncomingColors, [&](BasicBlock *Color) { return Color
!= FuncletPadBB; })) && "Cloning should leave this funclet's blocks monochromatic"
) ? void (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 840, __extension__ __PRETTY_FUNCTION__))
840 "Cloning should leave this funclet's blocks monochromatic")(static_cast <bool> ((IncomingColors.size() == 1 || llvm
::all_of(IncomingColors, [&](BasicBlock *Color) { return Color
!= FuncletPadBB; })) && "Cloning should leave this funclet's blocks monochromatic"
) ? void (0) : __assert_fail ("(IncomingColors.size() == 1 || llvm::all_of(IncomingColors, [&](BasicBlock *Color) { return Color != FuncletPadBB; })) && \"Cloning should leave this funclet's blocks monochromatic\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 840, __extension__ __PRETTY_FUNCTION__))
;
841 EdgeTargetsFunclet = (IncomingColors.front() == FuncletPadBB);
842 }
843 if (IsForOldBlock != EdgeTargetsFunclet)
844 continue;
845 PN->removeIncomingValue(IncomingBlock, /*DeletePHIIfEmpty=*/false);
846 // Revisit the next entry.
847 --PredIdx;
848 --PredEnd;
849 }
850 };
851
852 for (auto &BBMapping : Orig2Clone) {
853 BasicBlock *OldBlock = BBMapping.first;
854 BasicBlock *NewBlock = BBMapping.second;
855 for (PHINode &OldPN : OldBlock->phis()) {
856 UpdatePHIOnClonedBlock(&OldPN, /*IsForOldBlock=*/true);
857 }
858 for (PHINode &NewPN : NewBlock->phis()) {
859 UpdatePHIOnClonedBlock(&NewPN, /*IsForOldBlock=*/false);
860 }
861 }
862
863 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to
864 // the PHI nodes for NewBB now.
865 for (auto &BBMapping : Orig2Clone) {
866 BasicBlock *OldBlock = BBMapping.first;
867 BasicBlock *NewBlock = BBMapping.second;
868 for (BasicBlock *SuccBB : successors(NewBlock)) {
869 for (PHINode &SuccPN : SuccBB->phis()) {
870 // Ok, we have a PHI node. Figure out what the incoming value was for
871 // the OldBlock.
872 int OldBlockIdx = SuccPN.getBasicBlockIndex(OldBlock);
873 if (OldBlockIdx == -1)
874 break;
875 Value *IV = SuccPN.getIncomingValue(OldBlockIdx);
876
877 // Remap the value if necessary.
878 if (auto *Inst = dyn_cast<Instruction>(IV)) {
879 ValueToValueMapTy::iterator I = VMap.find(Inst);
880 if (I != VMap.end())
881 IV = I->second;
882 }
883
884 SuccPN.addIncoming(IV, NewBlock);
885 }
886 }
887 }
888
889 for (ValueToValueMapTy::value_type VT : VMap) {
890 // If there were values defined in BB that are used outside the funclet,
891 // then we now have to update all uses of the value to use either the
892 // original value, the cloned value, or some PHI derived value. This can
893 // require arbitrary PHI insertion, of which we are prepared to do, clean
894 // these up now.
895 SmallVector<Use *, 16> UsesToRename;
896
897 auto *OldI = dyn_cast<Instruction>(const_cast<Value *>(VT.first));
898 if (!OldI)
899 continue;
900 auto *NewI = cast<Instruction>(VT.second);
901 // Scan all uses of this instruction to see if it is used outside of its
902 // funclet, and if so, record them in UsesToRename.
903 for (Use &U : OldI->uses()) {
904 Instruction *UserI = cast<Instruction>(U.getUser());
905 BasicBlock *UserBB = UserI->getParent();
906 ColorVector &ColorsForUserBB = BlockColors[UserBB];
907 assert(!ColorsForUserBB.empty())(static_cast <bool> (!ColorsForUserBB.empty()) ? void (
0) : __assert_fail ("!ColorsForUserBB.empty()", "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 907, __extension__ __PRETTY_FUNCTION__))
;
908 if (ColorsForUserBB.size() > 1 ||
909 *ColorsForUserBB.begin() != FuncletPadBB)
910 UsesToRename.push_back(&U);
911 }
912
913 // If there are no uses outside the block, we're done with this
914 // instruction.
915 if (UsesToRename.empty())
916 continue;
917
918 // We found a use of OldI outside of the funclet. Rename all uses of OldI
919 // that are outside its funclet to be uses of the appropriate PHI node
920 // etc.
921 SSAUpdater SSAUpdate;
922 SSAUpdate.Initialize(OldI->getType(), OldI->getName());
923 SSAUpdate.AddAvailableValue(OldI->getParent(), OldI);
924 SSAUpdate.AddAvailableValue(NewI->getParent(), NewI);
925
926 while (!UsesToRename.empty())
927 SSAUpdate.RewriteUseAfterInsertions(*UsesToRename.pop_back_val());
928 }
929 }
930}
931
932void WinEHPrepare::removeImplausibleInstructions(Function &F) {
933 // Remove implausible terminators and replace them with UnreachableInst.
934 for (auto &Funclet : FuncletBlocks) {
935 BasicBlock *FuncletPadBB = Funclet.first;
936 std::vector<BasicBlock *> &BlocksInFunclet = Funclet.second;
937 Instruction *FirstNonPHI = FuncletPadBB->getFirstNonPHI();
938 auto *FuncletPad = dyn_cast<FuncletPadInst>(FirstNonPHI);
939 auto *CatchPad = dyn_cast_or_null<CatchPadInst>(FuncletPad);
940 auto *CleanupPad = dyn_cast_or_null<CleanupPadInst>(FuncletPad);
941
942 for (BasicBlock *BB : BlocksInFunclet) {
943 for (Instruction &I : *BB) {
944 CallSite CS(&I);
945 if (!CS)
946 continue;
947
948 Value *FuncletBundleOperand = nullptr;
949 if (auto BU = CS.getOperandBundle(LLVMContext::OB_funclet))
950 FuncletBundleOperand = BU->Inputs.front();
951
952 if (FuncletBundleOperand == FuncletPad)
953 continue;
954
955 // Skip call sites which are nounwind intrinsics or inline asm.
956 auto *CalledFn =
957 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
958 if (CalledFn && ((CalledFn->isIntrinsic() && CS.doesNotThrow()) ||
959 CS.isInlineAsm()))
960 continue;
961
962 // This call site was not part of this funclet, remove it.
963 if (CS.isInvoke()) {
964 // Remove the unwind edge if it was an invoke.
965 removeUnwindEdge(BB);
966 // Get a pointer to the new call.
967 BasicBlock::iterator CallI =
968 std::prev(BB->getTerminator()->getIterator());
969 auto *CI = cast<CallInst>(&*CallI);
970 changeToUnreachable(CI, /*UseLLVMTrap=*/false);
971 } else {
972 changeToUnreachable(&I, /*UseLLVMTrap=*/false);
973 }
974
975 // There are no more instructions in the block (except for unreachable),
976 // we are done.
977 break;
978 }
979
980 TerminatorInst *TI = BB->getTerminator();
981 // CatchPadInst and CleanupPadInst can't transfer control to a ReturnInst.
982 bool IsUnreachableRet = isa<ReturnInst>(TI) && FuncletPad;
983 // The token consumed by a CatchReturnInst must match the funclet token.
984 bool IsUnreachableCatchret = false;
985 if (auto *CRI = dyn_cast<CatchReturnInst>(TI))
986 IsUnreachableCatchret = CRI->getCatchPad() != CatchPad;
987 // The token consumed by a CleanupReturnInst must match the funclet token.
988 bool IsUnreachableCleanupret = false;
989 if (auto *CRI = dyn_cast<CleanupReturnInst>(TI))
990 IsUnreachableCleanupret = CRI->getCleanupPad() != CleanupPad;
991 if (IsUnreachableRet || IsUnreachableCatchret ||
992 IsUnreachableCleanupret) {
993 changeToUnreachable(TI, /*UseLLVMTrap=*/false);
994 } else if (isa<InvokeInst>(TI)) {
995 if (Personality == EHPersonality::MSVC_CXX && CleanupPad) {
996 // Invokes within a cleanuppad for the MSVC++ personality never
997 // transfer control to their unwind edge: the personality will
998 // terminate the program.
999 removeUnwindEdge(BB);
1000 }
1001 }
1002 }
1003 }
1004}
1005
1006void WinEHPrepare::cleanupPreparedFunclets(Function &F) {
1007 // Clean-up some of the mess we made by removing useles PHI nodes, trivial
1008 // branches, etc.
1009 for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE;) {
1010 BasicBlock *BB = &*FI++;
1011 SimplifyInstructionsInBlock(BB);
1012 ConstantFoldTerminator(BB, /*DeleteDeadConditions=*/true);
1013 MergeBlockIntoPredecessor(BB);
1014 }
1015
1016 // We might have some unreachable blocks after cleaning up some impossible
1017 // control flow.
1018 removeUnreachableBlocks(F);
1019}
1020
1021#ifndef NDEBUG
1022void WinEHPrepare::verifyPreparedFunclets(Function &F) {
1023 for (BasicBlock &BB : F) {
1024 size_t NumColors = BlockColors[&BB].size();
1025 assert(NumColors == 1 && "Expected monochromatic BB!")(static_cast <bool> (NumColors == 1 && "Expected monochromatic BB!"
) ? void (0) : __assert_fail ("NumColors == 1 && \"Expected monochromatic BB!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 1025, __extension__ __PRETTY_FUNCTION__))
;
1026 if (NumColors == 0)
1027 report_fatal_error("Uncolored BB!");
1028 if (NumColors > 1)
1029 report_fatal_error("Multicolor BB!");
1030 assert((DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) &&(static_cast <bool> ((DisableDemotion || !(BB.isEHPad()
&& isa<PHINode>(BB.begin()))) && "EH Pad still has a PHI!"
) ? void (0) : __assert_fail ("(DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) && \"EH Pad still has a PHI!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 1031, __extension__ __PRETTY_FUNCTION__))
1031 "EH Pad still has a PHI!")(static_cast <bool> ((DisableDemotion || !(BB.isEHPad()
&& isa<PHINode>(BB.begin()))) && "EH Pad still has a PHI!"
) ? void (0) : __assert_fail ("(DisableDemotion || !(BB.isEHPad() && isa<PHINode>(BB.begin()))) && \"EH Pad still has a PHI!\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 1031, __extension__ __PRETTY_FUNCTION__))
;
1032 }
1033}
1034#endif
1035
1036bool WinEHPrepare::prepareExplicitEH(Function &F) {
1037 // Remove unreachable blocks. It is not valuable to assign them a color and
1038 // their existence can trick us into thinking values are alive when they are
1039 // not.
1040 removeUnreachableBlocks(F);
1041
1042 // Determine which blocks are reachable from which funclet entries.
1043 colorFunclets(F);
1044
1045 cloneCommonBlocks(F);
1046
1047 if (!DisableDemotion)
1048 demotePHIsOnFunclets(F, DemoteCatchSwitchPHIOnly ||
1049 DemoteCatchSwitchPHIOnlyOpt);
1050
1051 if (!DisableCleanups) {
1052 LLVM_DEBUG(verifyFunction(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { verifyFunction(F); } } while (false)
;
1053 removeImplausibleInstructions(F);
1054
1055 LLVM_DEBUG(verifyFunction(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { verifyFunction(F); } } while (false)
;
1056 cleanupPreparedFunclets(F);
1057 }
1058
1059 LLVM_DEBUG(verifyPreparedFunclets(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { verifyPreparedFunclets(F); } } while (false
)
;
1060 // Recolor the CFG to verify that all is well.
1061 LLVM_DEBUG(colorFunclets(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { colorFunclets(F); } } while (false)
;
1062 LLVM_DEBUG(verifyPreparedFunclets(F))do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("winehprepare")) { verifyPreparedFunclets(F); } } while (false
)
;
1063
1064 BlockColors.clear();
1065 FuncletBlocks.clear();
1066
1067 return true;
1068}
1069
1070// TODO: Share loads when one use dominates another, or when a catchpad exit
1071// dominates uses (needs dominators).
1072AllocaInst *WinEHPrepare::insertPHILoads(PHINode *PN, Function &F) {
1073 BasicBlock *PHIBlock = PN->getParent();
1074 AllocaInst *SpillSlot = nullptr;
1075 Instruction *EHPad = PHIBlock->getFirstNonPHI();
1076
1077 if (!isa<TerminatorInst>(EHPad)) {
1078 // If the EHPad isn't a terminator, then we can insert a load in this block
1079 // that will dominate all uses.
1080 SpillSlot = new AllocaInst(PN->getType(), DL->getAllocaAddrSpace(), nullptr,
1081 Twine(PN->getName(), ".wineh.spillslot"),
1082 &F.getEntryBlock().front());
1083 Value *V = new LoadInst(SpillSlot, Twine(PN->getName(), ".wineh.reload"),
1084 &*PHIBlock->getFirstInsertionPt());
1085 PN->replaceAllUsesWith(V);
1086 return SpillSlot;
1087 }
1088
1089 // Otherwise, we have a PHI on a terminator EHPad, and we give up and insert
1090 // loads of the slot before every use.
1091 DenseMap<BasicBlock *, Value *> Loads;
1092 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
1093 UI != UE;) {
1094 Use &U = *UI++;
1095 auto *UsingInst = cast<Instruction>(U.getUser());
1096 if (isa<PHINode>(UsingInst) && UsingInst->getParent()->isEHPad()) {
1097 // Use is on an EH pad phi. Leave it alone; we'll insert loads and
1098 // stores for it separately.
1099 continue;
1100 }
1101 replaceUseWithLoad(PN, U, SpillSlot, Loads, F);
1102 }
1103 return SpillSlot;
1104}
1105
1106// TODO: improve store placement. Inserting at def is probably good, but need
1107// to be careful not to introduce interfering stores (needs liveness analysis).
1108// TODO: identify related phi nodes that can share spill slots, and share them
1109// (also needs liveness).
1110void WinEHPrepare::insertPHIStores(PHINode *OriginalPHI,
1111 AllocaInst *SpillSlot) {
1112 // Use a worklist of (Block, Value) pairs -- the given Value needs to be
1113 // stored to the spill slot by the end of the given Block.
1114 SmallVector<std::pair<BasicBlock *, Value *>, 4> Worklist;
1115
1116 Worklist.push_back({OriginalPHI->getParent(), OriginalPHI});
1117
1118 while (!Worklist.empty()) {
1119 BasicBlock *EHBlock;
1120 Value *InVal;
1121 std::tie(EHBlock, InVal) = Worklist.pop_back_val();
1122
1123 PHINode *PN = dyn_cast<PHINode>(InVal);
1124 if (PN && PN->getParent() == EHBlock) {
1125 // The value is defined by another PHI we need to remove, with no room to
1126 // insert a store after the PHI, so each predecessor needs to store its
1127 // incoming value.
1128 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
1129 Value *PredVal = PN->getIncomingValue(i);
1130
1131 // Undef can safely be skipped.
1132 if (isa<UndefValue>(PredVal))
1133 continue;
1134
1135 insertPHIStore(PN->getIncomingBlock(i), PredVal, SpillSlot, Worklist);
1136 }
1137 } else {
1138 // We need to store InVal, which dominates EHBlock, but can't put a store
1139 // in EHBlock, so need to put stores in each predecessor.
1140 for (BasicBlock *PredBlock : predecessors(EHBlock)) {
1141 insertPHIStore(PredBlock, InVal, SpillSlot, Worklist);
1142 }
1143 }
1144 }
1145}
1146
1147void WinEHPrepare::insertPHIStore(
1148 BasicBlock *PredBlock, Value *PredVal, AllocaInst *SpillSlot,
1149 SmallVectorImpl<std::pair<BasicBlock *, Value *>> &Worklist) {
1150
1151 if (PredBlock->isEHPad() &&
1152 isa<TerminatorInst>(PredBlock->getFirstNonPHI())) {
1153 // Pred is unsplittable, so we need to queue it on the worklist.
1154 Worklist.push_back({PredBlock, PredVal});
1155 return;
1156 }
1157
1158 // Otherwise, insert the store at the end of the basic block.
1159 new StoreInst(PredVal, SpillSlot, PredBlock->getTerminator());
1160}
1161
1162void WinEHPrepare::replaceUseWithLoad(Value *V, Use &U, AllocaInst *&SpillSlot,
1163 DenseMap<BasicBlock *, Value *> &Loads,
1164 Function &F) {
1165 // Lazilly create the spill slot.
1166 if (!SpillSlot)
1167 SpillSlot = new AllocaInst(V->getType(), DL->getAllocaAddrSpace(), nullptr,
1168 Twine(V->getName(), ".wineh.spillslot"),
1169 &F.getEntryBlock().front());
1170
1171 auto *UsingInst = cast<Instruction>(U.getUser());
1172 if (auto *UsingPHI = dyn_cast<PHINode>(UsingInst)) {
1173 // If this is a PHI node, we can't insert a load of the value before
1174 // the use. Instead insert the load in the predecessor block
1175 // corresponding to the incoming value.
1176 //
1177 // Note that if there are multiple edges from a basic block to this
1178 // PHI node that we cannot have multiple loads. The problem is that
1179 // the resulting PHI node will have multiple values (from each load)
1180 // coming in from the same block, which is illegal SSA form.
1181 // For this reason, we keep track of and reuse loads we insert.
1182 BasicBlock *IncomingBlock = UsingPHI->getIncomingBlock(U);
1183 if (auto *CatchRet =
1184 dyn_cast<CatchReturnInst>(IncomingBlock->getTerminator())) {
1185 // Putting a load above a catchret and use on the phi would still leave
1186 // a cross-funclet def/use. We need to split the edge, change the
1187 // catchret to target the new block, and put the load there.
1188 BasicBlock *PHIBlock = UsingInst->getParent();
1189 BasicBlock *NewBlock = SplitEdge(IncomingBlock, PHIBlock);
1190 // SplitEdge gives us:
1191 // IncomingBlock:
1192 // ...
1193 // br label %NewBlock
1194 // NewBlock:
1195 // catchret label %PHIBlock
1196 // But we need:
1197 // IncomingBlock:
1198 // ...
1199 // catchret label %NewBlock
1200 // NewBlock:
1201 // br label %PHIBlock
1202 // So move the terminators to each others' blocks and swap their
1203 // successors.
1204 BranchInst *Goto = cast<BranchInst>(IncomingBlock->getTerminator());
1205 Goto->removeFromParent();
1206 CatchRet->removeFromParent();
1207 IncomingBlock->getInstList().push_back(CatchRet);
1208 NewBlock->getInstList().push_back(Goto);
1209 Goto->setSuccessor(0, PHIBlock);
1210 CatchRet->setSuccessor(NewBlock);
1211 // Update the color mapping for the newly split edge.
1212 // Grab a reference to the ColorVector to be inserted before getting the
1213 // reference to the vector we are copying because inserting the new
1214 // element in BlockColors might cause the map to be reallocated.
1215 ColorVector &ColorsForNewBlock = BlockColors[NewBlock];
1216 ColorVector &ColorsForPHIBlock = BlockColors[PHIBlock];
1217 ColorsForNewBlock = ColorsForPHIBlock;
1218 for (BasicBlock *FuncletPad : ColorsForPHIBlock)
1219 FuncletBlocks[FuncletPad].push_back(NewBlock);
1220 // Treat the new block as incoming for load insertion.
1221 IncomingBlock = NewBlock;
1222 }
1223 Value *&Load = Loads[IncomingBlock];
1224 // Insert the load into the predecessor block
1225 if (!Load)
1226 Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1227 /*Volatile=*/false, IncomingBlock->getTerminator());
1228
1229 U.set(Load);
1230 } else {
1231 // Reload right before the old use.
1232 auto *Load = new LoadInst(SpillSlot, Twine(V->getName(), ".wineh.reload"),
1233 /*Volatile=*/false, UsingInst);
1234 U.set(Load);
1235 }
1236}
1237
1238void WinEHFuncInfo::addIPToStateRange(const InvokeInst *II,
1239 MCSymbol *InvokeBegin,
1240 MCSymbol *InvokeEnd) {
1241 assert(InvokeStateMap.count(II) &&(static_cast <bool> (InvokeStateMap.count(II) &&
"should get invoke with precomputed state") ? void (0) : __assert_fail
("InvokeStateMap.count(II) && \"should get invoke with precomputed state\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 1242, __extension__ __PRETTY_FUNCTION__))
1242 "should get invoke with precomputed state")(static_cast <bool> (InvokeStateMap.count(II) &&
"should get invoke with precomputed state") ? void (0) : __assert_fail
("InvokeStateMap.count(II) && \"should get invoke with precomputed state\""
, "/build/llvm-toolchain-snapshot-7~svn338205/lib/CodeGen/WinEHPrepare.cpp"
, 1242, __extension__ __PRETTY_FUNCTION__))
;
1243 LabelToStateMap[InvokeBegin] = std::make_pair(InvokeStateMap[II], InvokeEnd);
1244}
1245
1246WinEHFuncInfo::WinEHFuncInfo() {}

/build/llvm-toolchain-snapshot-7~svn338205/include/llvm/IR/Instructions.h

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