1 //===- Instructions.cpp - Implement the LLVM instructions -----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements all of the non-inline methods for the LLVM instruction
12 //===----------------------------------------------------------------------===//
14 #include "llvm/IR/Instructions.h"
15 #include "LLVMContextImpl.h"
16 #include "llvm/ADT/None.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/IR/Attributes.h"
20 #include "llvm/IR/BasicBlock.h"
21 #include "llvm/IR/CallSite.h"
22 #include "llvm/IR/Constant.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/Type.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/AtomicOrdering.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/MathExtras.h"
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
53 AllocaInst::getAllocationSizeInBits(const DataLayout
&DL
) const {
54 uint64_t Size
= DL
.getTypeAllocSizeInBits(getAllocatedType());
55 if (isArrayAllocation()) {
56 auto C
= dyn_cast
<ConstantInt
>(getArraySize());
59 Size
*= C
->getZExtValue();
64 //===----------------------------------------------------------------------===//
66 //===----------------------------------------------------------------------===//
68 User::op_iterator
CallSite::getCallee() const {
69 return cast
<CallBase
>(getInstruction())->op_end() - 1;
72 //===----------------------------------------------------------------------===//
74 //===----------------------------------------------------------------------===//
76 /// areInvalidOperands - Return a string if the specified operands are invalid
77 /// for a select operation, otherwise return null.
78 const char *SelectInst::areInvalidOperands(Value
*Op0
, Value
*Op1
, Value
*Op2
) {
79 if (Op1
->getType() != Op2
->getType())
80 return "both values to select must have same type";
82 if (Op1
->getType()->isTokenTy())
83 return "select values cannot have token type";
85 if (VectorType
*VT
= dyn_cast
<VectorType
>(Op0
->getType())) {
87 if (VT
->getElementType() != Type::getInt1Ty(Op0
->getContext()))
88 return "vector select condition element type must be i1";
89 VectorType
*ET
= dyn_cast
<VectorType
>(Op1
->getType());
91 return "selected values for vector select must be vectors";
92 if (ET
->getNumElements() != VT
->getNumElements())
93 return "vector select requires selected vectors to have "
94 "the same vector length as select condition";
95 } else if (Op0
->getType() != Type::getInt1Ty(Op0
->getContext())) {
96 return "select condition must be i1 or <n x i1>";
101 //===----------------------------------------------------------------------===//
103 //===----------------------------------------------------------------------===//
105 PHINode::PHINode(const PHINode
&PN
)
106 : Instruction(PN
.getType(), Instruction::PHI
, nullptr, PN
.getNumOperands()),
107 ReservedSpace(PN
.getNumOperands()) {
108 allocHungoffUses(PN
.getNumOperands());
109 std::copy(PN
.op_begin(), PN
.op_end(), op_begin());
110 std::copy(PN
.block_begin(), PN
.block_end(), block_begin());
111 SubclassOptionalData
= PN
.SubclassOptionalData
;
114 // removeIncomingValue - Remove an incoming value. This is useful if a
115 // predecessor basic block is deleted.
116 Value
*PHINode::removeIncomingValue(unsigned Idx
, bool DeletePHIIfEmpty
) {
117 Value
*Removed
= getIncomingValue(Idx
);
119 // Move everything after this operand down.
121 // FIXME: we could just swap with the end of the list, then erase. However,
122 // clients might not expect this to happen. The code as it is thrashes the
123 // use/def lists, which is kinda lame.
124 std::copy(op_begin() + Idx
+ 1, op_end(), op_begin() + Idx
);
125 std::copy(block_begin() + Idx
+ 1, block_end(), block_begin() + Idx
);
127 // Nuke the last value.
128 Op
<-1>().set(nullptr);
129 setNumHungOffUseOperands(getNumOperands() - 1);
131 // If the PHI node is dead, because it has zero entries, nuke it now.
132 if (getNumOperands() == 0 && DeletePHIIfEmpty
) {
133 // If anyone is using this PHI, make them use a dummy value instead...
134 replaceAllUsesWith(UndefValue::get(getType()));
140 /// growOperands - grow operands - This grows the operand list in response
141 /// to a push_back style of operation. This grows the number of ops by 1.5
144 void PHINode::growOperands() {
145 unsigned e
= getNumOperands();
146 unsigned NumOps
= e
+ e
/ 2;
147 if (NumOps
< 2) NumOps
= 2; // 2 op PHI nodes are VERY common.
149 ReservedSpace
= NumOps
;
150 growHungoffUses(ReservedSpace
, /* IsPhi */ true);
153 /// hasConstantValue - If the specified PHI node always merges together the same
154 /// value, return the value, otherwise return null.
155 Value
*PHINode::hasConstantValue() const {
156 // Exploit the fact that phi nodes always have at least one entry.
157 Value
*ConstantValue
= getIncomingValue(0);
158 for (unsigned i
= 1, e
= getNumIncomingValues(); i
!= e
; ++i
)
159 if (getIncomingValue(i
) != ConstantValue
&& getIncomingValue(i
) != this) {
160 if (ConstantValue
!= this)
161 return nullptr; // Incoming values not all the same.
162 // The case where the first value is this PHI.
163 ConstantValue
= getIncomingValue(i
);
165 if (ConstantValue
== this)
166 return UndefValue::get(getType());
167 return ConstantValue
;
170 /// hasConstantOrUndefValue - Whether the specified PHI node always merges
171 /// together the same value, assuming that undefs result in the same value as
173 /// Unlike \ref hasConstantValue, this does not return a value because the
174 /// unique non-undef incoming value need not dominate the PHI node.
175 bool PHINode::hasConstantOrUndefValue() const {
176 Value
*ConstantValue
= nullptr;
177 for (unsigned i
= 0, e
= getNumIncomingValues(); i
!= e
; ++i
) {
178 Value
*Incoming
= getIncomingValue(i
);
179 if (Incoming
!= this && !isa
<UndefValue
>(Incoming
)) {
180 if (ConstantValue
&& ConstantValue
!= Incoming
)
182 ConstantValue
= Incoming
;
188 //===----------------------------------------------------------------------===//
189 // LandingPadInst Implementation
190 //===----------------------------------------------------------------------===//
192 LandingPadInst::LandingPadInst(Type
*RetTy
, unsigned NumReservedValues
,
193 const Twine
&NameStr
, Instruction
*InsertBefore
)
194 : Instruction(RetTy
, Instruction::LandingPad
, nullptr, 0, InsertBefore
) {
195 init(NumReservedValues
, NameStr
);
198 LandingPadInst::LandingPadInst(Type
*RetTy
, unsigned NumReservedValues
,
199 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
200 : Instruction(RetTy
, Instruction::LandingPad
, nullptr, 0, InsertAtEnd
) {
201 init(NumReservedValues
, NameStr
);
204 LandingPadInst::LandingPadInst(const LandingPadInst
&LP
)
205 : Instruction(LP
.getType(), Instruction::LandingPad
, nullptr,
206 LP
.getNumOperands()),
207 ReservedSpace(LP
.getNumOperands()) {
208 allocHungoffUses(LP
.getNumOperands());
209 Use
*OL
= getOperandList();
210 const Use
*InOL
= LP
.getOperandList();
211 for (unsigned I
= 0, E
= ReservedSpace
; I
!= E
; ++I
)
214 setCleanup(LP
.isCleanup());
217 LandingPadInst
*LandingPadInst::Create(Type
*RetTy
, unsigned NumReservedClauses
,
218 const Twine
&NameStr
,
219 Instruction
*InsertBefore
) {
220 return new LandingPadInst(RetTy
, NumReservedClauses
, NameStr
, InsertBefore
);
223 LandingPadInst
*LandingPadInst::Create(Type
*RetTy
, unsigned NumReservedClauses
,
224 const Twine
&NameStr
,
225 BasicBlock
*InsertAtEnd
) {
226 return new LandingPadInst(RetTy
, NumReservedClauses
, NameStr
, InsertAtEnd
);
229 void LandingPadInst::init(unsigned NumReservedValues
, const Twine
&NameStr
) {
230 ReservedSpace
= NumReservedValues
;
231 setNumHungOffUseOperands(0);
232 allocHungoffUses(ReservedSpace
);
237 /// growOperands - grow operands - This grows the operand list in response to a
238 /// push_back style of operation. This grows the number of ops by 2 times.
239 void LandingPadInst::growOperands(unsigned Size
) {
240 unsigned e
= getNumOperands();
241 if (ReservedSpace
>= e
+ Size
) return;
242 ReservedSpace
= (std::max(e
, 1U) + Size
/ 2) * 2;
243 growHungoffUses(ReservedSpace
);
246 void LandingPadInst::addClause(Constant
*Val
) {
247 unsigned OpNo
= getNumOperands();
249 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
250 setNumHungOffUseOperands(getNumOperands() + 1);
251 getOperandList()[OpNo
] = Val
;
254 //===----------------------------------------------------------------------===//
255 // CallBase Implementation
256 //===----------------------------------------------------------------------===//
258 Function
*CallBase::getCaller() { return getParent()->getParent(); }
260 unsigned CallBase::getNumSubclassExtraOperandsDynamic() const {
261 assert(getOpcode() == Instruction::CallBr
&& "Unexpected opcode!");
262 return cast
<CallBrInst
>(this)->getNumIndirectDests() + 1;
265 bool CallBase::isIndirectCall() const {
266 const Value
*V
= getCalledValue();
267 if (isa
<Function
>(V
) || isa
<Constant
>(V
))
269 if (const CallInst
*CI
= dyn_cast
<CallInst
>(this))
270 if (CI
->isInlineAsm())
275 /// Tests if this call site must be tail call optimized. Only a CallInst can
276 /// be tail call optimized.
277 bool CallBase::isMustTailCall() const {
278 if (auto *CI
= dyn_cast
<CallInst
>(this))
279 return CI
->isMustTailCall();
283 /// Tests if this call site is marked as a tail call.
284 bool CallBase::isTailCall() const {
285 if (auto *CI
= dyn_cast
<CallInst
>(this))
286 return CI
->isTailCall();
290 Intrinsic::ID
CallBase::getIntrinsicID() const {
291 if (auto *F
= getCalledFunction())
292 return F
->getIntrinsicID();
293 return Intrinsic::not_intrinsic
;
296 bool CallBase::isReturnNonNull() const {
297 if (hasRetAttr(Attribute::NonNull
))
300 if (getDereferenceableBytes(AttributeList::ReturnIndex
) > 0 &&
301 !NullPointerIsDefined(getCaller(),
302 getType()->getPointerAddressSpace()))
308 Value
*CallBase::getReturnedArgOperand() const {
311 if (Attrs
.hasAttrSomewhere(Attribute::Returned
, &Index
) && Index
)
312 return getArgOperand(Index
- AttributeList::FirstArgIndex
);
313 if (const Function
*F
= getCalledFunction())
314 if (F
->getAttributes().hasAttrSomewhere(Attribute::Returned
, &Index
) &&
316 return getArgOperand(Index
- AttributeList::FirstArgIndex
);
321 bool CallBase::hasRetAttr(Attribute::AttrKind Kind
) const {
322 if (Attrs
.hasAttribute(AttributeList::ReturnIndex
, Kind
))
325 // Look at the callee, if available.
326 if (const Function
*F
= getCalledFunction())
327 return F
->getAttributes().hasAttribute(AttributeList::ReturnIndex
, Kind
);
331 /// Determine whether the argument or parameter has the given attribute.
332 bool CallBase::paramHasAttr(unsigned ArgNo
, Attribute::AttrKind Kind
) const {
333 assert(ArgNo
< getNumArgOperands() && "Param index out of bounds!");
335 if (Attrs
.hasParamAttribute(ArgNo
, Kind
))
337 if (const Function
*F
= getCalledFunction())
338 return F
->getAttributes().hasParamAttribute(ArgNo
, Kind
);
342 bool CallBase::hasFnAttrOnCalledFunction(Attribute::AttrKind Kind
) const {
343 if (const Function
*F
= getCalledFunction())
344 return F
->getAttributes().hasAttribute(AttributeList::FunctionIndex
, Kind
);
348 bool CallBase::hasFnAttrOnCalledFunction(StringRef Kind
) const {
349 if (const Function
*F
= getCalledFunction())
350 return F
->getAttributes().hasAttribute(AttributeList::FunctionIndex
, Kind
);
354 CallBase::op_iterator
355 CallBase::populateBundleOperandInfos(ArrayRef
<OperandBundleDef
> Bundles
,
356 const unsigned BeginIndex
) {
357 auto It
= op_begin() + BeginIndex
;
358 for (auto &B
: Bundles
)
359 It
= std::copy(B
.input_begin(), B
.input_end(), It
);
361 auto *ContextImpl
= getContext().pImpl
;
362 auto BI
= Bundles
.begin();
363 unsigned CurrentIndex
= BeginIndex
;
365 for (auto &BOI
: bundle_op_infos()) {
366 assert(BI
!= Bundles
.end() && "Incorrect allocation?");
368 BOI
.Tag
= ContextImpl
->getOrInsertBundleTag(BI
->getTag());
369 BOI
.Begin
= CurrentIndex
;
370 BOI
.End
= CurrentIndex
+ BI
->input_size();
371 CurrentIndex
= BOI
.End
;
375 assert(BI
== Bundles
.end() && "Incorrect allocation?");
380 //===----------------------------------------------------------------------===//
381 // CallInst Implementation
382 //===----------------------------------------------------------------------===//
384 void CallInst::init(FunctionType
*FTy
, Value
*Func
, ArrayRef
<Value
*> Args
,
385 ArrayRef
<OperandBundleDef
> Bundles
, const Twine
&NameStr
) {
387 assert(getNumOperands() == Args
.size() + CountBundleInputs(Bundles
) + 1 &&
388 "NumOperands not set up?");
389 setCalledOperand(Func
);
392 assert((Args
.size() == FTy
->getNumParams() ||
393 (FTy
->isVarArg() && Args
.size() > FTy
->getNumParams())) &&
394 "Calling a function with bad signature!");
396 for (unsigned i
= 0; i
!= Args
.size(); ++i
)
397 assert((i
>= FTy
->getNumParams() ||
398 FTy
->getParamType(i
) == Args
[i
]->getType()) &&
399 "Calling a function with a bad signature!");
402 llvm::copy(Args
, op_begin());
404 auto It
= populateBundleOperandInfos(Bundles
, Args
.size());
406 assert(It
+ 1 == op_end() && "Should add up!");
411 void CallInst::init(FunctionType
*FTy
, Value
*Func
, const Twine
&NameStr
) {
413 assert(getNumOperands() == 1 && "NumOperands not set up?");
414 setCalledOperand(Func
);
416 assert(FTy
->getNumParams() == 0 && "Calling a function with bad signature");
421 CallInst::CallInst(FunctionType
*Ty
, Value
*Func
, const Twine
&Name
,
422 Instruction
*InsertBefore
)
423 : CallBase(Ty
->getReturnType(), Instruction::Call
,
424 OperandTraits
<CallBase
>::op_end(this) - 1, 1, InsertBefore
) {
425 init(Ty
, Func
, Name
);
428 CallInst::CallInst(FunctionType
*Ty
, Value
*Func
, const Twine
&Name
,
429 BasicBlock
*InsertAtEnd
)
430 : CallBase(Ty
->getReturnType(), Instruction::Call
,
431 OperandTraits
<CallBase
>::op_end(this) - 1, 1, InsertAtEnd
) {
432 init(Ty
, Func
, Name
);
435 CallInst::CallInst(const CallInst
&CI
)
436 : CallBase(CI
.Attrs
, CI
.FTy
, CI
.getType(), Instruction::Call
,
437 OperandTraits
<CallBase
>::op_end(this) - CI
.getNumOperands(),
438 CI
.getNumOperands()) {
439 setTailCallKind(CI
.getTailCallKind());
440 setCallingConv(CI
.getCallingConv());
442 std::copy(CI
.op_begin(), CI
.op_end(), op_begin());
443 std::copy(CI
.bundle_op_info_begin(), CI
.bundle_op_info_end(),
444 bundle_op_info_begin());
445 SubclassOptionalData
= CI
.SubclassOptionalData
;
448 CallInst
*CallInst::Create(CallInst
*CI
, ArrayRef
<OperandBundleDef
> OpB
,
449 Instruction
*InsertPt
) {
450 std::vector
<Value
*> Args(CI
->arg_begin(), CI
->arg_end());
452 auto *NewCI
= CallInst::Create(CI
->getFunctionType(), CI
->getCalledValue(),
453 Args
, OpB
, CI
->getName(), InsertPt
);
454 NewCI
->setTailCallKind(CI
->getTailCallKind());
455 NewCI
->setCallingConv(CI
->getCallingConv());
456 NewCI
->SubclassOptionalData
= CI
->SubclassOptionalData
;
457 NewCI
->setAttributes(CI
->getAttributes());
458 NewCI
->setDebugLoc(CI
->getDebugLoc());
462 // Update profile weight for call instruction by scaling it using the ratio
463 // of S/T. The meaning of "branch_weights" meta data for call instruction is
464 // transfered to represent call count.
465 void CallInst::updateProfWeight(uint64_t S
, uint64_t T
) {
466 auto *ProfileData
= getMetadata(LLVMContext::MD_prof
);
467 if (ProfileData
== nullptr)
470 auto *ProfDataName
= dyn_cast
<MDString
>(ProfileData
->getOperand(0));
471 if (!ProfDataName
|| (!ProfDataName
->getString().equals("branch_weights") &&
472 !ProfDataName
->getString().equals("VP")))
476 LLVM_DEBUG(dbgs() << "Attempting to update profile weights will result in "
477 "div by 0. Ignoring. Likely the function "
478 << getParent()->getParent()->getName()
479 << " has 0 entry count, and contains call instructions "
480 "with non-zero prof info.");
484 MDBuilder
MDB(getContext());
485 SmallVector
<Metadata
*, 3> Vals
;
486 Vals
.push_back(ProfileData
->getOperand(0));
487 APInt
APS(128, S
), APT(128, T
);
488 if (ProfDataName
->getString().equals("branch_weights") &&
489 ProfileData
->getNumOperands() > 0) {
490 // Using APInt::div may be expensive, but most cases should fit 64 bits.
491 APInt
Val(128, mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(1))
495 Vals
.push_back(MDB
.createConstant(ConstantInt::get(
496 Type::getInt64Ty(getContext()), Val
.udiv(APT
).getLimitedValue())));
497 } else if (ProfDataName
->getString().equals("VP"))
498 for (unsigned i
= 1; i
< ProfileData
->getNumOperands(); i
+= 2) {
499 // The first value is the key of the value profile, which will not change.
500 Vals
.push_back(ProfileData
->getOperand(i
));
501 // Using APInt::div may be expensive, but most cases should fit 64 bits.
503 mdconst::dyn_extract
<ConstantInt
>(ProfileData
->getOperand(i
+ 1))
507 Vals
.push_back(MDB
.createConstant(
508 ConstantInt::get(Type::getInt64Ty(getContext()),
509 Val
.udiv(APT
).getLimitedValue())));
511 setMetadata(LLVMContext::MD_prof
, MDNode::get(getContext(), Vals
));
514 /// IsConstantOne - Return true only if val is constant int 1
515 static bool IsConstantOne(Value
*val
) {
516 assert(val
&& "IsConstantOne does not work with nullptr val");
517 const ConstantInt
*CVal
= dyn_cast
<ConstantInt
>(val
);
518 return CVal
&& CVal
->isOne();
521 static Instruction
*createMalloc(Instruction
*InsertBefore
,
522 BasicBlock
*InsertAtEnd
, Type
*IntPtrTy
,
523 Type
*AllocTy
, Value
*AllocSize
,
525 ArrayRef
<OperandBundleDef
> OpB
,
526 Function
*MallocF
, const Twine
&Name
) {
527 assert(((!InsertBefore
&& InsertAtEnd
) || (InsertBefore
&& !InsertAtEnd
)) &&
528 "createMalloc needs either InsertBefore or InsertAtEnd");
530 // malloc(type) becomes:
531 // bitcast (i8* malloc(typeSize)) to type*
532 // malloc(type, arraySize) becomes:
533 // bitcast (i8* malloc(typeSize*arraySize)) to type*
535 ArraySize
= ConstantInt::get(IntPtrTy
, 1);
536 else if (ArraySize
->getType() != IntPtrTy
) {
538 ArraySize
= CastInst::CreateIntegerCast(ArraySize
, IntPtrTy
, false,
541 ArraySize
= CastInst::CreateIntegerCast(ArraySize
, IntPtrTy
, false,
545 if (!IsConstantOne(ArraySize
)) {
546 if (IsConstantOne(AllocSize
)) {
547 AllocSize
= ArraySize
; // Operand * 1 = Operand
548 } else if (Constant
*CO
= dyn_cast
<Constant
>(ArraySize
)) {
549 Constant
*Scale
= ConstantExpr::getIntegerCast(CO
, IntPtrTy
,
551 // Malloc arg is constant product of type size and array size
552 AllocSize
= ConstantExpr::getMul(Scale
, cast
<Constant
>(AllocSize
));
554 // Multiply type size by the array size...
556 AllocSize
= BinaryOperator::CreateMul(ArraySize
, AllocSize
,
557 "mallocsize", InsertBefore
);
559 AllocSize
= BinaryOperator::CreateMul(ArraySize
, AllocSize
,
560 "mallocsize", InsertAtEnd
);
564 assert(AllocSize
->getType() == IntPtrTy
&& "malloc arg is wrong size");
565 // Create the call to Malloc.
566 BasicBlock
*BB
= InsertBefore
? InsertBefore
->getParent() : InsertAtEnd
;
567 Module
*M
= BB
->getParent()->getParent();
568 Type
*BPTy
= Type::getInt8PtrTy(BB
->getContext());
569 FunctionCallee MallocFunc
= MallocF
;
571 // prototype malloc as "void *malloc(size_t)"
572 MallocFunc
= M
->getOrInsertFunction("malloc", BPTy
, IntPtrTy
);
573 PointerType
*AllocPtrType
= PointerType::getUnqual(AllocTy
);
574 CallInst
*MCall
= nullptr;
575 Instruction
*Result
= nullptr;
577 MCall
= CallInst::Create(MallocFunc
, AllocSize
, OpB
, "malloccall",
580 if (Result
->getType() != AllocPtrType
)
581 // Create a cast instruction to convert to the right type...
582 Result
= new BitCastInst(MCall
, AllocPtrType
, Name
, InsertBefore
);
584 MCall
= CallInst::Create(MallocFunc
, AllocSize
, OpB
, "malloccall");
586 if (Result
->getType() != AllocPtrType
) {
587 InsertAtEnd
->getInstList().push_back(MCall
);
588 // Create a cast instruction to convert to the right type...
589 Result
= new BitCastInst(MCall
, AllocPtrType
, Name
);
592 MCall
->setTailCall();
593 if (Function
*F
= dyn_cast
<Function
>(MallocFunc
.getCallee())) {
594 MCall
->setCallingConv(F
->getCallingConv());
595 if (!F
->returnDoesNotAlias())
596 F
->setReturnDoesNotAlias();
598 assert(!MCall
->getType()->isVoidTy() && "Malloc has void return type");
603 /// CreateMalloc - Generate the IR for a call to malloc:
604 /// 1. Compute the malloc call's argument as the specified type's size,
605 /// possibly multiplied by the array size if the array size is not
607 /// 2. Call malloc with that argument.
608 /// 3. Bitcast the result of the malloc call to the specified type.
609 Instruction
*CallInst::CreateMalloc(Instruction
*InsertBefore
,
610 Type
*IntPtrTy
, Type
*AllocTy
,
611 Value
*AllocSize
, Value
*ArraySize
,
614 return createMalloc(InsertBefore
, nullptr, IntPtrTy
, AllocTy
, AllocSize
,
615 ArraySize
, None
, MallocF
, Name
);
617 Instruction
*CallInst::CreateMalloc(Instruction
*InsertBefore
,
618 Type
*IntPtrTy
, Type
*AllocTy
,
619 Value
*AllocSize
, Value
*ArraySize
,
620 ArrayRef
<OperandBundleDef
> OpB
,
623 return createMalloc(InsertBefore
, nullptr, IntPtrTy
, AllocTy
, AllocSize
,
624 ArraySize
, OpB
, MallocF
, Name
);
627 /// CreateMalloc - Generate the IR for a call to malloc:
628 /// 1. Compute the malloc call's argument as the specified type's size,
629 /// possibly multiplied by the array size if the array size is not
631 /// 2. Call malloc with that argument.
632 /// 3. Bitcast the result of the malloc call to the specified type.
633 /// Note: This function does not add the bitcast to the basic block, that is the
634 /// responsibility of the caller.
635 Instruction
*CallInst::CreateMalloc(BasicBlock
*InsertAtEnd
,
636 Type
*IntPtrTy
, Type
*AllocTy
,
637 Value
*AllocSize
, Value
*ArraySize
,
638 Function
*MallocF
, const Twine
&Name
) {
639 return createMalloc(nullptr, InsertAtEnd
, IntPtrTy
, AllocTy
, AllocSize
,
640 ArraySize
, None
, MallocF
, Name
);
642 Instruction
*CallInst::CreateMalloc(BasicBlock
*InsertAtEnd
,
643 Type
*IntPtrTy
, Type
*AllocTy
,
644 Value
*AllocSize
, Value
*ArraySize
,
645 ArrayRef
<OperandBundleDef
> OpB
,
646 Function
*MallocF
, const Twine
&Name
) {
647 return createMalloc(nullptr, InsertAtEnd
, IntPtrTy
, AllocTy
, AllocSize
,
648 ArraySize
, OpB
, MallocF
, Name
);
651 static Instruction
*createFree(Value
*Source
,
652 ArrayRef
<OperandBundleDef
> Bundles
,
653 Instruction
*InsertBefore
,
654 BasicBlock
*InsertAtEnd
) {
655 assert(((!InsertBefore
&& InsertAtEnd
) || (InsertBefore
&& !InsertAtEnd
)) &&
656 "createFree needs either InsertBefore or InsertAtEnd");
657 assert(Source
->getType()->isPointerTy() &&
658 "Can not free something of nonpointer type!");
660 BasicBlock
*BB
= InsertBefore
? InsertBefore
->getParent() : InsertAtEnd
;
661 Module
*M
= BB
->getParent()->getParent();
663 Type
*VoidTy
= Type::getVoidTy(M
->getContext());
664 Type
*IntPtrTy
= Type::getInt8PtrTy(M
->getContext());
665 // prototype free as "void free(void*)"
666 FunctionCallee FreeFunc
= M
->getOrInsertFunction("free", VoidTy
, IntPtrTy
);
667 CallInst
*Result
= nullptr;
668 Value
*PtrCast
= Source
;
670 if (Source
->getType() != IntPtrTy
)
671 PtrCast
= new BitCastInst(Source
, IntPtrTy
, "", InsertBefore
);
672 Result
= CallInst::Create(FreeFunc
, PtrCast
, Bundles
, "", InsertBefore
);
674 if (Source
->getType() != IntPtrTy
)
675 PtrCast
= new BitCastInst(Source
, IntPtrTy
, "", InsertAtEnd
);
676 Result
= CallInst::Create(FreeFunc
, PtrCast
, Bundles
, "");
678 Result
->setTailCall();
679 if (Function
*F
= dyn_cast
<Function
>(FreeFunc
.getCallee()))
680 Result
->setCallingConv(F
->getCallingConv());
685 /// CreateFree - Generate the IR for a call to the builtin free function.
686 Instruction
*CallInst::CreateFree(Value
*Source
, Instruction
*InsertBefore
) {
687 return createFree(Source
, None
, InsertBefore
, nullptr);
689 Instruction
*CallInst::CreateFree(Value
*Source
,
690 ArrayRef
<OperandBundleDef
> Bundles
,
691 Instruction
*InsertBefore
) {
692 return createFree(Source
, Bundles
, InsertBefore
, nullptr);
695 /// CreateFree - Generate the IR for a call to the builtin free function.
696 /// Note: This function does not add the call to the basic block, that is the
697 /// responsibility of the caller.
698 Instruction
*CallInst::CreateFree(Value
*Source
, BasicBlock
*InsertAtEnd
) {
699 Instruction
*FreeCall
= createFree(Source
, None
, nullptr, InsertAtEnd
);
700 assert(FreeCall
&& "CreateFree did not create a CallInst");
703 Instruction
*CallInst::CreateFree(Value
*Source
,
704 ArrayRef
<OperandBundleDef
> Bundles
,
705 BasicBlock
*InsertAtEnd
) {
706 Instruction
*FreeCall
= createFree(Source
, Bundles
, nullptr, InsertAtEnd
);
707 assert(FreeCall
&& "CreateFree did not create a CallInst");
711 //===----------------------------------------------------------------------===//
712 // InvokeInst Implementation
713 //===----------------------------------------------------------------------===//
715 void InvokeInst::init(FunctionType
*FTy
, Value
*Fn
, BasicBlock
*IfNormal
,
716 BasicBlock
*IfException
, ArrayRef
<Value
*> Args
,
717 ArrayRef
<OperandBundleDef
> Bundles
,
718 const Twine
&NameStr
) {
721 assert((int)getNumOperands() ==
722 ComputeNumOperands(Args
.size(), CountBundleInputs(Bundles
)) &&
723 "NumOperands not set up?");
724 setNormalDest(IfNormal
);
725 setUnwindDest(IfException
);
726 setCalledOperand(Fn
);
729 assert(((Args
.size() == FTy
->getNumParams()) ||
730 (FTy
->isVarArg() && Args
.size() > FTy
->getNumParams())) &&
731 "Invoking a function with bad signature");
733 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++)
734 assert((i
>= FTy
->getNumParams() ||
735 FTy
->getParamType(i
) == Args
[i
]->getType()) &&
736 "Invoking a function with a bad signature!");
739 llvm::copy(Args
, op_begin());
741 auto It
= populateBundleOperandInfos(Bundles
, Args
.size());
743 assert(It
+ 3 == op_end() && "Should add up!");
748 InvokeInst::InvokeInst(const InvokeInst
&II
)
749 : CallBase(II
.Attrs
, II
.FTy
, II
.getType(), Instruction::Invoke
,
750 OperandTraits
<CallBase
>::op_end(this) - II
.getNumOperands(),
751 II
.getNumOperands()) {
752 setCallingConv(II
.getCallingConv());
753 std::copy(II
.op_begin(), II
.op_end(), op_begin());
754 std::copy(II
.bundle_op_info_begin(), II
.bundle_op_info_end(),
755 bundle_op_info_begin());
756 SubclassOptionalData
= II
.SubclassOptionalData
;
759 InvokeInst
*InvokeInst::Create(InvokeInst
*II
, ArrayRef
<OperandBundleDef
> OpB
,
760 Instruction
*InsertPt
) {
761 std::vector
<Value
*> Args(II
->arg_begin(), II
->arg_end());
763 auto *NewII
= InvokeInst::Create(II
->getFunctionType(), II
->getCalledValue(),
764 II
->getNormalDest(), II
->getUnwindDest(),
765 Args
, OpB
, II
->getName(), InsertPt
);
766 NewII
->setCallingConv(II
->getCallingConv());
767 NewII
->SubclassOptionalData
= II
->SubclassOptionalData
;
768 NewII
->setAttributes(II
->getAttributes());
769 NewII
->setDebugLoc(II
->getDebugLoc());
774 LandingPadInst
*InvokeInst::getLandingPadInst() const {
775 return cast
<LandingPadInst
>(getUnwindDest()->getFirstNonPHI());
778 //===----------------------------------------------------------------------===//
779 // CallBrInst Implementation
780 //===----------------------------------------------------------------------===//
782 void CallBrInst::init(FunctionType
*FTy
, Value
*Fn
, BasicBlock
*Fallthrough
,
783 ArrayRef
<BasicBlock
*> IndirectDests
,
784 ArrayRef
<Value
*> Args
,
785 ArrayRef
<OperandBundleDef
> Bundles
,
786 const Twine
&NameStr
) {
789 assert((int)getNumOperands() ==
790 ComputeNumOperands(Args
.size(), IndirectDests
.size(),
791 CountBundleInputs(Bundles
)) &&
792 "NumOperands not set up?");
793 NumIndirectDests
= IndirectDests
.size();
794 setDefaultDest(Fallthrough
);
795 for (unsigned i
= 0; i
!= NumIndirectDests
; ++i
)
796 setIndirectDest(i
, IndirectDests
[i
]);
797 setCalledOperand(Fn
);
800 assert(((Args
.size() == FTy
->getNumParams()) ||
801 (FTy
->isVarArg() && Args
.size() > FTy
->getNumParams())) &&
802 "Calling a function with bad signature");
804 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++)
805 assert((i
>= FTy
->getNumParams() ||
806 FTy
->getParamType(i
) == Args
[i
]->getType()) &&
807 "Calling a function with a bad signature!");
810 std::copy(Args
.begin(), Args
.end(), op_begin());
812 auto It
= populateBundleOperandInfos(Bundles
, Args
.size());
814 assert(It
+ 2 + IndirectDests
.size() == op_end() && "Should add up!");
819 void CallBrInst::updateArgBlockAddresses(unsigned i
, BasicBlock
*B
) {
820 assert(getNumIndirectDests() > i
&& "IndirectDest # out of range for callbr");
821 if (BasicBlock
*OldBB
= getIndirectDest(i
)) {
822 BlockAddress
*Old
= BlockAddress::get(OldBB
);
823 BlockAddress
*New
= BlockAddress::get(B
);
824 for (unsigned ArgNo
= 0, e
= getNumArgOperands(); ArgNo
!= e
; ++ArgNo
)
825 if (dyn_cast
<BlockAddress
>(getArgOperand(ArgNo
)) == Old
)
826 setArgOperand(ArgNo
, New
);
830 CallBrInst::CallBrInst(const CallBrInst
&CBI
)
831 : CallBase(CBI
.Attrs
, CBI
.FTy
, CBI
.getType(), Instruction::CallBr
,
832 OperandTraits
<CallBase
>::op_end(this) - CBI
.getNumOperands(),
833 CBI
.getNumOperands()) {
834 setCallingConv(CBI
.getCallingConv());
835 std::copy(CBI
.op_begin(), CBI
.op_end(), op_begin());
836 std::copy(CBI
.bundle_op_info_begin(), CBI
.bundle_op_info_end(),
837 bundle_op_info_begin());
838 SubclassOptionalData
= CBI
.SubclassOptionalData
;
839 NumIndirectDests
= CBI
.NumIndirectDests
;
842 CallBrInst
*CallBrInst::Create(CallBrInst
*CBI
, ArrayRef
<OperandBundleDef
> OpB
,
843 Instruction
*InsertPt
) {
844 std::vector
<Value
*> Args(CBI
->arg_begin(), CBI
->arg_end());
846 auto *NewCBI
= CallBrInst::Create(CBI
->getFunctionType(),
847 CBI
->getCalledValue(),
848 CBI
->getDefaultDest(),
849 CBI
->getIndirectDests(),
850 Args
, OpB
, CBI
->getName(), InsertPt
);
851 NewCBI
->setCallingConv(CBI
->getCallingConv());
852 NewCBI
->SubclassOptionalData
= CBI
->SubclassOptionalData
;
853 NewCBI
->setAttributes(CBI
->getAttributes());
854 NewCBI
->setDebugLoc(CBI
->getDebugLoc());
855 NewCBI
->NumIndirectDests
= CBI
->NumIndirectDests
;
859 //===----------------------------------------------------------------------===//
860 // ReturnInst Implementation
861 //===----------------------------------------------------------------------===//
863 ReturnInst::ReturnInst(const ReturnInst
&RI
)
864 : Instruction(Type::getVoidTy(RI
.getContext()), Instruction::Ret
,
865 OperandTraits
<ReturnInst
>::op_end(this) - RI
.getNumOperands(),
866 RI
.getNumOperands()) {
867 if (RI
.getNumOperands())
868 Op
<0>() = RI
.Op
<0>();
869 SubclassOptionalData
= RI
.SubclassOptionalData
;
872 ReturnInst::ReturnInst(LLVMContext
&C
, Value
*retVal
, Instruction
*InsertBefore
)
873 : Instruction(Type::getVoidTy(C
), Instruction::Ret
,
874 OperandTraits
<ReturnInst
>::op_end(this) - !!retVal
, !!retVal
,
880 ReturnInst::ReturnInst(LLVMContext
&C
, Value
*retVal
, BasicBlock
*InsertAtEnd
)
881 : Instruction(Type::getVoidTy(C
), Instruction::Ret
,
882 OperandTraits
<ReturnInst
>::op_end(this) - !!retVal
, !!retVal
,
888 ReturnInst::ReturnInst(LLVMContext
&Context
, BasicBlock
*InsertAtEnd
)
889 : Instruction(Type::getVoidTy(Context
), Instruction::Ret
,
890 OperandTraits
<ReturnInst
>::op_end(this), 0, InsertAtEnd
) {}
892 //===----------------------------------------------------------------------===//
893 // ResumeInst Implementation
894 //===----------------------------------------------------------------------===//
896 ResumeInst::ResumeInst(const ResumeInst
&RI
)
897 : Instruction(Type::getVoidTy(RI
.getContext()), Instruction::Resume
,
898 OperandTraits
<ResumeInst
>::op_begin(this), 1) {
899 Op
<0>() = RI
.Op
<0>();
902 ResumeInst::ResumeInst(Value
*Exn
, Instruction
*InsertBefore
)
903 : Instruction(Type::getVoidTy(Exn
->getContext()), Instruction::Resume
,
904 OperandTraits
<ResumeInst
>::op_begin(this), 1, InsertBefore
) {
908 ResumeInst::ResumeInst(Value
*Exn
, BasicBlock
*InsertAtEnd
)
909 : Instruction(Type::getVoidTy(Exn
->getContext()), Instruction::Resume
,
910 OperandTraits
<ResumeInst
>::op_begin(this), 1, InsertAtEnd
) {
914 //===----------------------------------------------------------------------===//
915 // CleanupReturnInst Implementation
916 //===----------------------------------------------------------------------===//
918 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst
&CRI
)
919 : Instruction(CRI
.getType(), Instruction::CleanupRet
,
920 OperandTraits
<CleanupReturnInst
>::op_end(this) -
921 CRI
.getNumOperands(),
922 CRI
.getNumOperands()) {
923 setInstructionSubclassData(CRI
.getSubclassDataFromInstruction());
924 Op
<0>() = CRI
.Op
<0>();
925 if (CRI
.hasUnwindDest())
926 Op
<1>() = CRI
.Op
<1>();
929 void CleanupReturnInst::init(Value
*CleanupPad
, BasicBlock
*UnwindBB
) {
931 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
933 Op
<0>() = CleanupPad
;
938 CleanupReturnInst::CleanupReturnInst(Value
*CleanupPad
, BasicBlock
*UnwindBB
,
939 unsigned Values
, Instruction
*InsertBefore
)
940 : Instruction(Type::getVoidTy(CleanupPad
->getContext()),
941 Instruction::CleanupRet
,
942 OperandTraits
<CleanupReturnInst
>::op_end(this) - Values
,
943 Values
, InsertBefore
) {
944 init(CleanupPad
, UnwindBB
);
947 CleanupReturnInst::CleanupReturnInst(Value
*CleanupPad
, BasicBlock
*UnwindBB
,
948 unsigned Values
, BasicBlock
*InsertAtEnd
)
949 : Instruction(Type::getVoidTy(CleanupPad
->getContext()),
950 Instruction::CleanupRet
,
951 OperandTraits
<CleanupReturnInst
>::op_end(this) - Values
,
952 Values
, InsertAtEnd
) {
953 init(CleanupPad
, UnwindBB
);
956 //===----------------------------------------------------------------------===//
957 // CatchReturnInst Implementation
958 //===----------------------------------------------------------------------===//
959 void CatchReturnInst::init(Value
*CatchPad
, BasicBlock
*BB
) {
964 CatchReturnInst::CatchReturnInst(const CatchReturnInst
&CRI
)
965 : Instruction(Type::getVoidTy(CRI
.getContext()), Instruction::CatchRet
,
966 OperandTraits
<CatchReturnInst
>::op_begin(this), 2) {
967 Op
<0>() = CRI
.Op
<0>();
968 Op
<1>() = CRI
.Op
<1>();
971 CatchReturnInst::CatchReturnInst(Value
*CatchPad
, BasicBlock
*BB
,
972 Instruction
*InsertBefore
)
973 : Instruction(Type::getVoidTy(BB
->getContext()), Instruction::CatchRet
,
974 OperandTraits
<CatchReturnInst
>::op_begin(this), 2,
979 CatchReturnInst::CatchReturnInst(Value
*CatchPad
, BasicBlock
*BB
,
980 BasicBlock
*InsertAtEnd
)
981 : Instruction(Type::getVoidTy(BB
->getContext()), Instruction::CatchRet
,
982 OperandTraits
<CatchReturnInst
>::op_begin(this), 2,
987 //===----------------------------------------------------------------------===//
988 // CatchSwitchInst Implementation
989 //===----------------------------------------------------------------------===//
991 CatchSwitchInst::CatchSwitchInst(Value
*ParentPad
, BasicBlock
*UnwindDest
,
992 unsigned NumReservedValues
,
993 const Twine
&NameStr
,
994 Instruction
*InsertBefore
)
995 : Instruction(ParentPad
->getType(), Instruction::CatchSwitch
, nullptr, 0,
999 init(ParentPad
, UnwindDest
, NumReservedValues
+ 1);
1003 CatchSwitchInst::CatchSwitchInst(Value
*ParentPad
, BasicBlock
*UnwindDest
,
1004 unsigned NumReservedValues
,
1005 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
1006 : Instruction(ParentPad
->getType(), Instruction::CatchSwitch
, nullptr, 0,
1009 ++NumReservedValues
;
1010 init(ParentPad
, UnwindDest
, NumReservedValues
+ 1);
1014 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst
&CSI
)
1015 : Instruction(CSI
.getType(), Instruction::CatchSwitch
, nullptr,
1016 CSI
.getNumOperands()) {
1017 init(CSI
.getParentPad(), CSI
.getUnwindDest(), CSI
.getNumOperands());
1018 setNumHungOffUseOperands(ReservedSpace
);
1019 Use
*OL
= getOperandList();
1020 const Use
*InOL
= CSI
.getOperandList();
1021 for (unsigned I
= 1, E
= ReservedSpace
; I
!= E
; ++I
)
1025 void CatchSwitchInst::init(Value
*ParentPad
, BasicBlock
*UnwindDest
,
1026 unsigned NumReservedValues
) {
1027 assert(ParentPad
&& NumReservedValues
);
1029 ReservedSpace
= NumReservedValues
;
1030 setNumHungOffUseOperands(UnwindDest
? 2 : 1);
1031 allocHungoffUses(ReservedSpace
);
1033 Op
<0>() = ParentPad
;
1035 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
1036 setUnwindDest(UnwindDest
);
1040 /// growOperands - grow operands - This grows the operand list in response to a
1041 /// push_back style of operation. This grows the number of ops by 2 times.
1042 void CatchSwitchInst::growOperands(unsigned Size
) {
1043 unsigned NumOperands
= getNumOperands();
1044 assert(NumOperands
>= 1);
1045 if (ReservedSpace
>= NumOperands
+ Size
)
1047 ReservedSpace
= (NumOperands
+ Size
/ 2) * 2;
1048 growHungoffUses(ReservedSpace
);
1051 void CatchSwitchInst::addHandler(BasicBlock
*Handler
) {
1052 unsigned OpNo
= getNumOperands();
1054 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
1055 setNumHungOffUseOperands(getNumOperands() + 1);
1056 getOperandList()[OpNo
] = Handler
;
1059 void CatchSwitchInst::removeHandler(handler_iterator HI
) {
1060 // Move all subsequent handlers up one.
1061 Use
*EndDst
= op_end() - 1;
1062 for (Use
*CurDst
= HI
.getCurrent(); CurDst
!= EndDst
; ++CurDst
)
1063 *CurDst
= *(CurDst
+ 1);
1064 // Null out the last handler use.
1067 setNumHungOffUseOperands(getNumOperands() - 1);
1070 //===----------------------------------------------------------------------===//
1071 // FuncletPadInst Implementation
1072 //===----------------------------------------------------------------------===//
1073 void FuncletPadInst::init(Value
*ParentPad
, ArrayRef
<Value
*> Args
,
1074 const Twine
&NameStr
) {
1075 assert(getNumOperands() == 1 + Args
.size() && "NumOperands not set up?");
1076 llvm::copy(Args
, op_begin());
1077 setParentPad(ParentPad
);
1081 FuncletPadInst::FuncletPadInst(const FuncletPadInst
&FPI
)
1082 : Instruction(FPI
.getType(), FPI
.getOpcode(),
1083 OperandTraits
<FuncletPadInst
>::op_end(this) -
1084 FPI
.getNumOperands(),
1085 FPI
.getNumOperands()) {
1086 std::copy(FPI
.op_begin(), FPI
.op_end(), op_begin());
1087 setParentPad(FPI
.getParentPad());
1090 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op
, Value
*ParentPad
,
1091 ArrayRef
<Value
*> Args
, unsigned Values
,
1092 const Twine
&NameStr
, Instruction
*InsertBefore
)
1093 : Instruction(ParentPad
->getType(), Op
,
1094 OperandTraits
<FuncletPadInst
>::op_end(this) - Values
, Values
,
1096 init(ParentPad
, Args
, NameStr
);
1099 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op
, Value
*ParentPad
,
1100 ArrayRef
<Value
*> Args
, unsigned Values
,
1101 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
1102 : Instruction(ParentPad
->getType(), Op
,
1103 OperandTraits
<FuncletPadInst
>::op_end(this) - Values
, Values
,
1105 init(ParentPad
, Args
, NameStr
);
1108 //===----------------------------------------------------------------------===//
1109 // UnreachableInst Implementation
1110 //===----------------------------------------------------------------------===//
1112 UnreachableInst::UnreachableInst(LLVMContext
&Context
,
1113 Instruction
*InsertBefore
)
1114 : Instruction(Type::getVoidTy(Context
), Instruction::Unreachable
, nullptr,
1116 UnreachableInst::UnreachableInst(LLVMContext
&Context
, BasicBlock
*InsertAtEnd
)
1117 : Instruction(Type::getVoidTy(Context
), Instruction::Unreachable
, nullptr,
1120 //===----------------------------------------------------------------------===//
1121 // BranchInst Implementation
1122 //===----------------------------------------------------------------------===//
1124 void BranchInst::AssertOK() {
1125 if (isConditional())
1126 assert(getCondition()->getType()->isIntegerTy(1) &&
1127 "May only branch on boolean predicates!");
1130 BranchInst::BranchInst(BasicBlock
*IfTrue
, Instruction
*InsertBefore
)
1131 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1132 OperandTraits
<BranchInst
>::op_end(this) - 1, 1,
1134 assert(IfTrue
&& "Branch destination may not be null!");
1138 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*IfFalse
, Value
*Cond
,
1139 Instruction
*InsertBefore
)
1140 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1141 OperandTraits
<BranchInst
>::op_end(this) - 3, 3,
1151 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*InsertAtEnd
)
1152 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1153 OperandTraits
<BranchInst
>::op_end(this) - 1, 1, InsertAtEnd
) {
1154 assert(IfTrue
&& "Branch destination may not be null!");
1158 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*IfFalse
, Value
*Cond
,
1159 BasicBlock
*InsertAtEnd
)
1160 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1161 OperandTraits
<BranchInst
>::op_end(this) - 3, 3, InsertAtEnd
) {
1170 BranchInst::BranchInst(const BranchInst
&BI
)
1171 : Instruction(Type::getVoidTy(BI
.getContext()), Instruction::Br
,
1172 OperandTraits
<BranchInst
>::op_end(this) - BI
.getNumOperands(),
1173 BI
.getNumOperands()) {
1174 Op
<-1>() = BI
.Op
<-1>();
1175 if (BI
.getNumOperands() != 1) {
1176 assert(BI
.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1177 Op
<-3>() = BI
.Op
<-3>();
1178 Op
<-2>() = BI
.Op
<-2>();
1180 SubclassOptionalData
= BI
.SubclassOptionalData
;
1183 void BranchInst::swapSuccessors() {
1184 assert(isConditional() &&
1185 "Cannot swap successors of an unconditional branch");
1186 Op
<-1>().swap(Op
<-2>());
1188 // Update profile metadata if present and it matches our structural
1193 //===----------------------------------------------------------------------===//
1194 // AllocaInst Implementation
1195 //===----------------------------------------------------------------------===//
1197 static Value
*getAISize(LLVMContext
&Context
, Value
*Amt
) {
1199 Amt
= ConstantInt::get(Type::getInt32Ty(Context
), 1);
1201 assert(!isa
<BasicBlock
>(Amt
) &&
1202 "Passed basic block into allocation size parameter! Use other ctor");
1203 assert(Amt
->getType()->isIntegerTy() &&
1204 "Allocation array size is not an integer!");
1209 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, const Twine
&Name
,
1210 Instruction
*InsertBefore
)
1211 : AllocaInst(Ty
, AddrSpace
, /*ArraySize=*/nullptr, Name
, InsertBefore
) {}
1213 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, const Twine
&Name
,
1214 BasicBlock
*InsertAtEnd
)
1215 : AllocaInst(Ty
, AddrSpace
, /*ArraySize=*/nullptr, Name
, InsertAtEnd
) {}
1217 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1218 const Twine
&Name
, Instruction
*InsertBefore
)
1219 : AllocaInst(Ty
, AddrSpace
, ArraySize
, /*Align=*/0, Name
, InsertBefore
) {}
1221 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1222 const Twine
&Name
, BasicBlock
*InsertAtEnd
)
1223 : AllocaInst(Ty
, AddrSpace
, ArraySize
, /*Align=*/0, Name
, InsertAtEnd
) {}
1225 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1226 unsigned Align
, const Twine
&Name
,
1227 Instruction
*InsertBefore
)
1228 : UnaryInstruction(PointerType::get(Ty
, AddrSpace
), Alloca
,
1229 getAISize(Ty
->getContext(), ArraySize
), InsertBefore
),
1231 setAlignment(MaybeAlign(Align
));
1232 assert(!Ty
->isVoidTy() && "Cannot allocate void!");
1236 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1237 unsigned Align
, const Twine
&Name
,
1238 BasicBlock
*InsertAtEnd
)
1239 : UnaryInstruction(PointerType::get(Ty
, AddrSpace
), Alloca
,
1240 getAISize(Ty
->getContext(), ArraySize
), InsertAtEnd
),
1242 setAlignment(MaybeAlign(Align
));
1243 assert(!Ty
->isVoidTy() && "Cannot allocate void!");
1247 void AllocaInst::setAlignment(MaybeAlign Align
) {
1248 assert((!Align
|| *Align
<= MaximumAlignment
) &&
1249 "Alignment is greater than MaximumAlignment!");
1250 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1253 assert(getAlignment() == Align
->value() &&
1254 "Alignment representation error!");
1256 assert(getAlignment() == 0 && "Alignment representation error!");
1259 bool AllocaInst::isArrayAllocation() const {
1260 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(getOperand(0)))
1261 return !CI
->isOne();
1265 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1266 /// function and is a constant size. If so, the code generator will fold it
1267 /// into the prolog/epilog code, so it is basically free.
1268 bool AllocaInst::isStaticAlloca() const {
1269 // Must be constant size.
1270 if (!isa
<ConstantInt
>(getArraySize())) return false;
1272 // Must be in the entry block.
1273 const BasicBlock
*Parent
= getParent();
1274 return Parent
== &Parent
->getParent()->front() && !isUsedWithInAlloca();
1277 //===----------------------------------------------------------------------===//
1278 // LoadInst Implementation
1279 //===----------------------------------------------------------------------===//
1281 void LoadInst::AssertOK() {
1282 assert(getOperand(0)->getType()->isPointerTy() &&
1283 "Ptr must have pointer type.");
1284 assert(!(isAtomic() && getAlignment() == 0) &&
1285 "Alignment required for atomic load");
1288 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
,
1289 Instruction
*InsertBef
)
1290 : LoadInst(Ty
, Ptr
, Name
, /*isVolatile=*/false, InsertBef
) {}
1292 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
,
1293 BasicBlock
*InsertAE
)
1294 : LoadInst(Ty
, Ptr
, Name
, /*isVolatile=*/false, InsertAE
) {}
1296 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1297 Instruction
*InsertBef
)
1298 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, /*Align=*/0, InsertBef
) {}
1300 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1301 BasicBlock
*InsertAE
)
1302 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, /*Align=*/0, InsertAE
) {}
1304 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1305 unsigned Align
, Instruction
*InsertBef
)
1306 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1307 SyncScope::System
, InsertBef
) {}
1309 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1310 unsigned Align
, BasicBlock
*InsertAE
)
1311 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1312 SyncScope::System
, InsertAE
) {}
1314 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1315 unsigned Align
, AtomicOrdering Order
,
1316 SyncScope::ID SSID
, Instruction
*InsertBef
)
1317 : UnaryInstruction(Ty
, Load
, Ptr
, InsertBef
) {
1318 assert(Ty
== cast
<PointerType
>(Ptr
->getType())->getElementType());
1319 setVolatile(isVolatile
);
1320 setAlignment(MaybeAlign(Align
));
1321 setAtomic(Order
, SSID
);
1326 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1327 unsigned Align
, AtomicOrdering Order
, SyncScope::ID SSID
,
1328 BasicBlock
*InsertAE
)
1329 : UnaryInstruction(Ty
, Load
, Ptr
, InsertAE
) {
1330 assert(Ty
== cast
<PointerType
>(Ptr
->getType())->getElementType());
1331 setVolatile(isVolatile
);
1332 setAlignment(MaybeAlign(Align
));
1333 setAtomic(Order
, SSID
);
1338 void LoadInst::setAlignment(MaybeAlign Align
) {
1339 assert((!Align
|| *Align
<= MaximumAlignment
) &&
1340 "Alignment is greater than MaximumAlignment!");
1341 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1342 (encode(Align
) << 1));
1344 assert(getAlignment() == Align
->value() &&
1345 "Alignment representation error!");
1347 assert(getAlignment() == 0 && "Alignment representation error!");
1350 //===----------------------------------------------------------------------===//
1351 // StoreInst Implementation
1352 //===----------------------------------------------------------------------===//
1354 void StoreInst::AssertOK() {
1355 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1356 assert(getOperand(1)->getType()->isPointerTy() &&
1357 "Ptr must have pointer type!");
1358 assert(getOperand(0)->getType() ==
1359 cast
<PointerType
>(getOperand(1)->getType())->getElementType()
1360 && "Ptr must be a pointer to Val type!");
1361 assert(!(isAtomic() && getAlignment() == 0) &&
1362 "Alignment required for atomic store");
1365 StoreInst::StoreInst(Value
*val
, Value
*addr
, Instruction
*InsertBefore
)
1366 : StoreInst(val
, addr
, /*isVolatile=*/false, InsertBefore
) {}
1368 StoreInst::StoreInst(Value
*val
, Value
*addr
, BasicBlock
*InsertAtEnd
)
1369 : StoreInst(val
, addr
, /*isVolatile=*/false, InsertAtEnd
) {}
1371 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1372 Instruction
*InsertBefore
)
1373 : StoreInst(val
, addr
, isVolatile
, /*Align=*/0, InsertBefore
) {}
1375 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1376 BasicBlock
*InsertAtEnd
)
1377 : StoreInst(val
, addr
, isVolatile
, /*Align=*/0, InsertAtEnd
) {}
1379 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
, unsigned Align
,
1380 Instruction
*InsertBefore
)
1381 : StoreInst(val
, addr
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1382 SyncScope::System
, InsertBefore
) {}
1384 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
, unsigned Align
,
1385 BasicBlock
*InsertAtEnd
)
1386 : StoreInst(val
, addr
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1387 SyncScope::System
, InsertAtEnd
) {}
1389 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1390 unsigned Align
, AtomicOrdering Order
,
1392 Instruction
*InsertBefore
)
1393 : Instruction(Type::getVoidTy(val
->getContext()), Store
,
1394 OperandTraits
<StoreInst
>::op_begin(this),
1395 OperandTraits
<StoreInst
>::operands(this),
1399 setVolatile(isVolatile
);
1400 setAlignment(Align
);
1401 setAtomic(Order
, SSID
);
1405 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1406 unsigned Align
, AtomicOrdering Order
,
1408 BasicBlock
*InsertAtEnd
)
1409 : Instruction(Type::getVoidTy(val
->getContext()), Store
,
1410 OperandTraits
<StoreInst
>::op_begin(this),
1411 OperandTraits
<StoreInst
>::operands(this),
1415 setVolatile(isVolatile
);
1416 setAlignment(Align
);
1417 setAtomic(Order
, SSID
);
1421 void StoreInst::setAlignment(unsigned Align
) {
1422 setAlignment(llvm::MaybeAlign(Align
));
1425 void StoreInst::setAlignment(MaybeAlign Align
) {
1426 assert((!Align
|| *Align
<= MaximumAlignment
) &&
1427 "Alignment is greater than MaximumAlignment!");
1428 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1429 (encode(Align
) << 1));
1431 assert(getAlignment() == Align
->value() &&
1432 "Alignment representation error!");
1434 assert(getAlignment() == 0 && "Alignment representation error!");
1437 //===----------------------------------------------------------------------===//
1438 // AtomicCmpXchgInst Implementation
1439 //===----------------------------------------------------------------------===//
1441 void AtomicCmpXchgInst::Init(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1442 AtomicOrdering SuccessOrdering
,
1443 AtomicOrdering FailureOrdering
,
1444 SyncScope::ID SSID
) {
1448 setSuccessOrdering(SuccessOrdering
);
1449 setFailureOrdering(FailureOrdering
);
1450 setSyncScopeID(SSID
);
1452 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1453 "All operands must be non-null!");
1454 assert(getOperand(0)->getType()->isPointerTy() &&
1455 "Ptr must have pointer type!");
1456 assert(getOperand(1)->getType() ==
1457 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1458 && "Ptr must be a pointer to Cmp type!");
1459 assert(getOperand(2)->getType() ==
1460 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1461 && "Ptr must be a pointer to NewVal type!");
1462 assert(SuccessOrdering
!= AtomicOrdering::NotAtomic
&&
1463 "AtomicCmpXchg instructions must be atomic!");
1464 assert(FailureOrdering
!= AtomicOrdering::NotAtomic
&&
1465 "AtomicCmpXchg instructions must be atomic!");
1466 assert(!isStrongerThan(FailureOrdering
, SuccessOrdering
) &&
1467 "AtomicCmpXchg failure argument shall be no stronger than the success "
1469 assert(FailureOrdering
!= AtomicOrdering::Release
&&
1470 FailureOrdering
!= AtomicOrdering::AcquireRelease
&&
1471 "AtomicCmpXchg failure ordering cannot include release semantics");
1474 AtomicCmpXchgInst::AtomicCmpXchgInst(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1475 AtomicOrdering SuccessOrdering
,
1476 AtomicOrdering FailureOrdering
,
1478 Instruction
*InsertBefore
)
1480 StructType::get(Cmp
->getType(), Type::getInt1Ty(Cmp
->getContext())),
1481 AtomicCmpXchg
, OperandTraits
<AtomicCmpXchgInst
>::op_begin(this),
1482 OperandTraits
<AtomicCmpXchgInst
>::operands(this), InsertBefore
) {
1483 Init(Ptr
, Cmp
, NewVal
, SuccessOrdering
, FailureOrdering
, SSID
);
1486 AtomicCmpXchgInst::AtomicCmpXchgInst(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1487 AtomicOrdering SuccessOrdering
,
1488 AtomicOrdering FailureOrdering
,
1490 BasicBlock
*InsertAtEnd
)
1492 StructType::get(Cmp
->getType(), Type::getInt1Ty(Cmp
->getContext())),
1493 AtomicCmpXchg
, OperandTraits
<AtomicCmpXchgInst
>::op_begin(this),
1494 OperandTraits
<AtomicCmpXchgInst
>::operands(this), InsertAtEnd
) {
1495 Init(Ptr
, Cmp
, NewVal
, SuccessOrdering
, FailureOrdering
, SSID
);
1498 //===----------------------------------------------------------------------===//
1499 // AtomicRMWInst Implementation
1500 //===----------------------------------------------------------------------===//
1502 void AtomicRMWInst::Init(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1503 AtomicOrdering Ordering
,
1504 SyncScope::ID SSID
) {
1507 setOperation(Operation
);
1508 setOrdering(Ordering
);
1509 setSyncScopeID(SSID
);
1511 assert(getOperand(0) && getOperand(1) &&
1512 "All operands must be non-null!");
1513 assert(getOperand(0)->getType()->isPointerTy() &&
1514 "Ptr must have pointer type!");
1515 assert(getOperand(1)->getType() ==
1516 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1517 && "Ptr must be a pointer to Val type!");
1518 assert(Ordering
!= AtomicOrdering::NotAtomic
&&
1519 "AtomicRMW instructions must be atomic!");
1522 AtomicRMWInst::AtomicRMWInst(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1523 AtomicOrdering Ordering
,
1525 Instruction
*InsertBefore
)
1526 : Instruction(Val
->getType(), AtomicRMW
,
1527 OperandTraits
<AtomicRMWInst
>::op_begin(this),
1528 OperandTraits
<AtomicRMWInst
>::operands(this),
1530 Init(Operation
, Ptr
, Val
, Ordering
, SSID
);
1533 AtomicRMWInst::AtomicRMWInst(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1534 AtomicOrdering Ordering
,
1536 BasicBlock
*InsertAtEnd
)
1537 : Instruction(Val
->getType(), AtomicRMW
,
1538 OperandTraits
<AtomicRMWInst
>::op_begin(this),
1539 OperandTraits
<AtomicRMWInst
>::operands(this),
1541 Init(Operation
, Ptr
, Val
, Ordering
, SSID
);
1544 StringRef
AtomicRMWInst::getOperationName(BinOp Op
) {
1546 case AtomicRMWInst::Xchg
:
1548 case AtomicRMWInst::Add
:
1550 case AtomicRMWInst::Sub
:
1552 case AtomicRMWInst::And
:
1554 case AtomicRMWInst::Nand
:
1556 case AtomicRMWInst::Or
:
1558 case AtomicRMWInst::Xor
:
1560 case AtomicRMWInst::Max
:
1562 case AtomicRMWInst::Min
:
1564 case AtomicRMWInst::UMax
:
1566 case AtomicRMWInst::UMin
:
1568 case AtomicRMWInst::FAdd
:
1570 case AtomicRMWInst::FSub
:
1572 case AtomicRMWInst::BAD_BINOP
:
1573 return "<invalid operation>";
1576 llvm_unreachable("invalid atomicrmw operation");
1579 //===----------------------------------------------------------------------===//
1580 // FenceInst Implementation
1581 //===----------------------------------------------------------------------===//
1583 FenceInst::FenceInst(LLVMContext
&C
, AtomicOrdering Ordering
,
1585 Instruction
*InsertBefore
)
1586 : Instruction(Type::getVoidTy(C
), Fence
, nullptr, 0, InsertBefore
) {
1587 setOrdering(Ordering
);
1588 setSyncScopeID(SSID
);
1591 FenceInst::FenceInst(LLVMContext
&C
, AtomicOrdering Ordering
,
1593 BasicBlock
*InsertAtEnd
)
1594 : Instruction(Type::getVoidTy(C
), Fence
, nullptr, 0, InsertAtEnd
) {
1595 setOrdering(Ordering
);
1596 setSyncScopeID(SSID
);
1599 //===----------------------------------------------------------------------===//
1600 // GetElementPtrInst Implementation
1601 //===----------------------------------------------------------------------===//
1603 void GetElementPtrInst::init(Value
*Ptr
, ArrayRef
<Value
*> IdxList
,
1604 const Twine
&Name
) {
1605 assert(getNumOperands() == 1 + IdxList
.size() &&
1606 "NumOperands not initialized?");
1608 llvm::copy(IdxList
, op_begin() + 1);
1612 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst
&GEPI
)
1613 : Instruction(GEPI
.getType(), GetElementPtr
,
1614 OperandTraits
<GetElementPtrInst
>::op_end(this) -
1615 GEPI
.getNumOperands(),
1616 GEPI
.getNumOperands()),
1617 SourceElementType(GEPI
.SourceElementType
),
1618 ResultElementType(GEPI
.ResultElementType
) {
1619 std::copy(GEPI
.op_begin(), GEPI
.op_end(), op_begin());
1620 SubclassOptionalData
= GEPI
.SubclassOptionalData
;
1623 /// getIndexedType - Returns the type of the element that would be accessed with
1624 /// a gep instruction with the specified parameters.
1626 /// The Idxs pointer should point to a continuous piece of memory containing the
1627 /// indices, either as Value* or uint64_t.
1629 /// A null type is returned if the indices are invalid for the specified
1632 template <typename IndexTy
>
1633 static Type
*getIndexedTypeInternal(Type
*Agg
, ArrayRef
<IndexTy
> IdxList
) {
1634 // Handle the special case of the empty set index set, which is always valid.
1635 if (IdxList
.empty())
1638 // If there is at least one index, the top level type must be sized, otherwise
1639 // it cannot be 'stepped over'.
1640 if (!Agg
->isSized())
1643 unsigned CurIdx
= 1;
1644 for (; CurIdx
!= IdxList
.size(); ++CurIdx
) {
1645 CompositeType
*CT
= dyn_cast
<CompositeType
>(Agg
);
1646 if (!CT
|| CT
->isPointerTy()) return nullptr;
1647 IndexTy Index
= IdxList
[CurIdx
];
1648 if (!CT
->indexValid(Index
)) return nullptr;
1649 Agg
= CT
->getTypeAtIndex(Index
);
1651 return CurIdx
== IdxList
.size() ? Agg
: nullptr;
1654 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
, ArrayRef
<Value
*> IdxList
) {
1655 return getIndexedTypeInternal(Ty
, IdxList
);
1658 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
,
1659 ArrayRef
<Constant
*> IdxList
) {
1660 return getIndexedTypeInternal(Ty
, IdxList
);
1663 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
, ArrayRef
<uint64_t> IdxList
) {
1664 return getIndexedTypeInternal(Ty
, IdxList
);
1667 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1668 /// zeros. If so, the result pointer and the first operand have the same
1669 /// value, just potentially different types.
1670 bool GetElementPtrInst::hasAllZeroIndices() const {
1671 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1672 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(getOperand(i
))) {
1673 if (!CI
->isZero()) return false;
1681 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1682 /// constant integers. If so, the result pointer and the first operand have
1683 /// a constant offset between them.
1684 bool GetElementPtrInst::hasAllConstantIndices() const {
1685 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1686 if (!isa
<ConstantInt
>(getOperand(i
)))
1692 void GetElementPtrInst::setIsInBounds(bool B
) {
1693 cast
<GEPOperator
>(this)->setIsInBounds(B
);
1696 bool GetElementPtrInst::isInBounds() const {
1697 return cast
<GEPOperator
>(this)->isInBounds();
1700 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout
&DL
,
1701 APInt
&Offset
) const {
1702 // Delegate to the generic GEPOperator implementation.
1703 return cast
<GEPOperator
>(this)->accumulateConstantOffset(DL
, Offset
);
1706 //===----------------------------------------------------------------------===//
1707 // ExtractElementInst Implementation
1708 //===----------------------------------------------------------------------===//
1710 ExtractElementInst::ExtractElementInst(Value
*Val
, Value
*Index
,
1712 Instruction
*InsertBef
)
1713 : Instruction(cast
<VectorType
>(Val
->getType())->getElementType(),
1715 OperandTraits
<ExtractElementInst
>::op_begin(this),
1717 assert(isValidOperands(Val
, Index
) &&
1718 "Invalid extractelement instruction operands!");
1724 ExtractElementInst::ExtractElementInst(Value
*Val
, Value
*Index
,
1726 BasicBlock
*InsertAE
)
1727 : Instruction(cast
<VectorType
>(Val
->getType())->getElementType(),
1729 OperandTraits
<ExtractElementInst
>::op_begin(this),
1731 assert(isValidOperands(Val
, Index
) &&
1732 "Invalid extractelement instruction operands!");
1739 bool ExtractElementInst::isValidOperands(const Value
*Val
, const Value
*Index
) {
1740 if (!Val
->getType()->isVectorTy() || !Index
->getType()->isIntegerTy())
1745 //===----------------------------------------------------------------------===//
1746 // InsertElementInst Implementation
1747 //===----------------------------------------------------------------------===//
1749 InsertElementInst::InsertElementInst(Value
*Vec
, Value
*Elt
, Value
*Index
,
1751 Instruction
*InsertBef
)
1752 : Instruction(Vec
->getType(), InsertElement
,
1753 OperandTraits
<InsertElementInst
>::op_begin(this),
1755 assert(isValidOperands(Vec
, Elt
, Index
) &&
1756 "Invalid insertelement instruction operands!");
1763 InsertElementInst::InsertElementInst(Value
*Vec
, Value
*Elt
, Value
*Index
,
1765 BasicBlock
*InsertAE
)
1766 : Instruction(Vec
->getType(), InsertElement
,
1767 OperandTraits
<InsertElementInst
>::op_begin(this),
1769 assert(isValidOperands(Vec
, Elt
, Index
) &&
1770 "Invalid insertelement instruction operands!");
1778 bool InsertElementInst::isValidOperands(const Value
*Vec
, const Value
*Elt
,
1779 const Value
*Index
) {
1780 if (!Vec
->getType()->isVectorTy())
1781 return false; // First operand of insertelement must be vector type.
1783 if (Elt
->getType() != cast
<VectorType
>(Vec
->getType())->getElementType())
1784 return false;// Second operand of insertelement must be vector element type.
1786 if (!Index
->getType()->isIntegerTy())
1787 return false; // Third operand of insertelement must be i32.
1791 //===----------------------------------------------------------------------===//
1792 // ShuffleVectorInst Implementation
1793 //===----------------------------------------------------------------------===//
1795 ShuffleVectorInst::ShuffleVectorInst(Value
*V1
, Value
*V2
, Value
*Mask
,
1797 Instruction
*InsertBefore
)
1798 : Instruction(VectorType::get(cast
<VectorType
>(V1
->getType())->getElementType(),
1799 cast
<VectorType
>(Mask
->getType())->getNumElements()),
1801 OperandTraits
<ShuffleVectorInst
>::op_begin(this),
1802 OperandTraits
<ShuffleVectorInst
>::operands(this),
1804 assert(isValidOperands(V1
, V2
, Mask
) &&
1805 "Invalid shuffle vector instruction operands!");
1812 ShuffleVectorInst::ShuffleVectorInst(Value
*V1
, Value
*V2
, Value
*Mask
,
1814 BasicBlock
*InsertAtEnd
)
1815 : Instruction(VectorType::get(cast
<VectorType
>(V1
->getType())->getElementType(),
1816 cast
<VectorType
>(Mask
->getType())->getNumElements()),
1818 OperandTraits
<ShuffleVectorInst
>::op_begin(this),
1819 OperandTraits
<ShuffleVectorInst
>::operands(this),
1821 assert(isValidOperands(V1
, V2
, Mask
) &&
1822 "Invalid shuffle vector instruction operands!");
1830 void ShuffleVectorInst::commute() {
1831 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
1832 int NumMaskElts
= getMask()->getType()->getVectorNumElements();
1833 SmallVector
<Constant
*, 16> NewMask(NumMaskElts
);
1834 Type
*Int32Ty
= Type::getInt32Ty(getContext());
1835 for (int i
= 0; i
!= NumMaskElts
; ++i
) {
1836 int MaskElt
= getMaskValue(i
);
1837 if (MaskElt
== -1) {
1838 NewMask
[i
] = UndefValue::get(Int32Ty
);
1841 assert(MaskElt
>= 0 && MaskElt
< 2 * NumOpElts
&& "Out-of-range mask");
1842 MaskElt
= (MaskElt
< NumOpElts
) ? MaskElt
+ NumOpElts
: MaskElt
- NumOpElts
;
1843 NewMask
[i
] = ConstantInt::get(Int32Ty
, MaskElt
);
1845 Op
<2>() = ConstantVector::get(NewMask
);
1846 Op
<0>().swap(Op
<1>());
1849 bool ShuffleVectorInst::isValidOperands(const Value
*V1
, const Value
*V2
,
1850 const Value
*Mask
) {
1851 // V1 and V2 must be vectors of the same type.
1852 if (!V1
->getType()->isVectorTy() || V1
->getType() != V2
->getType())
1855 // Mask must be vector of i32.
1856 auto *MaskTy
= dyn_cast
<VectorType
>(Mask
->getType());
1857 if (!MaskTy
|| !MaskTy
->getElementType()->isIntegerTy(32))
1860 // Check to see if Mask is valid.
1861 if (isa
<UndefValue
>(Mask
) || isa
<ConstantAggregateZero
>(Mask
))
1864 if (const auto *MV
= dyn_cast
<ConstantVector
>(Mask
)) {
1865 unsigned V1Size
= cast
<VectorType
>(V1
->getType())->getNumElements();
1866 for (Value
*Op
: MV
->operands()) {
1867 if (auto *CI
= dyn_cast
<ConstantInt
>(Op
)) {
1868 if (CI
->uge(V1Size
*2))
1870 } else if (!isa
<UndefValue
>(Op
)) {
1877 if (const auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
)) {
1878 unsigned V1Size
= cast
<VectorType
>(V1
->getType())->getNumElements();
1879 for (unsigned i
= 0, e
= MaskTy
->getNumElements(); i
!= e
; ++i
)
1880 if (CDS
->getElementAsInteger(i
) >= V1Size
*2)
1885 // The bitcode reader can create a place holder for a forward reference
1886 // used as the shuffle mask. When this occurs, the shuffle mask will
1887 // fall into this case and fail. To avoid this error, do this bit of
1888 // ugliness to allow such a mask pass.
1889 if (const auto *CE
= dyn_cast
<ConstantExpr
>(Mask
))
1890 if (CE
->getOpcode() == Instruction::UserOp1
)
1896 int ShuffleVectorInst::getMaskValue(const Constant
*Mask
, unsigned i
) {
1897 assert(i
< Mask
->getType()->getVectorNumElements() && "Index out of range");
1898 if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
))
1899 return CDS
->getElementAsInteger(i
);
1900 Constant
*C
= Mask
->getAggregateElement(i
);
1901 if (isa
<UndefValue
>(C
))
1903 return cast
<ConstantInt
>(C
)->getZExtValue();
1906 void ShuffleVectorInst::getShuffleMask(const Constant
*Mask
,
1907 SmallVectorImpl
<int> &Result
) {
1908 unsigned NumElts
= Mask
->getType()->getVectorNumElements();
1910 if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
)) {
1911 for (unsigned i
= 0; i
!= NumElts
; ++i
)
1912 Result
.push_back(CDS
->getElementAsInteger(i
));
1915 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
1916 Constant
*C
= Mask
->getAggregateElement(i
);
1917 Result
.push_back(isa
<UndefValue
>(C
) ? -1 :
1918 cast
<ConstantInt
>(C
)->getZExtValue());
1922 static bool isSingleSourceMaskImpl(ArrayRef
<int> Mask
, int NumOpElts
) {
1923 assert(!Mask
.empty() && "Shuffle mask must contain elements");
1924 bool UsesLHS
= false;
1925 bool UsesRHS
= false;
1926 for (int i
= 0, NumMaskElts
= Mask
.size(); i
< NumMaskElts
; ++i
) {
1929 assert(Mask
[i
] >= 0 && Mask
[i
] < (NumOpElts
* 2) &&
1930 "Out-of-bounds shuffle mask element");
1931 UsesLHS
|= (Mask
[i
] < NumOpElts
);
1932 UsesRHS
|= (Mask
[i
] >= NumOpElts
);
1933 if (UsesLHS
&& UsesRHS
)
1936 assert((UsesLHS
^ UsesRHS
) && "Should have selected from exactly 1 source");
1940 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef
<int> Mask
) {
1941 // We don't have vector operand size information, so assume operands are the
1942 // same size as the mask.
1943 return isSingleSourceMaskImpl(Mask
, Mask
.size());
1946 static bool isIdentityMaskImpl(ArrayRef
<int> Mask
, int NumOpElts
) {
1947 if (!isSingleSourceMaskImpl(Mask
, NumOpElts
))
1949 for (int i
= 0, NumMaskElts
= Mask
.size(); i
< NumMaskElts
; ++i
) {
1952 if (Mask
[i
] != i
&& Mask
[i
] != (NumOpElts
+ i
))
1958 bool ShuffleVectorInst::isIdentityMask(ArrayRef
<int> Mask
) {
1959 // We don't have vector operand size information, so assume operands are the
1960 // same size as the mask.
1961 return isIdentityMaskImpl(Mask
, Mask
.size());
1964 bool ShuffleVectorInst::isReverseMask(ArrayRef
<int> Mask
) {
1965 if (!isSingleSourceMask(Mask
))
1967 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1970 if (Mask
[i
] != (NumElts
- 1 - i
) && Mask
[i
] != (NumElts
+ NumElts
- 1 - i
))
1976 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef
<int> Mask
) {
1977 if (!isSingleSourceMask(Mask
))
1979 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1982 if (Mask
[i
] != 0 && Mask
[i
] != NumElts
)
1988 bool ShuffleVectorInst::isSelectMask(ArrayRef
<int> Mask
) {
1989 // Select is differentiated from identity. It requires using both sources.
1990 if (isSingleSourceMask(Mask
))
1992 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1995 if (Mask
[i
] != i
&& Mask
[i
] != (NumElts
+ i
))
2001 bool ShuffleVectorInst::isTransposeMask(ArrayRef
<int> Mask
) {
2002 // Example masks that will return true:
2003 // v1 = <a, b, c, d>
2004 // v2 = <e, f, g, h>
2005 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
2006 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
2008 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
2009 int NumElts
= Mask
.size();
2010 if (NumElts
< 2 || !isPowerOf2_32(NumElts
))
2013 // 2. The first element of the mask must be either a 0 or a 1.
2014 if (Mask
[0] != 0 && Mask
[0] != 1)
2017 // 3. The difference between the first 2 elements must be equal to the
2018 // number of elements in the mask.
2019 if ((Mask
[1] - Mask
[0]) != NumElts
)
2022 // 4. The difference between consecutive even-numbered and odd-numbered
2023 // elements must be equal to 2.
2024 for (int i
= 2; i
< NumElts
; ++i
) {
2025 int MaskEltVal
= Mask
[i
];
2026 if (MaskEltVal
== -1)
2028 int MaskEltPrevVal
= Mask
[i
- 2];
2029 if (MaskEltVal
- MaskEltPrevVal
!= 2)
2035 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef
<int> Mask
,
2036 int NumSrcElts
, int &Index
) {
2037 // Must extract from a single source.
2038 if (!isSingleSourceMaskImpl(Mask
, NumSrcElts
))
2041 // Must be smaller (else this is an Identity shuffle).
2042 if (NumSrcElts
<= (int)Mask
.size())
2045 // Find start of extraction, accounting that we may start with an UNDEF.
2047 for (int i
= 0, e
= Mask
.size(); i
!= e
; ++i
) {
2051 int Offset
= (M
% NumSrcElts
) - i
;
2052 if (0 <= SubIndex
&& SubIndex
!= Offset
)
2057 if (0 <= SubIndex
) {
2064 bool ShuffleVectorInst::isIdentityWithPadding() const {
2065 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2066 int NumMaskElts
= getType()->getVectorNumElements();
2067 if (NumMaskElts
<= NumOpElts
)
2070 // The first part of the mask must choose elements from exactly 1 source op.
2071 SmallVector
<int, 16> Mask
= getShuffleMask();
2072 if (!isIdentityMaskImpl(Mask
, NumOpElts
))
2075 // All extending must be with undef elements.
2076 for (int i
= NumOpElts
; i
< NumMaskElts
; ++i
)
2083 bool ShuffleVectorInst::isIdentityWithExtract() const {
2084 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2085 int NumMaskElts
= getType()->getVectorNumElements();
2086 if (NumMaskElts
>= NumOpElts
)
2089 return isIdentityMaskImpl(getShuffleMask(), NumOpElts
);
2092 bool ShuffleVectorInst::isConcat() const {
2093 // Vector concatenation is differentiated from identity with padding.
2094 if (isa
<UndefValue
>(Op
<0>()) || isa
<UndefValue
>(Op
<1>()))
2097 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2098 int NumMaskElts
= getType()->getVectorNumElements();
2099 if (NumMaskElts
!= NumOpElts
* 2)
2102 // Use the mask length rather than the operands' vector lengths here. We
2103 // already know that the shuffle returns a vector twice as long as the inputs,
2104 // and neither of the inputs are undef vectors. If the mask picks consecutive
2105 // elements from both inputs, then this is a concatenation of the inputs.
2106 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts
);
2109 //===----------------------------------------------------------------------===//
2110 // InsertValueInst Class
2111 //===----------------------------------------------------------------------===//
2113 void InsertValueInst::init(Value
*Agg
, Value
*Val
, ArrayRef
<unsigned> Idxs
,
2114 const Twine
&Name
) {
2115 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2117 // There's no fundamental reason why we require at least one index
2118 // (other than weirdness with &*IdxBegin being invalid; see
2119 // getelementptr's init routine for example). But there's no
2120 // present need to support it.
2121 assert(!Idxs
.empty() && "InsertValueInst must have at least one index");
2123 assert(ExtractValueInst::getIndexedType(Agg
->getType(), Idxs
) ==
2124 Val
->getType() && "Inserted value must match indexed type!");
2128 Indices
.append(Idxs
.begin(), Idxs
.end());
2132 InsertValueInst::InsertValueInst(const InsertValueInst
&IVI
)
2133 : Instruction(IVI
.getType(), InsertValue
,
2134 OperandTraits
<InsertValueInst
>::op_begin(this), 2),
2135 Indices(IVI
.Indices
) {
2136 Op
<0>() = IVI
.getOperand(0);
2137 Op
<1>() = IVI
.getOperand(1);
2138 SubclassOptionalData
= IVI
.SubclassOptionalData
;
2141 //===----------------------------------------------------------------------===//
2142 // ExtractValueInst Class
2143 //===----------------------------------------------------------------------===//
2145 void ExtractValueInst::init(ArrayRef
<unsigned> Idxs
, const Twine
&Name
) {
2146 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2148 // There's no fundamental reason why we require at least one index.
2149 // But there's no present need to support it.
2150 assert(!Idxs
.empty() && "ExtractValueInst must have at least one index");
2152 Indices
.append(Idxs
.begin(), Idxs
.end());
2156 ExtractValueInst::ExtractValueInst(const ExtractValueInst
&EVI
)
2157 : UnaryInstruction(EVI
.getType(), ExtractValue
, EVI
.getOperand(0)),
2158 Indices(EVI
.Indices
) {
2159 SubclassOptionalData
= EVI
.SubclassOptionalData
;
2162 // getIndexedType - Returns the type of the element that would be extracted
2163 // with an extractvalue instruction with the specified parameters.
2165 // A null type is returned if the indices are invalid for the specified
2168 Type
*ExtractValueInst::getIndexedType(Type
*Agg
,
2169 ArrayRef
<unsigned> Idxs
) {
2170 for (unsigned Index
: Idxs
) {
2171 // We can't use CompositeType::indexValid(Index) here.
2172 // indexValid() always returns true for arrays because getelementptr allows
2173 // out-of-bounds indices. Since we don't allow those for extractvalue and
2174 // insertvalue we need to check array indexing manually.
2175 // Since the only other types we can index into are struct types it's just
2176 // as easy to check those manually as well.
2177 if (ArrayType
*AT
= dyn_cast
<ArrayType
>(Agg
)) {
2178 if (Index
>= AT
->getNumElements())
2180 } else if (StructType
*ST
= dyn_cast
<StructType
>(Agg
)) {
2181 if (Index
>= ST
->getNumElements())
2184 // Not a valid type to index into.
2188 Agg
= cast
<CompositeType
>(Agg
)->getTypeAtIndex(Index
);
2190 return const_cast<Type
*>(Agg
);
2193 //===----------------------------------------------------------------------===//
2194 // UnaryOperator Class
2195 //===----------------------------------------------------------------------===//
2197 UnaryOperator::UnaryOperator(UnaryOps iType
, Value
*S
,
2198 Type
*Ty
, const Twine
&Name
,
2199 Instruction
*InsertBefore
)
2200 : UnaryInstruction(Ty
, iType
, S
, InsertBefore
) {
2206 UnaryOperator::UnaryOperator(UnaryOps iType
, Value
*S
,
2207 Type
*Ty
, const Twine
&Name
,
2208 BasicBlock
*InsertAtEnd
)
2209 : UnaryInstruction(Ty
, iType
, S
, InsertAtEnd
) {
2215 UnaryOperator
*UnaryOperator::Create(UnaryOps Op
, Value
*S
,
2217 Instruction
*InsertBefore
) {
2218 return new UnaryOperator(Op
, S
, S
->getType(), Name
, InsertBefore
);
2221 UnaryOperator
*UnaryOperator::Create(UnaryOps Op
, Value
*S
,
2223 BasicBlock
*InsertAtEnd
) {
2224 UnaryOperator
*Res
= Create(Op
, S
, Name
);
2225 InsertAtEnd
->getInstList().push_back(Res
);
2229 void UnaryOperator::AssertOK() {
2230 Value
*LHS
= getOperand(0);
2231 (void)LHS
; // Silence warnings.
2233 switch (getOpcode()) {
2235 assert(getType() == LHS
->getType() &&
2236 "Unary operation should return same type as operand!");
2237 assert(getType()->isFPOrFPVectorTy() &&
2238 "Tried to create a floating-point operation on a "
2239 "non-floating-point type!");
2241 default: llvm_unreachable("Invalid opcode provided");
2246 //===----------------------------------------------------------------------===//
2247 // BinaryOperator Class
2248 //===----------------------------------------------------------------------===//
2250 BinaryOperator::BinaryOperator(BinaryOps iType
, Value
*S1
, Value
*S2
,
2251 Type
*Ty
, const Twine
&Name
,
2252 Instruction
*InsertBefore
)
2253 : Instruction(Ty
, iType
,
2254 OperandTraits
<BinaryOperator
>::op_begin(this),
2255 OperandTraits
<BinaryOperator
>::operands(this),
2263 BinaryOperator::BinaryOperator(BinaryOps iType
, Value
*S1
, Value
*S2
,
2264 Type
*Ty
, const Twine
&Name
,
2265 BasicBlock
*InsertAtEnd
)
2266 : Instruction(Ty
, iType
,
2267 OperandTraits
<BinaryOperator
>::op_begin(this),
2268 OperandTraits
<BinaryOperator
>::operands(this),
2276 void BinaryOperator::AssertOK() {
2277 Value
*LHS
= getOperand(0), *RHS
= getOperand(1);
2278 (void)LHS
; (void)RHS
; // Silence warnings.
2279 assert(LHS
->getType() == RHS
->getType() &&
2280 "Binary operator operand types must match!");
2282 switch (getOpcode()) {
2285 assert(getType() == LHS
->getType() &&
2286 "Arithmetic operation should return same type as operands!");
2287 assert(getType()->isIntOrIntVectorTy() &&
2288 "Tried to create an integer operation on a non-integer type!");
2290 case FAdd
: case FSub
:
2292 assert(getType() == LHS
->getType() &&
2293 "Arithmetic operation should return same type as operands!");
2294 assert(getType()->isFPOrFPVectorTy() &&
2295 "Tried to create a floating-point operation on a "
2296 "non-floating-point type!");
2300 assert(getType() == LHS
->getType() &&
2301 "Arithmetic operation should return same type as operands!");
2302 assert(getType()->isIntOrIntVectorTy() &&
2303 "Incorrect operand type (not integer) for S/UDIV");
2306 assert(getType() == LHS
->getType() &&
2307 "Arithmetic operation should return same type as operands!");
2308 assert(getType()->isFPOrFPVectorTy() &&
2309 "Incorrect operand type (not floating point) for FDIV");
2313 assert(getType() == LHS
->getType() &&
2314 "Arithmetic operation should return same type as operands!");
2315 assert(getType()->isIntOrIntVectorTy() &&
2316 "Incorrect operand type (not integer) for S/UREM");
2319 assert(getType() == LHS
->getType() &&
2320 "Arithmetic operation should return same type as operands!");
2321 assert(getType()->isFPOrFPVectorTy() &&
2322 "Incorrect operand type (not floating point) for FREM");
2327 assert(getType() == LHS
->getType() &&
2328 "Shift operation should return same type as operands!");
2329 assert(getType()->isIntOrIntVectorTy() &&
2330 "Tried to create a shift operation on a non-integral type!");
2334 assert(getType() == LHS
->getType() &&
2335 "Logical operation should return same type as operands!");
2336 assert(getType()->isIntOrIntVectorTy() &&
2337 "Tried to create a logical operation on a non-integral type!");
2339 default: llvm_unreachable("Invalid opcode provided");
2344 BinaryOperator
*BinaryOperator::Create(BinaryOps Op
, Value
*S1
, Value
*S2
,
2346 Instruction
*InsertBefore
) {
2347 assert(S1
->getType() == S2
->getType() &&
2348 "Cannot create binary operator with two operands of differing type!");
2349 return new BinaryOperator(Op
, S1
, S2
, S1
->getType(), Name
, InsertBefore
);
2352 BinaryOperator
*BinaryOperator::Create(BinaryOps Op
, Value
*S1
, Value
*S2
,
2354 BasicBlock
*InsertAtEnd
) {
2355 BinaryOperator
*Res
= Create(Op
, S1
, S2
, Name
);
2356 InsertAtEnd
->getInstList().push_back(Res
);
2360 BinaryOperator
*BinaryOperator::CreateNeg(Value
*Op
, const Twine
&Name
,
2361 Instruction
*InsertBefore
) {
2362 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2363 return new BinaryOperator(Instruction::Sub
,
2365 Op
->getType(), Name
, InsertBefore
);
2368 BinaryOperator
*BinaryOperator::CreateNeg(Value
*Op
, const Twine
&Name
,
2369 BasicBlock
*InsertAtEnd
) {
2370 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2371 return new BinaryOperator(Instruction::Sub
,
2373 Op
->getType(), Name
, InsertAtEnd
);
2376 BinaryOperator
*BinaryOperator::CreateNSWNeg(Value
*Op
, const Twine
&Name
,
2377 Instruction
*InsertBefore
) {
2378 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2379 return BinaryOperator::CreateNSWSub(zero
, Op
, Name
, InsertBefore
);
2382 BinaryOperator
*BinaryOperator::CreateNSWNeg(Value
*Op
, const Twine
&Name
,
2383 BasicBlock
*InsertAtEnd
) {
2384 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2385 return BinaryOperator::CreateNSWSub(zero
, Op
, Name
, InsertAtEnd
);
2388 BinaryOperator
*BinaryOperator::CreateNUWNeg(Value
*Op
, const Twine
&Name
,
2389 Instruction
*InsertBefore
) {
2390 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2391 return BinaryOperator::CreateNUWSub(zero
, Op
, Name
, InsertBefore
);
2394 BinaryOperator
*BinaryOperator::CreateNUWNeg(Value
*Op
, const Twine
&Name
,
2395 BasicBlock
*InsertAtEnd
) {
2396 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2397 return BinaryOperator::CreateNUWSub(zero
, Op
, Name
, InsertAtEnd
);
2400 BinaryOperator
*BinaryOperator::CreateFNeg(Value
*Op
, const Twine
&Name
,
2401 Instruction
*InsertBefore
) {
2402 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2403 return new BinaryOperator(Instruction::FSub
, zero
, Op
,
2404 Op
->getType(), Name
, InsertBefore
);
2407 BinaryOperator
*BinaryOperator::CreateFNeg(Value
*Op
, const Twine
&Name
,
2408 BasicBlock
*InsertAtEnd
) {
2409 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2410 return new BinaryOperator(Instruction::FSub
, zero
, Op
,
2411 Op
->getType(), Name
, InsertAtEnd
);
2414 BinaryOperator
*BinaryOperator::CreateNot(Value
*Op
, const Twine
&Name
,
2415 Instruction
*InsertBefore
) {
2416 Constant
*C
= Constant::getAllOnesValue(Op
->getType());
2417 return new BinaryOperator(Instruction::Xor
, Op
, C
,
2418 Op
->getType(), Name
, InsertBefore
);
2421 BinaryOperator
*BinaryOperator::CreateNot(Value
*Op
, const Twine
&Name
,
2422 BasicBlock
*InsertAtEnd
) {
2423 Constant
*AllOnes
= Constant::getAllOnesValue(Op
->getType());
2424 return new BinaryOperator(Instruction::Xor
, Op
, AllOnes
,
2425 Op
->getType(), Name
, InsertAtEnd
);
2428 // Exchange the two operands to this instruction. This instruction is safe to
2429 // use on any binary instruction and does not modify the semantics of the
2430 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2432 bool BinaryOperator::swapOperands() {
2433 if (!isCommutative())
2434 return true; // Can't commute operands
2435 Op
<0>().swap(Op
<1>());
2439 //===----------------------------------------------------------------------===//
2440 // FPMathOperator Class
2441 //===----------------------------------------------------------------------===//
2443 float FPMathOperator::getFPAccuracy() const {
2445 cast
<Instruction
>(this)->getMetadata(LLVMContext::MD_fpmath
);
2448 ConstantFP
*Accuracy
= mdconst::extract
<ConstantFP
>(MD
->getOperand(0));
2449 return Accuracy
->getValueAPF().convertToFloat();
2452 //===----------------------------------------------------------------------===//
2454 //===----------------------------------------------------------------------===//
2456 // Just determine if this cast only deals with integral->integral conversion.
2457 bool CastInst::isIntegerCast() const {
2458 switch (getOpcode()) {
2459 default: return false;
2460 case Instruction::ZExt
:
2461 case Instruction::SExt
:
2462 case Instruction::Trunc
:
2464 case Instruction::BitCast
:
2465 return getOperand(0)->getType()->isIntegerTy() &&
2466 getType()->isIntegerTy();
2470 bool CastInst::isLosslessCast() const {
2471 // Only BitCast can be lossless, exit fast if we're not BitCast
2472 if (getOpcode() != Instruction::BitCast
)
2475 // Identity cast is always lossless
2476 Type
*SrcTy
= getOperand(0)->getType();
2477 Type
*DstTy
= getType();
2481 // Pointer to pointer is always lossless.
2482 if (SrcTy
->isPointerTy())
2483 return DstTy
->isPointerTy();
2484 return false; // Other types have no identity values
2487 /// This function determines if the CastInst does not require any bits to be
2488 /// changed in order to effect the cast. Essentially, it identifies cases where
2489 /// no code gen is necessary for the cast, hence the name no-op cast. For
2490 /// example, the following are all no-op casts:
2491 /// # bitcast i32* %x to i8*
2492 /// # bitcast <2 x i32> %x to <4 x i16>
2493 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2494 /// Determine if the described cast is a no-op.
2495 bool CastInst::isNoopCast(Instruction::CastOps Opcode
,
2498 const DataLayout
&DL
) {
2500 default: llvm_unreachable("Invalid CastOp");
2501 case Instruction::Trunc
:
2502 case Instruction::ZExt
:
2503 case Instruction::SExt
:
2504 case Instruction::FPTrunc
:
2505 case Instruction::FPExt
:
2506 case Instruction::UIToFP
:
2507 case Instruction::SIToFP
:
2508 case Instruction::FPToUI
:
2509 case Instruction::FPToSI
:
2510 case Instruction::AddrSpaceCast
:
2511 // TODO: Target informations may give a more accurate answer here.
2513 case Instruction::BitCast
:
2514 return true; // BitCast never modifies bits.
2515 case Instruction::PtrToInt
:
2516 return DL
.getIntPtrType(SrcTy
)->getScalarSizeInBits() ==
2517 DestTy
->getScalarSizeInBits();
2518 case Instruction::IntToPtr
:
2519 return DL
.getIntPtrType(DestTy
)->getScalarSizeInBits() ==
2520 SrcTy
->getScalarSizeInBits();
2524 bool CastInst::isNoopCast(const DataLayout
&DL
) const {
2525 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL
);
2528 /// This function determines if a pair of casts can be eliminated and what
2529 /// opcode should be used in the elimination. This assumes that there are two
2530 /// instructions like this:
2531 /// * %F = firstOpcode SrcTy %x to MidTy
2532 /// * %S = secondOpcode MidTy %F to DstTy
2533 /// The function returns a resultOpcode so these two casts can be replaced with:
2534 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2535 /// If no such cast is permitted, the function returns 0.
2536 unsigned CastInst::isEliminableCastPair(
2537 Instruction::CastOps firstOp
, Instruction::CastOps secondOp
,
2538 Type
*SrcTy
, Type
*MidTy
, Type
*DstTy
, Type
*SrcIntPtrTy
, Type
*MidIntPtrTy
,
2539 Type
*DstIntPtrTy
) {
2540 // Define the 144 possibilities for these two cast instructions. The values
2541 // in this matrix determine what to do in a given situation and select the
2542 // case in the switch below. The rows correspond to firstOp, the columns
2543 // correspond to secondOp. In looking at the table below, keep in mind
2544 // the following cast properties:
2546 // Size Compare Source Destination
2547 // Operator Src ? Size Type Sign Type Sign
2548 // -------- ------------ ------------------- ---------------------
2549 // TRUNC > Integer Any Integral Any
2550 // ZEXT < Integral Unsigned Integer Any
2551 // SEXT < Integral Signed Integer Any
2552 // FPTOUI n/a FloatPt n/a Integral Unsigned
2553 // FPTOSI n/a FloatPt n/a Integral Signed
2554 // UITOFP n/a Integral Unsigned FloatPt n/a
2555 // SITOFP n/a Integral Signed FloatPt n/a
2556 // FPTRUNC > FloatPt n/a FloatPt n/a
2557 // FPEXT < FloatPt n/a FloatPt n/a
2558 // PTRTOINT n/a Pointer n/a Integral Unsigned
2559 // INTTOPTR n/a Integral Unsigned Pointer n/a
2560 // BITCAST = FirstClass n/a FirstClass n/a
2561 // ADDRSPCST n/a Pointer n/a Pointer n/a
2563 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2564 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2565 // into "fptoui double to i64", but this loses information about the range
2566 // of the produced value (we no longer know the top-part is all zeros).
2567 // Further this conversion is often much more expensive for typical hardware,
2568 // and causes issues when building libgcc. We disallow fptosi+sext for the
2570 const unsigned numCastOps
=
2571 Instruction::CastOpsEnd
- Instruction::CastOpsBegin
;
2572 static const uint8_t CastResults
[numCastOps
][numCastOps
] = {
2573 // T F F U S F F P I B A -+
2574 // R Z S P P I I T P 2 N T S |
2575 // U E E 2 2 2 2 R E I T C C +- secondOp
2576 // N X X U S F F N X N 2 V V |
2577 // C T T I I P P C T T P T T -+
2578 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2579 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2580 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2581 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2582 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2583 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2584 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2585 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2586 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
2587 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2588 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2589 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2590 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2593 // TODO: This logic could be encoded into the table above and handled in the
2595 // If either of the casts are a bitcast from scalar to vector, disallow the
2596 // merging. However, any pair of bitcasts are allowed.
2597 bool IsFirstBitcast
= (firstOp
== Instruction::BitCast
);
2598 bool IsSecondBitcast
= (secondOp
== Instruction::BitCast
);
2599 bool AreBothBitcasts
= IsFirstBitcast
&& IsSecondBitcast
;
2601 // Check if any of the casts convert scalars <-> vectors.
2602 if ((IsFirstBitcast
&& isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(MidTy
)) ||
2603 (IsSecondBitcast
&& isa
<VectorType
>(MidTy
) != isa
<VectorType
>(DstTy
)))
2604 if (!AreBothBitcasts
)
2607 int ElimCase
= CastResults
[firstOp
-Instruction::CastOpsBegin
]
2608 [secondOp
-Instruction::CastOpsBegin
];
2611 // Categorically disallowed.
2614 // Allowed, use first cast's opcode.
2617 // Allowed, use second cast's opcode.
2620 // No-op cast in second op implies firstOp as long as the DestTy
2621 // is integer and we are not converting between a vector and a
2623 if (!SrcTy
->isVectorTy() && DstTy
->isIntegerTy())
2627 // No-op cast in second op implies firstOp as long as the DestTy
2628 // is floating point.
2629 if (DstTy
->isFloatingPointTy())
2633 // No-op cast in first op implies secondOp as long as the SrcTy
2635 if (SrcTy
->isIntegerTy())
2639 // No-op cast in first op implies secondOp as long as the SrcTy
2640 // is a floating point.
2641 if (SrcTy
->isFloatingPointTy())
2645 // Cannot simplify if address spaces are different!
2646 if (SrcTy
->getPointerAddressSpace() != DstTy
->getPointerAddressSpace())
2649 unsigned MidSize
= MidTy
->getScalarSizeInBits();
2650 // We can still fold this without knowing the actual sizes as long we
2651 // know that the intermediate pointer is the largest possible
2653 // FIXME: Is this always true?
2655 return Instruction::BitCast
;
2657 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2658 if (!SrcIntPtrTy
|| DstIntPtrTy
!= SrcIntPtrTy
)
2660 unsigned PtrSize
= SrcIntPtrTy
->getScalarSizeInBits();
2661 if (MidSize
>= PtrSize
)
2662 return Instruction::BitCast
;
2666 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2667 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2668 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2669 unsigned SrcSize
= SrcTy
->getScalarSizeInBits();
2670 unsigned DstSize
= DstTy
->getScalarSizeInBits();
2671 if (SrcSize
== DstSize
)
2672 return Instruction::BitCast
;
2673 else if (SrcSize
< DstSize
)
2678 // zext, sext -> zext, because sext can't sign extend after zext
2679 return Instruction::ZExt
;
2681 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2684 unsigned PtrSize
= MidIntPtrTy
->getScalarSizeInBits();
2685 unsigned SrcSize
= SrcTy
->getScalarSizeInBits();
2686 unsigned DstSize
= DstTy
->getScalarSizeInBits();
2687 if (SrcSize
<= PtrSize
&& SrcSize
== DstSize
)
2688 return Instruction::BitCast
;
2692 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2693 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2694 if (SrcTy
->getPointerAddressSpace() != DstTy
->getPointerAddressSpace())
2695 return Instruction::AddrSpaceCast
;
2696 return Instruction::BitCast
;
2698 // FIXME: this state can be merged with (1), but the following assert
2699 // is useful to check the correcteness of the sequence due to semantic
2700 // change of bitcast.
2702 SrcTy
->isPtrOrPtrVectorTy() &&
2703 MidTy
->isPtrOrPtrVectorTy() &&
2704 DstTy
->isPtrOrPtrVectorTy() &&
2705 SrcTy
->getPointerAddressSpace() != MidTy
->getPointerAddressSpace() &&
2706 MidTy
->getPointerAddressSpace() == DstTy
->getPointerAddressSpace() &&
2707 "Illegal addrspacecast, bitcast sequence!");
2708 // Allowed, use first cast's opcode
2711 // bitcast, addrspacecast -> addrspacecast if the element type of
2712 // bitcast's source is the same as that of addrspacecast's destination.
2713 if (SrcTy
->getScalarType()->getPointerElementType() ==
2714 DstTy
->getScalarType()->getPointerElementType())
2715 return Instruction::AddrSpaceCast
;
2718 // FIXME: this state can be merged with (1), but the following assert
2719 // is useful to check the correcteness of the sequence due to semantic
2720 // change of bitcast.
2722 SrcTy
->isIntOrIntVectorTy() &&
2723 MidTy
->isPtrOrPtrVectorTy() &&
2724 DstTy
->isPtrOrPtrVectorTy() &&
2725 MidTy
->getPointerAddressSpace() == DstTy
->getPointerAddressSpace() &&
2726 "Illegal inttoptr, bitcast sequence!");
2727 // Allowed, use first cast's opcode
2730 // FIXME: this state can be merged with (2), but the following assert
2731 // is useful to check the correcteness of the sequence due to semantic
2732 // change of bitcast.
2734 SrcTy
->isPtrOrPtrVectorTy() &&
2735 MidTy
->isPtrOrPtrVectorTy() &&
2736 DstTy
->isIntOrIntVectorTy() &&
2737 SrcTy
->getPointerAddressSpace() == MidTy
->getPointerAddressSpace() &&
2738 "Illegal bitcast, ptrtoint sequence!");
2739 // Allowed, use second cast's opcode
2742 // (sitofp (zext x)) -> (uitofp x)
2743 return Instruction::UIToFP
;
2745 // Cast combination can't happen (error in input). This is for all cases
2746 // where the MidTy is not the same for the two cast instructions.
2747 llvm_unreachable("Invalid Cast Combination");
2749 llvm_unreachable("Error in CastResults table!!!");
2753 CastInst
*CastInst::Create(Instruction::CastOps op
, Value
*S
, Type
*Ty
,
2754 const Twine
&Name
, Instruction
*InsertBefore
) {
2755 assert(castIsValid(op
, S
, Ty
) && "Invalid cast!");
2756 // Construct and return the appropriate CastInst subclass
2758 case Trunc
: return new TruncInst (S
, Ty
, Name
, InsertBefore
);
2759 case ZExt
: return new ZExtInst (S
, Ty
, Name
, InsertBefore
);
2760 case SExt
: return new SExtInst (S
, Ty
, Name
, InsertBefore
);
2761 case FPTrunc
: return new FPTruncInst (S
, Ty
, Name
, InsertBefore
);
2762 case FPExt
: return new FPExtInst (S
, Ty
, Name
, InsertBefore
);
2763 case UIToFP
: return new UIToFPInst (S
, Ty
, Name
, InsertBefore
);
2764 case SIToFP
: return new SIToFPInst (S
, Ty
, Name
, InsertBefore
);
2765 case FPToUI
: return new FPToUIInst (S
, Ty
, Name
, InsertBefore
);
2766 case FPToSI
: return new FPToSIInst (S
, Ty
, Name
, InsertBefore
);
2767 case PtrToInt
: return new PtrToIntInst (S
, Ty
, Name
, InsertBefore
);
2768 case IntToPtr
: return new IntToPtrInst (S
, Ty
, Name
, InsertBefore
);
2769 case BitCast
: return new BitCastInst (S
, Ty
, Name
, InsertBefore
);
2770 case AddrSpaceCast
: return new AddrSpaceCastInst (S
, Ty
, Name
, InsertBefore
);
2771 default: llvm_unreachable("Invalid opcode provided");
2775 CastInst
*CastInst::Create(Instruction::CastOps op
, Value
*S
, Type
*Ty
,
2776 const Twine
&Name
, BasicBlock
*InsertAtEnd
) {
2777 assert(castIsValid(op
, S
, Ty
) && "Invalid cast!");
2778 // Construct and return the appropriate CastInst subclass
2780 case Trunc
: return new TruncInst (S
, Ty
, Name
, InsertAtEnd
);
2781 case ZExt
: return new ZExtInst (S
, Ty
, Name
, InsertAtEnd
);
2782 case SExt
: return new SExtInst (S
, Ty
, Name
, InsertAtEnd
);
2783 case FPTrunc
: return new FPTruncInst (S
, Ty
, Name
, InsertAtEnd
);
2784 case FPExt
: return new FPExtInst (S
, Ty
, Name
, InsertAtEnd
);
2785 case UIToFP
: return new UIToFPInst (S
, Ty
, Name
, InsertAtEnd
);
2786 case SIToFP
: return new SIToFPInst (S
, Ty
, Name
, InsertAtEnd
);
2787 case FPToUI
: return new FPToUIInst (S
, Ty
, Name
, InsertAtEnd
);
2788 case FPToSI
: return new FPToSIInst (S
, Ty
, Name
, InsertAtEnd
);
2789 case PtrToInt
: return new PtrToIntInst (S
, Ty
, Name
, InsertAtEnd
);
2790 case IntToPtr
: return new IntToPtrInst (S
, Ty
, Name
, InsertAtEnd
);
2791 case BitCast
: return new BitCastInst (S
, Ty
, Name
, InsertAtEnd
);
2792 case AddrSpaceCast
: return new AddrSpaceCastInst (S
, Ty
, Name
, InsertAtEnd
);
2793 default: llvm_unreachable("Invalid opcode provided");
2797 CastInst
*CastInst::CreateZExtOrBitCast(Value
*S
, Type
*Ty
,
2799 Instruction
*InsertBefore
) {
2800 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2801 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2802 return Create(Instruction::ZExt
, S
, Ty
, Name
, InsertBefore
);
2805 CastInst
*CastInst::CreateZExtOrBitCast(Value
*S
, Type
*Ty
,
2807 BasicBlock
*InsertAtEnd
) {
2808 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2809 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2810 return Create(Instruction::ZExt
, S
, Ty
, Name
, InsertAtEnd
);
2813 CastInst
*CastInst::CreateSExtOrBitCast(Value
*S
, Type
*Ty
,
2815 Instruction
*InsertBefore
) {
2816 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2817 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2818 return Create(Instruction::SExt
, S
, Ty
, Name
, InsertBefore
);
2821 CastInst
*CastInst::CreateSExtOrBitCast(Value
*S
, Type
*Ty
,
2823 BasicBlock
*InsertAtEnd
) {
2824 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2825 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2826 return Create(Instruction::SExt
, S
, Ty
, Name
, InsertAtEnd
);
2829 CastInst
*CastInst::CreateTruncOrBitCast(Value
*S
, Type
*Ty
,
2831 Instruction
*InsertBefore
) {
2832 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2833 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2834 return Create(Instruction::Trunc
, S
, Ty
, Name
, InsertBefore
);
2837 CastInst
*CastInst::CreateTruncOrBitCast(Value
*S
, Type
*Ty
,
2839 BasicBlock
*InsertAtEnd
) {
2840 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2841 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2842 return Create(Instruction::Trunc
, S
, Ty
, Name
, InsertAtEnd
);
2845 CastInst
*CastInst::CreatePointerCast(Value
*S
, Type
*Ty
,
2847 BasicBlock
*InsertAtEnd
) {
2848 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2849 assert((Ty
->isIntOrIntVectorTy() || Ty
->isPtrOrPtrVectorTy()) &&
2851 assert(Ty
->isVectorTy() == S
->getType()->isVectorTy() && "Invalid cast");
2852 assert((!Ty
->isVectorTy() ||
2853 Ty
->getVectorNumElements() == S
->getType()->getVectorNumElements()) &&
2856 if (Ty
->isIntOrIntVectorTy())
2857 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertAtEnd
);
2859 return CreatePointerBitCastOrAddrSpaceCast(S
, Ty
, Name
, InsertAtEnd
);
2862 /// Create a BitCast or a PtrToInt cast instruction
2863 CastInst
*CastInst::CreatePointerCast(Value
*S
, Type
*Ty
,
2865 Instruction
*InsertBefore
) {
2866 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2867 assert((Ty
->isIntOrIntVectorTy() || Ty
->isPtrOrPtrVectorTy()) &&
2869 assert(Ty
->isVectorTy() == S
->getType()->isVectorTy() && "Invalid cast");
2870 assert((!Ty
->isVectorTy() ||
2871 Ty
->getVectorNumElements() == S
->getType()->getVectorNumElements()) &&
2874 if (Ty
->isIntOrIntVectorTy())
2875 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertBefore
);
2877 return CreatePointerBitCastOrAddrSpaceCast(S
, Ty
, Name
, InsertBefore
);
2880 CastInst
*CastInst::CreatePointerBitCastOrAddrSpaceCast(
2883 BasicBlock
*InsertAtEnd
) {
2884 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2885 assert(Ty
->isPtrOrPtrVectorTy() && "Invalid cast");
2887 if (S
->getType()->getPointerAddressSpace() != Ty
->getPointerAddressSpace())
2888 return Create(Instruction::AddrSpaceCast
, S
, Ty
, Name
, InsertAtEnd
);
2890 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2893 CastInst
*CastInst::CreatePointerBitCastOrAddrSpaceCast(
2896 Instruction
*InsertBefore
) {
2897 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2898 assert(Ty
->isPtrOrPtrVectorTy() && "Invalid cast");
2900 if (S
->getType()->getPointerAddressSpace() != Ty
->getPointerAddressSpace())
2901 return Create(Instruction::AddrSpaceCast
, S
, Ty
, Name
, InsertBefore
);
2903 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2906 CastInst
*CastInst::CreateBitOrPointerCast(Value
*S
, Type
*Ty
,
2908 Instruction
*InsertBefore
) {
2909 if (S
->getType()->isPointerTy() && Ty
->isIntegerTy())
2910 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertBefore
);
2911 if (S
->getType()->isIntegerTy() && Ty
->isPointerTy())
2912 return Create(Instruction::IntToPtr
, S
, Ty
, Name
, InsertBefore
);
2914 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2917 CastInst
*CastInst::CreateIntegerCast(Value
*C
, Type
*Ty
,
2918 bool isSigned
, const Twine
&Name
,
2919 Instruction
*InsertBefore
) {
2920 assert(C
->getType()->isIntOrIntVectorTy() && Ty
->isIntOrIntVectorTy() &&
2921 "Invalid integer cast");
2922 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2923 unsigned DstBits
= Ty
->getScalarSizeInBits();
2924 Instruction::CastOps opcode
=
2925 (SrcBits
== DstBits
? Instruction::BitCast
:
2926 (SrcBits
> DstBits
? Instruction::Trunc
:
2927 (isSigned
? Instruction::SExt
: Instruction::ZExt
)));
2928 return Create(opcode
, C
, Ty
, Name
, InsertBefore
);
2931 CastInst
*CastInst::CreateIntegerCast(Value
*C
, Type
*Ty
,
2932 bool isSigned
, const Twine
&Name
,
2933 BasicBlock
*InsertAtEnd
) {
2934 assert(C
->getType()->isIntOrIntVectorTy() && Ty
->isIntOrIntVectorTy() &&
2936 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2937 unsigned DstBits
= Ty
->getScalarSizeInBits();
2938 Instruction::CastOps opcode
=
2939 (SrcBits
== DstBits
? Instruction::BitCast
:
2940 (SrcBits
> DstBits
? Instruction::Trunc
:
2941 (isSigned
? Instruction::SExt
: Instruction::ZExt
)));
2942 return Create(opcode
, C
, Ty
, Name
, InsertAtEnd
);
2945 CastInst
*CastInst::CreateFPCast(Value
*C
, Type
*Ty
,
2947 Instruction
*InsertBefore
) {
2948 assert(C
->getType()->isFPOrFPVectorTy() && Ty
->isFPOrFPVectorTy() &&
2950 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2951 unsigned DstBits
= Ty
->getScalarSizeInBits();
2952 Instruction::CastOps opcode
=
2953 (SrcBits
== DstBits
? Instruction::BitCast
:
2954 (SrcBits
> DstBits
? Instruction::FPTrunc
: Instruction::FPExt
));
2955 return Create(opcode
, C
, Ty
, Name
, InsertBefore
);
2958 CastInst
*CastInst::CreateFPCast(Value
*C
, Type
*Ty
,
2960 BasicBlock
*InsertAtEnd
) {
2961 assert(C
->getType()->isFPOrFPVectorTy() && Ty
->isFPOrFPVectorTy() &&
2963 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2964 unsigned DstBits
= Ty
->getScalarSizeInBits();
2965 Instruction::CastOps opcode
=
2966 (SrcBits
== DstBits
? Instruction::BitCast
:
2967 (SrcBits
> DstBits
? Instruction::FPTrunc
: Instruction::FPExt
));
2968 return Create(opcode
, C
, Ty
, Name
, InsertAtEnd
);
2971 // Check whether it is valid to call getCastOpcode for these types.
2972 // This routine must be kept in sync with getCastOpcode.
2973 bool CastInst::isCastable(Type
*SrcTy
, Type
*DestTy
) {
2974 if (!SrcTy
->isFirstClassType() || !DestTy
->isFirstClassType())
2977 if (SrcTy
== DestTy
)
2980 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
))
2981 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
))
2982 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
2983 // An element by element cast. Valid if casting the elements is valid.
2984 SrcTy
= SrcVecTy
->getElementType();
2985 DestTy
= DestVecTy
->getElementType();
2988 // Get the bit sizes, we'll need these
2989 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
2990 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
2992 // Run through the possibilities ...
2993 if (DestTy
->isIntegerTy()) { // Casting to integral
2994 if (SrcTy
->isIntegerTy()) // Casting from integral
2996 if (SrcTy
->isFloatingPointTy()) // Casting from floating pt
2998 if (SrcTy
->isVectorTy()) // Casting from vector
2999 return DestBits
== SrcBits
;
3000 // Casting from something else
3001 return SrcTy
->isPointerTy();
3003 if (DestTy
->isFloatingPointTy()) { // Casting to floating pt
3004 if (SrcTy
->isIntegerTy()) // Casting from integral
3006 if (SrcTy
->isFloatingPointTy()) // Casting from floating pt
3008 if (SrcTy
->isVectorTy()) // Casting from vector
3009 return DestBits
== SrcBits
;
3010 // Casting from something else
3013 if (DestTy
->isVectorTy()) // Casting to vector
3014 return DestBits
== SrcBits
;
3015 if (DestTy
->isPointerTy()) { // Casting to pointer
3016 if (SrcTy
->isPointerTy()) // Casting from pointer
3018 return SrcTy
->isIntegerTy(); // Casting from integral
3020 if (DestTy
->isX86_MMXTy()) {
3021 if (SrcTy
->isVectorTy())
3022 return DestBits
== SrcBits
; // 64-bit vector to MMX
3024 } // Casting to something else
3028 bool CastInst::isBitCastable(Type
*SrcTy
, Type
*DestTy
) {
3029 if (!SrcTy
->isFirstClassType() || !DestTy
->isFirstClassType())
3032 if (SrcTy
== DestTy
)
3035 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
)) {
3036 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
)) {
3037 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
3038 // An element by element cast. Valid if casting the elements is valid.
3039 SrcTy
= SrcVecTy
->getElementType();
3040 DestTy
= DestVecTy
->getElementType();
3045 if (PointerType
*DestPtrTy
= dyn_cast
<PointerType
>(DestTy
)) {
3046 if (PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
)) {
3047 return SrcPtrTy
->getAddressSpace() == DestPtrTy
->getAddressSpace();
3051 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
3052 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
3054 // Could still have vectors of pointers if the number of elements doesn't
3056 if (SrcBits
== 0 || DestBits
== 0)
3059 if (SrcBits
!= DestBits
)
3062 if (DestTy
->isX86_MMXTy() || SrcTy
->isX86_MMXTy())
3068 bool CastInst::isBitOrNoopPointerCastable(Type
*SrcTy
, Type
*DestTy
,
3069 const DataLayout
&DL
) {
3070 // ptrtoint and inttoptr are not allowed on non-integral pointers
3071 if (auto *PtrTy
= dyn_cast
<PointerType
>(SrcTy
))
3072 if (auto *IntTy
= dyn_cast
<IntegerType
>(DestTy
))
3073 return (IntTy
->getBitWidth() == DL
.getPointerTypeSizeInBits(PtrTy
) &&
3074 !DL
.isNonIntegralPointerType(PtrTy
));
3075 if (auto *PtrTy
= dyn_cast
<PointerType
>(DestTy
))
3076 if (auto *IntTy
= dyn_cast
<IntegerType
>(SrcTy
))
3077 return (IntTy
->getBitWidth() == DL
.getPointerTypeSizeInBits(PtrTy
) &&
3078 !DL
.isNonIntegralPointerType(PtrTy
));
3080 return isBitCastable(SrcTy
, DestTy
);
3083 // Provide a way to get a "cast" where the cast opcode is inferred from the
3084 // types and size of the operand. This, basically, is a parallel of the
3085 // logic in the castIsValid function below. This axiom should hold:
3086 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3087 // should not assert in castIsValid. In other words, this produces a "correct"
3088 // casting opcode for the arguments passed to it.
3089 // This routine must be kept in sync with isCastable.
3090 Instruction::CastOps
3091 CastInst::getCastOpcode(
3092 const Value
*Src
, bool SrcIsSigned
, Type
*DestTy
, bool DestIsSigned
) {
3093 Type
*SrcTy
= Src
->getType();
3095 assert(SrcTy
->isFirstClassType() && DestTy
->isFirstClassType() &&
3096 "Only first class types are castable!");
3098 if (SrcTy
== DestTy
)
3101 // FIXME: Check address space sizes here
3102 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
))
3103 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
))
3104 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
3105 // An element by element cast. Find the appropriate opcode based on the
3107 SrcTy
= SrcVecTy
->getElementType();
3108 DestTy
= DestVecTy
->getElementType();
3111 // Get the bit sizes, we'll need these
3112 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
3113 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
3115 // Run through the possibilities ...
3116 if (DestTy
->isIntegerTy()) { // Casting to integral
3117 if (SrcTy
->isIntegerTy()) { // Casting from integral
3118 if (DestBits
< SrcBits
)
3119 return Trunc
; // int -> smaller int
3120 else if (DestBits
> SrcBits
) { // its an extension
3122 return SExt
; // signed -> SEXT
3124 return ZExt
; // unsigned -> ZEXT
3126 return BitCast
; // Same size, No-op cast
3128 } else if (SrcTy
->isFloatingPointTy()) { // Casting from floating pt
3130 return FPToSI
; // FP -> sint
3132 return FPToUI
; // FP -> uint
3133 } else if (SrcTy
->isVectorTy()) {
3134 assert(DestBits
== SrcBits
&&
3135 "Casting vector to integer of different width");
3136 return BitCast
; // Same size, no-op cast
3138 assert(SrcTy
->isPointerTy() &&
3139 "Casting from a value that is not first-class type");
3140 return PtrToInt
; // ptr -> int
3142 } else if (DestTy
->isFloatingPointTy()) { // Casting to floating pt
3143 if (SrcTy
->isIntegerTy()) { // Casting from integral
3145 return SIToFP
; // sint -> FP
3147 return UIToFP
; // uint -> FP
3148 } else if (SrcTy
->isFloatingPointTy()) { // Casting from floating pt
3149 if (DestBits
< SrcBits
) {
3150 return FPTrunc
; // FP -> smaller FP
3151 } else if (DestBits
> SrcBits
) {
3152 return FPExt
; // FP -> larger FP
3154 return BitCast
; // same size, no-op cast
3156 } else if (SrcTy
->isVectorTy()) {
3157 assert(DestBits
== SrcBits
&&
3158 "Casting vector to floating point of different width");
3159 return BitCast
; // same size, no-op cast
3161 llvm_unreachable("Casting pointer or non-first class to float");
3162 } else if (DestTy
->isVectorTy()) {
3163 assert(DestBits
== SrcBits
&&
3164 "Illegal cast to vector (wrong type or size)");
3166 } else if (DestTy
->isPointerTy()) {
3167 if (SrcTy
->isPointerTy()) {
3168 if (DestTy
->getPointerAddressSpace() != SrcTy
->getPointerAddressSpace())
3169 return AddrSpaceCast
;
3170 return BitCast
; // ptr -> ptr
3171 } else if (SrcTy
->isIntegerTy()) {
3172 return IntToPtr
; // int -> ptr
3174 llvm_unreachable("Casting pointer to other than pointer or int");
3175 } else if (DestTy
->isX86_MMXTy()) {
3176 if (SrcTy
->isVectorTy()) {
3177 assert(DestBits
== SrcBits
&& "Casting vector of wrong width to X86_MMX");
3178 return BitCast
; // 64-bit vector to MMX
3180 llvm_unreachable("Illegal cast to X86_MMX");
3182 llvm_unreachable("Casting to type that is not first-class");
3185 //===----------------------------------------------------------------------===//
3186 // CastInst SubClass Constructors
3187 //===----------------------------------------------------------------------===//
3189 /// Check that the construction parameters for a CastInst are correct. This
3190 /// could be broken out into the separate constructors but it is useful to have
3191 /// it in one place and to eliminate the redundant code for getting the sizes
3192 /// of the types involved.
3194 CastInst::castIsValid(Instruction::CastOps op
, Value
*S
, Type
*DstTy
) {
3195 // Check for type sanity on the arguments
3196 Type
*SrcTy
= S
->getType();
3198 if (!SrcTy
->isFirstClassType() || !DstTy
->isFirstClassType() ||
3199 SrcTy
->isAggregateType() || DstTy
->isAggregateType())
3202 // Get the size of the types in bits, we'll need this later
3203 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3204 unsigned DstBitSize
= DstTy
->getScalarSizeInBits();
3206 // If these are vector types, get the lengths of the vectors (using zero for
3207 // scalar types means that checking that vector lengths match also checks that
3208 // scalars are not being converted to vectors or vectors to scalars).
3209 unsigned SrcLength
= SrcTy
->isVectorTy() ?
3210 cast
<VectorType
>(SrcTy
)->getNumElements() : 0;
3211 unsigned DstLength
= DstTy
->isVectorTy() ?
3212 cast
<VectorType
>(DstTy
)->getNumElements() : 0;
3214 // Switch on the opcode provided
3216 default: return false; // This is an input error
3217 case Instruction::Trunc
:
3218 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3219 SrcLength
== DstLength
&& SrcBitSize
> DstBitSize
;
3220 case Instruction::ZExt
:
3221 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3222 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3223 case Instruction::SExt
:
3224 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3225 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3226 case Instruction::FPTrunc
:
3227 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3228 SrcLength
== DstLength
&& SrcBitSize
> DstBitSize
;
3229 case Instruction::FPExt
:
3230 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3231 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3232 case Instruction::UIToFP
:
3233 case Instruction::SIToFP
:
3234 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3235 SrcLength
== DstLength
;
3236 case Instruction::FPToUI
:
3237 case Instruction::FPToSI
:
3238 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3239 SrcLength
== DstLength
;
3240 case Instruction::PtrToInt
:
3241 if (isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(DstTy
))
3243 if (VectorType
*VT
= dyn_cast
<VectorType
>(SrcTy
))
3244 if (VT
->getNumElements() != cast
<VectorType
>(DstTy
)->getNumElements())
3246 return SrcTy
->isPtrOrPtrVectorTy() && DstTy
->isIntOrIntVectorTy();
3247 case Instruction::IntToPtr
:
3248 if (isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(DstTy
))
3250 if (VectorType
*VT
= dyn_cast
<VectorType
>(SrcTy
))
3251 if (VT
->getNumElements() != cast
<VectorType
>(DstTy
)->getNumElements())
3253 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isPtrOrPtrVectorTy();
3254 case Instruction::BitCast
: {
3255 PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
->getScalarType());
3256 PointerType
*DstPtrTy
= dyn_cast
<PointerType
>(DstTy
->getScalarType());
3258 // BitCast implies a no-op cast of type only. No bits change.
3259 // However, you can't cast pointers to anything but pointers.
3260 if (!SrcPtrTy
!= !DstPtrTy
)
3263 // For non-pointer cases, the cast is okay if the source and destination bit
3264 // widths are identical.
3266 return SrcTy
->getPrimitiveSizeInBits() == DstTy
->getPrimitiveSizeInBits();
3268 // If both are pointers then the address spaces must match.
3269 if (SrcPtrTy
->getAddressSpace() != DstPtrTy
->getAddressSpace())
3272 // A vector of pointers must have the same number of elements.
3273 VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
);
3274 VectorType
*DstVecTy
= dyn_cast
<VectorType
>(DstTy
);
3275 if (SrcVecTy
&& DstVecTy
)
3276 return (SrcVecTy
->getNumElements() == DstVecTy
->getNumElements());
3278 return SrcVecTy
->getNumElements() == 1;
3280 return DstVecTy
->getNumElements() == 1;
3284 case Instruction::AddrSpaceCast
: {
3285 PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
->getScalarType());
3289 PointerType
*DstPtrTy
= dyn_cast
<PointerType
>(DstTy
->getScalarType());
3293 if (SrcPtrTy
->getAddressSpace() == DstPtrTy
->getAddressSpace())
3296 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
)) {
3297 if (VectorType
*DstVecTy
= dyn_cast
<VectorType
>(DstTy
))
3298 return (SrcVecTy
->getNumElements() == DstVecTy
->getNumElements());
3308 TruncInst::TruncInst(
3309 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3310 ) : CastInst(Ty
, Trunc
, S
, Name
, InsertBefore
) {
3311 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal Trunc");
3314 TruncInst::TruncInst(
3315 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3316 ) : CastInst(Ty
, Trunc
, S
, Name
, InsertAtEnd
) {
3317 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal Trunc");
3321 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3322 ) : CastInst(Ty
, ZExt
, S
, Name
, InsertBefore
) {
3323 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal ZExt");
3327 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3328 ) : CastInst(Ty
, ZExt
, S
, Name
, InsertAtEnd
) {
3329 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal ZExt");
3332 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3333 ) : CastInst(Ty
, SExt
, S
, Name
, InsertBefore
) {
3334 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SExt");
3338 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3339 ) : CastInst(Ty
, SExt
, S
, Name
, InsertAtEnd
) {
3340 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SExt");
3343 FPTruncInst::FPTruncInst(
3344 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3345 ) : CastInst(Ty
, FPTrunc
, S
, Name
, InsertBefore
) {
3346 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPTrunc");
3349 FPTruncInst::FPTruncInst(
3350 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3351 ) : CastInst(Ty
, FPTrunc
, S
, Name
, InsertAtEnd
) {
3352 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPTrunc");
3355 FPExtInst::FPExtInst(
3356 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3357 ) : CastInst(Ty
, FPExt
, S
, Name
, InsertBefore
) {
3358 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPExt");
3361 FPExtInst::FPExtInst(
3362 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3363 ) : CastInst(Ty
, FPExt
, S
, Name
, InsertAtEnd
) {
3364 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPExt");
3367 UIToFPInst::UIToFPInst(
3368 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3369 ) : CastInst(Ty
, UIToFP
, S
, Name
, InsertBefore
) {
3370 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal UIToFP");
3373 UIToFPInst::UIToFPInst(
3374 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3375 ) : CastInst(Ty
, UIToFP
, S
, Name
, InsertAtEnd
) {
3376 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal UIToFP");
3379 SIToFPInst::SIToFPInst(
3380 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3381 ) : CastInst(Ty
, SIToFP
, S
, Name
, InsertBefore
) {
3382 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SIToFP");
3385 SIToFPInst::SIToFPInst(
3386 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3387 ) : CastInst(Ty
, SIToFP
, S
, Name
, InsertAtEnd
) {
3388 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SIToFP");
3391 FPToUIInst::FPToUIInst(
3392 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3393 ) : CastInst(Ty
, FPToUI
, S
, Name
, InsertBefore
) {
3394 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToUI");
3397 FPToUIInst::FPToUIInst(
3398 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3399 ) : CastInst(Ty
, FPToUI
, S
, Name
, InsertAtEnd
) {
3400 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToUI");
3403 FPToSIInst::FPToSIInst(
3404 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3405 ) : CastInst(Ty
, FPToSI
, S
, Name
, InsertBefore
) {
3406 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToSI");
3409 FPToSIInst::FPToSIInst(
3410 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3411 ) : CastInst(Ty
, FPToSI
, S
, Name
, InsertAtEnd
) {
3412 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToSI");
3415 PtrToIntInst::PtrToIntInst(
3416 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3417 ) : CastInst(Ty
, PtrToInt
, S
, Name
, InsertBefore
) {
3418 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal PtrToInt");
3421 PtrToIntInst::PtrToIntInst(
3422 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3423 ) : CastInst(Ty
, PtrToInt
, S
, Name
, InsertAtEnd
) {
3424 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal PtrToInt");
3427 IntToPtrInst::IntToPtrInst(
3428 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3429 ) : CastInst(Ty
, IntToPtr
, S
, Name
, InsertBefore
) {
3430 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal IntToPtr");
3433 IntToPtrInst::IntToPtrInst(
3434 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3435 ) : CastInst(Ty
, IntToPtr
, S
, Name
, InsertAtEnd
) {
3436 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal IntToPtr");
3439 BitCastInst::BitCastInst(
3440 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3441 ) : CastInst(Ty
, BitCast
, S
, Name
, InsertBefore
) {
3442 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal BitCast");
3445 BitCastInst::BitCastInst(
3446 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3447 ) : CastInst(Ty
, BitCast
, S
, Name
, InsertAtEnd
) {
3448 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal BitCast");
3451 AddrSpaceCastInst::AddrSpaceCastInst(
3452 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3453 ) : CastInst(Ty
, AddrSpaceCast
, S
, Name
, InsertBefore
) {
3454 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal AddrSpaceCast");
3457 AddrSpaceCastInst::AddrSpaceCastInst(
3458 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3459 ) : CastInst(Ty
, AddrSpaceCast
, S
, Name
, InsertAtEnd
) {
3460 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal AddrSpaceCast");
3463 //===----------------------------------------------------------------------===//
3465 //===----------------------------------------------------------------------===//
3467 CmpInst::CmpInst(Type
*ty
, OtherOps op
, Predicate predicate
, Value
*LHS
,
3468 Value
*RHS
, const Twine
&Name
, Instruction
*InsertBefore
,
3469 Instruction
*FlagsSource
)
3470 : Instruction(ty
, op
,
3471 OperandTraits
<CmpInst
>::op_begin(this),
3472 OperandTraits
<CmpInst
>::operands(this),
3476 setPredicate((Predicate
)predicate
);
3479 copyIRFlags(FlagsSource
);
3482 CmpInst::CmpInst(Type
*ty
, OtherOps op
, Predicate predicate
, Value
*LHS
,
3483 Value
*RHS
, const Twine
&Name
, BasicBlock
*InsertAtEnd
)
3484 : Instruction(ty
, op
,
3485 OperandTraits
<CmpInst
>::op_begin(this),
3486 OperandTraits
<CmpInst
>::operands(this),
3490 setPredicate((Predicate
)predicate
);
3495 CmpInst::Create(OtherOps Op
, Predicate predicate
, Value
*S1
, Value
*S2
,
3496 const Twine
&Name
, Instruction
*InsertBefore
) {
3497 if (Op
== Instruction::ICmp
) {
3499 return new ICmpInst(InsertBefore
, CmpInst::Predicate(predicate
),
3502 return new ICmpInst(CmpInst::Predicate(predicate
),
3507 return new FCmpInst(InsertBefore
, CmpInst::Predicate(predicate
),
3510 return new FCmpInst(CmpInst::Predicate(predicate
),
3515 CmpInst::Create(OtherOps Op
, Predicate predicate
, Value
*S1
, Value
*S2
,
3516 const Twine
&Name
, BasicBlock
*InsertAtEnd
) {
3517 if (Op
== Instruction::ICmp
) {
3518 return new ICmpInst(*InsertAtEnd
, CmpInst::Predicate(predicate
),
3521 return new FCmpInst(*InsertAtEnd
, CmpInst::Predicate(predicate
),
3525 void CmpInst::swapOperands() {
3526 if (ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3529 cast
<FCmpInst
>(this)->swapOperands();
3532 bool CmpInst::isCommutative() const {
3533 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3534 return IC
->isCommutative();
3535 return cast
<FCmpInst
>(this)->isCommutative();
3538 bool CmpInst::isEquality() const {
3539 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3540 return IC
->isEquality();
3541 return cast
<FCmpInst
>(this)->isEquality();
3544 CmpInst::Predicate
CmpInst::getInversePredicate(Predicate pred
) {
3546 default: llvm_unreachable("Unknown cmp predicate!");
3547 case ICMP_EQ
: return ICMP_NE
;
3548 case ICMP_NE
: return ICMP_EQ
;
3549 case ICMP_UGT
: return ICMP_ULE
;
3550 case ICMP_ULT
: return ICMP_UGE
;
3551 case ICMP_UGE
: return ICMP_ULT
;
3552 case ICMP_ULE
: return ICMP_UGT
;
3553 case ICMP_SGT
: return ICMP_SLE
;
3554 case ICMP_SLT
: return ICMP_SGE
;
3555 case ICMP_SGE
: return ICMP_SLT
;
3556 case ICMP_SLE
: return ICMP_SGT
;
3558 case FCMP_OEQ
: return FCMP_UNE
;
3559 case FCMP_ONE
: return FCMP_UEQ
;
3560 case FCMP_OGT
: return FCMP_ULE
;
3561 case FCMP_OLT
: return FCMP_UGE
;
3562 case FCMP_OGE
: return FCMP_ULT
;
3563 case FCMP_OLE
: return FCMP_UGT
;
3564 case FCMP_UEQ
: return FCMP_ONE
;
3565 case FCMP_UNE
: return FCMP_OEQ
;
3566 case FCMP_UGT
: return FCMP_OLE
;
3567 case FCMP_ULT
: return FCMP_OGE
;
3568 case FCMP_UGE
: return FCMP_OLT
;
3569 case FCMP_ULE
: return FCMP_OGT
;
3570 case FCMP_ORD
: return FCMP_UNO
;
3571 case FCMP_UNO
: return FCMP_ORD
;
3572 case FCMP_TRUE
: return FCMP_FALSE
;
3573 case FCMP_FALSE
: return FCMP_TRUE
;
3577 StringRef
CmpInst::getPredicateName(Predicate Pred
) {
3579 default: return "unknown";
3580 case FCmpInst::FCMP_FALSE
: return "false";
3581 case FCmpInst::FCMP_OEQ
: return "oeq";
3582 case FCmpInst::FCMP_OGT
: return "ogt";
3583 case FCmpInst::FCMP_OGE
: return "oge";
3584 case FCmpInst::FCMP_OLT
: return "olt";
3585 case FCmpInst::FCMP_OLE
: return "ole";
3586 case FCmpInst::FCMP_ONE
: return "one";
3587 case FCmpInst::FCMP_ORD
: return "ord";
3588 case FCmpInst::FCMP_UNO
: return "uno";
3589 case FCmpInst::FCMP_UEQ
: return "ueq";
3590 case FCmpInst::FCMP_UGT
: return "ugt";
3591 case FCmpInst::FCMP_UGE
: return "uge";
3592 case FCmpInst::FCMP_ULT
: return "ult";
3593 case FCmpInst::FCMP_ULE
: return "ule";
3594 case FCmpInst::FCMP_UNE
: return "une";
3595 case FCmpInst::FCMP_TRUE
: return "true";
3596 case ICmpInst::ICMP_EQ
: return "eq";
3597 case ICmpInst::ICMP_NE
: return "ne";
3598 case ICmpInst::ICMP_SGT
: return "sgt";
3599 case ICmpInst::ICMP_SGE
: return "sge";
3600 case ICmpInst::ICMP_SLT
: return "slt";
3601 case ICmpInst::ICMP_SLE
: return "sle";
3602 case ICmpInst::ICMP_UGT
: return "ugt";
3603 case ICmpInst::ICMP_UGE
: return "uge";
3604 case ICmpInst::ICMP_ULT
: return "ult";
3605 case ICmpInst::ICMP_ULE
: return "ule";
3609 ICmpInst::Predicate
ICmpInst::getSignedPredicate(Predicate pred
) {
3611 default: llvm_unreachable("Unknown icmp predicate!");
3612 case ICMP_EQ
: case ICMP_NE
:
3613 case ICMP_SGT
: case ICMP_SLT
: case ICMP_SGE
: case ICMP_SLE
:
3615 case ICMP_UGT
: return ICMP_SGT
;
3616 case ICMP_ULT
: return ICMP_SLT
;
3617 case ICMP_UGE
: return ICMP_SGE
;
3618 case ICMP_ULE
: return ICMP_SLE
;
3622 ICmpInst::Predicate
ICmpInst::getUnsignedPredicate(Predicate pred
) {
3624 default: llvm_unreachable("Unknown icmp predicate!");
3625 case ICMP_EQ
: case ICMP_NE
:
3626 case ICMP_UGT
: case ICMP_ULT
: case ICMP_UGE
: case ICMP_ULE
:
3628 case ICMP_SGT
: return ICMP_UGT
;
3629 case ICMP_SLT
: return ICMP_ULT
;
3630 case ICMP_SGE
: return ICMP_UGE
;
3631 case ICMP_SLE
: return ICMP_ULE
;
3635 CmpInst::Predicate
CmpInst::getFlippedStrictnessPredicate(Predicate pred
) {
3637 default: llvm_unreachable("Unknown or unsupported cmp predicate!");
3638 case ICMP_SGT
: return ICMP_SGE
;
3639 case ICMP_SLT
: return ICMP_SLE
;
3640 case ICMP_SGE
: return ICMP_SGT
;
3641 case ICMP_SLE
: return ICMP_SLT
;
3642 case ICMP_UGT
: return ICMP_UGE
;
3643 case ICMP_ULT
: return ICMP_ULE
;
3644 case ICMP_UGE
: return ICMP_UGT
;
3645 case ICMP_ULE
: return ICMP_ULT
;
3647 case FCMP_OGT
: return FCMP_OGE
;
3648 case FCMP_OLT
: return FCMP_OLE
;
3649 case FCMP_OGE
: return FCMP_OGT
;
3650 case FCMP_OLE
: return FCMP_OLT
;
3651 case FCMP_UGT
: return FCMP_UGE
;
3652 case FCMP_ULT
: return FCMP_ULE
;
3653 case FCMP_UGE
: return FCMP_UGT
;
3654 case FCMP_ULE
: return FCMP_ULT
;
3658 CmpInst::Predicate
CmpInst::getSwappedPredicate(Predicate pred
) {
3660 default: llvm_unreachable("Unknown cmp predicate!");
3661 case ICMP_EQ
: case ICMP_NE
:
3663 case ICMP_SGT
: return ICMP_SLT
;
3664 case ICMP_SLT
: return ICMP_SGT
;
3665 case ICMP_SGE
: return ICMP_SLE
;
3666 case ICMP_SLE
: return ICMP_SGE
;
3667 case ICMP_UGT
: return ICMP_ULT
;
3668 case ICMP_ULT
: return ICMP_UGT
;
3669 case ICMP_UGE
: return ICMP_ULE
;
3670 case ICMP_ULE
: return ICMP_UGE
;
3672 case FCMP_FALSE
: case FCMP_TRUE
:
3673 case FCMP_OEQ
: case FCMP_ONE
:
3674 case FCMP_UEQ
: case FCMP_UNE
:
3675 case FCMP_ORD
: case FCMP_UNO
:
3677 case FCMP_OGT
: return FCMP_OLT
;
3678 case FCMP_OLT
: return FCMP_OGT
;
3679 case FCMP_OGE
: return FCMP_OLE
;
3680 case FCMP_OLE
: return FCMP_OGE
;
3681 case FCMP_UGT
: return FCMP_ULT
;
3682 case FCMP_ULT
: return FCMP_UGT
;
3683 case FCMP_UGE
: return FCMP_ULE
;
3684 case FCMP_ULE
: return FCMP_UGE
;
3688 CmpInst::Predicate
CmpInst::getNonStrictPredicate(Predicate pred
) {
3690 case ICMP_SGT
: return ICMP_SGE
;
3691 case ICMP_SLT
: return ICMP_SLE
;
3692 case ICMP_UGT
: return ICMP_UGE
;
3693 case ICMP_ULT
: return ICMP_ULE
;
3694 case FCMP_OGT
: return FCMP_OGE
;
3695 case FCMP_OLT
: return FCMP_OLE
;
3696 case FCMP_UGT
: return FCMP_UGE
;
3697 case FCMP_ULT
: return FCMP_ULE
;
3698 default: return pred
;
3702 CmpInst::Predicate
CmpInst::getSignedPredicate(Predicate pred
) {
3703 assert(CmpInst::isUnsigned(pred
) && "Call only with signed predicates!");
3707 llvm_unreachable("Unknown predicate!");
3708 case CmpInst::ICMP_ULT
:
3709 return CmpInst::ICMP_SLT
;
3710 case CmpInst::ICMP_ULE
:
3711 return CmpInst::ICMP_SLE
;
3712 case CmpInst::ICMP_UGT
:
3713 return CmpInst::ICMP_SGT
;
3714 case CmpInst::ICMP_UGE
:
3715 return CmpInst::ICMP_SGE
;
3719 bool CmpInst::isUnsigned(Predicate predicate
) {
3720 switch (predicate
) {
3721 default: return false;
3722 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_ULE
: case ICmpInst::ICMP_UGT
:
3723 case ICmpInst::ICMP_UGE
: return true;
3727 bool CmpInst::isSigned(Predicate predicate
) {
3728 switch (predicate
) {
3729 default: return false;
3730 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_SLE
: case ICmpInst::ICMP_SGT
:
3731 case ICmpInst::ICMP_SGE
: return true;
3735 bool CmpInst::isOrdered(Predicate predicate
) {
3736 switch (predicate
) {
3737 default: return false;
3738 case FCmpInst::FCMP_OEQ
: case FCmpInst::FCMP_ONE
: case FCmpInst::FCMP_OGT
:
3739 case FCmpInst::FCMP_OLT
: case FCmpInst::FCMP_OGE
: case FCmpInst::FCMP_OLE
:
3740 case FCmpInst::FCMP_ORD
: return true;
3744 bool CmpInst::isUnordered(Predicate predicate
) {
3745 switch (predicate
) {
3746 default: return false;
3747 case FCmpInst::FCMP_UEQ
: case FCmpInst::FCMP_UNE
: case FCmpInst::FCMP_UGT
:
3748 case FCmpInst::FCMP_ULT
: case FCmpInst::FCMP_UGE
: case FCmpInst::FCMP_ULE
:
3749 case FCmpInst::FCMP_UNO
: return true;
3753 bool CmpInst::isTrueWhenEqual(Predicate predicate
) {
3755 default: return false;
3756 case ICMP_EQ
: case ICMP_UGE
: case ICMP_ULE
: case ICMP_SGE
: case ICMP_SLE
:
3757 case FCMP_TRUE
: case FCMP_UEQ
: case FCMP_UGE
: case FCMP_ULE
: return true;
3761 bool CmpInst::isFalseWhenEqual(Predicate predicate
) {
3763 case ICMP_NE
: case ICMP_UGT
: case ICMP_ULT
: case ICMP_SGT
: case ICMP_SLT
:
3764 case FCMP_FALSE
: case FCMP_ONE
: case FCMP_OGT
: case FCMP_OLT
: return true;
3765 default: return false;
3769 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1
, Predicate Pred2
) {
3770 // If the predicates match, then we know the first condition implies the
3779 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
3780 return Pred2
== ICMP_UGE
|| Pred2
== ICMP_ULE
|| Pred2
== ICMP_SGE
||
3782 case ICMP_UGT
: // A >u B implies A != B and A >=u B are true.
3783 return Pred2
== ICMP_NE
|| Pred2
== ICMP_UGE
;
3784 case ICMP_ULT
: // A <u B implies A != B and A <=u B are true.
3785 return Pred2
== ICMP_NE
|| Pred2
== ICMP_ULE
;
3786 case ICMP_SGT
: // A >s B implies A != B and A >=s B are true.
3787 return Pred2
== ICMP_NE
|| Pred2
== ICMP_SGE
;
3788 case ICMP_SLT
: // A <s B implies A != B and A <=s B are true.
3789 return Pred2
== ICMP_NE
|| Pred2
== ICMP_SLE
;
3794 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1
, Predicate Pred2
) {
3795 return isImpliedTrueByMatchingCmp(Pred1
, getInversePredicate(Pred2
));
3798 //===----------------------------------------------------------------------===//
3799 // SwitchInst Implementation
3800 //===----------------------------------------------------------------------===//
3802 void SwitchInst::init(Value
*Value
, BasicBlock
*Default
, unsigned NumReserved
) {
3803 assert(Value
&& Default
&& NumReserved
);
3804 ReservedSpace
= NumReserved
;
3805 setNumHungOffUseOperands(2);
3806 allocHungoffUses(ReservedSpace
);
3812 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3813 /// switch on and a default destination. The number of additional cases can
3814 /// be specified here to make memory allocation more efficient. This
3815 /// constructor can also autoinsert before another instruction.
3816 SwitchInst::SwitchInst(Value
*Value
, BasicBlock
*Default
, unsigned NumCases
,
3817 Instruction
*InsertBefore
)
3818 : Instruction(Type::getVoidTy(Value
->getContext()), Instruction::Switch
,
3819 nullptr, 0, InsertBefore
) {
3820 init(Value
, Default
, 2+NumCases
*2);
3823 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3824 /// switch on and a default destination. The number of additional cases can
3825 /// be specified here to make memory allocation more efficient. This
3826 /// constructor also autoinserts at the end of the specified BasicBlock.
3827 SwitchInst::SwitchInst(Value
*Value
, BasicBlock
*Default
, unsigned NumCases
,
3828 BasicBlock
*InsertAtEnd
)
3829 : Instruction(Type::getVoidTy(Value
->getContext()), Instruction::Switch
,
3830 nullptr, 0, InsertAtEnd
) {
3831 init(Value
, Default
, 2+NumCases
*2);
3834 SwitchInst::SwitchInst(const SwitchInst
&SI
)
3835 : Instruction(SI
.getType(), Instruction::Switch
, nullptr, 0) {
3836 init(SI
.getCondition(), SI
.getDefaultDest(), SI
.getNumOperands());
3837 setNumHungOffUseOperands(SI
.getNumOperands());
3838 Use
*OL
= getOperandList();
3839 const Use
*InOL
= SI
.getOperandList();
3840 for (unsigned i
= 2, E
= SI
.getNumOperands(); i
!= E
; i
+= 2) {
3842 OL
[i
+1] = InOL
[i
+1];
3844 SubclassOptionalData
= SI
.SubclassOptionalData
;
3847 /// addCase - Add an entry to the switch instruction...
3849 void SwitchInst::addCase(ConstantInt
*OnVal
, BasicBlock
*Dest
) {
3850 unsigned NewCaseIdx
= getNumCases();
3851 unsigned OpNo
= getNumOperands();
3852 if (OpNo
+2 > ReservedSpace
)
3853 growOperands(); // Get more space!
3854 // Initialize some new operands.
3855 assert(OpNo
+1 < ReservedSpace
&& "Growing didn't work!");
3856 setNumHungOffUseOperands(OpNo
+2);
3857 CaseHandle
Case(this, NewCaseIdx
);
3858 Case
.setValue(OnVal
);
3859 Case
.setSuccessor(Dest
);
3862 /// removeCase - This method removes the specified case and its successor
3863 /// from the switch instruction.
3864 SwitchInst::CaseIt
SwitchInst::removeCase(CaseIt I
) {
3865 unsigned idx
= I
->getCaseIndex();
3867 assert(2 + idx
*2 < getNumOperands() && "Case index out of range!!!");
3869 unsigned NumOps
= getNumOperands();
3870 Use
*OL
= getOperandList();
3872 // Overwrite this case with the end of the list.
3873 if (2 + (idx
+ 1) * 2 != NumOps
) {
3874 OL
[2 + idx
* 2] = OL
[NumOps
- 2];
3875 OL
[2 + idx
* 2 + 1] = OL
[NumOps
- 1];
3878 // Nuke the last value.
3879 OL
[NumOps
-2].set(nullptr);
3880 OL
[NumOps
-2+1].set(nullptr);
3881 setNumHungOffUseOperands(NumOps
-2);
3883 return CaseIt(this, idx
);
3886 /// growOperands - grow operands - This grows the operand list in response
3887 /// to a push_back style of operation. This grows the number of ops by 3 times.
3889 void SwitchInst::growOperands() {
3890 unsigned e
= getNumOperands();
3891 unsigned NumOps
= e
*3;
3893 ReservedSpace
= NumOps
;
3894 growHungoffUses(ReservedSpace
);
3898 SwitchInstProfUpdateWrapper::getProfBranchWeightsMD(const SwitchInst
&SI
) {
3899 if (MDNode
*ProfileData
= SI
.getMetadata(LLVMContext::MD_prof
))
3900 if (auto *MDName
= dyn_cast
<MDString
>(ProfileData
->getOperand(0)))
3901 if (MDName
->getString() == "branch_weights")
3906 MDNode
*SwitchInstProfUpdateWrapper::buildProfBranchWeightsMD() {
3907 assert(Changed
&& "called only if metadata has changed");
3912 assert(SI
.getNumSuccessors() == Weights
->size() &&
3913 "num of prof branch_weights must accord with num of successors");
3916 all_of(Weights
.getValue(), [](uint32_t W
) { return W
== 0; });
3918 if (AllZeroes
|| Weights
.getValue().size() < 2)
3921 return MDBuilder(SI
.getParent()->getContext()).createBranchWeights(*Weights
);
3924 void SwitchInstProfUpdateWrapper::init() {
3925 MDNode
*ProfileData
= getProfBranchWeightsMD(SI
);
3929 if (ProfileData
->getNumOperands() != SI
.getNumSuccessors() + 1) {
3930 llvm_unreachable("number of prof branch_weights metadata operands does "
3931 "not correspond to number of succesors");
3934 SmallVector
<uint32_t, 8> Weights
;
3935 for (unsigned CI
= 1, CE
= SI
.getNumSuccessors(); CI
<= CE
; ++CI
) {
3936 ConstantInt
*C
= mdconst::extract
<ConstantInt
>(ProfileData
->getOperand(CI
));
3937 uint32_t CW
= C
->getValue().getZExtValue();
3938 Weights
.push_back(CW
);
3940 this->Weights
= std::move(Weights
);
3944 SwitchInstProfUpdateWrapper::removeCase(SwitchInst::CaseIt I
) {
3946 assert(SI
.getNumSuccessors() == Weights
->size() &&
3947 "num of prof branch_weights must accord with num of successors");
3949 // Copy the last case to the place of the removed one and shrink.
3950 // This is tightly coupled with the way SwitchInst::removeCase() removes
3951 // the cases in SwitchInst::removeCase(CaseIt).
3952 Weights
.getValue()[I
->getCaseIndex() + 1] = Weights
.getValue().back();
3953 Weights
.getValue().pop_back();
3955 return SI
.removeCase(I
);
3958 void SwitchInstProfUpdateWrapper::addCase(
3959 ConstantInt
*OnVal
, BasicBlock
*Dest
,
3960 SwitchInstProfUpdateWrapper::CaseWeightOpt W
) {
3961 SI
.addCase(OnVal
, Dest
);
3963 if (!Weights
&& W
&& *W
) {
3965 Weights
= SmallVector
<uint32_t, 8>(SI
.getNumSuccessors(), 0);
3966 Weights
.getValue()[SI
.getNumSuccessors() - 1] = *W
;
3967 } else if (Weights
) {
3969 Weights
.getValue().push_back(W
? *W
: 0);
3972 assert(SI
.getNumSuccessors() == Weights
->size() &&
3973 "num of prof branch_weights must accord with num of successors");
3976 SymbolTableList
<Instruction
>::iterator
3977 SwitchInstProfUpdateWrapper::eraseFromParent() {
3978 // Instruction is erased. Mark as unchanged to not touch it in the destructor.
3982 return SI
.eraseFromParent();
3985 SwitchInstProfUpdateWrapper::CaseWeightOpt
3986 SwitchInstProfUpdateWrapper::getSuccessorWeight(unsigned idx
) {
3989 return Weights
.getValue()[idx
];
3992 void SwitchInstProfUpdateWrapper::setSuccessorWeight(
3993 unsigned idx
, SwitchInstProfUpdateWrapper::CaseWeightOpt W
) {
3998 Weights
= SmallVector
<uint32_t, 8>(SI
.getNumSuccessors(), 0);
4001 auto &OldW
= Weights
.getValue()[idx
];
4009 SwitchInstProfUpdateWrapper::CaseWeightOpt
4010 SwitchInstProfUpdateWrapper::getSuccessorWeight(const SwitchInst
&SI
,
4012 if (MDNode
*ProfileData
= getProfBranchWeightsMD(SI
))
4013 if (ProfileData
->getNumOperands() == SI
.getNumSuccessors() + 1)
4014 return mdconst::extract
<ConstantInt
>(ProfileData
->getOperand(idx
+ 1))
4021 //===----------------------------------------------------------------------===//
4022 // IndirectBrInst Implementation
4023 //===----------------------------------------------------------------------===//
4025 void IndirectBrInst::init(Value
*Address
, unsigned NumDests
) {
4026 assert(Address
&& Address
->getType()->isPointerTy() &&
4027 "Address of indirectbr must be a pointer");
4028 ReservedSpace
= 1+NumDests
;
4029 setNumHungOffUseOperands(1);
4030 allocHungoffUses(ReservedSpace
);
4036 /// growOperands - grow operands - This grows the operand list in response
4037 /// to a push_back style of operation. This grows the number of ops by 2 times.
4039 void IndirectBrInst::growOperands() {
4040 unsigned e
= getNumOperands();
4041 unsigned NumOps
= e
*2;
4043 ReservedSpace
= NumOps
;
4044 growHungoffUses(ReservedSpace
);
4047 IndirectBrInst::IndirectBrInst(Value
*Address
, unsigned NumCases
,
4048 Instruction
*InsertBefore
)
4049 : Instruction(Type::getVoidTy(Address
->getContext()),
4050 Instruction::IndirectBr
, nullptr, 0, InsertBefore
) {
4051 init(Address
, NumCases
);
4054 IndirectBrInst::IndirectBrInst(Value
*Address
, unsigned NumCases
,
4055 BasicBlock
*InsertAtEnd
)
4056 : Instruction(Type::getVoidTy(Address
->getContext()),
4057 Instruction::IndirectBr
, nullptr, 0, InsertAtEnd
) {
4058 init(Address
, NumCases
);
4061 IndirectBrInst::IndirectBrInst(const IndirectBrInst
&IBI
)
4062 : Instruction(Type::getVoidTy(IBI
.getContext()), Instruction::IndirectBr
,
4063 nullptr, IBI
.getNumOperands()) {
4064 allocHungoffUses(IBI
.getNumOperands());
4065 Use
*OL
= getOperandList();
4066 const Use
*InOL
= IBI
.getOperandList();
4067 for (unsigned i
= 0, E
= IBI
.getNumOperands(); i
!= E
; ++i
)
4069 SubclassOptionalData
= IBI
.SubclassOptionalData
;
4072 /// addDestination - Add a destination.
4074 void IndirectBrInst::addDestination(BasicBlock
*DestBB
) {
4075 unsigned OpNo
= getNumOperands();
4076 if (OpNo
+1 > ReservedSpace
)
4077 growOperands(); // Get more space!
4078 // Initialize some new operands.
4079 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
4080 setNumHungOffUseOperands(OpNo
+1);
4081 getOperandList()[OpNo
] = DestBB
;
4084 /// removeDestination - This method removes the specified successor from the
4085 /// indirectbr instruction.
4086 void IndirectBrInst::removeDestination(unsigned idx
) {
4087 assert(idx
< getNumOperands()-1 && "Successor index out of range!");
4089 unsigned NumOps
= getNumOperands();
4090 Use
*OL
= getOperandList();
4092 // Replace this value with the last one.
4093 OL
[idx
+1] = OL
[NumOps
-1];
4095 // Nuke the last value.
4096 OL
[NumOps
-1].set(nullptr);
4097 setNumHungOffUseOperands(NumOps
-1);
4100 //===----------------------------------------------------------------------===//
4101 // cloneImpl() implementations
4102 //===----------------------------------------------------------------------===//
4104 // Define these methods here so vtables don't get emitted into every translation
4105 // unit that uses these classes.
4107 GetElementPtrInst
*GetElementPtrInst::cloneImpl() const {
4108 return new (getNumOperands()) GetElementPtrInst(*this);
4111 UnaryOperator
*UnaryOperator::cloneImpl() const {
4112 return Create(getOpcode(), Op
<0>());
4115 BinaryOperator
*BinaryOperator::cloneImpl() const {
4116 return Create(getOpcode(), Op
<0>(), Op
<1>());
4119 FCmpInst
*FCmpInst::cloneImpl() const {
4120 return new FCmpInst(getPredicate(), Op
<0>(), Op
<1>());
4123 ICmpInst
*ICmpInst::cloneImpl() const {
4124 return new ICmpInst(getPredicate(), Op
<0>(), Op
<1>());
4127 ExtractValueInst
*ExtractValueInst::cloneImpl() const {
4128 return new ExtractValueInst(*this);
4131 InsertValueInst
*InsertValueInst::cloneImpl() const {
4132 return new InsertValueInst(*this);
4135 AllocaInst
*AllocaInst::cloneImpl() const {
4136 AllocaInst
*Result
= new AllocaInst(getAllocatedType(),
4137 getType()->getAddressSpace(),
4138 (Value
*)getOperand(0), getAlignment());
4139 Result
->setUsedWithInAlloca(isUsedWithInAlloca());
4140 Result
->setSwiftError(isSwiftError());
4144 LoadInst
*LoadInst::cloneImpl() const {
4145 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
4146 getAlignment(), getOrdering(), getSyncScopeID());
4149 StoreInst
*StoreInst::cloneImpl() const {
4150 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
4151 getAlignment(), getOrdering(), getSyncScopeID());
4155 AtomicCmpXchgInst
*AtomicCmpXchgInst::cloneImpl() const {
4156 AtomicCmpXchgInst
*Result
=
4157 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
4158 getSuccessOrdering(), getFailureOrdering(),
4160 Result
->setVolatile(isVolatile());
4161 Result
->setWeak(isWeak());
4165 AtomicRMWInst
*AtomicRMWInst::cloneImpl() const {
4166 AtomicRMWInst
*Result
=
4167 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4168 getOrdering(), getSyncScopeID());
4169 Result
->setVolatile(isVolatile());
4173 FenceInst
*FenceInst::cloneImpl() const {
4174 return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
4177 TruncInst
*TruncInst::cloneImpl() const {
4178 return new TruncInst(getOperand(0), getType());
4181 ZExtInst
*ZExtInst::cloneImpl() const {
4182 return new ZExtInst(getOperand(0), getType());
4185 SExtInst
*SExtInst::cloneImpl() const {
4186 return new SExtInst(getOperand(0), getType());
4189 FPTruncInst
*FPTruncInst::cloneImpl() const {
4190 return new FPTruncInst(getOperand(0), getType());
4193 FPExtInst
*FPExtInst::cloneImpl() const {
4194 return new FPExtInst(getOperand(0), getType());
4197 UIToFPInst
*UIToFPInst::cloneImpl() const {
4198 return new UIToFPInst(getOperand(0), getType());
4201 SIToFPInst
*SIToFPInst::cloneImpl() const {
4202 return new SIToFPInst(getOperand(0), getType());
4205 FPToUIInst
*FPToUIInst::cloneImpl() const {
4206 return new FPToUIInst(getOperand(0), getType());
4209 FPToSIInst
*FPToSIInst::cloneImpl() const {
4210 return new FPToSIInst(getOperand(0), getType());
4213 PtrToIntInst
*PtrToIntInst::cloneImpl() const {
4214 return new PtrToIntInst(getOperand(0), getType());
4217 IntToPtrInst
*IntToPtrInst::cloneImpl() const {
4218 return new IntToPtrInst(getOperand(0), getType());
4221 BitCastInst
*BitCastInst::cloneImpl() const {
4222 return new BitCastInst(getOperand(0), getType());
4225 AddrSpaceCastInst
*AddrSpaceCastInst::cloneImpl() const {
4226 return new AddrSpaceCastInst(getOperand(0), getType());
4229 CallInst
*CallInst::cloneImpl() const {
4230 if (hasOperandBundles()) {
4231 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4232 return new(getNumOperands(), DescriptorBytes
) CallInst(*this);
4234 return new(getNumOperands()) CallInst(*this);
4237 SelectInst
*SelectInst::cloneImpl() const {
4238 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
4241 VAArgInst
*VAArgInst::cloneImpl() const {
4242 return new VAArgInst(getOperand(0), getType());
4245 ExtractElementInst
*ExtractElementInst::cloneImpl() const {
4246 return ExtractElementInst::Create(getOperand(0), getOperand(1));
4249 InsertElementInst
*InsertElementInst::cloneImpl() const {
4250 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4253 ShuffleVectorInst
*ShuffleVectorInst::cloneImpl() const {
4254 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4257 PHINode
*PHINode::cloneImpl() const { return new PHINode(*this); }
4259 LandingPadInst
*LandingPadInst::cloneImpl() const {
4260 return new LandingPadInst(*this);
4263 ReturnInst
*ReturnInst::cloneImpl() const {
4264 return new(getNumOperands()) ReturnInst(*this);
4267 BranchInst
*BranchInst::cloneImpl() const {
4268 return new(getNumOperands()) BranchInst(*this);
4271 SwitchInst
*SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4273 IndirectBrInst
*IndirectBrInst::cloneImpl() const {
4274 return new IndirectBrInst(*this);
4277 InvokeInst
*InvokeInst::cloneImpl() const {
4278 if (hasOperandBundles()) {
4279 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4280 return new(getNumOperands(), DescriptorBytes
) InvokeInst(*this);
4282 return new(getNumOperands()) InvokeInst(*this);
4285 CallBrInst
*CallBrInst::cloneImpl() const {
4286 if (hasOperandBundles()) {
4287 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4288 return new (getNumOperands(), DescriptorBytes
) CallBrInst(*this);
4290 return new (getNumOperands()) CallBrInst(*this);
4293 ResumeInst
*ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4295 CleanupReturnInst
*CleanupReturnInst::cloneImpl() const {
4296 return new (getNumOperands()) CleanupReturnInst(*this);
4299 CatchReturnInst
*CatchReturnInst::cloneImpl() const {
4300 return new (getNumOperands()) CatchReturnInst(*this);
4303 CatchSwitchInst
*CatchSwitchInst::cloneImpl() const {
4304 return new CatchSwitchInst(*this);
4307 FuncletPadInst
*FuncletPadInst::cloneImpl() const {
4308 return new (getNumOperands()) FuncletPadInst(*this);
4311 UnreachableInst
*UnreachableInst::cloneImpl() const {
4312 LLVMContext
&Context
= getContext();
4313 return new UnreachableInst(Context
);