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