1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements all of the non-inline methods for the LLVM instruction
10 // classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/IR/Instructions.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/IR/Attributes.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/Constant.h"
22 #include "llvm/IR/Constants.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/InstrTypes.h"
27 #include "llvm/IR/Instruction.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/MDBuilder.h"
31 #include "llvm/IR/Metadata.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Operator.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/AtomicOrdering.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/TypeSize.h"
41 #include <algorithm>
42 #include <cassert>
43 #include <cstdint>
44 #include <vector>
45
46 using namespace llvm;
47
48 //===----------------------------------------------------------------------===//
49 // AllocaInst Class
50 //===----------------------------------------------------------------------===//
51
52 Optional<TypeSize>
getAllocationSizeInBits(const DataLayout & DL) const53 AllocaInst::getAllocationSizeInBits(const DataLayout &DL) const {
54 TypeSize Size = DL.getTypeAllocSizeInBits(getAllocatedType());
55 if (isArrayAllocation()) {
56 auto *C = dyn_cast<ConstantInt>(getArraySize());
57 if (!C)
58 return None;
59 assert(!Size.isScalable() && "Array elements cannot have a scalable size");
60 Size *= C->getZExtValue();
61 }
62 return Size;
63 }
64
65 //===----------------------------------------------------------------------===//
66 // SelectInst Class
67 //===----------------------------------------------------------------------===//
68
69 /// areInvalidOperands - Return a string if the specified operands are invalid
70 /// for a select operation, otherwise return null.
areInvalidOperands(Value * Op0,Value * Op1,Value * Op2)71 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
72 if (Op1->getType() != Op2->getType())
73 return "both values to select must have same type";
74
75 if (Op1->getType()->isTokenTy())
76 return "select values cannot have token type";
77
78 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
79 // Vector select.
80 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
81 return "vector select condition element type must be i1";
82 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
83 if (!ET)
84 return "selected values for vector select must be vectors";
85 if (ET->getElementCount() != VT->getElementCount())
86 return "vector select requires selected vectors to have "
87 "the same vector length as select condition";
88 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
89 return "select condition must be i1 or <n x i1>";
90 }
91 return nullptr;
92 }
93
94 //===----------------------------------------------------------------------===//
95 // PHINode Class
96 //===----------------------------------------------------------------------===//
97
PHINode(const PHINode & PN)98 PHINode::PHINode(const PHINode &PN)
99 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
100 ReservedSpace(PN.getNumOperands()) {
101 allocHungoffUses(PN.getNumOperands());
102 std::copy(PN.op_begin(), PN.op_end(), op_begin());
103 std::copy(PN.block_begin(), PN.block_end(), block_begin());
104 SubclassOptionalData = PN.SubclassOptionalData;
105 }
106
107 // removeIncomingValue - Remove an incoming value. This is useful if a
108 // predecessor basic block is deleted.
removeIncomingValue(unsigned Idx,bool DeletePHIIfEmpty)109 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
110 Value *Removed = getIncomingValue(Idx);
111
112 // Move everything after this operand down.
113 //
114 // FIXME: we could just swap with the end of the list, then erase. However,
115 // clients might not expect this to happen. The code as it is thrashes the
116 // use/def lists, which is kinda lame.
117 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
118 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
119
120 // Nuke the last value.
121 Op<-1>().set(nullptr);
122 setNumHungOffUseOperands(getNumOperands() - 1);
123
124 // If the PHI node is dead, because it has zero entries, nuke it now.
125 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
126 // If anyone is using this PHI, make them use a dummy value instead...
127 replaceAllUsesWith(UndefValue::get(getType()));
128 eraseFromParent();
129 }
130 return Removed;
131 }
132
133 /// growOperands - grow operands - This grows the operand list in response
134 /// to a push_back style of operation. This grows the number of ops by 1.5
135 /// times.
136 ///
growOperands()137 void PHINode::growOperands() {
138 unsigned e = getNumOperands();
139 unsigned NumOps = e + e / 2;
140 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
141
142 ReservedSpace = NumOps;
143 growHungoffUses(ReservedSpace, /* IsPhi */ true);
144 }
145
146 /// hasConstantValue - If the specified PHI node always merges together the same
147 /// value, return the value, otherwise return null.
hasConstantValue() const148 Value *PHINode::hasConstantValue() const {
149 // Exploit the fact that phi nodes always have at least one entry.
150 Value *ConstantValue = getIncomingValue(0);
151 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
152 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
153 if (ConstantValue != this)
154 return nullptr; // Incoming values not all the same.
155 // The case where the first value is this PHI.
156 ConstantValue = getIncomingValue(i);
157 }
158 if (ConstantValue == this)
159 return UndefValue::get(getType());
160 return ConstantValue;
161 }
162
163 /// hasConstantOrUndefValue - Whether the specified PHI node always merges
164 /// together the same value, assuming that undefs result in the same value as
165 /// non-undefs.
166 /// Unlike \ref hasConstantValue, this does not return a value because the
167 /// unique non-undef incoming value need not dominate the PHI node.
hasConstantOrUndefValue() const168 bool PHINode::hasConstantOrUndefValue() const {
169 Value *ConstantValue = nullptr;
170 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
171 Value *Incoming = getIncomingValue(i);
172 if (Incoming != this && !isa<UndefValue>(Incoming)) {
173 if (ConstantValue && ConstantValue != Incoming)
174 return false;
175 ConstantValue = Incoming;
176 }
177 }
178 return true;
179 }
180
181 //===----------------------------------------------------------------------===//
182 // LandingPadInst Implementation
183 //===----------------------------------------------------------------------===//
184
LandingPadInst(Type * RetTy,unsigned NumReservedValues,const Twine & NameStr,Instruction * InsertBefore)185 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
186 const Twine &NameStr, Instruction *InsertBefore)
187 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
188 init(NumReservedValues, NameStr);
189 }
190
LandingPadInst(Type * RetTy,unsigned NumReservedValues,const Twine & NameStr,BasicBlock * InsertAtEnd)191 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
192 const Twine &NameStr, BasicBlock *InsertAtEnd)
193 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
194 init(NumReservedValues, NameStr);
195 }
196
LandingPadInst(const LandingPadInst & LP)197 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
198 : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
199 LP.getNumOperands()),
200 ReservedSpace(LP.getNumOperands()) {
201 allocHungoffUses(LP.getNumOperands());
202 Use *OL = getOperandList();
203 const Use *InOL = LP.getOperandList();
204 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
205 OL[I] = InOL[I];
206
207 setCleanup(LP.isCleanup());
208 }
209
Create(Type * RetTy,unsigned NumReservedClauses,const Twine & NameStr,Instruction * InsertBefore)210 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
211 const Twine &NameStr,
212 Instruction *InsertBefore) {
213 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
214 }
215
Create(Type * RetTy,unsigned NumReservedClauses,const Twine & NameStr,BasicBlock * InsertAtEnd)216 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
217 const Twine &NameStr,
218 BasicBlock *InsertAtEnd) {
219 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
220 }
221
init(unsigned NumReservedValues,const Twine & NameStr)222 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
223 ReservedSpace = NumReservedValues;
224 setNumHungOffUseOperands(0);
225 allocHungoffUses(ReservedSpace);
226 setName(NameStr);
227 setCleanup(false);
228 }
229
230 /// growOperands - grow operands - This grows the operand list in response to a
231 /// push_back style of operation. This grows the number of ops by 2 times.
growOperands(unsigned Size)232 void LandingPadInst::growOperands(unsigned Size) {
233 unsigned e = getNumOperands();
234 if (ReservedSpace >= e + Size) return;
235 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
236 growHungoffUses(ReservedSpace);
237 }
238
addClause(Constant * Val)239 void LandingPadInst::addClause(Constant *Val) {
240 unsigned OpNo = getNumOperands();
241 growOperands(1);
242 assert(OpNo < ReservedSpace && "Growing didn't work!");
243 setNumHungOffUseOperands(getNumOperands() + 1);
244 getOperandList()[OpNo] = Val;
245 }
246
247 //===----------------------------------------------------------------------===//
248 // CallBase Implementation
249 //===----------------------------------------------------------------------===//
250
Create(CallBase * CB,ArrayRef<OperandBundleDef> Bundles,Instruction * InsertPt)251 CallBase *CallBase::Create(CallBase *CB, ArrayRef<OperandBundleDef> Bundles,
252 Instruction *InsertPt) {
253 switch (CB->getOpcode()) {
254 case Instruction::Call:
255 return CallInst::Create(cast<CallInst>(CB), Bundles, InsertPt);
256 case Instruction::Invoke:
257 return InvokeInst::Create(cast<InvokeInst>(CB), Bundles, InsertPt);
258 case Instruction::CallBr:
259 return CallBrInst::Create(cast<CallBrInst>(CB), Bundles, InsertPt);
260 default:
261 llvm_unreachable("Unknown CallBase sub-class!");
262 }
263 }
264
getCaller()265 Function *CallBase::getCaller() { return getParent()->getParent(); }
266
getNumSubclassExtraOperandsDynamic() const267 unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
268 assert(getOpcode() == Instruction::CallBr && "Unexpected opcode!");
269 return cast<CallBrInst>(this)->getNumIndirectDests() + 1;
270 }
271
isIndirectCall() const272 bool CallBase::isIndirectCall() const {
273 const Value *V = getCalledOperand();
274 if (isa<Function>(V) || isa<Constant>(V))
275 return false;
276 return !isInlineAsm();
277 }
278
279 /// Tests if this call site must be tail call optimized. Only a CallInst can
280 /// be tail call optimized.
isMustTailCall() const281 bool CallBase::isMustTailCall() const {
282 if (auto *CI = dyn_cast<CallInst>(this))
283 return CI->isMustTailCall();
284 return false;
285 }
286
287 /// Tests if this call site is marked as a tail call.
isTailCall() const288 bool CallBase::isTailCall() const {
289 if (auto *CI = dyn_cast<CallInst>(this))
290 return CI->isTailCall();
291 return false;
292 }
293
getIntrinsicID() const294 Intrinsic::ID CallBase::getIntrinsicID() const {
295 if (auto *F = getCalledFunction())
296 return F->getIntrinsicID();
297 return Intrinsic::not_intrinsic;
298 }
299
isReturnNonNull() const300 bool CallBase::isReturnNonNull() const {
301 if (hasRetAttr(Attribute::NonNull))
302 return true;
303
304 if (getDereferenceableBytes(AttributeList::ReturnIndex) > 0 &&
305 !NullPointerIsDefined(getCaller(),
306 getType()->getPointerAddressSpace()))
307 return true;
308
309 return false;
310 }
311
getReturnedArgOperand() const312 Value *CallBase::getReturnedArgOperand() const {
313 unsigned Index;
314
315 if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index)
316 return getArgOperand(Index - AttributeList::FirstArgIndex);
317 if (const Function *F = getCalledFunction())
318 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) &&
319 Index)
320 return getArgOperand(Index - AttributeList::FirstArgIndex);
321
322 return nullptr;
323 }
324
hasRetAttr(Attribute::AttrKind Kind) const325 bool CallBase::hasRetAttr(Attribute::AttrKind Kind) const {
326 if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind))
327 return true;
328
329 // Look at the callee, if available.
330 if (const Function *F = getCalledFunction())
331 return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind);
332 return false;
333 }
334
335 /// Determine whether the argument or parameter has the given attribute.
paramHasAttr(unsigned ArgNo,Attribute::AttrKind Kind) const336 bool CallBase::paramHasAttr(unsigned ArgNo, Attribute::AttrKind Kind) const {
337 assert(ArgNo < getNumArgOperands() && "Param index out of bounds!");
338
339 if (Attrs.hasParamAttribute(ArgNo, Kind))
340 return true;
341 if (const Function *F = getCalledFunction())
342 return F->getAttributes().hasParamAttribute(ArgNo, Kind);
343 return false;
344 }
345
hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const346 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind) const {
347 if (const Function *F = getCalledFunction())
348 return F->getAttributes().hasFnAttribute(Kind);
349 return false;
350 }
351
hasFnAttrOnCalledFunction(StringRef Kind) const352 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind) const {
353 if (const Function *F = getCalledFunction())
354 return F->getAttributes().hasFnAttribute(Kind);
355 return false;
356 }
357
getOperandBundlesAsDefs(SmallVectorImpl<OperandBundleDef> & Defs) const358 void CallBase::getOperandBundlesAsDefs(
359 SmallVectorImpl<OperandBundleDef> &Defs) const {
360 for (unsigned i = 0, e = getNumOperandBundles(); i != e; ++i)
361 Defs.emplace_back(getOperandBundleAt(i));
362 }
363
364 CallBase::op_iterator
populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,const unsigned BeginIndex)365 CallBase::populateBundleOperandInfos(ArrayRef<OperandBundleDef> Bundles,
366 const unsigned BeginIndex) {
367 auto It = op_begin() + BeginIndex;
368 for (auto &B : Bundles)
369 It = std::copy(B.input_begin(), B.input_end(), It);
370
371 auto *ContextImpl = getContext().pImpl;
372 auto BI = Bundles.begin();
373 unsigned CurrentIndex = BeginIndex;
374
375 for (auto &BOI : bundle_op_infos()) {
376 assert(BI != Bundles.end() && "Incorrect allocation?");
377
378 BOI.Tag = ContextImpl->getOrInsertBundleTag(BI->getTag());
379 BOI.Begin = CurrentIndex;
380 BOI.End = CurrentIndex + BI->input_size();
381 CurrentIndex = BOI.End;
382 BI++;
383 }
384
385 assert(BI == Bundles.end() && "Incorrect allocation?");
386
387 return It;
388 }
389
getBundleOpInfoForOperand(unsigned OpIdx)390 CallBase::BundleOpInfo &CallBase::getBundleOpInfoForOperand(unsigned OpIdx) {
391 /// When there isn't many bundles, we do a simple linear search.
392 /// Else fallback to a binary-search that use the fact that bundles usually
393 /// have similar number of argument to get faster convergence.
394 if (bundle_op_info_end() - bundle_op_info_begin() < 8) {
395 for (auto &BOI : bundle_op_infos())
396 if (BOI.Begin <= OpIdx && OpIdx < BOI.End)
397 return BOI;
398
399 llvm_unreachable("Did not find operand bundle for operand!");
400 }
401
402 assert(OpIdx >= arg_size() && "the Idx is not in the operand bundles");
403 assert(bundle_op_info_end() - bundle_op_info_begin() > 0 &&
404 OpIdx < std::prev(bundle_op_info_end())->End &&
405 "The Idx isn't in the operand bundle");
406
407 /// We need a decimal number below and to prevent using floating point numbers
408 /// we use an intergal value multiplied by this constant.
409 constexpr unsigned NumberScaling = 1024;
410
411 bundle_op_iterator Begin = bundle_op_info_begin();
412 bundle_op_iterator End = bundle_op_info_end();
413 bundle_op_iterator Current;
414
415 while (Begin != End) {
416 unsigned ScaledOperandPerBundle =
417 NumberScaling * (std::prev(End)->End - Begin->Begin) / (End - Begin);
418 Current = Begin + (((OpIdx - Begin->Begin) * NumberScaling) /
419 ScaledOperandPerBundle);
420 if (Current >= End)
421 Current = std::prev(End);
422 assert(Current < End && Current >= Begin &&
423 "the operand bundle doesn't cover every value in the range");
424 if (OpIdx >= Current->Begin && OpIdx < Current->End)
425 break;
426 if (OpIdx >= Current->End)
427 Begin = Current + 1;
428 else
429 End = Current;
430 }
431
432 assert(OpIdx >= Current->Begin && OpIdx < Current->End &&
433 "the operand bundle doesn't cover every value in the range");
434 return *Current;
435 }
436
437 //===----------------------------------------------------------------------===//
438 // CallInst Implementation
439 //===----------------------------------------------------------------------===//
440
init(FunctionType * FTy,Value * Func,ArrayRef<Value * > Args,ArrayRef<OperandBundleDef> Bundles,const Twine & NameStr)441 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
442 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
443 this->FTy = FTy;
444 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
445 "NumOperands not set up?");
446 setCalledOperand(Func);
447
448 #ifndef NDEBUG
449 assert((Args.size() == FTy->getNumParams() ||
450 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
451 "Calling a function with bad signature!");
452
453 for (unsigned i = 0; i != Args.size(); ++i)
454 assert((i >= FTy->getNumParams() ||
455 FTy->getParamType(i) == Args[i]->getType()) &&
456 "Calling a function with a bad signature!");
457 #endif
458
459 llvm::copy(Args, op_begin());
460
461 auto It = populateBundleOperandInfos(Bundles, Args.size());
462 (void)It;
463 assert(It + 1 == op_end() && "Should add up!");
464
465 setName(NameStr);
466 }
467
init(FunctionType * FTy,Value * Func,const Twine & NameStr)468 void CallInst::init(FunctionType *FTy, Value *Func, const Twine &NameStr) {
469 this->FTy = FTy;
470 assert(getNumOperands() == 1 && "NumOperands not set up?");
471 setCalledOperand(Func);
472
473 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
474
475 setName(NameStr);
476 }
477
CallInst(FunctionType * Ty,Value * Func,const Twine & Name,Instruction * InsertBefore)478 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
479 Instruction *InsertBefore)
480 : CallBase(Ty->getReturnType(), Instruction::Call,
481 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertBefore) {
482 init(Ty, Func, Name);
483 }
484
CallInst(FunctionType * Ty,Value * Func,const Twine & Name,BasicBlock * InsertAtEnd)485 CallInst::CallInst(FunctionType *Ty, Value *Func, const Twine &Name,
486 BasicBlock *InsertAtEnd)
487 : CallBase(Ty->getReturnType(), Instruction::Call,
488 OperandTraits<CallBase>::op_end(this) - 1, 1, InsertAtEnd) {
489 init(Ty, Func, Name);
490 }
491
CallInst(const CallInst & CI)492 CallInst::CallInst(const CallInst &CI)
493 : CallBase(CI.Attrs, CI.FTy, CI.getType(), Instruction::Call,
494 OperandTraits<CallBase>::op_end(this) - CI.getNumOperands(),
495 CI.getNumOperands()) {
496 setTailCallKind(CI.getTailCallKind());
497 setCallingConv(CI.getCallingConv());
498
499 std::copy(CI.op_begin(), CI.op_end(), op_begin());
500 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
501 bundle_op_info_begin());
502 SubclassOptionalData = CI.SubclassOptionalData;
503 }
504
Create(CallInst * CI,ArrayRef<OperandBundleDef> OpB,Instruction * InsertPt)505 CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB,
506 Instruction *InsertPt) {
507 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
508
509 auto *NewCI = CallInst::Create(CI->getFunctionType(), CI->getCalledOperand(),
510 Args, OpB, CI->getName(), InsertPt);
511 NewCI->setTailCallKind(CI->getTailCallKind());
512 NewCI->setCallingConv(CI->getCallingConv());
513 NewCI->SubclassOptionalData = CI->SubclassOptionalData;
514 NewCI->setAttributes(CI->getAttributes());
515 NewCI->setDebugLoc(CI->getDebugLoc());
516 return NewCI;
517 }
518
CreateWithReplacedBundle(CallInst * CI,OperandBundleDef OpB,Instruction * InsertPt)519 CallInst *CallInst::CreateWithReplacedBundle(CallInst *CI, OperandBundleDef OpB,
520 Instruction *InsertPt) {
521 SmallVector<OperandBundleDef, 2> OpDefs;
522 for (unsigned i = 0, e = CI->getNumOperandBundles(); i < e; ++i) {
523 auto ChildOB = CI->getOperandBundleAt(i);
524 if (ChildOB.getTagName() != OpB.getTag())
525 OpDefs.emplace_back(ChildOB);
526 }
527 OpDefs.emplace_back(OpB);
528 return CallInst::Create(CI, OpDefs, InsertPt);
529 }
530
531 // Update profile weight for call instruction by scaling it using the ratio
532 // of S/T. The meaning of "branch_weights" meta data for call instruction is
533 // transfered to represent call count.
updateProfWeight(uint64_t S,uint64_t T)534 void CallInst::updateProfWeight(uint64_t S, uint64_t T) {
535 auto *ProfileData = getMetadata(LLVMContext::MD_prof);
536 if (ProfileData == nullptr)
537 return;
538
539 auto *ProfDataName = dyn_cast<MDString>(ProfileData->getOperand(0));
540 if (!ProfDataName || (!ProfDataName->getString().equals("branch_weights") &&
541 !ProfDataName->getString().equals("VP")))
542 return;
543
544 if (T == 0) {
545 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
546 "div by 0. Ignoring. Likely the function "
547 << getParent()->getParent()->getName()
548 << " has 0 entry count, and contains call instructions "
549 "with non-zero prof info.");
550 return;
551 }
552
553 MDBuilder MDB(getContext());
554 SmallVector<Metadata *, 3> Vals;
555 Vals.push_back(ProfileData->getOperand(0));
556 APInt APS(128, S), APT(128, T);
557 if (ProfDataName->getString().equals("branch_weights") &&
558 ProfileData->getNumOperands() > 0) {
559 // Using APInt::div may be expensive, but most cases should fit 64 bits.
560 APInt Val(128, mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1))
561 ->getValue()
562 .getZExtValue());
563 Val *= APS;
564 Vals.push_back(MDB.createConstant(
565 ConstantInt::get(Type::getInt32Ty(getContext()),
566 Val.udiv(APT).getLimitedValue(UINT32_MAX))));
567 } else if (ProfDataName->getString().equals("VP"))
568 for (unsigned i = 1; i < ProfileData->getNumOperands(); i += 2) {
569 // The first value is the key of the value profile, which will not change.
570 Vals.push_back(ProfileData->getOperand(i));
571 // Using APInt::div may be expensive, but most cases should fit 64 bits.
572 APInt Val(128,
573 mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(i + 1))
574 ->getValue()
575 .getZExtValue());
576 Val *= APS;
577 Vals.push_back(MDB.createConstant(
578 ConstantInt::get(Type::getInt64Ty(getContext()),
579 Val.udiv(APT).getLimitedValue())));
580 }
581 setMetadata(LLVMContext::MD_prof, MDNode::get(getContext(), Vals));
582 }
583
584 /// IsConstantOne - Return true only if val is constant int 1
IsConstantOne(Value * val)585 static bool IsConstantOne(Value *val) {
586 assert(val && "IsConstantOne does not work with nullptr val");
587 const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
588 return CVal && CVal->isOne();
589 }
590
createMalloc(Instruction * InsertBefore,BasicBlock * InsertAtEnd,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,ArrayRef<OperandBundleDef> OpB,Function * MallocF,const Twine & Name)591 static Instruction *createMalloc(Instruction *InsertBefore,
592 BasicBlock *InsertAtEnd, Type *IntPtrTy,
593 Type *AllocTy, Value *AllocSize,
594 Value *ArraySize,
595 ArrayRef<OperandBundleDef> OpB,
596 Function *MallocF, const Twine &Name) {
597 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
598 "createMalloc needs either InsertBefore or InsertAtEnd");
599
600 // malloc(type) becomes:
601 // bitcast (i8* malloc(typeSize)) to type*
602 // malloc(type, arraySize) becomes:
603 // bitcast (i8* malloc(typeSize*arraySize)) to type*
604 if (!ArraySize)
605 ArraySize = ConstantInt::get(IntPtrTy, 1);
606 else if (ArraySize->getType() != IntPtrTy) {
607 if (InsertBefore)
608 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
609 "", InsertBefore);
610 else
611 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
612 "", InsertAtEnd);
613 }
614
615 if (!IsConstantOne(ArraySize)) {
616 if (IsConstantOne(AllocSize)) {
617 AllocSize = ArraySize; // Operand * 1 = Operand
618 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
619 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
620 false /*ZExt*/);
621 // Malloc arg is constant product of type size and array size
622 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
623 } else {
624 // Multiply type size by the array size...
625 if (InsertBefore)
626 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
627 "mallocsize", InsertBefore);
628 else
629 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
630 "mallocsize", InsertAtEnd);
631 }
632 }
633
634 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
635 // Create the call to Malloc.
636 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
637 Module *M = BB->getParent()->getParent();
638 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
639 FunctionCallee MallocFunc = MallocF;
640 if (!MallocFunc)
641 // prototype malloc as "void *malloc(size_t)"
642 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
643 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
644 CallInst *MCall = nullptr;
645 Instruction *Result = nullptr;
646 if (InsertBefore) {
647 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
648 InsertBefore);
649 Result = MCall;
650 if (Result->getType() != AllocPtrType)
651 // Create a cast instruction to convert to the right type...
652 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
653 } else {
654 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
655 Result = MCall;
656 if (Result->getType() != AllocPtrType) {
657 InsertAtEnd->getInstList().push_back(MCall);
658 // Create a cast instruction to convert to the right type...
659 Result = new BitCastInst(MCall, AllocPtrType, Name);
660 }
661 }
662 MCall->setTailCall();
663 if (Function *F = dyn_cast<Function>(MallocFunc.getCallee())) {
664 MCall->setCallingConv(F->getCallingConv());
665 if (!F->returnDoesNotAlias())
666 F->setReturnDoesNotAlias();
667 }
668 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
669
670 return Result;
671 }
672
673 /// CreateMalloc - Generate the IR for a call to malloc:
674 /// 1. Compute the malloc call's argument as the specified type's size,
675 /// possibly multiplied by the array size if the array size is not
676 /// constant 1.
677 /// 2. Call malloc with that argument.
678 /// 3. Bitcast the result of the malloc call to the specified type.
CreateMalloc(Instruction * InsertBefore,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,Function * MallocF,const Twine & Name)679 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
680 Type *IntPtrTy, Type *AllocTy,
681 Value *AllocSize, Value *ArraySize,
682 Function *MallocF,
683 const Twine &Name) {
684 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
685 ArraySize, None, MallocF, Name);
686 }
CreateMalloc(Instruction * InsertBefore,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,ArrayRef<OperandBundleDef> OpB,Function * MallocF,const Twine & Name)687 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
688 Type *IntPtrTy, Type *AllocTy,
689 Value *AllocSize, Value *ArraySize,
690 ArrayRef<OperandBundleDef> OpB,
691 Function *MallocF,
692 const Twine &Name) {
693 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
694 ArraySize, OpB, MallocF, Name);
695 }
696
697 /// CreateMalloc - Generate the IR for a call to malloc:
698 /// 1. Compute the malloc call's argument as the specified type's size,
699 /// possibly multiplied by the array size if the array size is not
700 /// constant 1.
701 /// 2. Call malloc with that argument.
702 /// 3. Bitcast the result of the malloc call to the specified type.
703 /// Note: This function does not add the bitcast to the basic block, that is the
704 /// responsibility of the caller.
CreateMalloc(BasicBlock * InsertAtEnd,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,Function * MallocF,const Twine & Name)705 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
706 Type *IntPtrTy, Type *AllocTy,
707 Value *AllocSize, Value *ArraySize,
708 Function *MallocF, const Twine &Name) {
709 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
710 ArraySize, None, MallocF, Name);
711 }
CreateMalloc(BasicBlock * InsertAtEnd,Type * IntPtrTy,Type * AllocTy,Value * AllocSize,Value * ArraySize,ArrayRef<OperandBundleDef> OpB,Function * MallocF,const Twine & Name)712 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
713 Type *IntPtrTy, Type *AllocTy,
714 Value *AllocSize, Value *ArraySize,
715 ArrayRef<OperandBundleDef> OpB,
716 Function *MallocF, const Twine &Name) {
717 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
718 ArraySize, OpB, MallocF, Name);
719 }
720
createFree(Value * Source,ArrayRef<OperandBundleDef> Bundles,Instruction * InsertBefore,BasicBlock * InsertAtEnd)721 static Instruction *createFree(Value *Source,
722 ArrayRef<OperandBundleDef> Bundles,
723 Instruction *InsertBefore,
724 BasicBlock *InsertAtEnd) {
725 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
726 "createFree needs either InsertBefore or InsertAtEnd");
727 assert(Source->getType()->isPointerTy() &&
728 "Can not free something of nonpointer type!");
729
730 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
731 Module *M = BB->getParent()->getParent();
732
733 Type *VoidTy = Type::getVoidTy(M->getContext());
734 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
735 // prototype free as "void free(void*)"
736 FunctionCallee FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
737 CallInst *Result = nullptr;
738 Value *PtrCast = Source;
739 if (InsertBefore) {
740 if (Source->getType() != IntPtrTy)
741 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
742 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
743 } else {
744 if (Source->getType() != IntPtrTy)
745 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
746 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
747 }
748 Result->setTailCall();
749 if (Function *F = dyn_cast<Function>(FreeFunc.getCallee()))
750 Result->setCallingConv(F->getCallingConv());
751
752 return Result;
753 }
754
755 /// CreateFree - Generate the IR for a call to the builtin free function.
CreateFree(Value * Source,Instruction * InsertBefore)756 Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) {
757 return createFree(Source, None, InsertBefore, nullptr);
758 }
CreateFree(Value * Source,ArrayRef<OperandBundleDef> Bundles,Instruction * InsertBefore)759 Instruction *CallInst::CreateFree(Value *Source,
760 ArrayRef<OperandBundleDef> Bundles,
761 Instruction *InsertBefore) {
762 return createFree(Source, Bundles, InsertBefore, nullptr);
763 }
764
765 /// CreateFree - Generate the IR for a call to the builtin free function.
766 /// Note: This function does not add the call to the basic block, that is the
767 /// responsibility of the caller.
CreateFree(Value * Source,BasicBlock * InsertAtEnd)768 Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) {
769 Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
770 assert(FreeCall && "CreateFree did not create a CallInst");
771 return FreeCall;
772 }
CreateFree(Value * Source,ArrayRef<OperandBundleDef> Bundles,BasicBlock * InsertAtEnd)773 Instruction *CallInst::CreateFree(Value *Source,
774 ArrayRef<OperandBundleDef> Bundles,
775 BasicBlock *InsertAtEnd) {
776 Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
777 assert(FreeCall && "CreateFree did not create a CallInst");
778 return FreeCall;
779 }
780
781 //===----------------------------------------------------------------------===//
782 // InvokeInst Implementation
783 //===----------------------------------------------------------------------===//
784
init(FunctionType * FTy,Value * Fn,BasicBlock * IfNormal,BasicBlock * IfException,ArrayRef<Value * > Args,ArrayRef<OperandBundleDef> Bundles,const Twine & NameStr)785 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
786 BasicBlock *IfException, ArrayRef<Value *> Args,
787 ArrayRef<OperandBundleDef> Bundles,
788 const Twine &NameStr) {
789 this->FTy = FTy;
790
791 assert((int)getNumOperands() ==
792 ComputeNumOperands(Args.size(), CountBundleInputs(Bundles)) &&
793 "NumOperands not set up?");
794 setNormalDest(IfNormal);
795 setUnwindDest(IfException);
796 setCalledOperand(Fn);
797
798 #ifndef NDEBUG
799 assert(((Args.size() == FTy->getNumParams()) ||
800 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
801 "Invoking a function with bad signature");
802
803 for (unsigned i = 0, e = Args.size(); i != e; i++)
804 assert((i >= FTy->getNumParams() ||
805 FTy->getParamType(i) == Args[i]->getType()) &&
806 "Invoking a function with a bad signature!");
807 #endif
808
809 llvm::copy(Args, op_begin());
810
811 auto It = populateBundleOperandInfos(Bundles, Args.size());
812 (void)It;
813 assert(It + 3 == op_end() && "Should add up!");
814
815 setName(NameStr);
816 }
817
InvokeInst(const InvokeInst & II)818 InvokeInst::InvokeInst(const InvokeInst &II)
819 : CallBase(II.Attrs, II.FTy, II.getType(), Instruction::Invoke,
820 OperandTraits<CallBase>::op_end(this) - II.getNumOperands(),
821 II.getNumOperands()) {
822 setCallingConv(II.getCallingConv());
823 std::copy(II.op_begin(), II.op_end(), op_begin());
824 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
825 bundle_op_info_begin());
826 SubclassOptionalData = II.SubclassOptionalData;
827 }
828
Create(InvokeInst * II,ArrayRef<OperandBundleDef> OpB,Instruction * InsertPt)829 InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB,
830 Instruction *InsertPt) {
831 std::vector<Value *> Args(II->arg_begin(), II->arg_end());
832
833 auto *NewII = InvokeInst::Create(
834 II->getFunctionType(), II->getCalledOperand(), II->getNormalDest(),
835 II->getUnwindDest(), Args, OpB, II->getName(), InsertPt);
836 NewII->setCallingConv(II->getCallingConv());
837 NewII->SubclassOptionalData = II->SubclassOptionalData;
838 NewII->setAttributes(II->getAttributes());
839 NewII->setDebugLoc(II->getDebugLoc());
840 return NewII;
841 }
842
CreateWithReplacedBundle(InvokeInst * II,OperandBundleDef OpB,Instruction * InsertPt)843 InvokeInst *InvokeInst::CreateWithReplacedBundle(InvokeInst *II,
844 OperandBundleDef OpB,
845 Instruction *InsertPt) {
846 SmallVector<OperandBundleDef, 2> OpDefs;
847 for (unsigned i = 0, e = II->getNumOperandBundles(); i < e; ++i) {
848 auto ChildOB = II->getOperandBundleAt(i);
849 if (ChildOB.getTagName() != OpB.getTag())
850 OpDefs.emplace_back(ChildOB);
851 }
852 OpDefs.emplace_back(OpB);
853 return InvokeInst::Create(II, OpDefs, InsertPt);
854 }
855
getLandingPadInst() const856 LandingPadInst *InvokeInst::getLandingPadInst() const {
857 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
858 }
859
860 //===----------------------------------------------------------------------===//
861 // CallBrInst Implementation
862 //===----------------------------------------------------------------------===//
863
init(FunctionType * FTy,Value * Fn,BasicBlock * Fallthrough,ArrayRef<BasicBlock * > IndirectDests,ArrayRef<Value * > Args,ArrayRef<OperandBundleDef> Bundles,const Twine & NameStr)864 void CallBrInst::init(FunctionType *FTy, Value *Fn, BasicBlock *Fallthrough,
865 ArrayRef<BasicBlock *> IndirectDests,
866 ArrayRef<Value *> Args,
867 ArrayRef<OperandBundleDef> Bundles,
868 const Twine &NameStr) {
869 this->FTy = FTy;
870
871 assert((int)getNumOperands() ==
872 ComputeNumOperands(Args.size(), IndirectDests.size(),
873 CountBundleInputs(Bundles)) &&
874 "NumOperands not set up?");
875 NumIndirectDests = IndirectDests.size();
876 setDefaultDest(Fallthrough);
877 for (unsigned i = 0; i != NumIndirectDests; ++i)
878 setIndirectDest(i, IndirectDests[i]);
879 setCalledOperand(Fn);
880
881 #ifndef NDEBUG
882 assert(((Args.size() == FTy->getNumParams()) ||
883 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
884 "Calling a function with bad signature");
885
886 for (unsigned i = 0, e = Args.size(); i != e; i++)
887 assert((i >= FTy->getNumParams() ||
888 FTy->getParamType(i) == Args[i]->getType()) &&
889 "Calling a function with a bad signature!");
890 #endif
891
892 std::copy(Args.begin(), Args.end(), op_begin());
893
894 auto It = populateBundleOperandInfos(Bundles, Args.size());
895 (void)It;
896 assert(It + 2 + IndirectDests.size() == op_end() && "Should add up!");
897
898 setName(NameStr);
899 }
900
updateArgBlockAddresses(unsigned i,BasicBlock * B)901 void CallBrInst::updateArgBlockAddresses(unsigned i, BasicBlock *B) {
902 assert(getNumIndirectDests() > i && "IndirectDest # out of range for callbr");
903 if (BasicBlock *OldBB = getIndirectDest(i)) {
904 BlockAddress *Old = BlockAddress::get(OldBB);
905 BlockAddress *New = BlockAddress::get(B);
906 for (unsigned ArgNo = 0, e = getNumArgOperands(); ArgNo != e; ++ArgNo)
907 if (dyn_cast<BlockAddress>(getArgOperand(ArgNo)) == Old)
908 setArgOperand(ArgNo, New);
909 }
910 }
911
CallBrInst(const CallBrInst & CBI)912 CallBrInst::CallBrInst(const CallBrInst &CBI)
913 : CallBase(CBI.Attrs, CBI.FTy, CBI.getType(), Instruction::CallBr,
914 OperandTraits<CallBase>::op_end(this) - CBI.getNumOperands(),
915 CBI.getNumOperands()) {
916 setCallingConv(CBI.getCallingConv());
917 std::copy(CBI.op_begin(), CBI.op_end(), op_begin());
918 std::copy(CBI.bundle_op_info_begin(), CBI.bundle_op_info_end(),
919 bundle_op_info_begin());
920 SubclassOptionalData = CBI.SubclassOptionalData;
921 NumIndirectDests = CBI.NumIndirectDests;
922 }
923
Create(CallBrInst * CBI,ArrayRef<OperandBundleDef> OpB,Instruction * InsertPt)924 CallBrInst *CallBrInst::Create(CallBrInst *CBI, ArrayRef<OperandBundleDef> OpB,
925 Instruction *InsertPt) {
926 std::vector<Value *> Args(CBI->arg_begin(), CBI->arg_end());
927
928 auto *NewCBI = CallBrInst::Create(
929 CBI->getFunctionType(), CBI->getCalledOperand(), CBI->getDefaultDest(),
930 CBI->getIndirectDests(), Args, OpB, CBI->getName(), InsertPt);
931 NewCBI->setCallingConv(CBI->getCallingConv());
932 NewCBI->SubclassOptionalData = CBI->SubclassOptionalData;
933 NewCBI->setAttributes(CBI->getAttributes());
934 NewCBI->setDebugLoc(CBI->getDebugLoc());
935 NewCBI->NumIndirectDests = CBI->NumIndirectDests;
936 return NewCBI;
937 }
938
939 //===----------------------------------------------------------------------===//
940 // ReturnInst Implementation
941 //===----------------------------------------------------------------------===//
942
ReturnInst(const ReturnInst & RI)943 ReturnInst::ReturnInst(const ReturnInst &RI)
944 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Ret,
945 OperandTraits<ReturnInst>::op_end(this) - RI.getNumOperands(),
946 RI.getNumOperands()) {
947 if (RI.getNumOperands())
948 Op<0>() = RI.Op<0>();
949 SubclassOptionalData = RI.SubclassOptionalData;
950 }
951
ReturnInst(LLVMContext & C,Value * retVal,Instruction * InsertBefore)952 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
953 : Instruction(Type::getVoidTy(C), Instruction::Ret,
954 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
955 InsertBefore) {
956 if (retVal)
957 Op<0>() = retVal;
958 }
959
ReturnInst(LLVMContext & C,Value * retVal,BasicBlock * InsertAtEnd)960 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
961 : Instruction(Type::getVoidTy(C), Instruction::Ret,
962 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
963 InsertAtEnd) {
964 if (retVal)
965 Op<0>() = retVal;
966 }
967
ReturnInst(LLVMContext & Context,BasicBlock * InsertAtEnd)968 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
969 : Instruction(Type::getVoidTy(Context), Instruction::Ret,
970 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {}
971
972 //===----------------------------------------------------------------------===//
973 // ResumeInst Implementation
974 //===----------------------------------------------------------------------===//
975
ResumeInst(const ResumeInst & RI)976 ResumeInst::ResumeInst(const ResumeInst &RI)
977 : Instruction(Type::getVoidTy(RI.getContext()), Instruction::Resume,
978 OperandTraits<ResumeInst>::op_begin(this), 1) {
979 Op<0>() = RI.Op<0>();
980 }
981
ResumeInst(Value * Exn,Instruction * InsertBefore)982 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
983 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
984 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
985 Op<0>() = Exn;
986 }
987
ResumeInst(Value * Exn,BasicBlock * InsertAtEnd)988 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
989 : Instruction(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
990 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
991 Op<0>() = Exn;
992 }
993
994 //===----------------------------------------------------------------------===//
995 // CleanupReturnInst Implementation
996 //===----------------------------------------------------------------------===//
997
CleanupReturnInst(const CleanupReturnInst & CRI)998 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
999 : Instruction(CRI.getType(), Instruction::CleanupRet,
1000 OperandTraits<CleanupReturnInst>::op_end(this) -
1001 CRI.getNumOperands(),
1002 CRI.getNumOperands()) {
1003 setSubclassData<Instruction::OpaqueField>(
1004 CRI.getSubclassData<Instruction::OpaqueField>());
1005 Op<0>() = CRI.Op<0>();
1006 if (CRI.hasUnwindDest())
1007 Op<1>() = CRI.Op<1>();
1008 }
1009
init(Value * CleanupPad,BasicBlock * UnwindBB)1010 void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
1011 if (UnwindBB)
1012 setSubclassData<UnwindDestField>(true);
1013
1014 Op<0>() = CleanupPad;
1015 if (UnwindBB)
1016 Op<1>() = UnwindBB;
1017 }
1018
CleanupReturnInst(Value * CleanupPad,BasicBlock * UnwindBB,unsigned Values,Instruction * InsertBefore)1019 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
1020 unsigned Values, Instruction *InsertBefore)
1021 : Instruction(Type::getVoidTy(CleanupPad->getContext()),
1022 Instruction::CleanupRet,
1023 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
1024 Values, InsertBefore) {
1025 init(CleanupPad, UnwindBB);
1026 }
1027
CleanupReturnInst(Value * CleanupPad,BasicBlock * UnwindBB,unsigned Values,BasicBlock * InsertAtEnd)1028 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
1029 unsigned Values, BasicBlock *InsertAtEnd)
1030 : Instruction(Type::getVoidTy(CleanupPad->getContext()),
1031 Instruction::CleanupRet,
1032 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
1033 Values, InsertAtEnd) {
1034 init(CleanupPad, UnwindBB);
1035 }
1036
1037 //===----------------------------------------------------------------------===//
1038 // CatchReturnInst Implementation
1039 //===----------------------------------------------------------------------===//
init(Value * CatchPad,BasicBlock * BB)1040 void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
1041 Op<0>() = CatchPad;
1042 Op<1>() = BB;
1043 }
1044
CatchReturnInst(const CatchReturnInst & CRI)1045 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
1046 : Instruction(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
1047 OperandTraits<CatchReturnInst>::op_begin(this), 2) {
1048 Op<0>() = CRI.Op<0>();
1049 Op<1>() = CRI.Op<1>();
1050 }
1051
CatchReturnInst(Value * CatchPad,BasicBlock * BB,Instruction * InsertBefore)1052 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
1053 Instruction *InsertBefore)
1054 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
1055 OperandTraits<CatchReturnInst>::op_begin(this), 2,
1056 InsertBefore) {
1057 init(CatchPad, BB);
1058 }
1059
CatchReturnInst(Value * CatchPad,BasicBlock * BB,BasicBlock * InsertAtEnd)1060 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
1061 BasicBlock *InsertAtEnd)
1062 : Instruction(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
1063 OperandTraits<CatchReturnInst>::op_begin(this), 2,
1064 InsertAtEnd) {
1065 init(CatchPad, BB);
1066 }
1067
1068 //===----------------------------------------------------------------------===//
1069 // CatchSwitchInst Implementation
1070 //===----------------------------------------------------------------------===//
1071
CatchSwitchInst(Value * ParentPad,BasicBlock * UnwindDest,unsigned NumReservedValues,const Twine & NameStr,Instruction * InsertBefore)1072 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
1073 unsigned NumReservedValues,
1074 const Twine &NameStr,
1075 Instruction *InsertBefore)
1076 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
1077 InsertBefore) {
1078 if (UnwindDest)
1079 ++NumReservedValues;
1080 init(ParentPad, UnwindDest, NumReservedValues + 1);
1081 setName(NameStr);
1082 }
1083
CatchSwitchInst(Value * ParentPad,BasicBlock * UnwindDest,unsigned NumReservedValues,const Twine & NameStr,BasicBlock * InsertAtEnd)1084 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
1085 unsigned NumReservedValues,
1086 const Twine &NameStr, BasicBlock *InsertAtEnd)
1087 : Instruction(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
1088 InsertAtEnd) {
1089 if (UnwindDest)
1090 ++NumReservedValues;
1091 init(ParentPad, UnwindDest, NumReservedValues + 1);
1092 setName(NameStr);
1093 }
1094
CatchSwitchInst(const CatchSwitchInst & CSI)1095 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
1096 : Instruction(CSI.getType(), Instruction::CatchSwitch, nullptr,
1097 CSI.getNumOperands()) {
1098 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
1099 setNumHungOffUseOperands(ReservedSpace);
1100 Use *OL = getOperandList();
1101 const Use *InOL = CSI.getOperandList();
1102 for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
1103 OL[I] = InOL[I];
1104 }
1105
init(Value * ParentPad,BasicBlock * UnwindDest,unsigned NumReservedValues)1106 void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
1107 unsigned NumReservedValues) {
1108 assert(ParentPad && NumReservedValues);
1109
1110 ReservedSpace = NumReservedValues;
1111 setNumHungOffUseOperands(UnwindDest ? 2 : 1);
1112 allocHungoffUses(ReservedSpace);
1113
1114 Op<0>() = ParentPad;
1115 if (UnwindDest) {
1116 setSubclassData<UnwindDestField>(true);
1117 setUnwindDest(UnwindDest);
1118 }
1119 }
1120
1121 /// growOperands - grow operands - This grows the operand list in response to a
1122 /// push_back style of operation. This grows the number of ops by 2 times.
growOperands(unsigned Size)1123 void CatchSwitchInst::growOperands(unsigned Size) {
1124 unsigned NumOperands = getNumOperands();
1125 assert(NumOperands >= 1);
1126 if (ReservedSpace >= NumOperands + Size)
1127 return;
1128 ReservedSpace = (NumOperands + Size / 2) * 2;
1129 growHungoffUses(ReservedSpace);
1130 }
1131
addHandler(BasicBlock * Handler)1132 void CatchSwitchInst::addHandler(BasicBlock *Handler) {
1133 unsigned OpNo = getNumOperands();
1134 growOperands(1);
1135 assert(OpNo < ReservedSpace && "Growing didn't work!");
1136 setNumHungOffUseOperands(getNumOperands() + 1);
1137 getOperandList()[OpNo] = Handler;
1138 }
1139
removeHandler(handler_iterator HI)1140 void CatchSwitchInst::removeHandler(handler_iterator HI) {
1141 // Move all subsequent handlers up one.
1142 Use *EndDst = op_end() - 1;
1143 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
1144 *CurDst = *(CurDst + 1);
1145 // Null out the last handler use.
1146 *EndDst = nullptr;
1147
1148 setNumHungOffUseOperands(getNumOperands() - 1);
1149 }
1150
1151 //===----------------------------------------------------------------------===//
1152 // FuncletPadInst Implementation
1153 //===----------------------------------------------------------------------===//
init(Value * ParentPad,ArrayRef<Value * > Args,const Twine & NameStr)1154 void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
1155 const Twine &NameStr) {
1156 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
1157 llvm::copy(Args, op_begin());
1158 setParentPad(ParentPad);
1159 setName(NameStr);
1160 }
1161
FuncletPadInst(const FuncletPadInst & FPI)1162 FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI)
1163 : Instruction(FPI.getType(), FPI.getOpcode(),
1164 OperandTraits<FuncletPadInst>::op_end(this) -
1165 FPI.getNumOperands(),
1166 FPI.getNumOperands()) {
1167 std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
1168 setParentPad(FPI.getParentPad());
1169 }
1170
FuncletPadInst(Instruction::FuncletPadOps Op,Value * ParentPad,ArrayRef<Value * > Args,unsigned Values,const Twine & NameStr,Instruction * InsertBefore)1171 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1172 ArrayRef<Value *> Args, unsigned Values,
1173 const Twine &NameStr, Instruction *InsertBefore)
1174 : Instruction(ParentPad->getType(), Op,
1175 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
1176 InsertBefore) {
1177 init(ParentPad, Args, NameStr);
1178 }
1179
FuncletPadInst(Instruction::FuncletPadOps Op,Value * ParentPad,ArrayRef<Value * > Args,unsigned Values,const Twine & NameStr,BasicBlock * InsertAtEnd)1180 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1181 ArrayRef<Value *> Args, unsigned Values,
1182 const Twine &NameStr, BasicBlock *InsertAtEnd)
1183 : Instruction(ParentPad->getType(), Op,
1184 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
1185 InsertAtEnd) {
1186 init(ParentPad, Args, NameStr);
1187 }
1188
1189 //===----------------------------------------------------------------------===//
1190 // UnreachableInst Implementation
1191 //===----------------------------------------------------------------------===//
1192
UnreachableInst(LLVMContext & Context,Instruction * InsertBefore)1193 UnreachableInst::UnreachableInst(LLVMContext &Context,
1194 Instruction *InsertBefore)
1195 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
1196 0, InsertBefore) {}
UnreachableInst(LLVMContext & Context,BasicBlock * InsertAtEnd)1197 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1198 : Instruction(Type::getVoidTy(Context), Instruction::Unreachable, nullptr,
1199 0, InsertAtEnd) {}
1200
1201 //===----------------------------------------------------------------------===//
1202 // BranchInst Implementation
1203 //===----------------------------------------------------------------------===//
1204
AssertOK()1205 void BranchInst::AssertOK() {
1206 if (isConditional())
1207 assert(getCondition()->getType()->isIntegerTy(1) &&
1208 "May only branch on boolean predicates!");
1209 }
1210
BranchInst(BasicBlock * IfTrue,Instruction * InsertBefore)1211 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
1212 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1213 OperandTraits<BranchInst>::op_end(this) - 1, 1,
1214 InsertBefore) {
1215 assert(IfTrue && "Branch destination may not be null!");
1216 Op<-1>() = IfTrue;
1217 }
1218
BranchInst(BasicBlock * IfTrue,BasicBlock * IfFalse,Value * Cond,Instruction * InsertBefore)1219 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1220 Instruction *InsertBefore)
1221 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1222 OperandTraits<BranchInst>::op_end(this) - 3, 3,
1223 InsertBefore) {
1224 Op<-1>() = IfTrue;
1225 Op<-2>() = IfFalse;
1226 Op<-3>() = Cond;
1227 #ifndef NDEBUG
1228 AssertOK();
1229 #endif
1230 }
1231
BranchInst(BasicBlock * IfTrue,BasicBlock * InsertAtEnd)1232 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
1233 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1234 OperandTraits<BranchInst>::op_end(this) - 1, 1, InsertAtEnd) {
1235 assert(IfTrue && "Branch destination may not be null!");
1236 Op<-1>() = IfTrue;
1237 }
1238
BranchInst(BasicBlock * IfTrue,BasicBlock * IfFalse,Value * Cond,BasicBlock * InsertAtEnd)1239 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1240 BasicBlock *InsertAtEnd)
1241 : Instruction(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1242 OperandTraits<BranchInst>::op_end(this) - 3, 3, InsertAtEnd) {
1243 Op<-1>() = IfTrue;
1244 Op<-2>() = IfFalse;
1245 Op<-3>() = Cond;
1246 #ifndef NDEBUG
1247 AssertOK();
1248 #endif
1249 }
1250
BranchInst(const BranchInst & BI)1251 BranchInst::BranchInst(const BranchInst &BI)
1252 : Instruction(Type::getVoidTy(BI.getContext()), Instruction::Br,
1253 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
1254 BI.getNumOperands()) {
1255 Op<-1>() = BI.Op<-1>();
1256 if (BI.getNumOperands() != 1) {
1257 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1258 Op<-3>() = BI.Op<-3>();
1259 Op<-2>() = BI.Op<-2>();
1260 }
1261 SubclassOptionalData = BI.SubclassOptionalData;
1262 }
1263
swapSuccessors()1264 void BranchInst::swapSuccessors() {
1265 assert(isConditional() &&
1266 "Cannot swap successors of an unconditional branch");
1267 Op<-1>().swap(Op<-2>());
1268
1269 // Update profile metadata if present and it matches our structural
1270 // expectations.
1271 swapProfMetadata();
1272 }
1273
1274 //===----------------------------------------------------------------------===//
1275 // AllocaInst Implementation
1276 //===----------------------------------------------------------------------===//
1277
getAISize(LLVMContext & Context,Value * Amt)1278 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1279 if (!Amt)
1280 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1281 else {
1282 assert(!isa<BasicBlock>(Amt) &&
1283 "Passed basic block into allocation size parameter! Use other ctor");
1284 assert(Amt->getType()->isIntegerTy() &&
1285 "Allocation array size is not an integer!");
1286 }
1287 return Amt;
1288 }
1289
computeAllocaDefaultAlign(Type * Ty,BasicBlock * BB)1290 static Align computeAllocaDefaultAlign(Type *Ty, BasicBlock *BB) {
1291 assert(BB && "Insertion BB cannot be null when alignment not provided!");
1292 assert(BB->getParent() &&
1293 "BB must be in a Function when alignment not provided!");
1294 const DataLayout &DL = BB->getModule()->getDataLayout();
1295 return DL.getPrefTypeAlign(Ty);
1296 }
1297
computeAllocaDefaultAlign(Type * Ty,Instruction * I)1298 static Align computeAllocaDefaultAlign(Type *Ty, Instruction *I) {
1299 assert(I && "Insertion position cannot be null when alignment not provided!");
1300 return computeAllocaDefaultAlign(Ty, I->getParent());
1301 }
1302
AllocaInst(Type * Ty,unsigned AddrSpace,const Twine & Name,Instruction * InsertBefore)1303 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1304 Instruction *InsertBefore)
1305 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1306
AllocaInst(Type * Ty,unsigned AddrSpace,const Twine & Name,BasicBlock * InsertAtEnd)1307 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1308 BasicBlock *InsertAtEnd)
1309 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
1310
AllocaInst(Type * Ty,unsigned AddrSpace,Value * ArraySize,const Twine & Name,Instruction * InsertBefore)1311 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1312 const Twine &Name, Instruction *InsertBefore)
1313 : AllocaInst(Ty, AddrSpace, ArraySize,
1314 computeAllocaDefaultAlign(Ty, InsertBefore), Name,
1315 InsertBefore) {}
1316
AllocaInst(Type * Ty,unsigned AddrSpace,Value * ArraySize,const Twine & Name,BasicBlock * InsertAtEnd)1317 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1318 const Twine &Name, BasicBlock *InsertAtEnd)
1319 : AllocaInst(Ty, AddrSpace, ArraySize,
1320 computeAllocaDefaultAlign(Ty, InsertAtEnd), Name,
1321 InsertAtEnd) {}
1322
AllocaInst(Type * Ty,unsigned AddrSpace,Value * ArraySize,Align Align,const Twine & Name,Instruction * InsertBefore)1323 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1324 Align Align, const Twine &Name,
1325 Instruction *InsertBefore)
1326 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1327 getAISize(Ty->getContext(), ArraySize), InsertBefore),
1328 AllocatedType(Ty) {
1329 setAlignment(Align);
1330 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1331 setName(Name);
1332 }
1333
AllocaInst(Type * Ty,unsigned AddrSpace,Value * ArraySize,Align Align,const Twine & Name,BasicBlock * InsertAtEnd)1334 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1335 Align Align, const Twine &Name, BasicBlock *InsertAtEnd)
1336 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1337 getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
1338 AllocatedType(Ty) {
1339 setAlignment(Align);
1340 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1341 setName(Name);
1342 }
1343
1344
isArrayAllocation() const1345 bool AllocaInst::isArrayAllocation() const {
1346 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1347 return !CI->isOne();
1348 return true;
1349 }
1350
1351 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1352 /// function and is a constant size. If so, the code generator will fold it
1353 /// into the prolog/epilog code, so it is basically free.
isStaticAlloca() const1354 bool AllocaInst::isStaticAlloca() const {
1355 // Must be constant size.
1356 if (!isa<ConstantInt>(getArraySize())) return false;
1357
1358 // Must be in the entry block.
1359 const BasicBlock *Parent = getParent();
1360 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1361 }
1362
1363 //===----------------------------------------------------------------------===//
1364 // LoadInst Implementation
1365 //===----------------------------------------------------------------------===//
1366
AssertOK()1367 void LoadInst::AssertOK() {
1368 assert(getOperand(0)->getType()->isPointerTy() &&
1369 "Ptr must have pointer type.");
1370 assert(!(isAtomic() && getAlignment() == 0) &&
1371 "Alignment required for atomic load");
1372 }
1373
computeLoadStoreDefaultAlign(Type * Ty,BasicBlock * BB)1374 static Align computeLoadStoreDefaultAlign(Type *Ty, BasicBlock *BB) {
1375 assert(BB && "Insertion BB cannot be null when alignment not provided!");
1376 assert(BB->getParent() &&
1377 "BB must be in a Function when alignment not provided!");
1378 const DataLayout &DL = BB->getModule()->getDataLayout();
1379 return DL.getABITypeAlign(Ty);
1380 }
1381
computeLoadStoreDefaultAlign(Type * Ty,Instruction * I)1382 static Align computeLoadStoreDefaultAlign(Type *Ty, Instruction *I) {
1383 assert(I && "Insertion position cannot be null when alignment not provided!");
1384 return computeLoadStoreDefaultAlign(Ty, I->getParent());
1385 }
1386
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,Instruction * InsertBef)1387 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1388 Instruction *InsertBef)
1389 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1390
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,BasicBlock * InsertAE)1391 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name,
1392 BasicBlock *InsertAE)
1393 : LoadInst(Ty, Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1394
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Instruction * InsertBef)1395 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1396 Instruction *InsertBef)
1397 : LoadInst(Ty, Ptr, Name, isVolatile,
1398 computeLoadStoreDefaultAlign(Ty, InsertBef), InsertBef) {}
1399
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,BasicBlock * InsertAE)1400 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1401 BasicBlock *InsertAE)
1402 : LoadInst(Ty, Ptr, Name, isVolatile,
1403 computeLoadStoreDefaultAlign(Ty, InsertAE), InsertAE) {}
1404
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Align Align,Instruction * InsertBef)1405 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1406 Align Align, Instruction *InsertBef)
1407 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1408 SyncScope::System, InsertBef) {}
1409
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Align Align,BasicBlock * InsertAE)1410 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1411 Align Align, BasicBlock *InsertAE)
1412 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1413 SyncScope::System, InsertAE) {}
1414
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Align Align,AtomicOrdering Order,SyncScope::ID SSID,Instruction * InsertBef)1415 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1416 Align Align, AtomicOrdering Order, SyncScope::ID SSID,
1417 Instruction *InsertBef)
1418 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1419 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1420 setVolatile(isVolatile);
1421 setAlignment(Align);
1422 setAtomic(Order, SSID);
1423 AssertOK();
1424 setName(Name);
1425 }
1426
LoadInst(Type * Ty,Value * Ptr,const Twine & Name,bool isVolatile,Align Align,AtomicOrdering Order,SyncScope::ID SSID,BasicBlock * InsertAE)1427 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1428 Align Align, AtomicOrdering Order, SyncScope::ID SSID,
1429 BasicBlock *InsertAE)
1430 : UnaryInstruction(Ty, Load, Ptr, InsertAE) {
1431 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1432 setVolatile(isVolatile);
1433 setAlignment(Align);
1434 setAtomic(Order, SSID);
1435 AssertOK();
1436 setName(Name);
1437 }
1438
1439 //===----------------------------------------------------------------------===//
1440 // StoreInst Implementation
1441 //===----------------------------------------------------------------------===//
1442
AssertOK()1443 void StoreInst::AssertOK() {
1444 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1445 assert(getOperand(1)->getType()->isPointerTy() &&
1446 "Ptr must have pointer type!");
1447 assert(getOperand(0)->getType() ==
1448 cast<PointerType>(getOperand(1)->getType())->getElementType()
1449 && "Ptr must be a pointer to Val type!");
1450 assert(!(isAtomic() && getAlignment() == 0) &&
1451 "Alignment required for atomic store");
1452 }
1453
StoreInst(Value * val,Value * addr,Instruction * InsertBefore)1454 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1455 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1456
StoreInst(Value * val,Value * addr,BasicBlock * InsertAtEnd)1457 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1458 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1459
StoreInst(Value * val,Value * addr,bool isVolatile,Instruction * InsertBefore)1460 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1461 Instruction *InsertBefore)
1462 : StoreInst(val, addr, isVolatile,
1463 computeLoadStoreDefaultAlign(val->getType(), InsertBefore),
1464 InsertBefore) {}
1465
StoreInst(Value * val,Value * addr,bool isVolatile,BasicBlock * InsertAtEnd)1466 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1467 BasicBlock *InsertAtEnd)
1468 : StoreInst(val, addr, isVolatile,
1469 computeLoadStoreDefaultAlign(val->getType(), InsertAtEnd),
1470 InsertAtEnd) {}
1471
StoreInst(Value * val,Value * addr,bool isVolatile,Align Align,Instruction * InsertBefore)1472 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
1473 Instruction *InsertBefore)
1474 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1475 SyncScope::System, InsertBefore) {}
1476
StoreInst(Value * val,Value * addr,bool isVolatile,Align Align,BasicBlock * InsertAtEnd)1477 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
1478 BasicBlock *InsertAtEnd)
1479 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1480 SyncScope::System, InsertAtEnd) {}
1481
StoreInst(Value * val,Value * addr,bool isVolatile,Align Align,AtomicOrdering Order,SyncScope::ID SSID,Instruction * InsertBefore)1482 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
1483 AtomicOrdering Order, SyncScope::ID SSID,
1484 Instruction *InsertBefore)
1485 : Instruction(Type::getVoidTy(val->getContext()), Store,
1486 OperandTraits<StoreInst>::op_begin(this),
1487 OperandTraits<StoreInst>::operands(this), InsertBefore) {
1488 Op<0>() = val;
1489 Op<1>() = addr;
1490 setVolatile(isVolatile);
1491 setAlignment(Align);
1492 setAtomic(Order, SSID);
1493 AssertOK();
1494 }
1495
StoreInst(Value * val,Value * addr,bool isVolatile,Align Align,AtomicOrdering Order,SyncScope::ID SSID,BasicBlock * InsertAtEnd)1496 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, Align Align,
1497 AtomicOrdering Order, SyncScope::ID SSID,
1498 BasicBlock *InsertAtEnd)
1499 : Instruction(Type::getVoidTy(val->getContext()), Store,
1500 OperandTraits<StoreInst>::op_begin(this),
1501 OperandTraits<StoreInst>::operands(this), InsertAtEnd) {
1502 Op<0>() = val;
1503 Op<1>() = addr;
1504 setVolatile(isVolatile);
1505 setAlignment(Align);
1506 setAtomic(Order, SSID);
1507 AssertOK();
1508 }
1509
1510
1511 //===----------------------------------------------------------------------===//
1512 // AtomicCmpXchgInst Implementation
1513 //===----------------------------------------------------------------------===//
1514
Init(Value * Ptr,Value * Cmp,Value * NewVal,Align Alignment,AtomicOrdering SuccessOrdering,AtomicOrdering FailureOrdering,SyncScope::ID SSID)1515 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1516 Align Alignment, AtomicOrdering SuccessOrdering,
1517 AtomicOrdering FailureOrdering,
1518 SyncScope::ID SSID) {
1519 Op<0>() = Ptr;
1520 Op<1>() = Cmp;
1521 Op<2>() = NewVal;
1522 setSuccessOrdering(SuccessOrdering);
1523 setFailureOrdering(FailureOrdering);
1524 setSyncScopeID(SSID);
1525 setAlignment(Alignment);
1526
1527 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1528 "All operands must be non-null!");
1529 assert(getOperand(0)->getType()->isPointerTy() &&
1530 "Ptr must have pointer type!");
1531 assert(getOperand(1)->getType() ==
1532 cast<PointerType>(getOperand(0)->getType())->getElementType()
1533 && "Ptr must be a pointer to Cmp type!");
1534 assert(getOperand(2)->getType() ==
1535 cast<PointerType>(getOperand(0)->getType())->getElementType()
1536 && "Ptr must be a pointer to NewVal type!");
1537 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
1538 "AtomicCmpXchg instructions must be atomic!");
1539 assert(FailureOrdering != AtomicOrdering::NotAtomic &&
1540 "AtomicCmpXchg instructions must be atomic!");
1541 assert(!isStrongerThan(FailureOrdering, SuccessOrdering) &&
1542 "AtomicCmpXchg failure argument shall be no stronger than the success "
1543 "argument");
1544 assert(FailureOrdering != AtomicOrdering::Release &&
1545 FailureOrdering != AtomicOrdering::AcquireRelease &&
1546 "AtomicCmpXchg failure ordering cannot include release semantics");
1547 }
1548
AtomicCmpXchgInst(Value * Ptr,Value * Cmp,Value * NewVal,Align Alignment,AtomicOrdering SuccessOrdering,AtomicOrdering FailureOrdering,SyncScope::ID SSID,Instruction * InsertBefore)1549 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1550 Align Alignment,
1551 AtomicOrdering SuccessOrdering,
1552 AtomicOrdering FailureOrdering,
1553 SyncScope::ID SSID,
1554 Instruction *InsertBefore)
1555 : Instruction(
1556 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1557 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1558 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1559 Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
1560 }
1561
AtomicCmpXchgInst(Value * Ptr,Value * Cmp,Value * NewVal,Align Alignment,AtomicOrdering SuccessOrdering,AtomicOrdering FailureOrdering,SyncScope::ID SSID,BasicBlock * InsertAtEnd)1562 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1563 Align Alignment,
1564 AtomicOrdering SuccessOrdering,
1565 AtomicOrdering FailureOrdering,
1566 SyncScope::ID SSID,
1567 BasicBlock *InsertAtEnd)
1568 : Instruction(
1569 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext())),
1570 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1571 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1572 Init(Ptr, Cmp, NewVal, Alignment, SuccessOrdering, FailureOrdering, SSID);
1573 }
1574
1575 //===----------------------------------------------------------------------===//
1576 // AtomicRMWInst Implementation
1577 //===----------------------------------------------------------------------===//
1578
Init(BinOp Operation,Value * Ptr,Value * Val,Align Alignment,AtomicOrdering Ordering,SyncScope::ID SSID)1579 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1580 Align Alignment, AtomicOrdering Ordering,
1581 SyncScope::ID SSID) {
1582 Op<0>() = Ptr;
1583 Op<1>() = Val;
1584 setOperation(Operation);
1585 setOrdering(Ordering);
1586 setSyncScopeID(SSID);
1587 setAlignment(Alignment);
1588
1589 assert(getOperand(0) && getOperand(1) &&
1590 "All operands must be non-null!");
1591 assert(getOperand(0)->getType()->isPointerTy() &&
1592 "Ptr must have pointer type!");
1593 assert(getOperand(1)->getType() ==
1594 cast<PointerType>(getOperand(0)->getType())->getElementType()
1595 && "Ptr must be a pointer to Val type!");
1596 assert(Ordering != AtomicOrdering::NotAtomic &&
1597 "AtomicRMW instructions must be atomic!");
1598 }
1599
AtomicRMWInst(BinOp Operation,Value * Ptr,Value * Val,Align Alignment,AtomicOrdering Ordering,SyncScope::ID SSID,Instruction * InsertBefore)1600 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1601 Align Alignment, AtomicOrdering Ordering,
1602 SyncScope::ID SSID, Instruction *InsertBefore)
1603 : Instruction(Val->getType(), AtomicRMW,
1604 OperandTraits<AtomicRMWInst>::op_begin(this),
1605 OperandTraits<AtomicRMWInst>::operands(this), InsertBefore) {
1606 Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
1607 }
1608
AtomicRMWInst(BinOp Operation,Value * Ptr,Value * Val,Align Alignment,AtomicOrdering Ordering,SyncScope::ID SSID,BasicBlock * InsertAtEnd)1609 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1610 Align Alignment, AtomicOrdering Ordering,
1611 SyncScope::ID SSID, BasicBlock *InsertAtEnd)
1612 : Instruction(Val->getType(), AtomicRMW,
1613 OperandTraits<AtomicRMWInst>::op_begin(this),
1614 OperandTraits<AtomicRMWInst>::operands(this), InsertAtEnd) {
1615 Init(Operation, Ptr, Val, Alignment, Ordering, SSID);
1616 }
1617
getOperationName(BinOp Op)1618 StringRef AtomicRMWInst::getOperationName(BinOp Op) {
1619 switch (Op) {
1620 case AtomicRMWInst::Xchg:
1621 return "xchg";
1622 case AtomicRMWInst::Add:
1623 return "add";
1624 case AtomicRMWInst::Sub:
1625 return "sub";
1626 case AtomicRMWInst::And:
1627 return "and";
1628 case AtomicRMWInst::Nand:
1629 return "nand";
1630 case AtomicRMWInst::Or:
1631 return "or";
1632 case AtomicRMWInst::Xor:
1633 return "xor";
1634 case AtomicRMWInst::Max:
1635 return "max";
1636 case AtomicRMWInst::Min:
1637 return "min";
1638 case AtomicRMWInst::UMax:
1639 return "umax";
1640 case AtomicRMWInst::UMin:
1641 return "umin";
1642 case AtomicRMWInst::FAdd:
1643 return "fadd";
1644 case AtomicRMWInst::FSub:
1645 return "fsub";
1646 case AtomicRMWInst::BAD_BINOP:
1647 return "<invalid operation>";
1648 }
1649
1650 llvm_unreachable("invalid atomicrmw operation");
1651 }
1652
1653 //===----------------------------------------------------------------------===//
1654 // FenceInst Implementation
1655 //===----------------------------------------------------------------------===//
1656
FenceInst(LLVMContext & C,AtomicOrdering Ordering,SyncScope::ID SSID,Instruction * InsertBefore)1657 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1658 SyncScope::ID SSID,
1659 Instruction *InsertBefore)
1660 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1661 setOrdering(Ordering);
1662 setSyncScopeID(SSID);
1663 }
1664
FenceInst(LLVMContext & C,AtomicOrdering Ordering,SyncScope::ID SSID,BasicBlock * InsertAtEnd)1665 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1666 SyncScope::ID SSID,
1667 BasicBlock *InsertAtEnd)
1668 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1669 setOrdering(Ordering);
1670 setSyncScopeID(SSID);
1671 }
1672
1673 //===----------------------------------------------------------------------===//
1674 // GetElementPtrInst Implementation
1675 //===----------------------------------------------------------------------===//
1676
init(Value * Ptr,ArrayRef<Value * > IdxList,const Twine & Name)1677 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1678 const Twine &Name) {
1679 assert(getNumOperands() == 1 + IdxList.size() &&
1680 "NumOperands not initialized?");
1681 Op<0>() = Ptr;
1682 llvm::copy(IdxList, op_begin() + 1);
1683 setName(Name);
1684 }
1685
GetElementPtrInst(const GetElementPtrInst & GEPI)1686 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1687 : Instruction(GEPI.getType(), GetElementPtr,
1688 OperandTraits<GetElementPtrInst>::op_end(this) -
1689 GEPI.getNumOperands(),
1690 GEPI.getNumOperands()),
1691 SourceElementType(GEPI.SourceElementType),
1692 ResultElementType(GEPI.ResultElementType) {
1693 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1694 SubclassOptionalData = GEPI.SubclassOptionalData;
1695 }
1696
getTypeAtIndex(Type * Ty,Value * Idx)1697 Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, Value *Idx) {
1698 if (auto *Struct = dyn_cast<StructType>(Ty)) {
1699 if (!Struct->indexValid(Idx))
1700 return nullptr;
1701 return Struct->getTypeAtIndex(Idx);
1702 }
1703 if (!Idx->getType()->isIntOrIntVectorTy())
1704 return nullptr;
1705 if (auto *Array = dyn_cast<ArrayType>(Ty))
1706 return Array->getElementType();
1707 if (auto *Vector = dyn_cast<VectorType>(Ty))
1708 return Vector->getElementType();
1709 return nullptr;
1710 }
1711
getTypeAtIndex(Type * Ty,uint64_t Idx)1712 Type *GetElementPtrInst::getTypeAtIndex(Type *Ty, uint64_t Idx) {
1713 if (auto *Struct = dyn_cast<StructType>(Ty)) {
1714 if (Idx >= Struct->getNumElements())
1715 return nullptr;
1716 return Struct->getElementType(Idx);
1717 }
1718 if (auto *Array = dyn_cast<ArrayType>(Ty))
1719 return Array->getElementType();
1720 if (auto *Vector = dyn_cast<VectorType>(Ty))
1721 return Vector->getElementType();
1722 return nullptr;
1723 }
1724
1725 template <typename IndexTy>
getIndexedTypeInternal(Type * Ty,ArrayRef<IndexTy> IdxList)1726 static Type *getIndexedTypeInternal(Type *Ty, ArrayRef<IndexTy> IdxList) {
1727 if (IdxList.empty())
1728 return Ty;
1729 for (IndexTy V : IdxList.slice(1)) {
1730 Ty = GetElementPtrInst::getTypeAtIndex(Ty, V);
1731 if (!Ty)
1732 return Ty;
1733 }
1734 return Ty;
1735 }
1736
getIndexedType(Type * Ty,ArrayRef<Value * > IdxList)1737 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1738 return getIndexedTypeInternal(Ty, IdxList);
1739 }
1740
getIndexedType(Type * Ty,ArrayRef<Constant * > IdxList)1741 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1742 ArrayRef<Constant *> IdxList) {
1743 return getIndexedTypeInternal(Ty, IdxList);
1744 }
1745
getIndexedType(Type * Ty,ArrayRef<uint64_t> IdxList)1746 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1747 return getIndexedTypeInternal(Ty, IdxList);
1748 }
1749
1750 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1751 /// zeros. If so, the result pointer and the first operand have the same
1752 /// value, just potentially different types.
hasAllZeroIndices() const1753 bool GetElementPtrInst::hasAllZeroIndices() const {
1754 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1755 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1756 if (!CI->isZero()) return false;
1757 } else {
1758 return false;
1759 }
1760 }
1761 return true;
1762 }
1763
1764 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1765 /// constant integers. If so, the result pointer and the first operand have
1766 /// a constant offset between them.
hasAllConstantIndices() const1767 bool GetElementPtrInst::hasAllConstantIndices() const {
1768 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1769 if (!isa<ConstantInt>(getOperand(i)))
1770 return false;
1771 }
1772 return true;
1773 }
1774
setIsInBounds(bool B)1775 void GetElementPtrInst::setIsInBounds(bool B) {
1776 cast<GEPOperator>(this)->setIsInBounds(B);
1777 }
1778
isInBounds() const1779 bool GetElementPtrInst::isInBounds() const {
1780 return cast<GEPOperator>(this)->isInBounds();
1781 }
1782
accumulateConstantOffset(const DataLayout & DL,APInt & Offset) const1783 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1784 APInt &Offset) const {
1785 // Delegate to the generic GEPOperator implementation.
1786 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1787 }
1788
1789 //===----------------------------------------------------------------------===//
1790 // ExtractElementInst Implementation
1791 //===----------------------------------------------------------------------===//
1792
ExtractElementInst(Value * Val,Value * Index,const Twine & Name,Instruction * InsertBef)1793 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1794 const Twine &Name,
1795 Instruction *InsertBef)
1796 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1797 ExtractElement,
1798 OperandTraits<ExtractElementInst>::op_begin(this),
1799 2, InsertBef) {
1800 assert(isValidOperands(Val, Index) &&
1801 "Invalid extractelement instruction operands!");
1802 Op<0>() = Val;
1803 Op<1>() = Index;
1804 setName(Name);
1805 }
1806
ExtractElementInst(Value * Val,Value * Index,const Twine & Name,BasicBlock * InsertAE)1807 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1808 const Twine &Name,
1809 BasicBlock *InsertAE)
1810 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1811 ExtractElement,
1812 OperandTraits<ExtractElementInst>::op_begin(this),
1813 2, InsertAE) {
1814 assert(isValidOperands(Val, Index) &&
1815 "Invalid extractelement instruction operands!");
1816
1817 Op<0>() = Val;
1818 Op<1>() = Index;
1819 setName(Name);
1820 }
1821
isValidOperands(const Value * Val,const Value * Index)1822 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1823 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1824 return false;
1825 return true;
1826 }
1827
1828 //===----------------------------------------------------------------------===//
1829 // InsertElementInst Implementation
1830 //===----------------------------------------------------------------------===//
1831
InsertElementInst(Value * Vec,Value * Elt,Value * Index,const Twine & Name,Instruction * InsertBef)1832 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1833 const Twine &Name,
1834 Instruction *InsertBef)
1835 : Instruction(Vec->getType(), InsertElement,
1836 OperandTraits<InsertElementInst>::op_begin(this),
1837 3, InsertBef) {
1838 assert(isValidOperands(Vec, Elt, Index) &&
1839 "Invalid insertelement instruction operands!");
1840 Op<0>() = Vec;
1841 Op<1>() = Elt;
1842 Op<2>() = Index;
1843 setName(Name);
1844 }
1845
InsertElementInst(Value * Vec,Value * Elt,Value * Index,const Twine & Name,BasicBlock * InsertAE)1846 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1847 const Twine &Name,
1848 BasicBlock *InsertAE)
1849 : Instruction(Vec->getType(), InsertElement,
1850 OperandTraits<InsertElementInst>::op_begin(this),
1851 3, InsertAE) {
1852 assert(isValidOperands(Vec, Elt, Index) &&
1853 "Invalid insertelement instruction operands!");
1854
1855 Op<0>() = Vec;
1856 Op<1>() = Elt;
1857 Op<2>() = Index;
1858 setName(Name);
1859 }
1860
isValidOperands(const Value * Vec,const Value * Elt,const Value * Index)1861 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1862 const Value *Index) {
1863 if (!Vec->getType()->isVectorTy())
1864 return false; // First operand of insertelement must be vector type.
1865
1866 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1867 return false;// Second operand of insertelement must be vector element type.
1868
1869 if (!Index->getType()->isIntegerTy())
1870 return false; // Third operand of insertelement must be i32.
1871 return true;
1872 }
1873
1874 //===----------------------------------------------------------------------===//
1875 // ShuffleVectorInst Implementation
1876 //===----------------------------------------------------------------------===//
1877
ShuffleVectorInst(Value * V1,Value * V2,Value * Mask,const Twine & Name,Instruction * InsertBefore)1878 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1879 const Twine &Name,
1880 Instruction *InsertBefore)
1881 : Instruction(
1882 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1883 cast<VectorType>(Mask->getType())->getElementCount()),
1884 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1885 OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
1886 assert(isValidOperands(V1, V2, Mask) &&
1887 "Invalid shuffle vector instruction operands!");
1888
1889 Op<0>() = V1;
1890 Op<1>() = V2;
1891 SmallVector<int, 16> MaskArr;
1892 getShuffleMask(cast<Constant>(Mask), MaskArr);
1893 setShuffleMask(MaskArr);
1894 setName(Name);
1895 }
1896
ShuffleVectorInst(Value * V1,Value * V2,Value * Mask,const Twine & Name,BasicBlock * InsertAtEnd)1897 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1898 const Twine &Name, BasicBlock *InsertAtEnd)
1899 : Instruction(
1900 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1901 cast<VectorType>(Mask->getType())->getElementCount()),
1902 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1903 OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
1904 assert(isValidOperands(V1, V2, Mask) &&
1905 "Invalid shuffle vector instruction operands!");
1906
1907 Op<0>() = V1;
1908 Op<1>() = V2;
1909 SmallVector<int, 16> MaskArr;
1910 getShuffleMask(cast<Constant>(Mask), MaskArr);
1911 setShuffleMask(MaskArr);
1912 setName(Name);
1913 }
1914
ShuffleVectorInst(Value * V1,Value * V2,ArrayRef<int> Mask,const Twine & Name,Instruction * InsertBefore)1915 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
1916 const Twine &Name,
1917 Instruction *InsertBefore)
1918 : Instruction(
1919 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1920 Mask.size(), isa<ScalableVectorType>(V1->getType())),
1921 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1922 OperandTraits<ShuffleVectorInst>::operands(this), InsertBefore) {
1923 assert(isValidOperands(V1, V2, Mask) &&
1924 "Invalid shuffle vector instruction operands!");
1925 Op<0>() = V1;
1926 Op<1>() = V2;
1927 setShuffleMask(Mask);
1928 setName(Name);
1929 }
1930
ShuffleVectorInst(Value * V1,Value * V2,ArrayRef<int> Mask,const Twine & Name,BasicBlock * InsertAtEnd)1931 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, ArrayRef<int> Mask,
1932 const Twine &Name, BasicBlock *InsertAtEnd)
1933 : Instruction(
1934 VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1935 Mask.size(), isa<ScalableVectorType>(V1->getType())),
1936 ShuffleVector, OperandTraits<ShuffleVectorInst>::op_begin(this),
1937 OperandTraits<ShuffleVectorInst>::operands(this), InsertAtEnd) {
1938 assert(isValidOperands(V1, V2, Mask) &&
1939 "Invalid shuffle vector instruction operands!");
1940
1941 Op<0>() = V1;
1942 Op<1>() = V2;
1943 setShuffleMask(Mask);
1944 setName(Name);
1945 }
1946
commute()1947 void ShuffleVectorInst::commute() {
1948 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
1949 int NumMaskElts = ShuffleMask.size();
1950 SmallVector<int, 16> NewMask(NumMaskElts);
1951 for (int i = 0; i != NumMaskElts; ++i) {
1952 int MaskElt = getMaskValue(i);
1953 if (MaskElt == UndefMaskElem) {
1954 NewMask[i] = UndefMaskElem;
1955 continue;
1956 }
1957 assert(MaskElt >= 0 && MaskElt < 2 * NumOpElts && "Out-of-range mask");
1958 MaskElt = (MaskElt < NumOpElts) ? MaskElt + NumOpElts : MaskElt - NumOpElts;
1959 NewMask[i] = MaskElt;
1960 }
1961 setShuffleMask(NewMask);
1962 Op<0>().swap(Op<1>());
1963 }
1964
isValidOperands(const Value * V1,const Value * V2,ArrayRef<int> Mask)1965 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1966 ArrayRef<int> Mask) {
1967 // V1 and V2 must be vectors of the same type.
1968 if (!isa<VectorType>(V1->getType()) || V1->getType() != V2->getType())
1969 return false;
1970
1971 // Make sure the mask elements make sense.
1972 int V1Size =
1973 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
1974 for (int Elem : Mask)
1975 if (Elem != UndefMaskElem && Elem >= V1Size * 2)
1976 return false;
1977
1978 if (isa<ScalableVectorType>(V1->getType()))
1979 if ((Mask[0] != 0 && Mask[0] != UndefMaskElem) || !is_splat(Mask))
1980 return false;
1981
1982 return true;
1983 }
1984
isValidOperands(const Value * V1,const Value * V2,const Value * Mask)1985 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1986 const Value *Mask) {
1987 // V1 and V2 must be vectors of the same type.
1988 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1989 return false;
1990
1991 // Mask must be vector of i32, and must be the same kind of vector as the
1992 // input vectors
1993 auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
1994 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32) ||
1995 isa<ScalableVectorType>(MaskTy) != isa<ScalableVectorType>(V1->getType()))
1996 return false;
1997
1998 // Check to see if Mask is valid.
1999 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
2000 return true;
2001
2002 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
2003 unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
2004 for (Value *Op : MV->operands()) {
2005 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
2006 if (CI->uge(V1Size*2))
2007 return false;
2008 } else if (!isa<UndefValue>(Op)) {
2009 return false;
2010 }
2011 }
2012 return true;
2013 }
2014
2015 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
2016 unsigned V1Size = cast<FixedVectorType>(V1->getType())->getNumElements();
2017 for (unsigned i = 0, e = cast<FixedVectorType>(MaskTy)->getNumElements();
2018 i != e; ++i)
2019 if (CDS->getElementAsInteger(i) >= V1Size*2)
2020 return false;
2021 return true;
2022 }
2023
2024 return false;
2025 }
2026
getShuffleMask(const Constant * Mask,SmallVectorImpl<int> & Result)2027 void ShuffleVectorInst::getShuffleMask(const Constant *Mask,
2028 SmallVectorImpl<int> &Result) {
2029 ElementCount EC = cast<VectorType>(Mask->getType())->getElementCount();
2030
2031 if (isa<ConstantAggregateZero>(Mask)) {
2032 Result.resize(EC.getKnownMinValue(), 0);
2033 return;
2034 }
2035
2036 Result.reserve(EC.getKnownMinValue());
2037
2038 if (EC.isScalable()) {
2039 assert((isa<ConstantAggregateZero>(Mask) || isa<UndefValue>(Mask)) &&
2040 "Scalable vector shuffle mask must be undef or zeroinitializer");
2041 int MaskVal = isa<UndefValue>(Mask) ? -1 : 0;
2042 for (unsigned I = 0; I < EC.getKnownMinValue(); ++I)
2043 Result.emplace_back(MaskVal);
2044 return;
2045 }
2046
2047 unsigned NumElts = EC.getKnownMinValue();
2048
2049 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
2050 for (unsigned i = 0; i != NumElts; ++i)
2051 Result.push_back(CDS->getElementAsInteger(i));
2052 return;
2053 }
2054 for (unsigned i = 0; i != NumElts; ++i) {
2055 Constant *C = Mask->getAggregateElement(i);
2056 Result.push_back(isa<UndefValue>(C) ? -1 :
2057 cast<ConstantInt>(C)->getZExtValue());
2058 }
2059 }
2060
setShuffleMask(ArrayRef<int> Mask)2061 void ShuffleVectorInst::setShuffleMask(ArrayRef<int> Mask) {
2062 ShuffleMask.assign(Mask.begin(), Mask.end());
2063 ShuffleMaskForBitcode = convertShuffleMaskForBitcode(Mask, getType());
2064 }
convertShuffleMaskForBitcode(ArrayRef<int> Mask,Type * ResultTy)2065 Constant *ShuffleVectorInst::convertShuffleMaskForBitcode(ArrayRef<int> Mask,
2066 Type *ResultTy) {
2067 Type *Int32Ty = Type::getInt32Ty(ResultTy->getContext());
2068 if (isa<ScalableVectorType>(ResultTy)) {
2069 assert(is_splat(Mask) && "Unexpected shuffle");
2070 Type *VecTy = VectorType::get(Int32Ty, Mask.size(), true);
2071 if (Mask[0] == 0)
2072 return Constant::getNullValue(VecTy);
2073 return UndefValue::get(VecTy);
2074 }
2075 SmallVector<Constant *, 16> MaskConst;
2076 for (int Elem : Mask) {
2077 if (Elem == UndefMaskElem)
2078 MaskConst.push_back(UndefValue::get(Int32Ty));
2079 else
2080 MaskConst.push_back(ConstantInt::get(Int32Ty, Elem));
2081 }
2082 return ConstantVector::get(MaskConst);
2083 }
2084
isSingleSourceMaskImpl(ArrayRef<int> Mask,int NumOpElts)2085 static bool isSingleSourceMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
2086 assert(!Mask.empty() && "Shuffle mask must contain elements");
2087 bool UsesLHS = false;
2088 bool UsesRHS = false;
2089 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
2090 if (Mask[i] == -1)
2091 continue;
2092 assert(Mask[i] >= 0 && Mask[i] < (NumOpElts * 2) &&
2093 "Out-of-bounds shuffle mask element");
2094 UsesLHS |= (Mask[i] < NumOpElts);
2095 UsesRHS |= (Mask[i] >= NumOpElts);
2096 if (UsesLHS && UsesRHS)
2097 return false;
2098 }
2099 // Allow for degenerate case: completely undef mask means neither source is used.
2100 return UsesLHS || UsesRHS;
2101 }
2102
isSingleSourceMask(ArrayRef<int> Mask)2103 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef<int> Mask) {
2104 // We don't have vector operand size information, so assume operands are the
2105 // same size as the mask.
2106 return isSingleSourceMaskImpl(Mask, Mask.size());
2107 }
2108
isIdentityMaskImpl(ArrayRef<int> Mask,int NumOpElts)2109 static bool isIdentityMaskImpl(ArrayRef<int> Mask, int NumOpElts) {
2110 if (!isSingleSourceMaskImpl(Mask, NumOpElts))
2111 return false;
2112 for (int i = 0, NumMaskElts = Mask.size(); i < NumMaskElts; ++i) {
2113 if (Mask[i] == -1)
2114 continue;
2115 if (Mask[i] != i && Mask[i] != (NumOpElts + i))
2116 return false;
2117 }
2118 return true;
2119 }
2120
isIdentityMask(ArrayRef<int> Mask)2121 bool ShuffleVectorInst::isIdentityMask(ArrayRef<int> Mask) {
2122 // We don't have vector operand size information, so assume operands are the
2123 // same size as the mask.
2124 return isIdentityMaskImpl(Mask, Mask.size());
2125 }
2126
isReverseMask(ArrayRef<int> Mask)2127 bool ShuffleVectorInst::isReverseMask(ArrayRef<int> Mask) {
2128 if (!isSingleSourceMask(Mask))
2129 return false;
2130 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
2131 if (Mask[i] == -1)
2132 continue;
2133 if (Mask[i] != (NumElts - 1 - i) && Mask[i] != (NumElts + NumElts - 1 - i))
2134 return false;
2135 }
2136 return true;
2137 }
2138
isZeroEltSplatMask(ArrayRef<int> Mask)2139 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef<int> Mask) {
2140 if (!isSingleSourceMask(Mask))
2141 return false;
2142 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
2143 if (Mask[i] == -1)
2144 continue;
2145 if (Mask[i] != 0 && Mask[i] != NumElts)
2146 return false;
2147 }
2148 return true;
2149 }
2150
isSelectMask(ArrayRef<int> Mask)2151 bool ShuffleVectorInst::isSelectMask(ArrayRef<int> Mask) {
2152 // Select is differentiated from identity. It requires using both sources.
2153 if (isSingleSourceMask(Mask))
2154 return false;
2155 for (int i = 0, NumElts = Mask.size(); i < NumElts; ++i) {
2156 if (Mask[i] == -1)
2157 continue;
2158 if (Mask[i] != i && Mask[i] != (NumElts + i))
2159 return false;
2160 }
2161 return true;
2162 }
2163
isTransposeMask(ArrayRef<int> Mask)2164 bool ShuffleVectorInst::isTransposeMask(ArrayRef<int> Mask) {
2165 // Example masks that will return true:
2166 // v1 = <a, b, c, d>
2167 // v2 = <e, f, g, h>
2168 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
2169 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
2170
2171 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2172 int NumElts = Mask.size();
2173 if (NumElts < 2 || !isPowerOf2_32(NumElts))
2174 return false;
2175
2176 // 2. The first element of the mask must be either a 0 or a 1.
2177 if (Mask[0] != 0 && Mask[0] != 1)
2178 return false;
2179
2180 // 3. The difference between the first 2 elements must be equal to the
2181 // number of elements in the mask.
2182 if ((Mask[1] - Mask[0]) != NumElts)
2183 return false;
2184
2185 // 4. The difference between consecutive even-numbered and odd-numbered
2186 // elements must be equal to 2.
2187 for (int i = 2; i < NumElts; ++i) {
2188 int MaskEltVal = Mask[i];
2189 if (MaskEltVal == -1)
2190 return false;
2191 int MaskEltPrevVal = Mask[i - 2];
2192 if (MaskEltVal - MaskEltPrevVal != 2)
2193 return false;
2194 }
2195 return true;
2196 }
2197
isExtractSubvectorMask(ArrayRef<int> Mask,int NumSrcElts,int & Index)2198 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef<int> Mask,
2199 int NumSrcElts, int &Index) {
2200 // Must extract from a single source.
2201 if (!isSingleSourceMaskImpl(Mask, NumSrcElts))
2202 return false;
2203
2204 // Must be smaller (else this is an Identity shuffle).
2205 if (NumSrcElts <= (int)Mask.size())
2206 return false;
2207
2208 // Find start of extraction, accounting that we may start with an UNDEF.
2209 int SubIndex = -1;
2210 for (int i = 0, e = Mask.size(); i != e; ++i) {
2211 int M = Mask[i];
2212 if (M < 0)
2213 continue;
2214 int Offset = (M % NumSrcElts) - i;
2215 if (0 <= SubIndex && SubIndex != Offset)
2216 return false;
2217 SubIndex = Offset;
2218 }
2219
2220 if (0 <= SubIndex && SubIndex + (int)Mask.size() <= NumSrcElts) {
2221 Index = SubIndex;
2222 return true;
2223 }
2224 return false;
2225 }
2226
isIdentityWithPadding() const2227 bool ShuffleVectorInst::isIdentityWithPadding() const {
2228 if (isa<UndefValue>(Op<2>()))
2229 return false;
2230
2231 // FIXME: Not currently possible to express a shuffle mask for a scalable
2232 // vector for this case.
2233 if (isa<ScalableVectorType>(getType()))
2234 return false;
2235
2236 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2237 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2238 if (NumMaskElts <= NumOpElts)
2239 return false;
2240
2241 // The first part of the mask must choose elements from exactly 1 source op.
2242 ArrayRef<int> Mask = getShuffleMask();
2243 if (!isIdentityMaskImpl(Mask, NumOpElts))
2244 return false;
2245
2246 // All extending must be with undef elements.
2247 for (int i = NumOpElts; i < NumMaskElts; ++i)
2248 if (Mask[i] != -1)
2249 return false;
2250
2251 return true;
2252 }
2253
isIdentityWithExtract() const2254 bool ShuffleVectorInst::isIdentityWithExtract() const {
2255 if (isa<UndefValue>(Op<2>()))
2256 return false;
2257
2258 // FIXME: Not currently possible to express a shuffle mask for a scalable
2259 // vector for this case.
2260 if (isa<ScalableVectorType>(getType()))
2261 return false;
2262
2263 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2264 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2265 if (NumMaskElts >= NumOpElts)
2266 return false;
2267
2268 return isIdentityMaskImpl(getShuffleMask(), NumOpElts);
2269 }
2270
isConcat() const2271 bool ShuffleVectorInst::isConcat() const {
2272 // Vector concatenation is differentiated from identity with padding.
2273 if (isa<UndefValue>(Op<0>()) || isa<UndefValue>(Op<1>()) ||
2274 isa<UndefValue>(Op<2>()))
2275 return false;
2276
2277 // FIXME: Not currently possible to express a shuffle mask for a scalable
2278 // vector for this case.
2279 if (isa<ScalableVectorType>(getType()))
2280 return false;
2281
2282 int NumOpElts = cast<FixedVectorType>(Op<0>()->getType())->getNumElements();
2283 int NumMaskElts = cast<FixedVectorType>(getType())->getNumElements();
2284 if (NumMaskElts != NumOpElts * 2)
2285 return false;
2286
2287 // Use the mask length rather than the operands' vector lengths here. We
2288 // already know that the shuffle returns a vector twice as long as the inputs,
2289 // and neither of the inputs are undef vectors. If the mask picks consecutive
2290 // elements from both inputs, then this is a concatenation of the inputs.
2291 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts);
2292 }
2293
2294 //===----------------------------------------------------------------------===//
2295 // InsertValueInst Class
2296 //===----------------------------------------------------------------------===//
2297
init(Value * Agg,Value * Val,ArrayRef<unsigned> Idxs,const Twine & Name)2298 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
2299 const Twine &Name) {
2300 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2301
2302 // There's no fundamental reason why we require at least one index
2303 // (other than weirdness with &*IdxBegin being invalid; see
2304 // getelementptr's init routine for example). But there's no
2305 // present need to support it.
2306 assert(!Idxs.empty() && "InsertValueInst must have at least one index");
2307
2308 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
2309 Val->getType() && "Inserted value must match indexed type!");
2310 Op<0>() = Agg;
2311 Op<1>() = Val;
2312
2313 Indices.append(Idxs.begin(), Idxs.end());
2314 setName(Name);
2315 }
2316
InsertValueInst(const InsertValueInst & IVI)2317 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
2318 : Instruction(IVI.getType(), InsertValue,
2319 OperandTraits<InsertValueInst>::op_begin(this), 2),
2320 Indices(IVI.Indices) {
2321 Op<0>() = IVI.getOperand(0);
2322 Op<1>() = IVI.getOperand(1);
2323 SubclassOptionalData = IVI.SubclassOptionalData;
2324 }
2325
2326 //===----------------------------------------------------------------------===//
2327 // ExtractValueInst Class
2328 //===----------------------------------------------------------------------===//
2329
init(ArrayRef<unsigned> Idxs,const Twine & Name)2330 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
2331 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2332
2333 // There's no fundamental reason why we require at least one index.
2334 // But there's no present need to support it.
2335 assert(!Idxs.empty() && "ExtractValueInst must have at least one index");
2336
2337 Indices.append(Idxs.begin(), Idxs.end());
2338 setName(Name);
2339 }
2340
ExtractValueInst(const ExtractValueInst & EVI)2341 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
2342 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
2343 Indices(EVI.Indices) {
2344 SubclassOptionalData = EVI.SubclassOptionalData;
2345 }
2346
2347 // getIndexedType - Returns the type of the element that would be extracted
2348 // with an extractvalue instruction with the specified parameters.
2349 //
2350 // A null type is returned if the indices are invalid for the specified
2351 // pointer type.
2352 //
getIndexedType(Type * Agg,ArrayRef<unsigned> Idxs)2353 Type *ExtractValueInst::getIndexedType(Type *Agg,
2354 ArrayRef<unsigned> Idxs) {
2355 for (unsigned Index : Idxs) {
2356 // We can't use CompositeType::indexValid(Index) here.
2357 // indexValid() always returns true for arrays because getelementptr allows
2358 // out-of-bounds indices. Since we don't allow those for extractvalue and
2359 // insertvalue we need to check array indexing manually.
2360 // Since the only other types we can index into are struct types it's just
2361 // as easy to check those manually as well.
2362 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
2363 if (Index >= AT->getNumElements())
2364 return nullptr;
2365 Agg = AT->getElementType();
2366 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
2367 if (Index >= ST->getNumElements())
2368 return nullptr;
2369 Agg = ST->getElementType(Index);
2370 } else {
2371 // Not a valid type to index into.
2372 return nullptr;
2373 }
2374 }
2375 return const_cast<Type*>(Agg);
2376 }
2377
2378 //===----------------------------------------------------------------------===//
2379 // UnaryOperator Class
2380 //===----------------------------------------------------------------------===//
2381
UnaryOperator(UnaryOps iType,Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)2382 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2383 Type *Ty, const Twine &Name,
2384 Instruction *InsertBefore)
2385 : UnaryInstruction(Ty, iType, S, InsertBefore) {
2386 Op<0>() = S;
2387 setName(Name);
2388 AssertOK();
2389 }
2390
UnaryOperator(UnaryOps iType,Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2391 UnaryOperator::UnaryOperator(UnaryOps iType, Value *S,
2392 Type *Ty, const Twine &Name,
2393 BasicBlock *InsertAtEnd)
2394 : UnaryInstruction(Ty, iType, S, InsertAtEnd) {
2395 Op<0>() = S;
2396 setName(Name);
2397 AssertOK();
2398 }
2399
Create(UnaryOps Op,Value * S,const Twine & Name,Instruction * InsertBefore)2400 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2401 const Twine &Name,
2402 Instruction *InsertBefore) {
2403 return new UnaryOperator(Op, S, S->getType(), Name, InsertBefore);
2404 }
2405
Create(UnaryOps Op,Value * S,const Twine & Name,BasicBlock * InsertAtEnd)2406 UnaryOperator *UnaryOperator::Create(UnaryOps Op, Value *S,
2407 const Twine &Name,
2408 BasicBlock *InsertAtEnd) {
2409 UnaryOperator *Res = Create(Op, S, Name);
2410 InsertAtEnd->getInstList().push_back(Res);
2411 return Res;
2412 }
2413
AssertOK()2414 void UnaryOperator::AssertOK() {
2415 Value *LHS = getOperand(0);
2416 (void)LHS; // Silence warnings.
2417 #ifndef NDEBUG
2418 switch (getOpcode()) {
2419 case FNeg:
2420 assert(getType() == LHS->getType() &&
2421 "Unary operation should return same type as operand!");
2422 assert(getType()->isFPOrFPVectorTy() &&
2423 "Tried to create a floating-point operation on a "
2424 "non-floating-point type!");
2425 break;
2426 default: llvm_unreachable("Invalid opcode provided");
2427 }
2428 #endif
2429 }
2430
2431 //===----------------------------------------------------------------------===//
2432 // BinaryOperator Class
2433 //===----------------------------------------------------------------------===//
2434
BinaryOperator(BinaryOps iType,Value * S1,Value * S2,Type * Ty,const Twine & Name,Instruction * InsertBefore)2435 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2436 Type *Ty, const Twine &Name,
2437 Instruction *InsertBefore)
2438 : Instruction(Ty, iType,
2439 OperandTraits<BinaryOperator>::op_begin(this),
2440 OperandTraits<BinaryOperator>::operands(this),
2441 InsertBefore) {
2442 Op<0>() = S1;
2443 Op<1>() = S2;
2444 setName(Name);
2445 AssertOK();
2446 }
2447
BinaryOperator(BinaryOps iType,Value * S1,Value * S2,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2448 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2449 Type *Ty, const Twine &Name,
2450 BasicBlock *InsertAtEnd)
2451 : Instruction(Ty, iType,
2452 OperandTraits<BinaryOperator>::op_begin(this),
2453 OperandTraits<BinaryOperator>::operands(this),
2454 InsertAtEnd) {
2455 Op<0>() = S1;
2456 Op<1>() = S2;
2457 setName(Name);
2458 AssertOK();
2459 }
2460
AssertOK()2461 void BinaryOperator::AssertOK() {
2462 Value *LHS = getOperand(0), *RHS = getOperand(1);
2463 (void)LHS; (void)RHS; // Silence warnings.
2464 assert(LHS->getType() == RHS->getType() &&
2465 "Binary operator operand types must match!");
2466 #ifndef NDEBUG
2467 switch (getOpcode()) {
2468 case Add: case Sub:
2469 case Mul:
2470 assert(getType() == LHS->getType() &&
2471 "Arithmetic operation should return same type as operands!");
2472 assert(getType()->isIntOrIntVectorTy() &&
2473 "Tried to create an integer operation on a non-integer type!");
2474 break;
2475 case FAdd: case FSub:
2476 case FMul:
2477 assert(getType() == LHS->getType() &&
2478 "Arithmetic operation should return same type as operands!");
2479 assert(getType()->isFPOrFPVectorTy() &&
2480 "Tried to create a floating-point operation on a "
2481 "non-floating-point type!");
2482 break;
2483 case UDiv:
2484 case SDiv:
2485 assert(getType() == LHS->getType() &&
2486 "Arithmetic operation should return same type as operands!");
2487 assert(getType()->isIntOrIntVectorTy() &&
2488 "Incorrect operand type (not integer) for S/UDIV");
2489 break;
2490 case FDiv:
2491 assert(getType() == LHS->getType() &&
2492 "Arithmetic operation should return same type as operands!");
2493 assert(getType()->isFPOrFPVectorTy() &&
2494 "Incorrect operand type (not floating point) for FDIV");
2495 break;
2496 case URem:
2497 case SRem:
2498 assert(getType() == LHS->getType() &&
2499 "Arithmetic operation should return same type as operands!");
2500 assert(getType()->isIntOrIntVectorTy() &&
2501 "Incorrect operand type (not integer) for S/UREM");
2502 break;
2503 case FRem:
2504 assert(getType() == LHS->getType() &&
2505 "Arithmetic operation should return same type as operands!");
2506 assert(getType()->isFPOrFPVectorTy() &&
2507 "Incorrect operand type (not floating point) for FREM");
2508 break;
2509 case Shl:
2510 case LShr:
2511 case AShr:
2512 assert(getType() == LHS->getType() &&
2513 "Shift operation should return same type as operands!");
2514 assert(getType()->isIntOrIntVectorTy() &&
2515 "Tried to create a shift operation on a non-integral type!");
2516 break;
2517 case And: case Or:
2518 case Xor:
2519 assert(getType() == LHS->getType() &&
2520 "Logical operation should return same type as operands!");
2521 assert(getType()->isIntOrIntVectorTy() &&
2522 "Tried to create a logical operation on a non-integral type!");
2523 break;
2524 default: llvm_unreachable("Invalid opcode provided");
2525 }
2526 #endif
2527 }
2528
Create(BinaryOps Op,Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore)2529 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2530 const Twine &Name,
2531 Instruction *InsertBefore) {
2532 assert(S1->getType() == S2->getType() &&
2533 "Cannot create binary operator with two operands of differing type!");
2534 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2535 }
2536
Create(BinaryOps Op,Value * S1,Value * S2,const Twine & Name,BasicBlock * InsertAtEnd)2537 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2538 const Twine &Name,
2539 BasicBlock *InsertAtEnd) {
2540 BinaryOperator *Res = Create(Op, S1, S2, Name);
2541 InsertAtEnd->getInstList().push_back(Res);
2542 return Res;
2543 }
2544
CreateNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)2545 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2546 Instruction *InsertBefore) {
2547 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2548 return new BinaryOperator(Instruction::Sub,
2549 zero, Op,
2550 Op->getType(), Name, InsertBefore);
2551 }
2552
CreateNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)2553 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2554 BasicBlock *InsertAtEnd) {
2555 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2556 return new BinaryOperator(Instruction::Sub,
2557 zero, Op,
2558 Op->getType(), Name, InsertAtEnd);
2559 }
2560
CreateNSWNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)2561 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2562 Instruction *InsertBefore) {
2563 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2564 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2565 }
2566
CreateNSWNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)2567 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2568 BasicBlock *InsertAtEnd) {
2569 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2570 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2571 }
2572
CreateNUWNeg(Value * Op,const Twine & Name,Instruction * InsertBefore)2573 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2574 Instruction *InsertBefore) {
2575 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2576 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2577 }
2578
CreateNUWNeg(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)2579 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2580 BasicBlock *InsertAtEnd) {
2581 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2582 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2583 }
2584
CreateNot(Value * Op,const Twine & Name,Instruction * InsertBefore)2585 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2586 Instruction *InsertBefore) {
2587 Constant *C = Constant::getAllOnesValue(Op->getType());
2588 return new BinaryOperator(Instruction::Xor, Op, C,
2589 Op->getType(), Name, InsertBefore);
2590 }
2591
CreateNot(Value * Op,const Twine & Name,BasicBlock * InsertAtEnd)2592 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2593 BasicBlock *InsertAtEnd) {
2594 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2595 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2596 Op->getType(), Name, InsertAtEnd);
2597 }
2598
2599 // Exchange the two operands to this instruction. This instruction is safe to
2600 // use on any binary instruction and does not modify the semantics of the
2601 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2602 // is changed.
swapOperands()2603 bool BinaryOperator::swapOperands() {
2604 if (!isCommutative())
2605 return true; // Can't commute operands
2606 Op<0>().swap(Op<1>());
2607 return false;
2608 }
2609
2610 //===----------------------------------------------------------------------===//
2611 // FPMathOperator Class
2612 //===----------------------------------------------------------------------===//
2613
getFPAccuracy() const2614 float FPMathOperator::getFPAccuracy() const {
2615 const MDNode *MD =
2616 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2617 if (!MD)
2618 return 0.0;
2619 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2620 return Accuracy->getValueAPF().convertToFloat();
2621 }
2622
2623 //===----------------------------------------------------------------------===//
2624 // CastInst Class
2625 //===----------------------------------------------------------------------===//
2626
2627 // Just determine if this cast only deals with integral->integral conversion.
isIntegerCast() const2628 bool CastInst::isIntegerCast() const {
2629 switch (getOpcode()) {
2630 default: return false;
2631 case Instruction::ZExt:
2632 case Instruction::SExt:
2633 case Instruction::Trunc:
2634 return true;
2635 case Instruction::BitCast:
2636 return getOperand(0)->getType()->isIntegerTy() &&
2637 getType()->isIntegerTy();
2638 }
2639 }
2640
isLosslessCast() const2641 bool CastInst::isLosslessCast() const {
2642 // Only BitCast can be lossless, exit fast if we're not BitCast
2643 if (getOpcode() != Instruction::BitCast)
2644 return false;
2645
2646 // Identity cast is always lossless
2647 Type *SrcTy = getOperand(0)->getType();
2648 Type *DstTy = getType();
2649 if (SrcTy == DstTy)
2650 return true;
2651
2652 // Pointer to pointer is always lossless.
2653 if (SrcTy->isPointerTy())
2654 return DstTy->isPointerTy();
2655 return false; // Other types have no identity values
2656 }
2657
2658 /// This function determines if the CastInst does not require any bits to be
2659 /// changed in order to effect the cast. Essentially, it identifies cases where
2660 /// no code gen is necessary for the cast, hence the name no-op cast. For
2661 /// example, the following are all no-op casts:
2662 /// # bitcast i32* %x to i8*
2663 /// # bitcast <2 x i32> %x to <4 x i16>
2664 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2665 /// Determine if the described cast is a no-op.
isNoopCast(Instruction::CastOps Opcode,Type * SrcTy,Type * DestTy,const DataLayout & DL)2666 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2667 Type *SrcTy,
2668 Type *DestTy,
2669 const DataLayout &DL) {
2670 assert(castIsValid(Opcode, SrcTy, DestTy) && "method precondition");
2671 switch (Opcode) {
2672 default: llvm_unreachable("Invalid CastOp");
2673 case Instruction::Trunc:
2674 case Instruction::ZExt:
2675 case Instruction::SExt:
2676 case Instruction::FPTrunc:
2677 case Instruction::FPExt:
2678 case Instruction::UIToFP:
2679 case Instruction::SIToFP:
2680 case Instruction::FPToUI:
2681 case Instruction::FPToSI:
2682 case Instruction::AddrSpaceCast:
2683 // TODO: Target informations may give a more accurate answer here.
2684 return false;
2685 case Instruction::BitCast:
2686 return true; // BitCast never modifies bits.
2687 case Instruction::PtrToInt:
2688 return DL.getIntPtrType(SrcTy)->getScalarSizeInBits() ==
2689 DestTy->getScalarSizeInBits();
2690 case Instruction::IntToPtr:
2691 return DL.getIntPtrType(DestTy)->getScalarSizeInBits() ==
2692 SrcTy->getScalarSizeInBits();
2693 }
2694 }
2695
isNoopCast(const DataLayout & DL) const2696 bool CastInst::isNoopCast(const DataLayout &DL) const {
2697 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL);
2698 }
2699
2700 /// This function determines if a pair of casts can be eliminated and what
2701 /// opcode should be used in the elimination. This assumes that there are two
2702 /// instructions like this:
2703 /// * %F = firstOpcode SrcTy %x to MidTy
2704 /// * %S = secondOpcode MidTy %F to DstTy
2705 /// The function returns a resultOpcode so these two casts can be replaced with:
2706 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2707 /// If no such cast is permitted, the function returns 0.
isEliminableCastPair(Instruction::CastOps firstOp,Instruction::CastOps secondOp,Type * SrcTy,Type * MidTy,Type * DstTy,Type * SrcIntPtrTy,Type * MidIntPtrTy,Type * DstIntPtrTy)2708 unsigned CastInst::isEliminableCastPair(
2709 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2710 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2711 Type *DstIntPtrTy) {
2712 // Define the 144 possibilities for these two cast instructions. The values
2713 // in this matrix determine what to do in a given situation and select the
2714 // case in the switch below. The rows correspond to firstOp, the columns
2715 // correspond to secondOp. In looking at the table below, keep in mind
2716 // the following cast properties:
2717 //
2718 // Size Compare Source Destination
2719 // Operator Src ? Size Type Sign Type Sign
2720 // -------- ------------ ------------------- ---------------------
2721 // TRUNC > Integer Any Integral Any
2722 // ZEXT < Integral Unsigned Integer Any
2723 // SEXT < Integral Signed Integer Any
2724 // FPTOUI n/a FloatPt n/a Integral Unsigned
2725 // FPTOSI n/a FloatPt n/a Integral Signed
2726 // UITOFP n/a Integral Unsigned FloatPt n/a
2727 // SITOFP n/a Integral Signed FloatPt n/a
2728 // FPTRUNC > FloatPt n/a FloatPt n/a
2729 // FPEXT < FloatPt n/a FloatPt n/a
2730 // PTRTOINT n/a Pointer n/a Integral Unsigned
2731 // INTTOPTR n/a Integral Unsigned Pointer n/a
2732 // BITCAST = FirstClass n/a FirstClass n/a
2733 // ADDRSPCST n/a Pointer n/a Pointer n/a
2734 //
2735 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2736 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2737 // into "fptoui double to i64", but this loses information about the range
2738 // of the produced value (we no longer know the top-part is all zeros).
2739 // Further this conversion is often much more expensive for typical hardware,
2740 // and causes issues when building libgcc. We disallow fptosi+sext for the
2741 // same reason.
2742 const unsigned numCastOps =
2743 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2744 static const uint8_t CastResults[numCastOps][numCastOps] = {
2745 // T F F U S F F P I B A -+
2746 // R Z S P P I I T P 2 N T S |
2747 // U E E 2 2 2 2 R E I T C C +- secondOp
2748 // N X X U S F F N X N 2 V V |
2749 // C T T I I P P C T T P T T -+
2750 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2751 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2752 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2753 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2754 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2755 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2756 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2757 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2758 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
2759 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2760 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2761 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2762 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2763 };
2764
2765 // TODO: This logic could be encoded into the table above and handled in the
2766 // switch below.
2767 // If either of the casts are a bitcast from scalar to vector, disallow the
2768 // merging. However, any pair of bitcasts are allowed.
2769 bool IsFirstBitcast = (firstOp == Instruction::BitCast);
2770 bool IsSecondBitcast = (secondOp == Instruction::BitCast);
2771 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
2772
2773 // Check if any of the casts convert scalars <-> vectors.
2774 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2775 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2776 if (!AreBothBitcasts)
2777 return 0;
2778
2779 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2780 [secondOp-Instruction::CastOpsBegin];
2781 switch (ElimCase) {
2782 case 0:
2783 // Categorically disallowed.
2784 return 0;
2785 case 1:
2786 // Allowed, use first cast's opcode.
2787 return firstOp;
2788 case 2:
2789 // Allowed, use second cast's opcode.
2790 return secondOp;
2791 case 3:
2792 // No-op cast in second op implies firstOp as long as the DestTy
2793 // is integer and we are not converting between a vector and a
2794 // non-vector type.
2795 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2796 return firstOp;
2797 return 0;
2798 case 4:
2799 // No-op cast in second op implies firstOp as long as the DestTy
2800 // is floating point.
2801 if (DstTy->isFloatingPointTy())
2802 return firstOp;
2803 return 0;
2804 case 5:
2805 // No-op cast in first op implies secondOp as long as the SrcTy
2806 // is an integer.
2807 if (SrcTy->isIntegerTy())
2808 return secondOp;
2809 return 0;
2810 case 6:
2811 // No-op cast in first op implies secondOp as long as the SrcTy
2812 // is a floating point.
2813 if (SrcTy->isFloatingPointTy())
2814 return secondOp;
2815 return 0;
2816 case 7: {
2817 // Cannot simplify if address spaces are different!
2818 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2819 return 0;
2820
2821 unsigned MidSize = MidTy->getScalarSizeInBits();
2822 // We can still fold this without knowing the actual sizes as long we
2823 // know that the intermediate pointer is the largest possible
2824 // pointer size.
2825 // FIXME: Is this always true?
2826 if (MidSize == 64)
2827 return Instruction::BitCast;
2828
2829 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2830 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2831 return 0;
2832 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2833 if (MidSize >= PtrSize)
2834 return Instruction::BitCast;
2835 return 0;
2836 }
2837 case 8: {
2838 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2839 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2840 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2841 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2842 unsigned DstSize = DstTy->getScalarSizeInBits();
2843 if (SrcSize == DstSize)
2844 return Instruction::BitCast;
2845 else if (SrcSize < DstSize)
2846 return firstOp;
2847 return secondOp;
2848 }
2849 case 9:
2850 // zext, sext -> zext, because sext can't sign extend after zext
2851 return Instruction::ZExt;
2852 case 11: {
2853 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2854 if (!MidIntPtrTy)
2855 return 0;
2856 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2857 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2858 unsigned DstSize = DstTy->getScalarSizeInBits();
2859 if (SrcSize <= PtrSize && SrcSize == DstSize)
2860 return Instruction::BitCast;
2861 return 0;
2862 }
2863 case 12:
2864 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2865 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2866 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2867 return Instruction::AddrSpaceCast;
2868 return Instruction::BitCast;
2869 case 13:
2870 // FIXME: this state can be merged with (1), but the following assert
2871 // is useful to check the correcteness of the sequence due to semantic
2872 // change of bitcast.
2873 assert(
2874 SrcTy->isPtrOrPtrVectorTy() &&
2875 MidTy->isPtrOrPtrVectorTy() &&
2876 DstTy->isPtrOrPtrVectorTy() &&
2877 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2878 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2879 "Illegal addrspacecast, bitcast sequence!");
2880 // Allowed, use first cast's opcode
2881 return firstOp;
2882 case 14:
2883 // bitcast, addrspacecast -> addrspacecast if the element type of
2884 // bitcast's source is the same as that of addrspacecast's destination.
2885 if (SrcTy->getScalarType()->getPointerElementType() ==
2886 DstTy->getScalarType()->getPointerElementType())
2887 return Instruction::AddrSpaceCast;
2888 return 0;
2889 case 15:
2890 // FIXME: this state can be merged with (1), but the following assert
2891 // is useful to check the correcteness of the sequence due to semantic
2892 // change of bitcast.
2893 assert(
2894 SrcTy->isIntOrIntVectorTy() &&
2895 MidTy->isPtrOrPtrVectorTy() &&
2896 DstTy->isPtrOrPtrVectorTy() &&
2897 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2898 "Illegal inttoptr, bitcast sequence!");
2899 // Allowed, use first cast's opcode
2900 return firstOp;
2901 case 16:
2902 // FIXME: this state can be merged with (2), but the following assert
2903 // is useful to check the correcteness of the sequence due to semantic
2904 // change of bitcast.
2905 assert(
2906 SrcTy->isPtrOrPtrVectorTy() &&
2907 MidTy->isPtrOrPtrVectorTy() &&
2908 DstTy->isIntOrIntVectorTy() &&
2909 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2910 "Illegal bitcast, ptrtoint sequence!");
2911 // Allowed, use second cast's opcode
2912 return secondOp;
2913 case 17:
2914 // (sitofp (zext x)) -> (uitofp x)
2915 return Instruction::UIToFP;
2916 case 99:
2917 // Cast combination can't happen (error in input). This is for all cases
2918 // where the MidTy is not the same for the two cast instructions.
2919 llvm_unreachable("Invalid Cast Combination");
2920 default:
2921 llvm_unreachable("Error in CastResults table!!!");
2922 }
2923 }
2924
Create(Instruction::CastOps op,Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)2925 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2926 const Twine &Name, Instruction *InsertBefore) {
2927 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2928 // Construct and return the appropriate CastInst subclass
2929 switch (op) {
2930 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2931 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2932 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2933 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2934 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2935 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2936 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2937 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2938 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2939 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2940 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2941 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2942 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2943 default: llvm_unreachable("Invalid opcode provided");
2944 }
2945 }
2946
Create(Instruction::CastOps op,Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2947 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2948 const Twine &Name, BasicBlock *InsertAtEnd) {
2949 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2950 // Construct and return the appropriate CastInst subclass
2951 switch (op) {
2952 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2953 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2954 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2955 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2956 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2957 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2958 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2959 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2960 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2961 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2962 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2963 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2964 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2965 default: llvm_unreachable("Invalid opcode provided");
2966 }
2967 }
2968
CreateZExtOrBitCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)2969 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2970 const Twine &Name,
2971 Instruction *InsertBefore) {
2972 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2973 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2974 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2975 }
2976
CreateZExtOrBitCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2977 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2978 const Twine &Name,
2979 BasicBlock *InsertAtEnd) {
2980 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2981 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2982 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2983 }
2984
CreateSExtOrBitCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)2985 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2986 const Twine &Name,
2987 Instruction *InsertBefore) {
2988 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2989 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2990 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2991 }
2992
CreateSExtOrBitCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)2993 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2994 const Twine &Name,
2995 BasicBlock *InsertAtEnd) {
2996 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2997 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2998 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2999 }
3000
CreateTruncOrBitCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3001 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
3002 const Twine &Name,
3003 Instruction *InsertBefore) {
3004 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3005 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3006 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
3007 }
3008
CreateTruncOrBitCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3009 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
3010 const Twine &Name,
3011 BasicBlock *InsertAtEnd) {
3012 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
3013 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
3014 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
3015 }
3016
CreatePointerCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3017 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
3018 const Twine &Name,
3019 BasicBlock *InsertAtEnd) {
3020 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3021 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
3022 "Invalid cast");
3023 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
3024 assert((!Ty->isVectorTy() ||
3025 cast<VectorType>(Ty)->getElementCount() ==
3026 cast<VectorType>(S->getType())->getElementCount()) &&
3027 "Invalid cast");
3028
3029 if (Ty->isIntOrIntVectorTy())
3030 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
3031
3032 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
3033 }
3034
3035 /// Create a BitCast or a PtrToInt cast instruction
CreatePointerCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3036 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
3037 const Twine &Name,
3038 Instruction *InsertBefore) {
3039 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3040 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
3041 "Invalid cast");
3042 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
3043 assert((!Ty->isVectorTy() ||
3044 cast<VectorType>(Ty)->getElementCount() ==
3045 cast<VectorType>(S->getType())->getElementCount()) &&
3046 "Invalid cast");
3047
3048 if (Ty->isIntOrIntVectorTy())
3049 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3050
3051 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
3052 }
3053
CreatePointerBitCastOrAddrSpaceCast(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3054 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
3055 Value *S, Type *Ty,
3056 const Twine &Name,
3057 BasicBlock *InsertAtEnd) {
3058 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3059 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
3060
3061 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
3062 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
3063
3064 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
3065 }
3066
CreatePointerBitCastOrAddrSpaceCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3067 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
3068 Value *S, Type *Ty,
3069 const Twine &Name,
3070 Instruction *InsertBefore) {
3071 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
3072 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
3073
3074 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
3075 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
3076
3077 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3078 }
3079
CreateBitOrPointerCast(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3080 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
3081 const Twine &Name,
3082 Instruction *InsertBefore) {
3083 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
3084 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
3085 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
3086 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
3087
3088 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
3089 }
3090
CreateIntegerCast(Value * C,Type * Ty,bool isSigned,const Twine & Name,Instruction * InsertBefore)3091 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
3092 bool isSigned, const Twine &Name,
3093 Instruction *InsertBefore) {
3094 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
3095 "Invalid integer cast");
3096 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3097 unsigned DstBits = Ty->getScalarSizeInBits();
3098 Instruction::CastOps opcode =
3099 (SrcBits == DstBits ? Instruction::BitCast :
3100 (SrcBits > DstBits ? Instruction::Trunc :
3101 (isSigned ? Instruction::SExt : Instruction::ZExt)));
3102 return Create(opcode, C, Ty, Name, InsertBefore);
3103 }
3104
CreateIntegerCast(Value * C,Type * Ty,bool isSigned,const Twine & Name,BasicBlock * InsertAtEnd)3105 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
3106 bool isSigned, const Twine &Name,
3107 BasicBlock *InsertAtEnd) {
3108 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
3109 "Invalid cast");
3110 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3111 unsigned DstBits = Ty->getScalarSizeInBits();
3112 Instruction::CastOps opcode =
3113 (SrcBits == DstBits ? Instruction::BitCast :
3114 (SrcBits > DstBits ? Instruction::Trunc :
3115 (isSigned ? Instruction::SExt : Instruction::ZExt)));
3116 return Create(opcode, C, Ty, Name, InsertAtEnd);
3117 }
3118
CreateFPCast(Value * C,Type * Ty,const Twine & Name,Instruction * InsertBefore)3119 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
3120 const Twine &Name,
3121 Instruction *InsertBefore) {
3122 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
3123 "Invalid cast");
3124 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3125 unsigned DstBits = Ty->getScalarSizeInBits();
3126 Instruction::CastOps opcode =
3127 (SrcBits == DstBits ? Instruction::BitCast :
3128 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
3129 return Create(opcode, C, Ty, Name, InsertBefore);
3130 }
3131
CreateFPCast(Value * C,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3132 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
3133 const Twine &Name,
3134 BasicBlock *InsertAtEnd) {
3135 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
3136 "Invalid cast");
3137 unsigned SrcBits = C->getType()->getScalarSizeInBits();
3138 unsigned DstBits = Ty->getScalarSizeInBits();
3139 Instruction::CastOps opcode =
3140 (SrcBits == DstBits ? Instruction::BitCast :
3141 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
3142 return Create(opcode, C, Ty, Name, InsertAtEnd);
3143 }
3144
isBitCastable(Type * SrcTy,Type * DestTy)3145 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
3146 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
3147 return false;
3148
3149 if (SrcTy == DestTy)
3150 return true;
3151
3152 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3153 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
3154 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3155 // An element by element cast. Valid if casting the elements is valid.
3156 SrcTy = SrcVecTy->getElementType();
3157 DestTy = DestVecTy->getElementType();
3158 }
3159 }
3160 }
3161
3162 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
3163 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
3164 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
3165 }
3166 }
3167
3168 TypeSize SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3169 TypeSize DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3170
3171 // Could still have vectors of pointers if the number of elements doesn't
3172 // match
3173 if (SrcBits.getKnownMinSize() == 0 || DestBits.getKnownMinSize() == 0)
3174 return false;
3175
3176 if (SrcBits != DestBits)
3177 return false;
3178
3179 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
3180 return false;
3181
3182 return true;
3183 }
3184
isBitOrNoopPointerCastable(Type * SrcTy,Type * DestTy,const DataLayout & DL)3185 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
3186 const DataLayout &DL) {
3187 // ptrtoint and inttoptr are not allowed on non-integral pointers
3188 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
3189 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
3190 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3191 !DL.isNonIntegralPointerType(PtrTy));
3192 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
3193 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
3194 return (IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy) &&
3195 !DL.isNonIntegralPointerType(PtrTy));
3196
3197 return isBitCastable(SrcTy, DestTy);
3198 }
3199
3200 // Provide a way to get a "cast" where the cast opcode is inferred from the
3201 // types and size of the operand. This, basically, is a parallel of the
3202 // logic in the castIsValid function below. This axiom should hold:
3203 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3204 // should not assert in castIsValid. In other words, this produces a "correct"
3205 // casting opcode for the arguments passed to it.
3206 Instruction::CastOps
getCastOpcode(const Value * Src,bool SrcIsSigned,Type * DestTy,bool DestIsSigned)3207 CastInst::getCastOpcode(
3208 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
3209 Type *SrcTy = Src->getType();
3210
3211 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
3212 "Only first class types are castable!");
3213
3214 if (SrcTy == DestTy)
3215 return BitCast;
3216
3217 // FIXME: Check address space sizes here
3218 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
3219 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
3220 if (SrcVecTy->getElementCount() == DestVecTy->getElementCount()) {
3221 // An element by element cast. Find the appropriate opcode based on the
3222 // element types.
3223 SrcTy = SrcVecTy->getElementType();
3224 DestTy = DestVecTy->getElementType();
3225 }
3226
3227 // Get the bit sizes, we'll need these
3228 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3229 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3230
3231 // Run through the possibilities ...
3232 if (DestTy->isIntegerTy()) { // Casting to integral
3233 if (SrcTy->isIntegerTy()) { // Casting from integral
3234 if (DestBits < SrcBits)
3235 return Trunc; // int -> smaller int
3236 else if (DestBits > SrcBits) { // its an extension
3237 if (SrcIsSigned)
3238 return SExt; // signed -> SEXT
3239 else
3240 return ZExt; // unsigned -> ZEXT
3241 } else {
3242 return BitCast; // Same size, No-op cast
3243 }
3244 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3245 if (DestIsSigned)
3246 return FPToSI; // FP -> sint
3247 else
3248 return FPToUI; // FP -> uint
3249 } else if (SrcTy->isVectorTy()) {
3250 assert(DestBits == SrcBits &&
3251 "Casting vector to integer of different width");
3252 return BitCast; // Same size, no-op cast
3253 } else {
3254 assert(SrcTy->isPointerTy() &&
3255 "Casting from a value that is not first-class type");
3256 return PtrToInt; // ptr -> int
3257 }
3258 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3259 if (SrcTy->isIntegerTy()) { // Casting from integral
3260 if (SrcIsSigned)
3261 return SIToFP; // sint -> FP
3262 else
3263 return UIToFP; // uint -> FP
3264 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3265 if (DestBits < SrcBits) {
3266 return FPTrunc; // FP -> smaller FP
3267 } else if (DestBits > SrcBits) {
3268 return FPExt; // FP -> larger FP
3269 } else {
3270 return BitCast; // same size, no-op cast
3271 }
3272 } else if (SrcTy->isVectorTy()) {
3273 assert(DestBits == SrcBits &&
3274 "Casting vector to floating point of different width");
3275 return BitCast; // same size, no-op cast
3276 }
3277 llvm_unreachable("Casting pointer or non-first class to float");
3278 } else if (DestTy->isVectorTy()) {
3279 assert(DestBits == SrcBits &&
3280 "Illegal cast to vector (wrong type or size)");
3281 return BitCast;
3282 } else if (DestTy->isPointerTy()) {
3283 if (SrcTy->isPointerTy()) {
3284 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3285 return AddrSpaceCast;
3286 return BitCast; // ptr -> ptr
3287 } else if (SrcTy->isIntegerTy()) {
3288 return IntToPtr; // int -> ptr
3289 }
3290 llvm_unreachable("Casting pointer to other than pointer or int");
3291 } else if (DestTy->isX86_MMXTy()) {
3292 if (SrcTy->isVectorTy()) {
3293 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3294 return BitCast; // 64-bit vector to MMX
3295 }
3296 llvm_unreachable("Illegal cast to X86_MMX");
3297 }
3298 llvm_unreachable("Casting to type that is not first-class");
3299 }
3300
3301 //===----------------------------------------------------------------------===//
3302 // CastInst SubClass Constructors
3303 //===----------------------------------------------------------------------===//
3304
3305 /// Check that the construction parameters for a CastInst are correct. This
3306 /// could be broken out into the separate constructors but it is useful to have
3307 /// it in one place and to eliminate the redundant code for getting the sizes
3308 /// of the types involved.
3309 bool
castIsValid(Instruction::CastOps op,Type * SrcTy,Type * DstTy)3310 CastInst::castIsValid(Instruction::CastOps op, Type *SrcTy, Type *DstTy) {
3311 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3312 SrcTy->isAggregateType() || DstTy->isAggregateType())
3313 return false;
3314
3315 // Get the size of the types in bits, and whether we are dealing
3316 // with vector types, we'll need this later.
3317 bool SrcIsVec = isa<VectorType>(SrcTy);
3318 bool DstIsVec = isa<VectorType>(DstTy);
3319 unsigned SrcScalarBitSize = SrcTy->getScalarSizeInBits();
3320 unsigned DstScalarBitSize = DstTy->getScalarSizeInBits();
3321
3322 // If these are vector types, get the lengths of the vectors (using zero for
3323 // scalar types means that checking that vector lengths match also checks that
3324 // scalars are not being converted to vectors or vectors to scalars).
3325 ElementCount SrcEC = SrcIsVec ? cast<VectorType>(SrcTy)->getElementCount()
3326 : ElementCount::getFixed(0);
3327 ElementCount DstEC = DstIsVec ? cast<VectorType>(DstTy)->getElementCount()
3328 : ElementCount::getFixed(0);
3329
3330 // Switch on the opcode provided
3331 switch (op) {
3332 default: return false; // This is an input error
3333 case Instruction::Trunc:
3334 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3335 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3336 case Instruction::ZExt:
3337 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3338 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3339 case Instruction::SExt:
3340 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3341 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3342 case Instruction::FPTrunc:
3343 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3344 SrcEC == DstEC && SrcScalarBitSize > DstScalarBitSize;
3345 case Instruction::FPExt:
3346 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3347 SrcEC == DstEC && SrcScalarBitSize < DstScalarBitSize;
3348 case Instruction::UIToFP:
3349 case Instruction::SIToFP:
3350 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3351 SrcEC == DstEC;
3352 case Instruction::FPToUI:
3353 case Instruction::FPToSI:
3354 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3355 SrcEC == DstEC;
3356 case Instruction::PtrToInt:
3357 if (SrcEC != DstEC)
3358 return false;
3359 return SrcTy->isPtrOrPtrVectorTy() && DstTy->isIntOrIntVectorTy();
3360 case Instruction::IntToPtr:
3361 if (SrcEC != DstEC)
3362 return false;
3363 return SrcTy->isIntOrIntVectorTy() && DstTy->isPtrOrPtrVectorTy();
3364 case Instruction::BitCast: {
3365 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3366 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3367
3368 // BitCast implies a no-op cast of type only. No bits change.
3369 // However, you can't cast pointers to anything but pointers.
3370 if (!SrcPtrTy != !DstPtrTy)
3371 return false;
3372
3373 // For non-pointer cases, the cast is okay if the source and destination bit
3374 // widths are identical.
3375 if (!SrcPtrTy)
3376 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3377
3378 // If both are pointers then the address spaces must match.
3379 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3380 return false;
3381
3382 // A vector of pointers must have the same number of elements.
3383 if (SrcIsVec && DstIsVec)
3384 return SrcEC == DstEC;
3385 if (SrcIsVec)
3386 return SrcEC == ElementCount::getFixed(1);
3387 if (DstIsVec)
3388 return DstEC == ElementCount::getFixed(1);
3389
3390 return true;
3391 }
3392 case Instruction::AddrSpaceCast: {
3393 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3394 if (!SrcPtrTy)
3395 return false;
3396
3397 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3398 if (!DstPtrTy)
3399 return false;
3400
3401 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3402 return false;
3403
3404 return SrcEC == DstEC;
3405 }
3406 }
3407 }
3408
TruncInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3409 TruncInst::TruncInst(
3410 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3411 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3412 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3413 }
3414
TruncInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3415 TruncInst::TruncInst(
3416 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3417 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3418 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3419 }
3420
ZExtInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3421 ZExtInst::ZExtInst(
3422 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3423 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3424 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3425 }
3426
ZExtInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3427 ZExtInst::ZExtInst(
3428 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3429 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3430 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3431 }
SExtInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3432 SExtInst::SExtInst(
3433 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3434 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3435 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3436 }
3437
SExtInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3438 SExtInst::SExtInst(
3439 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3440 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3441 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3442 }
3443
FPTruncInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3444 FPTruncInst::FPTruncInst(
3445 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3446 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3447 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3448 }
3449
FPTruncInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3450 FPTruncInst::FPTruncInst(
3451 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3452 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3453 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3454 }
3455
FPExtInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3456 FPExtInst::FPExtInst(
3457 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3458 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3459 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3460 }
3461
FPExtInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3462 FPExtInst::FPExtInst(
3463 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3464 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3465 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3466 }
3467
UIToFPInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3468 UIToFPInst::UIToFPInst(
3469 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3470 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3471 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3472 }
3473
UIToFPInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3474 UIToFPInst::UIToFPInst(
3475 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3476 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3477 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3478 }
3479
SIToFPInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3480 SIToFPInst::SIToFPInst(
3481 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3482 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3483 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3484 }
3485
SIToFPInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3486 SIToFPInst::SIToFPInst(
3487 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3488 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3489 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3490 }
3491
FPToUIInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3492 FPToUIInst::FPToUIInst(
3493 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3494 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3495 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3496 }
3497
FPToUIInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3498 FPToUIInst::FPToUIInst(
3499 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3500 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3501 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3502 }
3503
FPToSIInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3504 FPToSIInst::FPToSIInst(
3505 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3506 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3507 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3508 }
3509
FPToSIInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3510 FPToSIInst::FPToSIInst(
3511 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3512 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3513 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3514 }
3515
PtrToIntInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3516 PtrToIntInst::PtrToIntInst(
3517 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3518 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3519 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3520 }
3521
PtrToIntInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3522 PtrToIntInst::PtrToIntInst(
3523 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3524 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3525 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3526 }
3527
IntToPtrInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3528 IntToPtrInst::IntToPtrInst(
3529 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3530 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3531 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3532 }
3533
IntToPtrInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3534 IntToPtrInst::IntToPtrInst(
3535 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3536 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3537 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3538 }
3539
BitCastInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3540 BitCastInst::BitCastInst(
3541 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3542 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3543 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3544 }
3545
BitCastInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3546 BitCastInst::BitCastInst(
3547 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3548 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3549 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3550 }
3551
AddrSpaceCastInst(Value * S,Type * Ty,const Twine & Name,Instruction * InsertBefore)3552 AddrSpaceCastInst::AddrSpaceCastInst(
3553 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3554 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3555 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3556 }
3557
AddrSpaceCastInst(Value * S,Type * Ty,const Twine & Name,BasicBlock * InsertAtEnd)3558 AddrSpaceCastInst::AddrSpaceCastInst(
3559 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3560 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3561 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3562 }
3563
3564 //===----------------------------------------------------------------------===//
3565 // CmpInst Classes
3566 //===----------------------------------------------------------------------===//
3567
CmpInst(Type * ty,OtherOps op,Predicate predicate,Value * LHS,Value * RHS,const Twine & Name,Instruction * InsertBefore,Instruction * FlagsSource)3568 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3569 Value *RHS, const Twine &Name, Instruction *InsertBefore,
3570 Instruction *FlagsSource)
3571 : Instruction(ty, op,
3572 OperandTraits<CmpInst>::op_begin(this),
3573 OperandTraits<CmpInst>::operands(this),
3574 InsertBefore) {
3575 Op<0>() = LHS;
3576 Op<1>() = RHS;
3577 setPredicate((Predicate)predicate);
3578 setName(Name);
3579 if (FlagsSource)
3580 copyIRFlags(FlagsSource);
3581 }
3582
CmpInst(Type * ty,OtherOps op,Predicate predicate,Value * LHS,Value * RHS,const Twine & Name,BasicBlock * InsertAtEnd)3583 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3584 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
3585 : Instruction(ty, op,
3586 OperandTraits<CmpInst>::op_begin(this),
3587 OperandTraits<CmpInst>::operands(this),
3588 InsertAtEnd) {
3589 Op<0>() = LHS;
3590 Op<1>() = RHS;
3591 setPredicate((Predicate)predicate);
3592 setName(Name);
3593 }
3594
3595 CmpInst *
Create(OtherOps Op,Predicate predicate,Value * S1,Value * S2,const Twine & Name,Instruction * InsertBefore)3596 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3597 const Twine &Name, Instruction *InsertBefore) {
3598 if (Op == Instruction::ICmp) {
3599 if (InsertBefore)
3600 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3601 S1, S2, Name);
3602 else
3603 return new ICmpInst(CmpInst::Predicate(predicate),
3604 S1, S2, Name);
3605 }
3606
3607 if (InsertBefore)
3608 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3609 S1, S2, Name);
3610 else
3611 return new FCmpInst(CmpInst::Predicate(predicate),
3612 S1, S2, Name);
3613 }
3614
3615 CmpInst *
Create(OtherOps Op,Predicate predicate,Value * S1,Value * S2,const Twine & Name,BasicBlock * InsertAtEnd)3616 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3617 const Twine &Name, BasicBlock *InsertAtEnd) {
3618 if (Op == Instruction::ICmp) {
3619 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3620 S1, S2, Name);
3621 }
3622 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3623 S1, S2, Name);
3624 }
3625
swapOperands()3626 void CmpInst::swapOperands() {
3627 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3628 IC->swapOperands();
3629 else
3630 cast<FCmpInst>(this)->swapOperands();
3631 }
3632
isCommutative() const3633 bool CmpInst::isCommutative() const {
3634 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3635 return IC->isCommutative();
3636 return cast<FCmpInst>(this)->isCommutative();
3637 }
3638
isEquality(Predicate P)3639 bool CmpInst::isEquality(Predicate P) {
3640 if (ICmpInst::isIntPredicate(P))
3641 return ICmpInst::isEquality(P);
3642 if (FCmpInst::isFPPredicate(P))
3643 return FCmpInst::isEquality(P);
3644 llvm_unreachable("Unsupported predicate kind");
3645 }
3646
getInversePredicate(Predicate pred)3647 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3648 switch (pred) {
3649 default: llvm_unreachable("Unknown cmp predicate!");
3650 case ICMP_EQ: return ICMP_NE;
3651 case ICMP_NE: return ICMP_EQ;
3652 case ICMP_UGT: return ICMP_ULE;
3653 case ICMP_ULT: return ICMP_UGE;
3654 case ICMP_UGE: return ICMP_ULT;
3655 case ICMP_ULE: return ICMP_UGT;
3656 case ICMP_SGT: return ICMP_SLE;
3657 case ICMP_SLT: return ICMP_SGE;
3658 case ICMP_SGE: return ICMP_SLT;
3659 case ICMP_SLE: return ICMP_SGT;
3660
3661 case FCMP_OEQ: return FCMP_UNE;
3662 case FCMP_ONE: return FCMP_UEQ;
3663 case FCMP_OGT: return FCMP_ULE;
3664 case FCMP_OLT: return FCMP_UGE;
3665 case FCMP_OGE: return FCMP_ULT;
3666 case FCMP_OLE: return FCMP_UGT;
3667 case FCMP_UEQ: return FCMP_ONE;
3668 case FCMP_UNE: return FCMP_OEQ;
3669 case FCMP_UGT: return FCMP_OLE;
3670 case FCMP_ULT: return FCMP_OGE;
3671 case FCMP_UGE: return FCMP_OLT;
3672 case FCMP_ULE: return FCMP_OGT;
3673 case FCMP_ORD: return FCMP_UNO;
3674 case FCMP_UNO: return FCMP_ORD;
3675 case FCMP_TRUE: return FCMP_FALSE;
3676 case FCMP_FALSE: return FCMP_TRUE;
3677 }
3678 }
3679
getPredicateName(Predicate Pred)3680 StringRef CmpInst::getPredicateName(Predicate Pred) {
3681 switch (Pred) {
3682 default: return "unknown";
3683 case FCmpInst::FCMP_FALSE: return "false";
3684 case FCmpInst::FCMP_OEQ: return "oeq";
3685 case FCmpInst::FCMP_OGT: return "ogt";
3686 case FCmpInst::FCMP_OGE: return "oge";
3687 case FCmpInst::FCMP_OLT: return "olt";
3688 case FCmpInst::FCMP_OLE: return "ole";
3689 case FCmpInst::FCMP_ONE: return "one";
3690 case FCmpInst::FCMP_ORD: return "ord";
3691 case FCmpInst::FCMP_UNO: return "uno";
3692 case FCmpInst::FCMP_UEQ: return "ueq";
3693 case FCmpInst::FCMP_UGT: return "ugt";
3694 case FCmpInst::FCMP_UGE: return "uge";
3695 case FCmpInst::FCMP_ULT: return "ult";
3696 case FCmpInst::FCMP_ULE: return "ule";
3697 case FCmpInst::FCMP_UNE: return "une";
3698 case FCmpInst::FCMP_TRUE: return "true";
3699 case ICmpInst::ICMP_EQ: return "eq";
3700 case ICmpInst::ICMP_NE: return "ne";
3701 case ICmpInst::ICMP_SGT: return "sgt";
3702 case ICmpInst::ICMP_SGE: return "sge";
3703 case ICmpInst::ICMP_SLT: return "slt";
3704 case ICmpInst::ICMP_SLE: return "sle";
3705 case ICmpInst::ICMP_UGT: return "ugt";
3706 case ICmpInst::ICMP_UGE: return "uge";
3707 case ICmpInst::ICMP_ULT: return "ult";
3708 case ICmpInst::ICMP_ULE: return "ule";
3709 }
3710 }
3711
getSignedPredicate(Predicate pred)3712 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3713 switch (pred) {
3714 default: llvm_unreachable("Unknown icmp predicate!");
3715 case ICMP_EQ: case ICMP_NE:
3716 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3717 return pred;
3718 case ICMP_UGT: return ICMP_SGT;
3719 case ICMP_ULT: return ICMP_SLT;
3720 case ICMP_UGE: return ICMP_SGE;
3721 case ICMP_ULE: return ICMP_SLE;
3722 }
3723 }
3724
getUnsignedPredicate(Predicate pred)3725 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3726 switch (pred) {
3727 default: llvm_unreachable("Unknown icmp predicate!");
3728 case ICMP_EQ: case ICMP_NE:
3729 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3730 return pred;
3731 case ICMP_SGT: return ICMP_UGT;
3732 case ICMP_SLT: return ICMP_ULT;
3733 case ICMP_SGE: return ICMP_UGE;
3734 case ICMP_SLE: return ICMP_ULE;
3735 }
3736 }
3737
getSwappedPredicate(Predicate pred)3738 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3739 switch (pred) {
3740 default: llvm_unreachable("Unknown cmp predicate!");
3741 case ICMP_EQ: case ICMP_NE:
3742 return pred;
3743 case ICMP_SGT: return ICMP_SLT;
3744 case ICMP_SLT: return ICMP_SGT;
3745 case ICMP_SGE: return ICMP_SLE;
3746 case ICMP_SLE: return ICMP_SGE;
3747 case ICMP_UGT: return ICMP_ULT;
3748 case ICMP_ULT: return ICMP_UGT;
3749 case ICMP_UGE: return ICMP_ULE;
3750 case ICMP_ULE: return ICMP_UGE;
3751
3752 case FCMP_FALSE: case FCMP_TRUE:
3753 case FCMP_OEQ: case FCMP_ONE:
3754 case FCMP_UEQ: case FCMP_UNE:
3755 case FCMP_ORD: case FCMP_UNO:
3756 return pred;
3757 case FCMP_OGT: return FCMP_OLT;
3758 case FCMP_OLT: return FCMP_OGT;
3759 case FCMP_OGE: return FCMP_OLE;
3760 case FCMP_OLE: return FCMP_OGE;
3761 case FCMP_UGT: return FCMP_ULT;
3762 case FCMP_ULT: return FCMP_UGT;
3763 case FCMP_UGE: return FCMP_ULE;
3764 case FCMP_ULE: return FCMP_UGE;
3765 }
3766 }
3767
isNonStrictPredicate(Predicate pred)3768 bool CmpInst::isNonStrictPredicate(Predicate pred) {
3769 switch (pred) {
3770 case ICMP_SGE:
3771 case ICMP_SLE:
3772 case ICMP_UGE:
3773 case ICMP_ULE:
3774 case FCMP_OGE:
3775 case FCMP_OLE:
3776 case FCMP_UGE:
3777 case FCMP_ULE:
3778 return true;
3779 default:
3780 return false;
3781 }
3782 }
3783
isStrictPredicate(Predicate pred)3784 bool CmpInst::isStrictPredicate(Predicate pred) {
3785 switch (pred) {
3786 case ICMP_SGT:
3787 case ICMP_SLT:
3788 case ICMP_UGT:
3789 case ICMP_ULT:
3790 case FCMP_OGT:
3791 case FCMP_OLT:
3792 case FCMP_UGT:
3793 case FCMP_ULT:
3794 return true;
3795 default:
3796 return false;
3797 }
3798 }
3799
getStrictPredicate(Predicate pred)3800 CmpInst::Predicate CmpInst::getStrictPredicate(Predicate pred) {
3801 switch (pred) {
3802 case ICMP_SGE:
3803 return ICMP_SGT;
3804 case ICMP_SLE:
3805 return ICMP_SLT;
3806 case ICMP_UGE:
3807 return ICMP_UGT;
3808 case ICMP_ULE:
3809 return ICMP_ULT;
3810 case FCMP_OGE:
3811 return FCMP_OGT;
3812 case FCMP_OLE:
3813 return FCMP_OLT;
3814 case FCMP_UGE:
3815 return FCMP_UGT;
3816 case FCMP_ULE:
3817 return FCMP_ULT;
3818 default:
3819 return pred;
3820 }
3821 }
3822
getNonStrictPredicate(Predicate pred)3823 CmpInst::Predicate CmpInst::getNonStrictPredicate(Predicate pred) {
3824 switch (pred) {
3825 case ICMP_SGT:
3826 return ICMP_SGE;
3827 case ICMP_SLT:
3828 return ICMP_SLE;
3829 case ICMP_UGT:
3830 return ICMP_UGE;
3831 case ICMP_ULT:
3832 return ICMP_ULE;
3833 case FCMP_OGT:
3834 return FCMP_OGE;
3835 case FCMP_OLT:
3836 return FCMP_OLE;
3837 case FCMP_UGT:
3838 return FCMP_UGE;
3839 case FCMP_ULT:
3840 return FCMP_ULE;
3841 default:
3842 return pred;
3843 }
3844 }
3845
getFlippedStrictnessPredicate(Predicate pred)3846 CmpInst::Predicate CmpInst::getFlippedStrictnessPredicate(Predicate pred) {
3847 assert(CmpInst::isRelational(pred) && "Call only with relational predicate!");
3848
3849 if (isStrictPredicate(pred))
3850 return getNonStrictPredicate(pred);
3851 if (isNonStrictPredicate(pred))
3852 return getStrictPredicate(pred);
3853
3854 llvm_unreachable("Unknown predicate!");
3855 }
3856
getSignedPredicate(Predicate pred)3857 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
3858 assert(CmpInst::isUnsigned(pred) && "Call only with unsigned predicates!");
3859
3860 switch (pred) {
3861 default:
3862 llvm_unreachable("Unknown predicate!");
3863 case CmpInst::ICMP_ULT:
3864 return CmpInst::ICMP_SLT;
3865 case CmpInst::ICMP_ULE:
3866 return CmpInst::ICMP_SLE;
3867 case CmpInst::ICMP_UGT:
3868 return CmpInst::ICMP_SGT;
3869 case CmpInst::ICMP_UGE:
3870 return CmpInst::ICMP_SGE;
3871 }
3872 }
3873
getUnsignedPredicate(Predicate pred)3874 CmpInst::Predicate CmpInst::getUnsignedPredicate(Predicate pred) {
3875 assert(CmpInst::isSigned(pred) && "Call only with signed predicates!");
3876
3877 switch (pred) {
3878 default:
3879 llvm_unreachable("Unknown predicate!");
3880 case CmpInst::ICMP_SLT:
3881 return CmpInst::ICMP_ULT;
3882 case CmpInst::ICMP_SLE:
3883 return CmpInst::ICMP_ULE;
3884 case CmpInst::ICMP_SGT:
3885 return CmpInst::ICMP_UGT;
3886 case CmpInst::ICMP_SGE:
3887 return CmpInst::ICMP_UGE;
3888 }
3889 }
3890
isUnsigned(Predicate predicate)3891 bool CmpInst::isUnsigned(Predicate predicate) {
3892 switch (predicate) {
3893 default: return false;
3894 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3895 case ICmpInst::ICMP_UGE: return true;
3896 }
3897 }
3898
isSigned(Predicate predicate)3899 bool CmpInst::isSigned(Predicate predicate) {
3900 switch (predicate) {
3901 default: return false;
3902 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3903 case ICmpInst::ICMP_SGE: return true;
3904 }
3905 }
3906
getFlippedSignednessPredicate(Predicate pred)3907 CmpInst::Predicate CmpInst::getFlippedSignednessPredicate(Predicate pred) {
3908 assert(CmpInst::isRelational(pred) &&
3909 "Call only with non-equality predicates!");
3910
3911 if (isSigned(pred))
3912 return getUnsignedPredicate(pred);
3913 if (isUnsigned(pred))
3914 return getSignedPredicate(pred);
3915
3916 llvm_unreachable("Unknown predicate!");
3917 }
3918
isOrdered(Predicate predicate)3919 bool CmpInst::isOrdered(Predicate predicate) {
3920 switch (predicate) {
3921 default: return false;
3922 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3923 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3924 case FCmpInst::FCMP_ORD: return true;
3925 }
3926 }
3927
isUnordered(Predicate predicate)3928 bool CmpInst::isUnordered(Predicate predicate) {
3929 switch (predicate) {
3930 default: return false;
3931 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3932 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3933 case FCmpInst::FCMP_UNO: return true;
3934 }
3935 }
3936
isTrueWhenEqual(Predicate predicate)3937 bool CmpInst::isTrueWhenEqual(Predicate predicate) {
3938 switch(predicate) {
3939 default: return false;
3940 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3941 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3942 }
3943 }
3944
isFalseWhenEqual(Predicate predicate)3945 bool CmpInst::isFalseWhenEqual(Predicate predicate) {
3946 switch(predicate) {
3947 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3948 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3949 default: return false;
3950 }
3951 }
3952
isImpliedTrueByMatchingCmp(Predicate Pred1,Predicate Pred2)3953 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3954 // If the predicates match, then we know the first condition implies the
3955 // second is true.
3956 if (Pred1 == Pred2)
3957 return true;
3958
3959 switch (Pred1) {
3960 default:
3961 break;
3962 case ICMP_EQ:
3963 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
3964 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
3965 Pred2 == ICMP_SLE;
3966 case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
3967 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
3968 case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
3969 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
3970 case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
3971 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
3972 case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
3973 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
3974 }
3975 return false;
3976 }
3977
isImpliedFalseByMatchingCmp(Predicate Pred1,Predicate Pred2)3978 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3979 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
3980 }
3981
3982 //===----------------------------------------------------------------------===//
3983 // SwitchInst Implementation
3984 //===----------------------------------------------------------------------===//
3985
init(Value * Value,BasicBlock * Default,unsigned NumReserved)3986 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3987 assert(Value && Default && NumReserved);
3988 ReservedSpace = NumReserved;
3989 setNumHungOffUseOperands(2);
3990 allocHungoffUses(ReservedSpace);
3991
3992 Op<0>() = Value;
3993 Op<1>() = Default;
3994 }
3995
3996 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3997 /// switch on and a default destination. The number of additional cases can
3998 /// be specified here to make memory allocation more efficient. This
3999 /// constructor can also autoinsert before another instruction.
SwitchInst(Value * Value,BasicBlock * Default,unsigned NumCases,Instruction * InsertBefore)4000 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
4001 Instruction *InsertBefore)
4002 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
4003 nullptr, 0, InsertBefore) {
4004 init(Value, Default, 2+NumCases*2);
4005 }
4006
4007 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
4008 /// switch on and a default destination. The number of additional cases can
4009 /// be specified here to make memory allocation more efficient. This
4010 /// constructor also autoinserts at the end of the specified BasicBlock.
SwitchInst(Value * Value,BasicBlock * Default,unsigned NumCases,BasicBlock * InsertAtEnd)4011 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
4012 BasicBlock *InsertAtEnd)
4013 : Instruction(Type::getVoidTy(Value->getContext()), Instruction::Switch,
4014 nullptr, 0, InsertAtEnd) {
4015 init(Value, Default, 2+NumCases*2);
4016 }
4017
SwitchInst(const SwitchInst & SI)4018 SwitchInst::SwitchInst(const SwitchInst &SI)
4019 : Instruction(SI.getType(), Instruction::Switch, nullptr, 0) {
4020 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
4021 setNumHungOffUseOperands(SI.getNumOperands());
4022 Use *OL = getOperandList();
4023 const Use *InOL = SI.getOperandList();
4024 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
4025 OL[i] = InOL[i];
4026 OL[i+1] = InOL[i+1];
4027 }
4028 SubclassOptionalData = SI.SubclassOptionalData;
4029 }
4030
4031 /// addCase - Add an entry to the switch instruction...
4032 ///
addCase(ConstantInt * OnVal,BasicBlock * Dest)4033 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
4034 unsigned NewCaseIdx = getNumCases();
4035 unsigned OpNo = getNumOperands();
4036 if (OpNo+2 > ReservedSpace)
4037 growOperands(); // Get more space!
4038 // Initialize some new operands.
4039 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
4040 setNumHungOffUseOperands(OpNo+2);
4041 CaseHandle Case(this, NewCaseIdx);
4042 Case.setValue(OnVal);
4043 Case.setSuccessor(Dest);
4044 }
4045
4046 /// removeCase - This method removes the specified case and its successor
4047 /// from the switch instruction.
removeCase(CaseIt I)4048 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
4049 unsigned idx = I->getCaseIndex();
4050
4051 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
4052
4053 unsigned NumOps = getNumOperands();
4054 Use *OL = getOperandList();
4055
4056 // Overwrite this case with the end of the list.
4057 if (2 + (idx + 1) * 2 != NumOps) {
4058 OL[2 + idx * 2] = OL[NumOps - 2];
4059 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
4060 }
4061
4062 // Nuke the last value.
4063 OL[NumOps-2].set(nullptr);
4064 OL[NumOps-2+1].set(nullptr);
4065 setNumHungOffUseOperands(NumOps-2);
4066
4067 return CaseIt(this, idx);
4068 }
4069
4070 /// growOperands - grow operands - This grows the operand list in response
4071 /// to a push_back style of operation. This grows the number of ops by 3 times.
4072 ///
growOperands()4073 void SwitchInst::growOperands() {
4074 unsigned e = getNumOperands();
4075 unsigned NumOps = e*3;
4076
4077 ReservedSpace = NumOps;
4078 growHungoffUses(ReservedSpace);
4079 }
4080
4081 MDNode *
getProfBranchWeightsMD(const SwitchInst & SI)4082 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst &SI) {
4083 if (MDNode *ProfileData = SI.getMetadata(LLVMContext::MD_prof))
4084 if (auto *MDName = dyn_cast<MDString>(ProfileData->getOperand(0)))
4085 if (MDName->getString() == "branch_weights")
4086 return ProfileData;
4087 return nullptr;
4088 }
4089
buildProfBranchWeightsMD()4090 MDNode *SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
4091 assert(Changed && "called only if metadata has changed");
4092
4093 if (!Weights)
4094 return nullptr;
4095
4096 assert(SI.getNumSuccessors() == Weights->size() &&
4097 "num of prof branch_weights must accord with num of successors");
4098
4099 bool AllZeroes =
4100 all_of(Weights.getValue(), [](uint32_t W) { return W == 0; });
4101
4102 if (AllZeroes || Weights.getValue().size() < 2)
4103 return nullptr;
4104
4105 return MDBuilder(SI.getParent()->getContext()).createBranchWeights(*Weights);
4106 }
4107
init()4108 void SwitchInstProfUpdateWrapper::init() {
4109 MDNode *ProfileData = getProfBranchWeightsMD(SI);
4110 if (!ProfileData)
4111 return;
4112
4113 if (ProfileData->getNumOperands() != SI.getNumSuccessors() + 1) {
4114 llvm_unreachable("number of prof branch_weights metadata operands does "
4115 "not correspond to number of succesors");
4116 }
4117
4118 SmallVector<uint32_t, 8> Weights;
4119 for (unsigned CI = 1, CE = SI.getNumSuccessors(); CI <= CE; ++CI) {
4120 ConstantInt *C = mdconst::extract<ConstantInt>(ProfileData->getOperand(CI));
4121 uint32_t CW = C->getValue().getZExtValue();
4122 Weights.push_back(CW);
4123 }
4124 this->Weights = std::move(Weights);
4125 }
4126
4127 SwitchInst::CaseIt
removeCase(SwitchInst::CaseIt I)4128 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I) {
4129 if (Weights) {
4130 assert(SI.getNumSuccessors() == Weights->size() &&
4131 "num of prof branch_weights must accord with num of successors");
4132 Changed = true;
4133 // Copy the last case to the place of the removed one and shrink.
4134 // This is tightly coupled with the way SwitchInst::removeCase() removes
4135 // the cases in SwitchInst::removeCase(CaseIt).
4136 Weights.getValue()[I->getCaseIndex() + 1] = Weights.getValue().back();
4137 Weights.getValue().pop_back();
4138 }
4139 return SI.removeCase(I);
4140 }
4141
addCase(ConstantInt * OnVal,BasicBlock * Dest,SwitchInstProfUpdateWrapper::CaseWeightOpt W)4142 void SwitchInstProfUpdateWrapper::addCase(
4143 ConstantInt *OnVal, BasicBlock *Dest,
4144 SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
4145 SI.addCase(OnVal, Dest);
4146
4147 if (!Weights && W && *W) {
4148 Changed = true;
4149 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4150 Weights.getValue()[SI.getNumSuccessors() - 1] = *W;
4151 } else if (Weights) {
4152 Changed = true;
4153 Weights.getValue().push_back(W ? *W : 0);
4154 }
4155 if (Weights)
4156 assert(SI.getNumSuccessors() == Weights->size() &&
4157 "num of prof branch_weights must accord with num of successors");
4158 }
4159
4160 SymbolTableList<Instruction>::iterator
eraseFromParent()4161 SwitchInstProfUpdateWrapper::eraseFromParent() {
4162 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
4163 Changed = false;
4164 if (Weights)
4165 Weights->resize(0);
4166 return SI.eraseFromParent();
4167 }
4168
4169 SwitchInstProfUpdateWrapper::CaseWeightOpt
getSuccessorWeight(unsigned idx)4170 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx) {
4171 if (!Weights)
4172 return None;
4173 return Weights.getValue()[idx];
4174 }
4175
setSuccessorWeight(unsigned idx,SwitchInstProfUpdateWrapper::CaseWeightOpt W)4176 void SwitchInstProfUpdateWrapper::setSuccessorWeight(
4177 unsigned idx, SwitchInstProfUpdateWrapper::CaseWeightOpt W) {
4178 if (!W)
4179 return;
4180
4181 if (!Weights && *W)
4182 Weights = SmallVector<uint32_t, 8>(SI.getNumSuccessors(), 0);
4183
4184 if (Weights) {
4185 auto &OldW = Weights.getValue()[idx];
4186 if (*W != OldW) {
4187 Changed = true;
4188 OldW = *W;
4189 }
4190 }
4191 }
4192
4193 SwitchInstProfUpdateWrapper::CaseWeightOpt
getSuccessorWeight(const SwitchInst & SI,unsigned idx)4194 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst &SI,
4195 unsigned idx) {
4196 if (MDNode *ProfileData = getProfBranchWeightsMD(SI))
4197 if (ProfileData->getNumOperands() == SI.getNumSuccessors() + 1)
4198 return mdconst::extract<ConstantInt>(ProfileData->getOperand(idx + 1))
4199 ->getValue()
4200 .getZExtValue();
4201
4202 return None;
4203 }
4204
4205 //===----------------------------------------------------------------------===//
4206 // IndirectBrInst Implementation
4207 //===----------------------------------------------------------------------===//
4208
init(Value * Address,unsigned NumDests)4209 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
4210 assert(Address && Address->getType()->isPointerTy() &&
4211 "Address of indirectbr must be a pointer");
4212 ReservedSpace = 1+NumDests;
4213 setNumHungOffUseOperands(1);
4214 allocHungoffUses(ReservedSpace);
4215
4216 Op<0>() = Address;
4217 }
4218
4219
4220 /// growOperands - grow operands - This grows the operand list in response
4221 /// to a push_back style of operation. This grows the number of ops by 2 times.
4222 ///
growOperands()4223 void IndirectBrInst::growOperands() {
4224 unsigned e = getNumOperands();
4225 unsigned NumOps = e*2;
4226
4227 ReservedSpace = NumOps;
4228 growHungoffUses(ReservedSpace);
4229 }
4230
IndirectBrInst(Value * Address,unsigned NumCases,Instruction * InsertBefore)4231 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4232 Instruction *InsertBefore)
4233 : Instruction(Type::getVoidTy(Address->getContext()),
4234 Instruction::IndirectBr, nullptr, 0, InsertBefore) {
4235 init(Address, NumCases);
4236 }
4237
IndirectBrInst(Value * Address,unsigned NumCases,BasicBlock * InsertAtEnd)4238 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
4239 BasicBlock *InsertAtEnd)
4240 : Instruction(Type::getVoidTy(Address->getContext()),
4241 Instruction::IndirectBr, nullptr, 0, InsertAtEnd) {
4242 init(Address, NumCases);
4243 }
4244
IndirectBrInst(const IndirectBrInst & IBI)4245 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
4246 : Instruction(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
4247 nullptr, IBI.getNumOperands()) {
4248 allocHungoffUses(IBI.getNumOperands());
4249 Use *OL = getOperandList();
4250 const Use *InOL = IBI.getOperandList();
4251 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
4252 OL[i] = InOL[i];
4253 SubclassOptionalData = IBI.SubclassOptionalData;
4254 }
4255
4256 /// addDestination - Add a destination.
4257 ///
addDestination(BasicBlock * DestBB)4258 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
4259 unsigned OpNo = getNumOperands();
4260 if (OpNo+1 > ReservedSpace)
4261 growOperands(); // Get more space!
4262 // Initialize some new operands.
4263 assert(OpNo < ReservedSpace && "Growing didn't work!");
4264 setNumHungOffUseOperands(OpNo+1);
4265 getOperandList()[OpNo] = DestBB;
4266 }
4267
4268 /// removeDestination - This method removes the specified successor from the
4269 /// indirectbr instruction.
removeDestination(unsigned idx)4270 void IndirectBrInst::removeDestination(unsigned idx) {
4271 assert(idx < getNumOperands()-1 && "Successor index out of range!");
4272
4273 unsigned NumOps = getNumOperands();
4274 Use *OL = getOperandList();
4275
4276 // Replace this value with the last one.
4277 OL[idx+1] = OL[NumOps-1];
4278
4279 // Nuke the last value.
4280 OL[NumOps-1].set(nullptr);
4281 setNumHungOffUseOperands(NumOps-1);
4282 }
4283
4284 //===----------------------------------------------------------------------===//
4285 // FreezeInst Implementation
4286 //===----------------------------------------------------------------------===//
4287
FreezeInst(Value * S,const Twine & Name,Instruction * InsertBefore)4288 FreezeInst::FreezeInst(Value *S,
4289 const Twine &Name, Instruction *InsertBefore)
4290 : UnaryInstruction(S->getType(), Freeze, S, InsertBefore) {
4291 setName(Name);
4292 }
4293
FreezeInst(Value * S,const Twine & Name,BasicBlock * InsertAtEnd)4294 FreezeInst::FreezeInst(Value *S,
4295 const Twine &Name, BasicBlock *InsertAtEnd)
4296 : UnaryInstruction(S->getType(), Freeze, S, InsertAtEnd) {
4297 setName(Name);
4298 }
4299
4300 //===----------------------------------------------------------------------===//
4301 // cloneImpl() implementations
4302 //===----------------------------------------------------------------------===//
4303
4304 // Define these methods here so vtables don't get emitted into every translation
4305 // unit that uses these classes.
4306
cloneImpl() const4307 GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
4308 return new (getNumOperands()) GetElementPtrInst(*this);
4309 }
4310
cloneImpl() const4311 UnaryOperator *UnaryOperator::cloneImpl() const {
4312 return Create(getOpcode(), Op<0>());
4313 }
4314
cloneImpl() const4315 BinaryOperator *BinaryOperator::cloneImpl() const {
4316 return Create(getOpcode(), Op<0>(), Op<1>());
4317 }
4318
cloneImpl() const4319 FCmpInst *FCmpInst::cloneImpl() const {
4320 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
4321 }
4322
cloneImpl() const4323 ICmpInst *ICmpInst::cloneImpl() const {
4324 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
4325 }
4326
cloneImpl() const4327 ExtractValueInst *ExtractValueInst::cloneImpl() const {
4328 return new ExtractValueInst(*this);
4329 }
4330
cloneImpl() const4331 InsertValueInst *InsertValueInst::cloneImpl() const {
4332 return new InsertValueInst(*this);
4333 }
4334
cloneImpl() const4335 AllocaInst *AllocaInst::cloneImpl() const {
4336 AllocaInst *Result =
4337 new AllocaInst(getAllocatedType(), getType()->getAddressSpace(),
4338 getOperand(0), getAlign());
4339 Result->setUsedWithInAlloca(isUsedWithInAlloca());
4340 Result->setSwiftError(isSwiftError());
4341 return Result;
4342 }
4343
cloneImpl() const4344 LoadInst *LoadInst::cloneImpl() const {
4345 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4346 getAlign(), getOrdering(), getSyncScopeID());
4347 }
4348
cloneImpl() const4349 StoreInst *StoreInst::cloneImpl() const {
4350 return new StoreInst(getOperand(0), getOperand(1), isVolatile(), getAlign(),
4351 getOrdering(), getSyncScopeID());
4352 }
4353
cloneImpl() const4354 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
4355 AtomicCmpXchgInst *Result = new AtomicCmpXchgInst(
4356 getOperand(0), getOperand(1), getOperand(2), getAlign(),
4357 getSuccessOrdering(), getFailureOrdering(), getSyncScopeID());
4358 Result->setVolatile(isVolatile());
4359 Result->setWeak(isWeak());
4360 return Result;
4361 }
4362
cloneImpl() const4363 AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
4364 AtomicRMWInst *Result =
4365 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4366 getAlign(), getOrdering(), getSyncScopeID());
4367 Result->setVolatile(isVolatile());
4368 return Result;
4369 }
4370
cloneImpl() const4371 FenceInst *FenceInst::cloneImpl() const {
4372 return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
4373 }
4374
cloneImpl() const4375 TruncInst *TruncInst::cloneImpl() const {
4376 return new TruncInst(getOperand(0), getType());
4377 }
4378
cloneImpl() const4379 ZExtInst *ZExtInst::cloneImpl() const {
4380 return new ZExtInst(getOperand(0), getType());
4381 }
4382
cloneImpl() const4383 SExtInst *SExtInst::cloneImpl() const {
4384 return new SExtInst(getOperand(0), getType());
4385 }
4386
cloneImpl() const4387 FPTruncInst *FPTruncInst::cloneImpl() const {
4388 return new FPTruncInst(getOperand(0), getType());
4389 }
4390
cloneImpl() const4391 FPExtInst *FPExtInst::cloneImpl() const {
4392 return new FPExtInst(getOperand(0), getType());
4393 }
4394
cloneImpl() const4395 UIToFPInst *UIToFPInst::cloneImpl() const {
4396 return new UIToFPInst(getOperand(0), getType());
4397 }
4398
cloneImpl() const4399 SIToFPInst *SIToFPInst::cloneImpl() const {
4400 return new SIToFPInst(getOperand(0), getType());
4401 }
4402
cloneImpl() const4403 FPToUIInst *FPToUIInst::cloneImpl() const {
4404 return new FPToUIInst(getOperand(0), getType());
4405 }
4406
cloneImpl() const4407 FPToSIInst *FPToSIInst::cloneImpl() const {
4408 return new FPToSIInst(getOperand(0), getType());
4409 }
4410
cloneImpl() const4411 PtrToIntInst *PtrToIntInst::cloneImpl() const {
4412 return new PtrToIntInst(getOperand(0), getType());
4413 }
4414
cloneImpl() const4415 IntToPtrInst *IntToPtrInst::cloneImpl() const {
4416 return new IntToPtrInst(getOperand(0), getType());
4417 }
4418
cloneImpl() const4419 BitCastInst *BitCastInst::cloneImpl() const {
4420 return new BitCastInst(getOperand(0), getType());
4421 }
4422
cloneImpl() const4423 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
4424 return new AddrSpaceCastInst(getOperand(0), getType());
4425 }
4426
cloneImpl() const4427 CallInst *CallInst::cloneImpl() const {
4428 if (hasOperandBundles()) {
4429 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4430 return new(getNumOperands(), DescriptorBytes) CallInst(*this);
4431 }
4432 return new(getNumOperands()) CallInst(*this);
4433 }
4434
cloneImpl() const4435 SelectInst *SelectInst::cloneImpl() const {
4436 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
4437 }
4438
cloneImpl() const4439 VAArgInst *VAArgInst::cloneImpl() const {
4440 return new VAArgInst(getOperand(0), getType());
4441 }
4442
cloneImpl() const4443 ExtractElementInst *ExtractElementInst::cloneImpl() const {
4444 return ExtractElementInst::Create(getOperand(0), getOperand(1));
4445 }
4446
cloneImpl() const4447 InsertElementInst *InsertElementInst::cloneImpl() const {
4448 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4449 }
4450
cloneImpl() const4451 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
4452 return new ShuffleVectorInst(getOperand(0), getOperand(1), getShuffleMask());
4453 }
4454
cloneImpl() const4455 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
4456
cloneImpl() const4457 LandingPadInst *LandingPadInst::cloneImpl() const {
4458 return new LandingPadInst(*this);
4459 }
4460
cloneImpl() const4461 ReturnInst *ReturnInst::cloneImpl() const {
4462 return new(getNumOperands()) ReturnInst(*this);
4463 }
4464
cloneImpl() const4465 BranchInst *BranchInst::cloneImpl() const {
4466 return new(getNumOperands()) BranchInst(*this);
4467 }
4468
cloneImpl() const4469 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4470
cloneImpl() const4471 IndirectBrInst *IndirectBrInst::cloneImpl() const {
4472 return new IndirectBrInst(*this);
4473 }
4474
cloneImpl() const4475 InvokeInst *InvokeInst::cloneImpl() const {
4476 if (hasOperandBundles()) {
4477 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4478 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
4479 }
4480 return new(getNumOperands()) InvokeInst(*this);
4481 }
4482
cloneImpl() const4483 CallBrInst *CallBrInst::cloneImpl() const {
4484 if (hasOperandBundles()) {
4485 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4486 return new (getNumOperands(), DescriptorBytes) CallBrInst(*this);
4487 }
4488 return new (getNumOperands()) CallBrInst(*this);
4489 }
4490
cloneImpl() const4491 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4492
cloneImpl() const4493 CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4494 return new (getNumOperands()) CleanupReturnInst(*this);
4495 }
4496
cloneImpl() const4497 CatchReturnInst *CatchReturnInst::cloneImpl() const {
4498 return new (getNumOperands()) CatchReturnInst(*this);
4499 }
4500
cloneImpl() const4501 CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
4502 return new CatchSwitchInst(*this);
4503 }
4504
cloneImpl() const4505 FuncletPadInst *FuncletPadInst::cloneImpl() const {
4506 return new (getNumOperands()) FuncletPadInst(*this);
4507 }
4508
cloneImpl() const4509 UnreachableInst *UnreachableInst::cloneImpl() const {
4510 LLVMContext &Context = getContext();
4511 return new UnreachableInst(Context);
4512 }
4513
cloneImpl() const4514 FreezeInst *FreezeInst::cloneImpl() const {
4515 return new FreezeInst(getOperand(0));
4516 }
4517