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