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 CallBrInst::CallBrInst(const CallBrInst
&CBI
)
820 : CallBase(CBI
.Attrs
, CBI
.FTy
, CBI
.getType(), Instruction::CallBr
,
821 OperandTraits
<CallBase
>::op_end(this) - CBI
.getNumOperands(),
822 CBI
.getNumOperands()) {
823 setCallingConv(CBI
.getCallingConv());
824 std::copy(CBI
.op_begin(), CBI
.op_end(), op_begin());
825 std::copy(CBI
.bundle_op_info_begin(), CBI
.bundle_op_info_end(),
826 bundle_op_info_begin());
827 SubclassOptionalData
= CBI
.SubclassOptionalData
;
828 NumIndirectDests
= CBI
.NumIndirectDests
;
831 CallBrInst
*CallBrInst::Create(CallBrInst
*CBI
, ArrayRef
<OperandBundleDef
> OpB
,
832 Instruction
*InsertPt
) {
833 std::vector
<Value
*> Args(CBI
->arg_begin(), CBI
->arg_end());
835 auto *NewCBI
= CallBrInst::Create(CBI
->getFunctionType(),
836 CBI
->getCalledValue(),
837 CBI
->getDefaultDest(),
838 CBI
->getIndirectDests(),
839 Args
, OpB
, CBI
->getName(), InsertPt
);
840 NewCBI
->setCallingConv(CBI
->getCallingConv());
841 NewCBI
->SubclassOptionalData
= CBI
->SubclassOptionalData
;
842 NewCBI
->setAttributes(CBI
->getAttributes());
843 NewCBI
->setDebugLoc(CBI
->getDebugLoc());
844 NewCBI
->NumIndirectDests
= CBI
->NumIndirectDests
;
848 //===----------------------------------------------------------------------===//
849 // ReturnInst Implementation
850 //===----------------------------------------------------------------------===//
852 ReturnInst::ReturnInst(const ReturnInst
&RI
)
853 : Instruction(Type::getVoidTy(RI
.getContext()), Instruction::Ret
,
854 OperandTraits
<ReturnInst
>::op_end(this) - RI
.getNumOperands(),
855 RI
.getNumOperands()) {
856 if (RI
.getNumOperands())
857 Op
<0>() = RI
.Op
<0>();
858 SubclassOptionalData
= RI
.SubclassOptionalData
;
861 ReturnInst::ReturnInst(LLVMContext
&C
, Value
*retVal
, Instruction
*InsertBefore
)
862 : Instruction(Type::getVoidTy(C
), Instruction::Ret
,
863 OperandTraits
<ReturnInst
>::op_end(this) - !!retVal
, !!retVal
,
869 ReturnInst::ReturnInst(LLVMContext
&C
, Value
*retVal
, BasicBlock
*InsertAtEnd
)
870 : Instruction(Type::getVoidTy(C
), Instruction::Ret
,
871 OperandTraits
<ReturnInst
>::op_end(this) - !!retVal
, !!retVal
,
877 ReturnInst::ReturnInst(LLVMContext
&Context
, BasicBlock
*InsertAtEnd
)
878 : Instruction(Type::getVoidTy(Context
), Instruction::Ret
,
879 OperandTraits
<ReturnInst
>::op_end(this), 0, InsertAtEnd
) {}
881 //===----------------------------------------------------------------------===//
882 // ResumeInst Implementation
883 //===----------------------------------------------------------------------===//
885 ResumeInst::ResumeInst(const ResumeInst
&RI
)
886 : Instruction(Type::getVoidTy(RI
.getContext()), Instruction::Resume
,
887 OperandTraits
<ResumeInst
>::op_begin(this), 1) {
888 Op
<0>() = RI
.Op
<0>();
891 ResumeInst::ResumeInst(Value
*Exn
, Instruction
*InsertBefore
)
892 : Instruction(Type::getVoidTy(Exn
->getContext()), Instruction::Resume
,
893 OperandTraits
<ResumeInst
>::op_begin(this), 1, InsertBefore
) {
897 ResumeInst::ResumeInst(Value
*Exn
, BasicBlock
*InsertAtEnd
)
898 : Instruction(Type::getVoidTy(Exn
->getContext()), Instruction::Resume
,
899 OperandTraits
<ResumeInst
>::op_begin(this), 1, InsertAtEnd
) {
903 //===----------------------------------------------------------------------===//
904 // CleanupReturnInst Implementation
905 //===----------------------------------------------------------------------===//
907 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst
&CRI
)
908 : Instruction(CRI
.getType(), Instruction::CleanupRet
,
909 OperandTraits
<CleanupReturnInst
>::op_end(this) -
910 CRI
.getNumOperands(),
911 CRI
.getNumOperands()) {
912 setInstructionSubclassData(CRI
.getSubclassDataFromInstruction());
913 Op
<0>() = CRI
.Op
<0>();
914 if (CRI
.hasUnwindDest())
915 Op
<1>() = CRI
.Op
<1>();
918 void CleanupReturnInst::init(Value
*CleanupPad
, BasicBlock
*UnwindBB
) {
920 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
922 Op
<0>() = CleanupPad
;
927 CleanupReturnInst::CleanupReturnInst(Value
*CleanupPad
, BasicBlock
*UnwindBB
,
928 unsigned Values
, Instruction
*InsertBefore
)
929 : Instruction(Type::getVoidTy(CleanupPad
->getContext()),
930 Instruction::CleanupRet
,
931 OperandTraits
<CleanupReturnInst
>::op_end(this) - Values
,
932 Values
, InsertBefore
) {
933 init(CleanupPad
, UnwindBB
);
936 CleanupReturnInst::CleanupReturnInst(Value
*CleanupPad
, BasicBlock
*UnwindBB
,
937 unsigned Values
, BasicBlock
*InsertAtEnd
)
938 : Instruction(Type::getVoidTy(CleanupPad
->getContext()),
939 Instruction::CleanupRet
,
940 OperandTraits
<CleanupReturnInst
>::op_end(this) - Values
,
941 Values
, InsertAtEnd
) {
942 init(CleanupPad
, UnwindBB
);
945 //===----------------------------------------------------------------------===//
946 // CatchReturnInst Implementation
947 //===----------------------------------------------------------------------===//
948 void CatchReturnInst::init(Value
*CatchPad
, BasicBlock
*BB
) {
953 CatchReturnInst::CatchReturnInst(const CatchReturnInst
&CRI
)
954 : Instruction(Type::getVoidTy(CRI
.getContext()), Instruction::CatchRet
,
955 OperandTraits
<CatchReturnInst
>::op_begin(this), 2) {
956 Op
<0>() = CRI
.Op
<0>();
957 Op
<1>() = CRI
.Op
<1>();
960 CatchReturnInst::CatchReturnInst(Value
*CatchPad
, BasicBlock
*BB
,
961 Instruction
*InsertBefore
)
962 : Instruction(Type::getVoidTy(BB
->getContext()), Instruction::CatchRet
,
963 OperandTraits
<CatchReturnInst
>::op_begin(this), 2,
968 CatchReturnInst::CatchReturnInst(Value
*CatchPad
, BasicBlock
*BB
,
969 BasicBlock
*InsertAtEnd
)
970 : Instruction(Type::getVoidTy(BB
->getContext()), Instruction::CatchRet
,
971 OperandTraits
<CatchReturnInst
>::op_begin(this), 2,
976 //===----------------------------------------------------------------------===//
977 // CatchSwitchInst Implementation
978 //===----------------------------------------------------------------------===//
980 CatchSwitchInst::CatchSwitchInst(Value
*ParentPad
, BasicBlock
*UnwindDest
,
981 unsigned NumReservedValues
,
982 const Twine
&NameStr
,
983 Instruction
*InsertBefore
)
984 : Instruction(ParentPad
->getType(), Instruction::CatchSwitch
, nullptr, 0,
988 init(ParentPad
, UnwindDest
, NumReservedValues
+ 1);
992 CatchSwitchInst::CatchSwitchInst(Value
*ParentPad
, BasicBlock
*UnwindDest
,
993 unsigned NumReservedValues
,
994 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
995 : Instruction(ParentPad
->getType(), Instruction::CatchSwitch
, nullptr, 0,
999 init(ParentPad
, UnwindDest
, NumReservedValues
+ 1);
1003 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst
&CSI
)
1004 : Instruction(CSI
.getType(), Instruction::CatchSwitch
, nullptr,
1005 CSI
.getNumOperands()) {
1006 init(CSI
.getParentPad(), CSI
.getUnwindDest(), CSI
.getNumOperands());
1007 setNumHungOffUseOperands(ReservedSpace
);
1008 Use
*OL
= getOperandList();
1009 const Use
*InOL
= CSI
.getOperandList();
1010 for (unsigned I
= 1, E
= ReservedSpace
; I
!= E
; ++I
)
1014 void CatchSwitchInst::init(Value
*ParentPad
, BasicBlock
*UnwindDest
,
1015 unsigned NumReservedValues
) {
1016 assert(ParentPad
&& NumReservedValues
);
1018 ReservedSpace
= NumReservedValues
;
1019 setNumHungOffUseOperands(UnwindDest
? 2 : 1);
1020 allocHungoffUses(ReservedSpace
);
1022 Op
<0>() = ParentPad
;
1024 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
1025 setUnwindDest(UnwindDest
);
1029 /// growOperands - grow operands - This grows the operand list in response to a
1030 /// push_back style of operation. This grows the number of ops by 2 times.
1031 void CatchSwitchInst::growOperands(unsigned Size
) {
1032 unsigned NumOperands
= getNumOperands();
1033 assert(NumOperands
>= 1);
1034 if (ReservedSpace
>= NumOperands
+ Size
)
1036 ReservedSpace
= (NumOperands
+ Size
/ 2) * 2;
1037 growHungoffUses(ReservedSpace
);
1040 void CatchSwitchInst::addHandler(BasicBlock
*Handler
) {
1041 unsigned OpNo
= getNumOperands();
1043 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
1044 setNumHungOffUseOperands(getNumOperands() + 1);
1045 getOperandList()[OpNo
] = Handler
;
1048 void CatchSwitchInst::removeHandler(handler_iterator HI
) {
1049 // Move all subsequent handlers up one.
1050 Use
*EndDst
= op_end() - 1;
1051 for (Use
*CurDst
= HI
.getCurrent(); CurDst
!= EndDst
; ++CurDst
)
1052 *CurDst
= *(CurDst
+ 1);
1053 // Null out the last handler use.
1056 setNumHungOffUseOperands(getNumOperands() - 1);
1059 //===----------------------------------------------------------------------===//
1060 // FuncletPadInst Implementation
1061 //===----------------------------------------------------------------------===//
1062 void FuncletPadInst::init(Value
*ParentPad
, ArrayRef
<Value
*> Args
,
1063 const Twine
&NameStr
) {
1064 assert(getNumOperands() == 1 + Args
.size() && "NumOperands not set up?");
1065 llvm::copy(Args
, op_begin());
1066 setParentPad(ParentPad
);
1070 FuncletPadInst::FuncletPadInst(const FuncletPadInst
&FPI
)
1071 : Instruction(FPI
.getType(), FPI
.getOpcode(),
1072 OperandTraits
<FuncletPadInst
>::op_end(this) -
1073 FPI
.getNumOperands(),
1074 FPI
.getNumOperands()) {
1075 std::copy(FPI
.op_begin(), FPI
.op_end(), op_begin());
1076 setParentPad(FPI
.getParentPad());
1079 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op
, Value
*ParentPad
,
1080 ArrayRef
<Value
*> Args
, unsigned Values
,
1081 const Twine
&NameStr
, Instruction
*InsertBefore
)
1082 : Instruction(ParentPad
->getType(), Op
,
1083 OperandTraits
<FuncletPadInst
>::op_end(this) - Values
, Values
,
1085 init(ParentPad
, Args
, NameStr
);
1088 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op
, Value
*ParentPad
,
1089 ArrayRef
<Value
*> Args
, unsigned Values
,
1090 const Twine
&NameStr
, BasicBlock
*InsertAtEnd
)
1091 : Instruction(ParentPad
->getType(), Op
,
1092 OperandTraits
<FuncletPadInst
>::op_end(this) - Values
, Values
,
1094 init(ParentPad
, Args
, NameStr
);
1097 //===----------------------------------------------------------------------===//
1098 // UnreachableInst Implementation
1099 //===----------------------------------------------------------------------===//
1101 UnreachableInst::UnreachableInst(LLVMContext
&Context
,
1102 Instruction
*InsertBefore
)
1103 : Instruction(Type::getVoidTy(Context
), Instruction::Unreachable
, nullptr,
1105 UnreachableInst::UnreachableInst(LLVMContext
&Context
, BasicBlock
*InsertAtEnd
)
1106 : Instruction(Type::getVoidTy(Context
), Instruction::Unreachable
, nullptr,
1109 //===----------------------------------------------------------------------===//
1110 // BranchInst Implementation
1111 //===----------------------------------------------------------------------===//
1113 void BranchInst::AssertOK() {
1114 if (isConditional())
1115 assert(getCondition()->getType()->isIntegerTy(1) &&
1116 "May only branch on boolean predicates!");
1119 BranchInst::BranchInst(BasicBlock
*IfTrue
, Instruction
*InsertBefore
)
1120 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1121 OperandTraits
<BranchInst
>::op_end(this) - 1, 1,
1123 assert(IfTrue
&& "Branch destination may not be null!");
1127 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*IfFalse
, Value
*Cond
,
1128 Instruction
*InsertBefore
)
1129 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1130 OperandTraits
<BranchInst
>::op_end(this) - 3, 3,
1140 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*InsertAtEnd
)
1141 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1142 OperandTraits
<BranchInst
>::op_end(this) - 1, 1, InsertAtEnd
) {
1143 assert(IfTrue
&& "Branch destination may not be null!");
1147 BranchInst::BranchInst(BasicBlock
*IfTrue
, BasicBlock
*IfFalse
, Value
*Cond
,
1148 BasicBlock
*InsertAtEnd
)
1149 : Instruction(Type::getVoidTy(IfTrue
->getContext()), Instruction::Br
,
1150 OperandTraits
<BranchInst
>::op_end(this) - 3, 3, InsertAtEnd
) {
1159 BranchInst::BranchInst(const BranchInst
&BI
)
1160 : Instruction(Type::getVoidTy(BI
.getContext()), Instruction::Br
,
1161 OperandTraits
<BranchInst
>::op_end(this) - BI
.getNumOperands(),
1162 BI
.getNumOperands()) {
1163 Op
<-1>() = BI
.Op
<-1>();
1164 if (BI
.getNumOperands() != 1) {
1165 assert(BI
.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1166 Op
<-3>() = BI
.Op
<-3>();
1167 Op
<-2>() = BI
.Op
<-2>();
1169 SubclassOptionalData
= BI
.SubclassOptionalData
;
1172 void BranchInst::swapSuccessors() {
1173 assert(isConditional() &&
1174 "Cannot swap successors of an unconditional branch");
1175 Op
<-1>().swap(Op
<-2>());
1177 // Update profile metadata if present and it matches our structural
1182 //===----------------------------------------------------------------------===//
1183 // AllocaInst Implementation
1184 //===----------------------------------------------------------------------===//
1186 static Value
*getAISize(LLVMContext
&Context
, Value
*Amt
) {
1188 Amt
= ConstantInt::get(Type::getInt32Ty(Context
), 1);
1190 assert(!isa
<BasicBlock
>(Amt
) &&
1191 "Passed basic block into allocation size parameter! Use other ctor");
1192 assert(Amt
->getType()->isIntegerTy() &&
1193 "Allocation array size is not an integer!");
1198 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, const Twine
&Name
,
1199 Instruction
*InsertBefore
)
1200 : AllocaInst(Ty
, AddrSpace
, /*ArraySize=*/nullptr, Name
, InsertBefore
) {}
1202 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, const Twine
&Name
,
1203 BasicBlock
*InsertAtEnd
)
1204 : AllocaInst(Ty
, AddrSpace
, /*ArraySize=*/nullptr, Name
, InsertAtEnd
) {}
1206 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1207 const Twine
&Name
, Instruction
*InsertBefore
)
1208 : AllocaInst(Ty
, AddrSpace
, ArraySize
, /*Align=*/0, Name
, InsertBefore
) {}
1210 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1211 const Twine
&Name
, BasicBlock
*InsertAtEnd
)
1212 : AllocaInst(Ty
, AddrSpace
, ArraySize
, /*Align=*/0, Name
, InsertAtEnd
) {}
1214 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1215 unsigned Align
, const Twine
&Name
,
1216 Instruction
*InsertBefore
)
1217 : UnaryInstruction(PointerType::get(Ty
, AddrSpace
), Alloca
,
1218 getAISize(Ty
->getContext(), ArraySize
), InsertBefore
),
1220 setAlignment(Align
);
1221 assert(!Ty
->isVoidTy() && "Cannot allocate void!");
1225 AllocaInst::AllocaInst(Type
*Ty
, unsigned AddrSpace
, Value
*ArraySize
,
1226 unsigned Align
, const Twine
&Name
,
1227 BasicBlock
*InsertAtEnd
)
1228 : UnaryInstruction(PointerType::get(Ty
, AddrSpace
), Alloca
,
1229 getAISize(Ty
->getContext(), ArraySize
), InsertAtEnd
),
1231 setAlignment(Align
);
1232 assert(!Ty
->isVoidTy() && "Cannot allocate void!");
1236 void AllocaInst::setAlignment(unsigned Align
) {
1237 assert((Align
& (Align
-1)) == 0 && "Alignment is not a power of 2!");
1238 assert(Align
<= MaximumAlignment
&&
1239 "Alignment is greater than MaximumAlignment!");
1240 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1241 (Log2_32(Align
) + 1));
1242 assert(getAlignment() == Align
&& "Alignment representation error!");
1245 bool AllocaInst::isArrayAllocation() const {
1246 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(getOperand(0)))
1247 return !CI
->isOne();
1251 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1252 /// function and is a constant size. If so, the code generator will fold it
1253 /// into the prolog/epilog code, so it is basically free.
1254 bool AllocaInst::isStaticAlloca() const {
1255 // Must be constant size.
1256 if (!isa
<ConstantInt
>(getArraySize())) return false;
1258 // Must be in the entry block.
1259 const BasicBlock
*Parent
= getParent();
1260 return Parent
== &Parent
->getParent()->front() && !isUsedWithInAlloca();
1263 //===----------------------------------------------------------------------===//
1264 // LoadInst Implementation
1265 //===----------------------------------------------------------------------===//
1267 void LoadInst::AssertOK() {
1268 assert(getOperand(0)->getType()->isPointerTy() &&
1269 "Ptr must have pointer type.");
1270 assert(!(isAtomic() && getAlignment() == 0) &&
1271 "Alignment required for atomic load");
1274 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
,
1275 Instruction
*InsertBef
)
1276 : LoadInst(Ty
, Ptr
, Name
, /*isVolatile=*/false, InsertBef
) {}
1278 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
,
1279 BasicBlock
*InsertAE
)
1280 : LoadInst(Ty
, Ptr
, Name
, /*isVolatile=*/false, InsertAE
) {}
1282 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1283 Instruction
*InsertBef
)
1284 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, /*Align=*/0, InsertBef
) {}
1286 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1287 BasicBlock
*InsertAE
)
1288 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, /*Align=*/0, InsertAE
) {}
1290 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1291 unsigned Align
, Instruction
*InsertBef
)
1292 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1293 SyncScope::System
, InsertBef
) {}
1295 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1296 unsigned Align
, BasicBlock
*InsertAE
)
1297 : LoadInst(Ty
, Ptr
, Name
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1298 SyncScope::System
, InsertAE
) {}
1300 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1301 unsigned Align
, AtomicOrdering Order
,
1302 SyncScope::ID SSID
, Instruction
*InsertBef
)
1303 : UnaryInstruction(Ty
, Load
, Ptr
, InsertBef
) {
1304 assert(Ty
== cast
<PointerType
>(Ptr
->getType())->getElementType());
1305 setVolatile(isVolatile
);
1306 setAlignment(Align
);
1307 setAtomic(Order
, SSID
);
1312 LoadInst::LoadInst(Type
*Ty
, Value
*Ptr
, const Twine
&Name
, bool isVolatile
,
1313 unsigned Align
, AtomicOrdering Order
, SyncScope::ID SSID
,
1314 BasicBlock
*InsertAE
)
1315 : UnaryInstruction(Ty
, Load
, Ptr
, InsertAE
) {
1316 assert(Ty
== cast
<PointerType
>(Ptr
->getType())->getElementType());
1317 setVolatile(isVolatile
);
1318 setAlignment(Align
);
1319 setAtomic(Order
, SSID
);
1324 void LoadInst::setAlignment(unsigned Align
) {
1325 assert((Align
& (Align
-1)) == 0 && "Alignment is not a power of 2!");
1326 assert(Align
<= MaximumAlignment
&&
1327 "Alignment is greater than MaximumAlignment!");
1328 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1329 ((Log2_32(Align
)+1)<<1));
1330 assert(getAlignment() == Align
&& "Alignment representation error!");
1333 //===----------------------------------------------------------------------===//
1334 // StoreInst Implementation
1335 //===----------------------------------------------------------------------===//
1337 void StoreInst::AssertOK() {
1338 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1339 assert(getOperand(1)->getType()->isPointerTy() &&
1340 "Ptr must have pointer type!");
1341 assert(getOperand(0)->getType() ==
1342 cast
<PointerType
>(getOperand(1)->getType())->getElementType()
1343 && "Ptr must be a pointer to Val type!");
1344 assert(!(isAtomic() && getAlignment() == 0) &&
1345 "Alignment required for atomic store");
1348 StoreInst::StoreInst(Value
*val
, Value
*addr
, Instruction
*InsertBefore
)
1349 : StoreInst(val
, addr
, /*isVolatile=*/false, InsertBefore
) {}
1351 StoreInst::StoreInst(Value
*val
, Value
*addr
, BasicBlock
*InsertAtEnd
)
1352 : StoreInst(val
, addr
, /*isVolatile=*/false, InsertAtEnd
) {}
1354 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1355 Instruction
*InsertBefore
)
1356 : StoreInst(val
, addr
, isVolatile
, /*Align=*/0, InsertBefore
) {}
1358 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1359 BasicBlock
*InsertAtEnd
)
1360 : StoreInst(val
, addr
, isVolatile
, /*Align=*/0, InsertAtEnd
) {}
1362 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
, unsigned Align
,
1363 Instruction
*InsertBefore
)
1364 : StoreInst(val
, addr
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1365 SyncScope::System
, InsertBefore
) {}
1367 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
, unsigned Align
,
1368 BasicBlock
*InsertAtEnd
)
1369 : StoreInst(val
, addr
, isVolatile
, Align
, AtomicOrdering::NotAtomic
,
1370 SyncScope::System
, InsertAtEnd
) {}
1372 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1373 unsigned Align
, AtomicOrdering Order
,
1375 Instruction
*InsertBefore
)
1376 : Instruction(Type::getVoidTy(val
->getContext()), Store
,
1377 OperandTraits
<StoreInst
>::op_begin(this),
1378 OperandTraits
<StoreInst
>::operands(this),
1382 setVolatile(isVolatile
);
1383 setAlignment(Align
);
1384 setAtomic(Order
, SSID
);
1388 StoreInst::StoreInst(Value
*val
, Value
*addr
, bool isVolatile
,
1389 unsigned Align
, AtomicOrdering Order
,
1391 BasicBlock
*InsertAtEnd
)
1392 : Instruction(Type::getVoidTy(val
->getContext()), Store
,
1393 OperandTraits
<StoreInst
>::op_begin(this),
1394 OperandTraits
<StoreInst
>::operands(this),
1398 setVolatile(isVolatile
);
1399 setAlignment(Align
);
1400 setAtomic(Order
, SSID
);
1404 void StoreInst::setAlignment(unsigned Align
) {
1405 assert((Align
& (Align
-1)) == 0 && "Alignment is not a power of 2!");
1406 assert(Align
<= MaximumAlignment
&&
1407 "Alignment is greater than MaximumAlignment!");
1408 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1409 ((Log2_32(Align
)+1) << 1));
1410 assert(getAlignment() == Align
&& "Alignment representation error!");
1413 //===----------------------------------------------------------------------===//
1414 // AtomicCmpXchgInst Implementation
1415 //===----------------------------------------------------------------------===//
1417 void AtomicCmpXchgInst::Init(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1418 AtomicOrdering SuccessOrdering
,
1419 AtomicOrdering FailureOrdering
,
1420 SyncScope::ID SSID
) {
1424 setSuccessOrdering(SuccessOrdering
);
1425 setFailureOrdering(FailureOrdering
);
1426 setSyncScopeID(SSID
);
1428 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1429 "All operands must be non-null!");
1430 assert(getOperand(0)->getType()->isPointerTy() &&
1431 "Ptr must have pointer type!");
1432 assert(getOperand(1)->getType() ==
1433 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1434 && "Ptr must be a pointer to Cmp type!");
1435 assert(getOperand(2)->getType() ==
1436 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1437 && "Ptr must be a pointer to NewVal type!");
1438 assert(SuccessOrdering
!= AtomicOrdering::NotAtomic
&&
1439 "AtomicCmpXchg instructions must be atomic!");
1440 assert(FailureOrdering
!= AtomicOrdering::NotAtomic
&&
1441 "AtomicCmpXchg instructions must be atomic!");
1442 assert(!isStrongerThan(FailureOrdering
, SuccessOrdering
) &&
1443 "AtomicCmpXchg failure argument shall be no stronger than the success "
1445 assert(FailureOrdering
!= AtomicOrdering::Release
&&
1446 FailureOrdering
!= AtomicOrdering::AcquireRelease
&&
1447 "AtomicCmpXchg failure ordering cannot include release semantics");
1450 AtomicCmpXchgInst::AtomicCmpXchgInst(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1451 AtomicOrdering SuccessOrdering
,
1452 AtomicOrdering FailureOrdering
,
1454 Instruction
*InsertBefore
)
1456 StructType::get(Cmp
->getType(), Type::getInt1Ty(Cmp
->getContext())),
1457 AtomicCmpXchg
, OperandTraits
<AtomicCmpXchgInst
>::op_begin(this),
1458 OperandTraits
<AtomicCmpXchgInst
>::operands(this), InsertBefore
) {
1459 Init(Ptr
, Cmp
, NewVal
, SuccessOrdering
, FailureOrdering
, SSID
);
1462 AtomicCmpXchgInst::AtomicCmpXchgInst(Value
*Ptr
, Value
*Cmp
, Value
*NewVal
,
1463 AtomicOrdering SuccessOrdering
,
1464 AtomicOrdering FailureOrdering
,
1466 BasicBlock
*InsertAtEnd
)
1468 StructType::get(Cmp
->getType(), Type::getInt1Ty(Cmp
->getContext())),
1469 AtomicCmpXchg
, OperandTraits
<AtomicCmpXchgInst
>::op_begin(this),
1470 OperandTraits
<AtomicCmpXchgInst
>::operands(this), InsertAtEnd
) {
1471 Init(Ptr
, Cmp
, NewVal
, SuccessOrdering
, FailureOrdering
, SSID
);
1474 //===----------------------------------------------------------------------===//
1475 // AtomicRMWInst Implementation
1476 //===----------------------------------------------------------------------===//
1478 void AtomicRMWInst::Init(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1479 AtomicOrdering Ordering
,
1480 SyncScope::ID SSID
) {
1483 setOperation(Operation
);
1484 setOrdering(Ordering
);
1485 setSyncScopeID(SSID
);
1487 assert(getOperand(0) && getOperand(1) &&
1488 "All operands must be non-null!");
1489 assert(getOperand(0)->getType()->isPointerTy() &&
1490 "Ptr must have pointer type!");
1491 assert(getOperand(1)->getType() ==
1492 cast
<PointerType
>(getOperand(0)->getType())->getElementType()
1493 && "Ptr must be a pointer to Val type!");
1494 assert(Ordering
!= AtomicOrdering::NotAtomic
&&
1495 "AtomicRMW instructions must be atomic!");
1498 AtomicRMWInst::AtomicRMWInst(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1499 AtomicOrdering Ordering
,
1501 Instruction
*InsertBefore
)
1502 : Instruction(Val
->getType(), AtomicRMW
,
1503 OperandTraits
<AtomicRMWInst
>::op_begin(this),
1504 OperandTraits
<AtomicRMWInst
>::operands(this),
1506 Init(Operation
, Ptr
, Val
, Ordering
, SSID
);
1509 AtomicRMWInst::AtomicRMWInst(BinOp Operation
, Value
*Ptr
, Value
*Val
,
1510 AtomicOrdering Ordering
,
1512 BasicBlock
*InsertAtEnd
)
1513 : Instruction(Val
->getType(), AtomicRMW
,
1514 OperandTraits
<AtomicRMWInst
>::op_begin(this),
1515 OperandTraits
<AtomicRMWInst
>::operands(this),
1517 Init(Operation
, Ptr
, Val
, Ordering
, SSID
);
1520 StringRef
AtomicRMWInst::getOperationName(BinOp Op
) {
1522 case AtomicRMWInst::Xchg
:
1524 case AtomicRMWInst::Add
:
1526 case AtomicRMWInst::Sub
:
1528 case AtomicRMWInst::And
:
1530 case AtomicRMWInst::Nand
:
1532 case AtomicRMWInst::Or
:
1534 case AtomicRMWInst::Xor
:
1536 case AtomicRMWInst::Max
:
1538 case AtomicRMWInst::Min
:
1540 case AtomicRMWInst::UMax
:
1542 case AtomicRMWInst::UMin
:
1544 case AtomicRMWInst::FAdd
:
1546 case AtomicRMWInst::FSub
:
1548 case AtomicRMWInst::BAD_BINOP
:
1549 return "<invalid operation>";
1552 llvm_unreachable("invalid atomicrmw operation");
1555 //===----------------------------------------------------------------------===//
1556 // FenceInst Implementation
1557 //===----------------------------------------------------------------------===//
1559 FenceInst::FenceInst(LLVMContext
&C
, AtomicOrdering Ordering
,
1561 Instruction
*InsertBefore
)
1562 : Instruction(Type::getVoidTy(C
), Fence
, nullptr, 0, InsertBefore
) {
1563 setOrdering(Ordering
);
1564 setSyncScopeID(SSID
);
1567 FenceInst::FenceInst(LLVMContext
&C
, AtomicOrdering Ordering
,
1569 BasicBlock
*InsertAtEnd
)
1570 : Instruction(Type::getVoidTy(C
), Fence
, nullptr, 0, InsertAtEnd
) {
1571 setOrdering(Ordering
);
1572 setSyncScopeID(SSID
);
1575 //===----------------------------------------------------------------------===//
1576 // GetElementPtrInst Implementation
1577 //===----------------------------------------------------------------------===//
1579 void GetElementPtrInst::init(Value
*Ptr
, ArrayRef
<Value
*> IdxList
,
1580 const Twine
&Name
) {
1581 assert(getNumOperands() == 1 + IdxList
.size() &&
1582 "NumOperands not initialized?");
1584 llvm::copy(IdxList
, op_begin() + 1);
1588 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst
&GEPI
)
1589 : Instruction(GEPI
.getType(), GetElementPtr
,
1590 OperandTraits
<GetElementPtrInst
>::op_end(this) -
1591 GEPI
.getNumOperands(),
1592 GEPI
.getNumOperands()),
1593 SourceElementType(GEPI
.SourceElementType
),
1594 ResultElementType(GEPI
.ResultElementType
) {
1595 std::copy(GEPI
.op_begin(), GEPI
.op_end(), op_begin());
1596 SubclassOptionalData
= GEPI
.SubclassOptionalData
;
1599 /// getIndexedType - Returns the type of the element that would be accessed with
1600 /// a gep instruction with the specified parameters.
1602 /// The Idxs pointer should point to a continuous piece of memory containing the
1603 /// indices, either as Value* or uint64_t.
1605 /// A null type is returned if the indices are invalid for the specified
1608 template <typename IndexTy
>
1609 static Type
*getIndexedTypeInternal(Type
*Agg
, ArrayRef
<IndexTy
> IdxList
) {
1610 // Handle the special case of the empty set index set, which is always valid.
1611 if (IdxList
.empty())
1614 // If there is at least one index, the top level type must be sized, otherwise
1615 // it cannot be 'stepped over'.
1616 if (!Agg
->isSized())
1619 unsigned CurIdx
= 1;
1620 for (; CurIdx
!= IdxList
.size(); ++CurIdx
) {
1621 CompositeType
*CT
= dyn_cast
<CompositeType
>(Agg
);
1622 if (!CT
|| CT
->isPointerTy()) return nullptr;
1623 IndexTy Index
= IdxList
[CurIdx
];
1624 if (!CT
->indexValid(Index
)) return nullptr;
1625 Agg
= CT
->getTypeAtIndex(Index
);
1627 return CurIdx
== IdxList
.size() ? Agg
: nullptr;
1630 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
, ArrayRef
<Value
*> IdxList
) {
1631 return getIndexedTypeInternal(Ty
, IdxList
);
1634 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
,
1635 ArrayRef
<Constant
*> IdxList
) {
1636 return getIndexedTypeInternal(Ty
, IdxList
);
1639 Type
*GetElementPtrInst::getIndexedType(Type
*Ty
, ArrayRef
<uint64_t> IdxList
) {
1640 return getIndexedTypeInternal(Ty
, IdxList
);
1643 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1644 /// zeros. If so, the result pointer and the first operand have the same
1645 /// value, just potentially different types.
1646 bool GetElementPtrInst::hasAllZeroIndices() const {
1647 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1648 if (ConstantInt
*CI
= dyn_cast
<ConstantInt
>(getOperand(i
))) {
1649 if (!CI
->isZero()) return false;
1657 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1658 /// constant integers. If so, the result pointer and the first operand have
1659 /// a constant offset between them.
1660 bool GetElementPtrInst::hasAllConstantIndices() const {
1661 for (unsigned i
= 1, e
= getNumOperands(); i
!= e
; ++i
) {
1662 if (!isa
<ConstantInt
>(getOperand(i
)))
1668 void GetElementPtrInst::setIsInBounds(bool B
) {
1669 cast
<GEPOperator
>(this)->setIsInBounds(B
);
1672 bool GetElementPtrInst::isInBounds() const {
1673 return cast
<GEPOperator
>(this)->isInBounds();
1676 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout
&DL
,
1677 APInt
&Offset
) const {
1678 // Delegate to the generic GEPOperator implementation.
1679 return cast
<GEPOperator
>(this)->accumulateConstantOffset(DL
, Offset
);
1682 //===----------------------------------------------------------------------===//
1683 // ExtractElementInst Implementation
1684 //===----------------------------------------------------------------------===//
1686 ExtractElementInst::ExtractElementInst(Value
*Val
, Value
*Index
,
1688 Instruction
*InsertBef
)
1689 : Instruction(cast
<VectorType
>(Val
->getType())->getElementType(),
1691 OperandTraits
<ExtractElementInst
>::op_begin(this),
1693 assert(isValidOperands(Val
, Index
) &&
1694 "Invalid extractelement instruction operands!");
1700 ExtractElementInst::ExtractElementInst(Value
*Val
, Value
*Index
,
1702 BasicBlock
*InsertAE
)
1703 : Instruction(cast
<VectorType
>(Val
->getType())->getElementType(),
1705 OperandTraits
<ExtractElementInst
>::op_begin(this),
1707 assert(isValidOperands(Val
, Index
) &&
1708 "Invalid extractelement instruction operands!");
1715 bool ExtractElementInst::isValidOperands(const Value
*Val
, const Value
*Index
) {
1716 if (!Val
->getType()->isVectorTy() || !Index
->getType()->isIntegerTy())
1721 //===----------------------------------------------------------------------===//
1722 // InsertElementInst Implementation
1723 //===----------------------------------------------------------------------===//
1725 InsertElementInst::InsertElementInst(Value
*Vec
, Value
*Elt
, Value
*Index
,
1727 Instruction
*InsertBef
)
1728 : Instruction(Vec
->getType(), InsertElement
,
1729 OperandTraits
<InsertElementInst
>::op_begin(this),
1731 assert(isValidOperands(Vec
, Elt
, Index
) &&
1732 "Invalid insertelement instruction operands!");
1739 InsertElementInst::InsertElementInst(Value
*Vec
, Value
*Elt
, Value
*Index
,
1741 BasicBlock
*InsertAE
)
1742 : Instruction(Vec
->getType(), InsertElement
,
1743 OperandTraits
<InsertElementInst
>::op_begin(this),
1745 assert(isValidOperands(Vec
, Elt
, Index
) &&
1746 "Invalid insertelement instruction operands!");
1754 bool InsertElementInst::isValidOperands(const Value
*Vec
, const Value
*Elt
,
1755 const Value
*Index
) {
1756 if (!Vec
->getType()->isVectorTy())
1757 return false; // First operand of insertelement must be vector type.
1759 if (Elt
->getType() != cast
<VectorType
>(Vec
->getType())->getElementType())
1760 return false;// Second operand of insertelement must be vector element type.
1762 if (!Index
->getType()->isIntegerTy())
1763 return false; // Third operand of insertelement must be i32.
1767 //===----------------------------------------------------------------------===//
1768 // ShuffleVectorInst Implementation
1769 //===----------------------------------------------------------------------===//
1771 ShuffleVectorInst::ShuffleVectorInst(Value
*V1
, Value
*V2
, Value
*Mask
,
1773 Instruction
*InsertBefore
)
1774 : Instruction(VectorType::get(cast
<VectorType
>(V1
->getType())->getElementType(),
1775 cast
<VectorType
>(Mask
->getType())->getNumElements()),
1777 OperandTraits
<ShuffleVectorInst
>::op_begin(this),
1778 OperandTraits
<ShuffleVectorInst
>::operands(this),
1780 assert(isValidOperands(V1
, V2
, Mask
) &&
1781 "Invalid shuffle vector instruction operands!");
1788 ShuffleVectorInst::ShuffleVectorInst(Value
*V1
, Value
*V2
, Value
*Mask
,
1790 BasicBlock
*InsertAtEnd
)
1791 : Instruction(VectorType::get(cast
<VectorType
>(V1
->getType())->getElementType(),
1792 cast
<VectorType
>(Mask
->getType())->getNumElements()),
1794 OperandTraits
<ShuffleVectorInst
>::op_begin(this),
1795 OperandTraits
<ShuffleVectorInst
>::operands(this),
1797 assert(isValidOperands(V1
, V2
, Mask
) &&
1798 "Invalid shuffle vector instruction operands!");
1806 void ShuffleVectorInst::commute() {
1807 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
1808 int NumMaskElts
= getMask()->getType()->getVectorNumElements();
1809 SmallVector
<Constant
*, 16> NewMask(NumMaskElts
);
1810 Type
*Int32Ty
= Type::getInt32Ty(getContext());
1811 for (int i
= 0; i
!= NumMaskElts
; ++i
) {
1812 int MaskElt
= getMaskValue(i
);
1813 if (MaskElt
== -1) {
1814 NewMask
[i
] = UndefValue::get(Int32Ty
);
1817 assert(MaskElt
>= 0 && MaskElt
< 2 * NumOpElts
&& "Out-of-range mask");
1818 MaskElt
= (MaskElt
< NumOpElts
) ? MaskElt
+ NumOpElts
: MaskElt
- NumOpElts
;
1819 NewMask
[i
] = ConstantInt::get(Int32Ty
, MaskElt
);
1821 Op
<2>() = ConstantVector::get(NewMask
);
1822 Op
<0>().swap(Op
<1>());
1825 bool ShuffleVectorInst::isValidOperands(const Value
*V1
, const Value
*V2
,
1826 const Value
*Mask
) {
1827 // V1 and V2 must be vectors of the same type.
1828 if (!V1
->getType()->isVectorTy() || V1
->getType() != V2
->getType())
1831 // Mask must be vector of i32.
1832 auto *MaskTy
= dyn_cast
<VectorType
>(Mask
->getType());
1833 if (!MaskTy
|| !MaskTy
->getElementType()->isIntegerTy(32))
1836 // Check to see if Mask is valid.
1837 if (isa
<UndefValue
>(Mask
) || isa
<ConstantAggregateZero
>(Mask
))
1840 if (const auto *MV
= dyn_cast
<ConstantVector
>(Mask
)) {
1841 unsigned V1Size
= cast
<VectorType
>(V1
->getType())->getNumElements();
1842 for (Value
*Op
: MV
->operands()) {
1843 if (auto *CI
= dyn_cast
<ConstantInt
>(Op
)) {
1844 if (CI
->uge(V1Size
*2))
1846 } else if (!isa
<UndefValue
>(Op
)) {
1853 if (const auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
)) {
1854 unsigned V1Size
= cast
<VectorType
>(V1
->getType())->getNumElements();
1855 for (unsigned i
= 0, e
= MaskTy
->getNumElements(); i
!= e
; ++i
)
1856 if (CDS
->getElementAsInteger(i
) >= V1Size
*2)
1861 // The bitcode reader can create a place holder for a forward reference
1862 // used as the shuffle mask. When this occurs, the shuffle mask will
1863 // fall into this case and fail. To avoid this error, do this bit of
1864 // ugliness to allow such a mask pass.
1865 if (const auto *CE
= dyn_cast
<ConstantExpr
>(Mask
))
1866 if (CE
->getOpcode() == Instruction::UserOp1
)
1872 int ShuffleVectorInst::getMaskValue(const Constant
*Mask
, unsigned i
) {
1873 assert(i
< Mask
->getType()->getVectorNumElements() && "Index out of range");
1874 if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
))
1875 return CDS
->getElementAsInteger(i
);
1876 Constant
*C
= Mask
->getAggregateElement(i
);
1877 if (isa
<UndefValue
>(C
))
1879 return cast
<ConstantInt
>(C
)->getZExtValue();
1882 void ShuffleVectorInst::getShuffleMask(const Constant
*Mask
,
1883 SmallVectorImpl
<int> &Result
) {
1884 unsigned NumElts
= Mask
->getType()->getVectorNumElements();
1886 if (auto *CDS
= dyn_cast
<ConstantDataSequential
>(Mask
)) {
1887 for (unsigned i
= 0; i
!= NumElts
; ++i
)
1888 Result
.push_back(CDS
->getElementAsInteger(i
));
1891 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
1892 Constant
*C
= Mask
->getAggregateElement(i
);
1893 Result
.push_back(isa
<UndefValue
>(C
) ? -1 :
1894 cast
<ConstantInt
>(C
)->getZExtValue());
1898 static bool isSingleSourceMaskImpl(ArrayRef
<int> Mask
, int NumOpElts
) {
1899 assert(!Mask
.empty() && "Shuffle mask must contain elements");
1900 bool UsesLHS
= false;
1901 bool UsesRHS
= false;
1902 for (int i
= 0, NumMaskElts
= Mask
.size(); i
< NumMaskElts
; ++i
) {
1905 assert(Mask
[i
] >= 0 && Mask
[i
] < (NumOpElts
* 2) &&
1906 "Out-of-bounds shuffle mask element");
1907 UsesLHS
|= (Mask
[i
] < NumOpElts
);
1908 UsesRHS
|= (Mask
[i
] >= NumOpElts
);
1909 if (UsesLHS
&& UsesRHS
)
1912 assert((UsesLHS
^ UsesRHS
) && "Should have selected from exactly 1 source");
1916 bool ShuffleVectorInst::isSingleSourceMask(ArrayRef
<int> Mask
) {
1917 // We don't have vector operand size information, so assume operands are the
1918 // same size as the mask.
1919 return isSingleSourceMaskImpl(Mask
, Mask
.size());
1922 static bool isIdentityMaskImpl(ArrayRef
<int> Mask
, int NumOpElts
) {
1923 if (!isSingleSourceMaskImpl(Mask
, NumOpElts
))
1925 for (int i
= 0, NumMaskElts
= Mask
.size(); i
< NumMaskElts
; ++i
) {
1928 if (Mask
[i
] != i
&& Mask
[i
] != (NumOpElts
+ i
))
1934 bool ShuffleVectorInst::isIdentityMask(ArrayRef
<int> Mask
) {
1935 // We don't have vector operand size information, so assume operands are the
1936 // same size as the mask.
1937 return isIdentityMaskImpl(Mask
, Mask
.size());
1940 bool ShuffleVectorInst::isReverseMask(ArrayRef
<int> Mask
) {
1941 if (!isSingleSourceMask(Mask
))
1943 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1946 if (Mask
[i
] != (NumElts
- 1 - i
) && Mask
[i
] != (NumElts
+ NumElts
- 1 - i
))
1952 bool ShuffleVectorInst::isZeroEltSplatMask(ArrayRef
<int> Mask
) {
1953 if (!isSingleSourceMask(Mask
))
1955 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1958 if (Mask
[i
] != 0 && Mask
[i
] != NumElts
)
1964 bool ShuffleVectorInst::isSelectMask(ArrayRef
<int> Mask
) {
1965 // Select is differentiated from identity. It requires using both sources.
1966 if (isSingleSourceMask(Mask
))
1968 for (int i
= 0, NumElts
= Mask
.size(); i
< NumElts
; ++i
) {
1971 if (Mask
[i
] != i
&& Mask
[i
] != (NumElts
+ i
))
1977 bool ShuffleVectorInst::isTransposeMask(ArrayRef
<int> Mask
) {
1978 // Example masks that will return true:
1979 // v1 = <a, b, c, d>
1980 // v2 = <e, f, g, h>
1981 // trn1 = shufflevector v1, v2 <0, 4, 2, 6> = <a, e, c, g>
1982 // trn2 = shufflevector v1, v2 <1, 5, 3, 7> = <b, f, d, h>
1984 // 1. The number of elements in the mask must be a power-of-2 and at least 2.
1985 int NumElts
= Mask
.size();
1986 if (NumElts
< 2 || !isPowerOf2_32(NumElts
))
1989 // 2. The first element of the mask must be either a 0 or a 1.
1990 if (Mask
[0] != 0 && Mask
[0] != 1)
1993 // 3. The difference between the first 2 elements must be equal to the
1994 // number of elements in the mask.
1995 if ((Mask
[1] - Mask
[0]) != NumElts
)
1998 // 4. The difference between consecutive even-numbered and odd-numbered
1999 // elements must be equal to 2.
2000 for (int i
= 2; i
< NumElts
; ++i
) {
2001 int MaskEltVal
= Mask
[i
];
2002 if (MaskEltVal
== -1)
2004 int MaskEltPrevVal
= Mask
[i
- 2];
2005 if (MaskEltVal
- MaskEltPrevVal
!= 2)
2011 bool ShuffleVectorInst::isExtractSubvectorMask(ArrayRef
<int> Mask
,
2012 int NumSrcElts
, int &Index
) {
2013 // Must extract from a single source.
2014 if (!isSingleSourceMaskImpl(Mask
, NumSrcElts
))
2017 // Must be smaller (else this is an Identity shuffle).
2018 if (NumSrcElts
<= (int)Mask
.size())
2021 // Find start of extraction, accounting that we may start with an UNDEF.
2023 for (int i
= 0, e
= Mask
.size(); i
!= e
; ++i
) {
2027 int Offset
= (M
% NumSrcElts
) - i
;
2028 if (0 <= SubIndex
&& SubIndex
!= Offset
)
2033 if (0 <= SubIndex
) {
2040 bool ShuffleVectorInst::isIdentityWithPadding() const {
2041 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2042 int NumMaskElts
= getType()->getVectorNumElements();
2043 if (NumMaskElts
<= NumOpElts
)
2046 // The first part of the mask must choose elements from exactly 1 source op.
2047 SmallVector
<int, 16> Mask
= getShuffleMask();
2048 if (!isIdentityMaskImpl(Mask
, NumOpElts
))
2051 // All extending must be with undef elements.
2052 for (int i
= NumOpElts
; i
< NumMaskElts
; ++i
)
2059 bool ShuffleVectorInst::isIdentityWithExtract() const {
2060 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2061 int NumMaskElts
= getType()->getVectorNumElements();
2062 if (NumMaskElts
>= NumOpElts
)
2065 return isIdentityMaskImpl(getShuffleMask(), NumOpElts
);
2068 bool ShuffleVectorInst::isConcat() const {
2069 // Vector concatenation is differentiated from identity with padding.
2070 if (isa
<UndefValue
>(Op
<0>()) || isa
<UndefValue
>(Op
<1>()))
2073 int NumOpElts
= Op
<0>()->getType()->getVectorNumElements();
2074 int NumMaskElts
= getType()->getVectorNumElements();
2075 if (NumMaskElts
!= NumOpElts
* 2)
2078 // Use the mask length rather than the operands' vector lengths here. We
2079 // already know that the shuffle returns a vector twice as long as the inputs,
2080 // and neither of the inputs are undef vectors. If the mask picks consecutive
2081 // elements from both inputs, then this is a concatenation of the inputs.
2082 return isIdentityMaskImpl(getShuffleMask(), NumMaskElts
);
2085 //===----------------------------------------------------------------------===//
2086 // InsertValueInst Class
2087 //===----------------------------------------------------------------------===//
2089 void InsertValueInst::init(Value
*Agg
, Value
*Val
, ArrayRef
<unsigned> Idxs
,
2090 const Twine
&Name
) {
2091 assert(getNumOperands() == 2 && "NumOperands not initialized?");
2093 // There's no fundamental reason why we require at least one index
2094 // (other than weirdness with &*IdxBegin being invalid; see
2095 // getelementptr's init routine for example). But there's no
2096 // present need to support it.
2097 assert(!Idxs
.empty() && "InsertValueInst must have at least one index");
2099 assert(ExtractValueInst::getIndexedType(Agg
->getType(), Idxs
) ==
2100 Val
->getType() && "Inserted value must match indexed type!");
2104 Indices
.append(Idxs
.begin(), Idxs
.end());
2108 InsertValueInst::InsertValueInst(const InsertValueInst
&IVI
)
2109 : Instruction(IVI
.getType(), InsertValue
,
2110 OperandTraits
<InsertValueInst
>::op_begin(this), 2),
2111 Indices(IVI
.Indices
) {
2112 Op
<0>() = IVI
.getOperand(0);
2113 Op
<1>() = IVI
.getOperand(1);
2114 SubclassOptionalData
= IVI
.SubclassOptionalData
;
2117 //===----------------------------------------------------------------------===//
2118 // ExtractValueInst Class
2119 //===----------------------------------------------------------------------===//
2121 void ExtractValueInst::init(ArrayRef
<unsigned> Idxs
, const Twine
&Name
) {
2122 assert(getNumOperands() == 1 && "NumOperands not initialized?");
2124 // There's no fundamental reason why we require at least one index.
2125 // But there's no present need to support it.
2126 assert(!Idxs
.empty() && "ExtractValueInst must have at least one index");
2128 Indices
.append(Idxs
.begin(), Idxs
.end());
2132 ExtractValueInst::ExtractValueInst(const ExtractValueInst
&EVI
)
2133 : UnaryInstruction(EVI
.getType(), ExtractValue
, EVI
.getOperand(0)),
2134 Indices(EVI
.Indices
) {
2135 SubclassOptionalData
= EVI
.SubclassOptionalData
;
2138 // getIndexedType - Returns the type of the element that would be extracted
2139 // with an extractvalue instruction with the specified parameters.
2141 // A null type is returned if the indices are invalid for the specified
2144 Type
*ExtractValueInst::getIndexedType(Type
*Agg
,
2145 ArrayRef
<unsigned> Idxs
) {
2146 for (unsigned Index
: Idxs
) {
2147 // We can't use CompositeType::indexValid(Index) here.
2148 // indexValid() always returns true for arrays because getelementptr allows
2149 // out-of-bounds indices. Since we don't allow those for extractvalue and
2150 // insertvalue we need to check array indexing manually.
2151 // Since the only other types we can index into are struct types it's just
2152 // as easy to check those manually as well.
2153 if (ArrayType
*AT
= dyn_cast
<ArrayType
>(Agg
)) {
2154 if (Index
>= AT
->getNumElements())
2156 } else if (StructType
*ST
= dyn_cast
<StructType
>(Agg
)) {
2157 if (Index
>= ST
->getNumElements())
2160 // Not a valid type to index into.
2164 Agg
= cast
<CompositeType
>(Agg
)->getTypeAtIndex(Index
);
2166 return const_cast<Type
*>(Agg
);
2169 //===----------------------------------------------------------------------===//
2170 // UnaryOperator Class
2171 //===----------------------------------------------------------------------===//
2173 UnaryOperator::UnaryOperator(UnaryOps iType
, Value
*S
,
2174 Type
*Ty
, const Twine
&Name
,
2175 Instruction
*InsertBefore
)
2176 : UnaryInstruction(Ty
, iType
, S
, InsertBefore
) {
2182 UnaryOperator::UnaryOperator(UnaryOps iType
, Value
*S
,
2183 Type
*Ty
, const Twine
&Name
,
2184 BasicBlock
*InsertAtEnd
)
2185 : UnaryInstruction(Ty
, iType
, S
, InsertAtEnd
) {
2191 UnaryOperator
*UnaryOperator::Create(UnaryOps Op
, Value
*S
,
2193 Instruction
*InsertBefore
) {
2194 return new UnaryOperator(Op
, S
, S
->getType(), Name
, InsertBefore
);
2197 UnaryOperator
*UnaryOperator::Create(UnaryOps Op
, Value
*S
,
2199 BasicBlock
*InsertAtEnd
) {
2200 UnaryOperator
*Res
= Create(Op
, S
, Name
);
2201 InsertAtEnd
->getInstList().push_back(Res
);
2205 void UnaryOperator::AssertOK() {
2206 Value
*LHS
= getOperand(0);
2207 (void)LHS
; // Silence warnings.
2209 switch (getOpcode()) {
2211 assert(getType() == LHS
->getType() &&
2212 "Unary operation should return same type as operand!");
2213 assert(getType()->isFPOrFPVectorTy() &&
2214 "Tried to create a floating-point operation on a "
2215 "non-floating-point type!");
2217 default: llvm_unreachable("Invalid opcode provided");
2222 //===----------------------------------------------------------------------===//
2223 // BinaryOperator Class
2224 //===----------------------------------------------------------------------===//
2226 BinaryOperator::BinaryOperator(BinaryOps iType
, Value
*S1
, Value
*S2
,
2227 Type
*Ty
, const Twine
&Name
,
2228 Instruction
*InsertBefore
)
2229 : Instruction(Ty
, iType
,
2230 OperandTraits
<BinaryOperator
>::op_begin(this),
2231 OperandTraits
<BinaryOperator
>::operands(this),
2239 BinaryOperator::BinaryOperator(BinaryOps iType
, Value
*S1
, Value
*S2
,
2240 Type
*Ty
, const Twine
&Name
,
2241 BasicBlock
*InsertAtEnd
)
2242 : Instruction(Ty
, iType
,
2243 OperandTraits
<BinaryOperator
>::op_begin(this),
2244 OperandTraits
<BinaryOperator
>::operands(this),
2252 void BinaryOperator::AssertOK() {
2253 Value
*LHS
= getOperand(0), *RHS
= getOperand(1);
2254 (void)LHS
; (void)RHS
; // Silence warnings.
2255 assert(LHS
->getType() == RHS
->getType() &&
2256 "Binary operator operand types must match!");
2258 switch (getOpcode()) {
2261 assert(getType() == LHS
->getType() &&
2262 "Arithmetic operation should return same type as operands!");
2263 assert(getType()->isIntOrIntVectorTy() &&
2264 "Tried to create an integer operation on a non-integer type!");
2266 case FAdd
: case FSub
:
2268 assert(getType() == LHS
->getType() &&
2269 "Arithmetic operation should return same type as operands!");
2270 assert(getType()->isFPOrFPVectorTy() &&
2271 "Tried to create a floating-point operation on a "
2272 "non-floating-point type!");
2276 assert(getType() == LHS
->getType() &&
2277 "Arithmetic operation should return same type as operands!");
2278 assert(getType()->isIntOrIntVectorTy() &&
2279 "Incorrect operand type (not integer) for S/UDIV");
2282 assert(getType() == LHS
->getType() &&
2283 "Arithmetic operation should return same type as operands!");
2284 assert(getType()->isFPOrFPVectorTy() &&
2285 "Incorrect operand type (not floating point) for FDIV");
2289 assert(getType() == LHS
->getType() &&
2290 "Arithmetic operation should return same type as operands!");
2291 assert(getType()->isIntOrIntVectorTy() &&
2292 "Incorrect operand type (not integer) for S/UREM");
2295 assert(getType() == LHS
->getType() &&
2296 "Arithmetic operation should return same type as operands!");
2297 assert(getType()->isFPOrFPVectorTy() &&
2298 "Incorrect operand type (not floating point) for FREM");
2303 assert(getType() == LHS
->getType() &&
2304 "Shift operation should return same type as operands!");
2305 assert(getType()->isIntOrIntVectorTy() &&
2306 "Tried to create a shift operation on a non-integral type!");
2310 assert(getType() == LHS
->getType() &&
2311 "Logical operation should return same type as operands!");
2312 assert(getType()->isIntOrIntVectorTy() &&
2313 "Tried to create a logical operation on a non-integral type!");
2315 default: llvm_unreachable("Invalid opcode provided");
2320 BinaryOperator
*BinaryOperator::Create(BinaryOps Op
, Value
*S1
, Value
*S2
,
2322 Instruction
*InsertBefore
) {
2323 assert(S1
->getType() == S2
->getType() &&
2324 "Cannot create binary operator with two operands of differing type!");
2325 return new BinaryOperator(Op
, S1
, S2
, S1
->getType(), Name
, InsertBefore
);
2328 BinaryOperator
*BinaryOperator::Create(BinaryOps Op
, Value
*S1
, Value
*S2
,
2330 BasicBlock
*InsertAtEnd
) {
2331 BinaryOperator
*Res
= Create(Op
, S1
, S2
, Name
);
2332 InsertAtEnd
->getInstList().push_back(Res
);
2336 BinaryOperator
*BinaryOperator::CreateNeg(Value
*Op
, const Twine
&Name
,
2337 Instruction
*InsertBefore
) {
2338 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2339 return new BinaryOperator(Instruction::Sub
,
2341 Op
->getType(), Name
, InsertBefore
);
2344 BinaryOperator
*BinaryOperator::CreateNeg(Value
*Op
, const Twine
&Name
,
2345 BasicBlock
*InsertAtEnd
) {
2346 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2347 return new BinaryOperator(Instruction::Sub
,
2349 Op
->getType(), Name
, InsertAtEnd
);
2352 BinaryOperator
*BinaryOperator::CreateNSWNeg(Value
*Op
, const Twine
&Name
,
2353 Instruction
*InsertBefore
) {
2354 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2355 return BinaryOperator::CreateNSWSub(zero
, Op
, Name
, InsertBefore
);
2358 BinaryOperator
*BinaryOperator::CreateNSWNeg(Value
*Op
, const Twine
&Name
,
2359 BasicBlock
*InsertAtEnd
) {
2360 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2361 return BinaryOperator::CreateNSWSub(zero
, Op
, Name
, InsertAtEnd
);
2364 BinaryOperator
*BinaryOperator::CreateNUWNeg(Value
*Op
, const Twine
&Name
,
2365 Instruction
*InsertBefore
) {
2366 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2367 return BinaryOperator::CreateNUWSub(zero
, Op
, Name
, InsertBefore
);
2370 BinaryOperator
*BinaryOperator::CreateNUWNeg(Value
*Op
, const Twine
&Name
,
2371 BasicBlock
*InsertAtEnd
) {
2372 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2373 return BinaryOperator::CreateNUWSub(zero
, Op
, Name
, InsertAtEnd
);
2376 BinaryOperator
*BinaryOperator::CreateFNeg(Value
*Op
, const Twine
&Name
,
2377 Instruction
*InsertBefore
) {
2378 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2379 return new BinaryOperator(Instruction::FSub
, zero
, Op
,
2380 Op
->getType(), Name
, InsertBefore
);
2383 BinaryOperator
*BinaryOperator::CreateFNeg(Value
*Op
, const Twine
&Name
,
2384 BasicBlock
*InsertAtEnd
) {
2385 Value
*zero
= ConstantFP::getZeroValueForNegation(Op
->getType());
2386 return new BinaryOperator(Instruction::FSub
, zero
, Op
,
2387 Op
->getType(), Name
, InsertAtEnd
);
2390 BinaryOperator
*BinaryOperator::CreateNot(Value
*Op
, const Twine
&Name
,
2391 Instruction
*InsertBefore
) {
2392 Constant
*C
= Constant::getAllOnesValue(Op
->getType());
2393 return new BinaryOperator(Instruction::Xor
, Op
, C
,
2394 Op
->getType(), Name
, InsertBefore
);
2397 BinaryOperator
*BinaryOperator::CreateNot(Value
*Op
, const Twine
&Name
,
2398 BasicBlock
*InsertAtEnd
) {
2399 Constant
*AllOnes
= Constant::getAllOnesValue(Op
->getType());
2400 return new BinaryOperator(Instruction::Xor
, Op
, AllOnes
,
2401 Op
->getType(), Name
, InsertAtEnd
);
2404 // Exchange the two operands to this instruction. This instruction is safe to
2405 // use on any binary instruction and does not modify the semantics of the
2406 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2408 bool BinaryOperator::swapOperands() {
2409 if (!isCommutative())
2410 return true; // Can't commute operands
2411 Op
<0>().swap(Op
<1>());
2415 //===----------------------------------------------------------------------===//
2416 // FPMathOperator Class
2417 //===----------------------------------------------------------------------===//
2419 float FPMathOperator::getFPAccuracy() const {
2421 cast
<Instruction
>(this)->getMetadata(LLVMContext::MD_fpmath
);
2424 ConstantFP
*Accuracy
= mdconst::extract
<ConstantFP
>(MD
->getOperand(0));
2425 return Accuracy
->getValueAPF().convertToFloat();
2428 //===----------------------------------------------------------------------===//
2430 //===----------------------------------------------------------------------===//
2432 // Just determine if this cast only deals with integral->integral conversion.
2433 bool CastInst::isIntegerCast() const {
2434 switch (getOpcode()) {
2435 default: return false;
2436 case Instruction::ZExt
:
2437 case Instruction::SExt
:
2438 case Instruction::Trunc
:
2440 case Instruction::BitCast
:
2441 return getOperand(0)->getType()->isIntegerTy() &&
2442 getType()->isIntegerTy();
2446 bool CastInst::isLosslessCast() const {
2447 // Only BitCast can be lossless, exit fast if we're not BitCast
2448 if (getOpcode() != Instruction::BitCast
)
2451 // Identity cast is always lossless
2452 Type
*SrcTy
= getOperand(0)->getType();
2453 Type
*DstTy
= getType();
2457 // Pointer to pointer is always lossless.
2458 if (SrcTy
->isPointerTy())
2459 return DstTy
->isPointerTy();
2460 return false; // Other types have no identity values
2463 /// This function determines if the CastInst does not require any bits to be
2464 /// changed in order to effect the cast. Essentially, it identifies cases where
2465 /// no code gen is necessary for the cast, hence the name no-op cast. For
2466 /// example, the following are all no-op casts:
2467 /// # bitcast i32* %x to i8*
2468 /// # bitcast <2 x i32> %x to <4 x i16>
2469 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2470 /// Determine if the described cast is a no-op.
2471 bool CastInst::isNoopCast(Instruction::CastOps Opcode
,
2474 const DataLayout
&DL
) {
2476 default: llvm_unreachable("Invalid CastOp");
2477 case Instruction::Trunc
:
2478 case Instruction::ZExt
:
2479 case Instruction::SExt
:
2480 case Instruction::FPTrunc
:
2481 case Instruction::FPExt
:
2482 case Instruction::UIToFP
:
2483 case Instruction::SIToFP
:
2484 case Instruction::FPToUI
:
2485 case Instruction::FPToSI
:
2486 case Instruction::AddrSpaceCast
:
2487 // TODO: Target informations may give a more accurate answer here.
2489 case Instruction::BitCast
:
2490 return true; // BitCast never modifies bits.
2491 case Instruction::PtrToInt
:
2492 return DL
.getIntPtrType(SrcTy
)->getScalarSizeInBits() ==
2493 DestTy
->getScalarSizeInBits();
2494 case Instruction::IntToPtr
:
2495 return DL
.getIntPtrType(DestTy
)->getScalarSizeInBits() ==
2496 SrcTy
->getScalarSizeInBits();
2500 bool CastInst::isNoopCast(const DataLayout
&DL
) const {
2501 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), DL
);
2504 /// This function determines if a pair of casts can be eliminated and what
2505 /// opcode should be used in the elimination. This assumes that there are two
2506 /// instructions like this:
2507 /// * %F = firstOpcode SrcTy %x to MidTy
2508 /// * %S = secondOpcode MidTy %F to DstTy
2509 /// The function returns a resultOpcode so these two casts can be replaced with:
2510 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2511 /// If no such cast is permitted, the function returns 0.
2512 unsigned CastInst::isEliminableCastPair(
2513 Instruction::CastOps firstOp
, Instruction::CastOps secondOp
,
2514 Type
*SrcTy
, Type
*MidTy
, Type
*DstTy
, Type
*SrcIntPtrTy
, Type
*MidIntPtrTy
,
2515 Type
*DstIntPtrTy
) {
2516 // Define the 144 possibilities for these two cast instructions. The values
2517 // in this matrix determine what to do in a given situation and select the
2518 // case in the switch below. The rows correspond to firstOp, the columns
2519 // correspond to secondOp. In looking at the table below, keep in mind
2520 // the following cast properties:
2522 // Size Compare Source Destination
2523 // Operator Src ? Size Type Sign Type Sign
2524 // -------- ------------ ------------------- ---------------------
2525 // TRUNC > Integer Any Integral Any
2526 // ZEXT < Integral Unsigned Integer Any
2527 // SEXT < Integral Signed Integer Any
2528 // FPTOUI n/a FloatPt n/a Integral Unsigned
2529 // FPTOSI n/a FloatPt n/a Integral Signed
2530 // UITOFP n/a Integral Unsigned FloatPt n/a
2531 // SITOFP n/a Integral Signed FloatPt n/a
2532 // FPTRUNC > FloatPt n/a FloatPt n/a
2533 // FPEXT < FloatPt n/a FloatPt n/a
2534 // PTRTOINT n/a Pointer n/a Integral Unsigned
2535 // INTTOPTR n/a Integral Unsigned Pointer n/a
2536 // BITCAST = FirstClass n/a FirstClass n/a
2537 // ADDRSPCST n/a Pointer n/a Pointer n/a
2539 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2540 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2541 // into "fptoui double to i64", but this loses information about the range
2542 // of the produced value (we no longer know the top-part is all zeros).
2543 // Further this conversion is often much more expensive for typical hardware,
2544 // and causes issues when building libgcc. We disallow fptosi+sext for the
2546 const unsigned numCastOps
=
2547 Instruction::CastOpsEnd
- Instruction::CastOpsBegin
;
2548 static const uint8_t CastResults
[numCastOps
][numCastOps
] = {
2549 // T F F U S F F P I B A -+
2550 // R Z S P P I I T P 2 N T S |
2551 // U E E 2 2 2 2 R E I T C C +- secondOp
2552 // N X X U S F F N X N 2 V V |
2553 // C T T I I P P C T T P T T -+
2554 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2555 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2556 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2557 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2558 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2559 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2560 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2561 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2562 { 99,99,99, 2, 2,99,99, 8, 2,99,99, 4, 0}, // FPExt |
2563 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2564 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2565 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2566 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2569 // TODO: This logic could be encoded into the table above and handled in the
2571 // If either of the casts are a bitcast from scalar to vector, disallow the
2572 // merging. However, any pair of bitcasts are allowed.
2573 bool IsFirstBitcast
= (firstOp
== Instruction::BitCast
);
2574 bool IsSecondBitcast
= (secondOp
== Instruction::BitCast
);
2575 bool AreBothBitcasts
= IsFirstBitcast
&& IsSecondBitcast
;
2577 // Check if any of the casts convert scalars <-> vectors.
2578 if ((IsFirstBitcast
&& isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(MidTy
)) ||
2579 (IsSecondBitcast
&& isa
<VectorType
>(MidTy
) != isa
<VectorType
>(DstTy
)))
2580 if (!AreBothBitcasts
)
2583 int ElimCase
= CastResults
[firstOp
-Instruction::CastOpsBegin
]
2584 [secondOp
-Instruction::CastOpsBegin
];
2587 // Categorically disallowed.
2590 // Allowed, use first cast's opcode.
2593 // Allowed, use second cast's opcode.
2596 // No-op cast in second op implies firstOp as long as the DestTy
2597 // is integer and we are not converting between a vector and a
2599 if (!SrcTy
->isVectorTy() && DstTy
->isIntegerTy())
2603 // No-op cast in second op implies firstOp as long as the DestTy
2604 // is floating point.
2605 if (DstTy
->isFloatingPointTy())
2609 // No-op cast in first op implies secondOp as long as the SrcTy
2611 if (SrcTy
->isIntegerTy())
2615 // No-op cast in first op implies secondOp as long as the SrcTy
2616 // is a floating point.
2617 if (SrcTy
->isFloatingPointTy())
2621 // Cannot simplify if address spaces are different!
2622 if (SrcTy
->getPointerAddressSpace() != DstTy
->getPointerAddressSpace())
2625 unsigned MidSize
= MidTy
->getScalarSizeInBits();
2626 // We can still fold this without knowing the actual sizes as long we
2627 // know that the intermediate pointer is the largest possible
2629 // FIXME: Is this always true?
2631 return Instruction::BitCast
;
2633 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2634 if (!SrcIntPtrTy
|| DstIntPtrTy
!= SrcIntPtrTy
)
2636 unsigned PtrSize
= SrcIntPtrTy
->getScalarSizeInBits();
2637 if (MidSize
>= PtrSize
)
2638 return Instruction::BitCast
;
2642 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2643 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2644 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2645 unsigned SrcSize
= SrcTy
->getScalarSizeInBits();
2646 unsigned DstSize
= DstTy
->getScalarSizeInBits();
2647 if (SrcSize
== DstSize
)
2648 return Instruction::BitCast
;
2649 else if (SrcSize
< DstSize
)
2654 // zext, sext -> zext, because sext can't sign extend after zext
2655 return Instruction::ZExt
;
2657 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2660 unsigned PtrSize
= MidIntPtrTy
->getScalarSizeInBits();
2661 unsigned SrcSize
= SrcTy
->getScalarSizeInBits();
2662 unsigned DstSize
= DstTy
->getScalarSizeInBits();
2663 if (SrcSize
<= PtrSize
&& SrcSize
== DstSize
)
2664 return Instruction::BitCast
;
2668 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2669 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2670 if (SrcTy
->getPointerAddressSpace() != DstTy
->getPointerAddressSpace())
2671 return Instruction::AddrSpaceCast
;
2672 return Instruction::BitCast
;
2674 // FIXME: this state can be merged with (1), but the following assert
2675 // is useful to check the correcteness of the sequence due to semantic
2676 // change of bitcast.
2678 SrcTy
->isPtrOrPtrVectorTy() &&
2679 MidTy
->isPtrOrPtrVectorTy() &&
2680 DstTy
->isPtrOrPtrVectorTy() &&
2681 SrcTy
->getPointerAddressSpace() != MidTy
->getPointerAddressSpace() &&
2682 MidTy
->getPointerAddressSpace() == DstTy
->getPointerAddressSpace() &&
2683 "Illegal addrspacecast, bitcast sequence!");
2684 // Allowed, use first cast's opcode
2687 // bitcast, addrspacecast -> addrspacecast if the element type of
2688 // bitcast's source is the same as that of addrspacecast's destination.
2689 if (SrcTy
->getScalarType()->getPointerElementType() ==
2690 DstTy
->getScalarType()->getPointerElementType())
2691 return Instruction::AddrSpaceCast
;
2694 // FIXME: this state can be merged with (1), but the following assert
2695 // is useful to check the correcteness of the sequence due to semantic
2696 // change of bitcast.
2698 SrcTy
->isIntOrIntVectorTy() &&
2699 MidTy
->isPtrOrPtrVectorTy() &&
2700 DstTy
->isPtrOrPtrVectorTy() &&
2701 MidTy
->getPointerAddressSpace() == DstTy
->getPointerAddressSpace() &&
2702 "Illegal inttoptr, bitcast sequence!");
2703 // Allowed, use first cast's opcode
2706 // FIXME: this state can be merged with (2), but the following assert
2707 // is useful to check the correcteness of the sequence due to semantic
2708 // change of bitcast.
2710 SrcTy
->isPtrOrPtrVectorTy() &&
2711 MidTy
->isPtrOrPtrVectorTy() &&
2712 DstTy
->isIntOrIntVectorTy() &&
2713 SrcTy
->getPointerAddressSpace() == MidTy
->getPointerAddressSpace() &&
2714 "Illegal bitcast, ptrtoint sequence!");
2715 // Allowed, use second cast's opcode
2718 // (sitofp (zext x)) -> (uitofp x)
2719 return Instruction::UIToFP
;
2721 // Cast combination can't happen (error in input). This is for all cases
2722 // where the MidTy is not the same for the two cast instructions.
2723 llvm_unreachable("Invalid Cast Combination");
2725 llvm_unreachable("Error in CastResults table!!!");
2729 CastInst
*CastInst::Create(Instruction::CastOps op
, Value
*S
, Type
*Ty
,
2730 const Twine
&Name
, Instruction
*InsertBefore
) {
2731 assert(castIsValid(op
, S
, Ty
) && "Invalid cast!");
2732 // Construct and return the appropriate CastInst subclass
2734 case Trunc
: return new TruncInst (S
, Ty
, Name
, InsertBefore
);
2735 case ZExt
: return new ZExtInst (S
, Ty
, Name
, InsertBefore
);
2736 case SExt
: return new SExtInst (S
, Ty
, Name
, InsertBefore
);
2737 case FPTrunc
: return new FPTruncInst (S
, Ty
, Name
, InsertBefore
);
2738 case FPExt
: return new FPExtInst (S
, Ty
, Name
, InsertBefore
);
2739 case UIToFP
: return new UIToFPInst (S
, Ty
, Name
, InsertBefore
);
2740 case SIToFP
: return new SIToFPInst (S
, Ty
, Name
, InsertBefore
);
2741 case FPToUI
: return new FPToUIInst (S
, Ty
, Name
, InsertBefore
);
2742 case FPToSI
: return new FPToSIInst (S
, Ty
, Name
, InsertBefore
);
2743 case PtrToInt
: return new PtrToIntInst (S
, Ty
, Name
, InsertBefore
);
2744 case IntToPtr
: return new IntToPtrInst (S
, Ty
, Name
, InsertBefore
);
2745 case BitCast
: return new BitCastInst (S
, Ty
, Name
, InsertBefore
);
2746 case AddrSpaceCast
: return new AddrSpaceCastInst (S
, Ty
, Name
, InsertBefore
);
2747 default: llvm_unreachable("Invalid opcode provided");
2751 CastInst
*CastInst::Create(Instruction::CastOps op
, Value
*S
, Type
*Ty
,
2752 const Twine
&Name
, BasicBlock
*InsertAtEnd
) {
2753 assert(castIsValid(op
, S
, Ty
) && "Invalid cast!");
2754 // Construct and return the appropriate CastInst subclass
2756 case Trunc
: return new TruncInst (S
, Ty
, Name
, InsertAtEnd
);
2757 case ZExt
: return new ZExtInst (S
, Ty
, Name
, InsertAtEnd
);
2758 case SExt
: return new SExtInst (S
, Ty
, Name
, InsertAtEnd
);
2759 case FPTrunc
: return new FPTruncInst (S
, Ty
, Name
, InsertAtEnd
);
2760 case FPExt
: return new FPExtInst (S
, Ty
, Name
, InsertAtEnd
);
2761 case UIToFP
: return new UIToFPInst (S
, Ty
, Name
, InsertAtEnd
);
2762 case SIToFP
: return new SIToFPInst (S
, Ty
, Name
, InsertAtEnd
);
2763 case FPToUI
: return new FPToUIInst (S
, Ty
, Name
, InsertAtEnd
);
2764 case FPToSI
: return new FPToSIInst (S
, Ty
, Name
, InsertAtEnd
);
2765 case PtrToInt
: return new PtrToIntInst (S
, Ty
, Name
, InsertAtEnd
);
2766 case IntToPtr
: return new IntToPtrInst (S
, Ty
, Name
, InsertAtEnd
);
2767 case BitCast
: return new BitCastInst (S
, Ty
, Name
, InsertAtEnd
);
2768 case AddrSpaceCast
: return new AddrSpaceCastInst (S
, Ty
, Name
, InsertAtEnd
);
2769 default: llvm_unreachable("Invalid opcode provided");
2773 CastInst
*CastInst::CreateZExtOrBitCast(Value
*S
, Type
*Ty
,
2775 Instruction
*InsertBefore
) {
2776 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2777 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2778 return Create(Instruction::ZExt
, S
, Ty
, Name
, InsertBefore
);
2781 CastInst
*CastInst::CreateZExtOrBitCast(Value
*S
, Type
*Ty
,
2783 BasicBlock
*InsertAtEnd
) {
2784 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2785 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2786 return Create(Instruction::ZExt
, S
, Ty
, Name
, InsertAtEnd
);
2789 CastInst
*CastInst::CreateSExtOrBitCast(Value
*S
, Type
*Ty
,
2791 Instruction
*InsertBefore
) {
2792 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2793 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2794 return Create(Instruction::SExt
, S
, Ty
, Name
, InsertBefore
);
2797 CastInst
*CastInst::CreateSExtOrBitCast(Value
*S
, Type
*Ty
,
2799 BasicBlock
*InsertAtEnd
) {
2800 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2801 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2802 return Create(Instruction::SExt
, S
, Ty
, Name
, InsertAtEnd
);
2805 CastInst
*CastInst::CreateTruncOrBitCast(Value
*S
, Type
*Ty
,
2807 Instruction
*InsertBefore
) {
2808 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2809 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2810 return Create(Instruction::Trunc
, S
, Ty
, Name
, InsertBefore
);
2813 CastInst
*CastInst::CreateTruncOrBitCast(Value
*S
, Type
*Ty
,
2815 BasicBlock
*InsertAtEnd
) {
2816 if (S
->getType()->getScalarSizeInBits() == Ty
->getScalarSizeInBits())
2817 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2818 return Create(Instruction::Trunc
, S
, Ty
, Name
, InsertAtEnd
);
2821 CastInst
*CastInst::CreatePointerCast(Value
*S
, Type
*Ty
,
2823 BasicBlock
*InsertAtEnd
) {
2824 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2825 assert((Ty
->isIntOrIntVectorTy() || Ty
->isPtrOrPtrVectorTy()) &&
2827 assert(Ty
->isVectorTy() == S
->getType()->isVectorTy() && "Invalid cast");
2828 assert((!Ty
->isVectorTy() ||
2829 Ty
->getVectorNumElements() == S
->getType()->getVectorNumElements()) &&
2832 if (Ty
->isIntOrIntVectorTy())
2833 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertAtEnd
);
2835 return CreatePointerBitCastOrAddrSpaceCast(S
, Ty
, Name
, InsertAtEnd
);
2838 /// Create a BitCast or a PtrToInt cast instruction
2839 CastInst
*CastInst::CreatePointerCast(Value
*S
, Type
*Ty
,
2841 Instruction
*InsertBefore
) {
2842 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2843 assert((Ty
->isIntOrIntVectorTy() || Ty
->isPtrOrPtrVectorTy()) &&
2845 assert(Ty
->isVectorTy() == S
->getType()->isVectorTy() && "Invalid cast");
2846 assert((!Ty
->isVectorTy() ||
2847 Ty
->getVectorNumElements() == S
->getType()->getVectorNumElements()) &&
2850 if (Ty
->isIntOrIntVectorTy())
2851 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertBefore
);
2853 return CreatePointerBitCastOrAddrSpaceCast(S
, Ty
, Name
, InsertBefore
);
2856 CastInst
*CastInst::CreatePointerBitCastOrAddrSpaceCast(
2859 BasicBlock
*InsertAtEnd
) {
2860 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2861 assert(Ty
->isPtrOrPtrVectorTy() && "Invalid cast");
2863 if (S
->getType()->getPointerAddressSpace() != Ty
->getPointerAddressSpace())
2864 return Create(Instruction::AddrSpaceCast
, S
, Ty
, Name
, InsertAtEnd
);
2866 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertAtEnd
);
2869 CastInst
*CastInst::CreatePointerBitCastOrAddrSpaceCast(
2872 Instruction
*InsertBefore
) {
2873 assert(S
->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2874 assert(Ty
->isPtrOrPtrVectorTy() && "Invalid cast");
2876 if (S
->getType()->getPointerAddressSpace() != Ty
->getPointerAddressSpace())
2877 return Create(Instruction::AddrSpaceCast
, S
, Ty
, Name
, InsertBefore
);
2879 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2882 CastInst
*CastInst::CreateBitOrPointerCast(Value
*S
, Type
*Ty
,
2884 Instruction
*InsertBefore
) {
2885 if (S
->getType()->isPointerTy() && Ty
->isIntegerTy())
2886 return Create(Instruction::PtrToInt
, S
, Ty
, Name
, InsertBefore
);
2887 if (S
->getType()->isIntegerTy() && Ty
->isPointerTy())
2888 return Create(Instruction::IntToPtr
, S
, Ty
, Name
, InsertBefore
);
2890 return Create(Instruction::BitCast
, S
, Ty
, Name
, InsertBefore
);
2893 CastInst
*CastInst::CreateIntegerCast(Value
*C
, Type
*Ty
,
2894 bool isSigned
, const Twine
&Name
,
2895 Instruction
*InsertBefore
) {
2896 assert(C
->getType()->isIntOrIntVectorTy() && Ty
->isIntOrIntVectorTy() &&
2897 "Invalid integer cast");
2898 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2899 unsigned DstBits
= Ty
->getScalarSizeInBits();
2900 Instruction::CastOps opcode
=
2901 (SrcBits
== DstBits
? Instruction::BitCast
:
2902 (SrcBits
> DstBits
? Instruction::Trunc
:
2903 (isSigned
? Instruction::SExt
: Instruction::ZExt
)));
2904 return Create(opcode
, C
, Ty
, Name
, InsertBefore
);
2907 CastInst
*CastInst::CreateIntegerCast(Value
*C
, Type
*Ty
,
2908 bool isSigned
, const Twine
&Name
,
2909 BasicBlock
*InsertAtEnd
) {
2910 assert(C
->getType()->isIntOrIntVectorTy() && Ty
->isIntOrIntVectorTy() &&
2912 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2913 unsigned DstBits
= Ty
->getScalarSizeInBits();
2914 Instruction::CastOps opcode
=
2915 (SrcBits
== DstBits
? Instruction::BitCast
:
2916 (SrcBits
> DstBits
? Instruction::Trunc
:
2917 (isSigned
? Instruction::SExt
: Instruction::ZExt
)));
2918 return Create(opcode
, C
, Ty
, Name
, InsertAtEnd
);
2921 CastInst
*CastInst::CreateFPCast(Value
*C
, Type
*Ty
,
2923 Instruction
*InsertBefore
) {
2924 assert(C
->getType()->isFPOrFPVectorTy() && Ty
->isFPOrFPVectorTy() &&
2926 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2927 unsigned DstBits
= Ty
->getScalarSizeInBits();
2928 Instruction::CastOps opcode
=
2929 (SrcBits
== DstBits
? Instruction::BitCast
:
2930 (SrcBits
> DstBits
? Instruction::FPTrunc
: Instruction::FPExt
));
2931 return Create(opcode
, C
, Ty
, Name
, InsertBefore
);
2934 CastInst
*CastInst::CreateFPCast(Value
*C
, Type
*Ty
,
2936 BasicBlock
*InsertAtEnd
) {
2937 assert(C
->getType()->isFPOrFPVectorTy() && Ty
->isFPOrFPVectorTy() &&
2939 unsigned SrcBits
= C
->getType()->getScalarSizeInBits();
2940 unsigned DstBits
= Ty
->getScalarSizeInBits();
2941 Instruction::CastOps opcode
=
2942 (SrcBits
== DstBits
? Instruction::BitCast
:
2943 (SrcBits
> DstBits
? Instruction::FPTrunc
: Instruction::FPExt
));
2944 return Create(opcode
, C
, Ty
, Name
, InsertAtEnd
);
2947 // Check whether it is valid to call getCastOpcode for these types.
2948 // This routine must be kept in sync with getCastOpcode.
2949 bool CastInst::isCastable(Type
*SrcTy
, Type
*DestTy
) {
2950 if (!SrcTy
->isFirstClassType() || !DestTy
->isFirstClassType())
2953 if (SrcTy
== DestTy
)
2956 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
))
2957 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
))
2958 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
2959 // An element by element cast. Valid if casting the elements is valid.
2960 SrcTy
= SrcVecTy
->getElementType();
2961 DestTy
= DestVecTy
->getElementType();
2964 // Get the bit sizes, we'll need these
2965 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
2966 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
2968 // Run through the possibilities ...
2969 if (DestTy
->isIntegerTy()) { // Casting to integral
2970 if (SrcTy
->isIntegerTy()) // Casting from integral
2972 if (SrcTy
->isFloatingPointTy()) // Casting from floating pt
2974 if (SrcTy
->isVectorTy()) // Casting from vector
2975 return DestBits
== SrcBits
;
2976 // Casting from something else
2977 return SrcTy
->isPointerTy();
2979 if (DestTy
->isFloatingPointTy()) { // Casting to floating pt
2980 if (SrcTy
->isIntegerTy()) // Casting from integral
2982 if (SrcTy
->isFloatingPointTy()) // Casting from floating pt
2984 if (SrcTy
->isVectorTy()) // Casting from vector
2985 return DestBits
== SrcBits
;
2986 // Casting from something else
2989 if (DestTy
->isVectorTy()) // Casting to vector
2990 return DestBits
== SrcBits
;
2991 if (DestTy
->isPointerTy()) { // Casting to pointer
2992 if (SrcTy
->isPointerTy()) // Casting from pointer
2994 return SrcTy
->isIntegerTy(); // Casting from integral
2996 if (DestTy
->isX86_MMXTy()) {
2997 if (SrcTy
->isVectorTy())
2998 return DestBits
== SrcBits
; // 64-bit vector to MMX
3000 } // Casting to something else
3004 bool CastInst::isBitCastable(Type
*SrcTy
, Type
*DestTy
) {
3005 if (!SrcTy
->isFirstClassType() || !DestTy
->isFirstClassType())
3008 if (SrcTy
== DestTy
)
3011 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
)) {
3012 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
)) {
3013 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
3014 // An element by element cast. Valid if casting the elements is valid.
3015 SrcTy
= SrcVecTy
->getElementType();
3016 DestTy
= DestVecTy
->getElementType();
3021 if (PointerType
*DestPtrTy
= dyn_cast
<PointerType
>(DestTy
)) {
3022 if (PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
)) {
3023 return SrcPtrTy
->getAddressSpace() == DestPtrTy
->getAddressSpace();
3027 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
3028 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
3030 // Could still have vectors of pointers if the number of elements doesn't
3032 if (SrcBits
== 0 || DestBits
== 0)
3035 if (SrcBits
!= DestBits
)
3038 if (DestTy
->isX86_MMXTy() || SrcTy
->isX86_MMXTy())
3044 bool CastInst::isBitOrNoopPointerCastable(Type
*SrcTy
, Type
*DestTy
,
3045 const DataLayout
&DL
) {
3046 // ptrtoint and inttoptr are not allowed on non-integral pointers
3047 if (auto *PtrTy
= dyn_cast
<PointerType
>(SrcTy
))
3048 if (auto *IntTy
= dyn_cast
<IntegerType
>(DestTy
))
3049 return (IntTy
->getBitWidth() == DL
.getPointerTypeSizeInBits(PtrTy
) &&
3050 !DL
.isNonIntegralPointerType(PtrTy
));
3051 if (auto *PtrTy
= dyn_cast
<PointerType
>(DestTy
))
3052 if (auto *IntTy
= dyn_cast
<IntegerType
>(SrcTy
))
3053 return (IntTy
->getBitWidth() == DL
.getPointerTypeSizeInBits(PtrTy
) &&
3054 !DL
.isNonIntegralPointerType(PtrTy
));
3056 return isBitCastable(SrcTy
, DestTy
);
3059 // Provide a way to get a "cast" where the cast opcode is inferred from the
3060 // types and size of the operand. This, basically, is a parallel of the
3061 // logic in the castIsValid function below. This axiom should hold:
3062 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
3063 // should not assert in castIsValid. In other words, this produces a "correct"
3064 // casting opcode for the arguments passed to it.
3065 // This routine must be kept in sync with isCastable.
3066 Instruction::CastOps
3067 CastInst::getCastOpcode(
3068 const Value
*Src
, bool SrcIsSigned
, Type
*DestTy
, bool DestIsSigned
) {
3069 Type
*SrcTy
= Src
->getType();
3071 assert(SrcTy
->isFirstClassType() && DestTy
->isFirstClassType() &&
3072 "Only first class types are castable!");
3074 if (SrcTy
== DestTy
)
3077 // FIXME: Check address space sizes here
3078 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
))
3079 if (VectorType
*DestVecTy
= dyn_cast
<VectorType
>(DestTy
))
3080 if (SrcVecTy
->getNumElements() == DestVecTy
->getNumElements()) {
3081 // An element by element cast. Find the appropriate opcode based on the
3083 SrcTy
= SrcVecTy
->getElementType();
3084 DestTy
= DestVecTy
->getElementType();
3087 // Get the bit sizes, we'll need these
3088 unsigned SrcBits
= SrcTy
->getPrimitiveSizeInBits(); // 0 for ptr
3089 unsigned DestBits
= DestTy
->getPrimitiveSizeInBits(); // 0 for ptr
3091 // Run through the possibilities ...
3092 if (DestTy
->isIntegerTy()) { // Casting to integral
3093 if (SrcTy
->isIntegerTy()) { // Casting from integral
3094 if (DestBits
< SrcBits
)
3095 return Trunc
; // int -> smaller int
3096 else if (DestBits
> SrcBits
) { // its an extension
3098 return SExt
; // signed -> SEXT
3100 return ZExt
; // unsigned -> ZEXT
3102 return BitCast
; // Same size, No-op cast
3104 } else if (SrcTy
->isFloatingPointTy()) { // Casting from floating pt
3106 return FPToSI
; // FP -> sint
3108 return FPToUI
; // FP -> uint
3109 } else if (SrcTy
->isVectorTy()) {
3110 assert(DestBits
== SrcBits
&&
3111 "Casting vector to integer of different width");
3112 return BitCast
; // Same size, no-op cast
3114 assert(SrcTy
->isPointerTy() &&
3115 "Casting from a value that is not first-class type");
3116 return PtrToInt
; // ptr -> int
3118 } else if (DestTy
->isFloatingPointTy()) { // Casting to floating pt
3119 if (SrcTy
->isIntegerTy()) { // Casting from integral
3121 return SIToFP
; // sint -> FP
3123 return UIToFP
; // uint -> FP
3124 } else if (SrcTy
->isFloatingPointTy()) { // Casting from floating pt
3125 if (DestBits
< SrcBits
) {
3126 return FPTrunc
; // FP -> smaller FP
3127 } else if (DestBits
> SrcBits
) {
3128 return FPExt
; // FP -> larger FP
3130 return BitCast
; // same size, no-op cast
3132 } else if (SrcTy
->isVectorTy()) {
3133 assert(DestBits
== SrcBits
&&
3134 "Casting vector to floating point of different width");
3135 return BitCast
; // same size, no-op cast
3137 llvm_unreachable("Casting pointer or non-first class to float");
3138 } else if (DestTy
->isVectorTy()) {
3139 assert(DestBits
== SrcBits
&&
3140 "Illegal cast to vector (wrong type or size)");
3142 } else if (DestTy
->isPointerTy()) {
3143 if (SrcTy
->isPointerTy()) {
3144 if (DestTy
->getPointerAddressSpace() != SrcTy
->getPointerAddressSpace())
3145 return AddrSpaceCast
;
3146 return BitCast
; // ptr -> ptr
3147 } else if (SrcTy
->isIntegerTy()) {
3148 return IntToPtr
; // int -> ptr
3150 llvm_unreachable("Casting pointer to other than pointer or int");
3151 } else if (DestTy
->isX86_MMXTy()) {
3152 if (SrcTy
->isVectorTy()) {
3153 assert(DestBits
== SrcBits
&& "Casting vector of wrong width to X86_MMX");
3154 return BitCast
; // 64-bit vector to MMX
3156 llvm_unreachable("Illegal cast to X86_MMX");
3158 llvm_unreachable("Casting to type that is not first-class");
3161 //===----------------------------------------------------------------------===//
3162 // CastInst SubClass Constructors
3163 //===----------------------------------------------------------------------===//
3165 /// Check that the construction parameters for a CastInst are correct. This
3166 /// could be broken out into the separate constructors but it is useful to have
3167 /// it in one place and to eliminate the redundant code for getting the sizes
3168 /// of the types involved.
3170 CastInst::castIsValid(Instruction::CastOps op
, Value
*S
, Type
*DstTy
) {
3171 // Check for type sanity on the arguments
3172 Type
*SrcTy
= S
->getType();
3174 if (!SrcTy
->isFirstClassType() || !DstTy
->isFirstClassType() ||
3175 SrcTy
->isAggregateType() || DstTy
->isAggregateType())
3178 // Get the size of the types in bits, we'll need this later
3179 unsigned SrcBitSize
= SrcTy
->getScalarSizeInBits();
3180 unsigned DstBitSize
= DstTy
->getScalarSizeInBits();
3182 // If these are vector types, get the lengths of the vectors (using zero for
3183 // scalar types means that checking that vector lengths match also checks that
3184 // scalars are not being converted to vectors or vectors to scalars).
3185 unsigned SrcLength
= SrcTy
->isVectorTy() ?
3186 cast
<VectorType
>(SrcTy
)->getNumElements() : 0;
3187 unsigned DstLength
= DstTy
->isVectorTy() ?
3188 cast
<VectorType
>(DstTy
)->getNumElements() : 0;
3190 // Switch on the opcode provided
3192 default: return false; // This is an input error
3193 case Instruction::Trunc
:
3194 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3195 SrcLength
== DstLength
&& SrcBitSize
> DstBitSize
;
3196 case Instruction::ZExt
:
3197 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3198 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3199 case Instruction::SExt
:
3200 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3201 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3202 case Instruction::FPTrunc
:
3203 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3204 SrcLength
== DstLength
&& SrcBitSize
> DstBitSize
;
3205 case Instruction::FPExt
:
3206 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3207 SrcLength
== DstLength
&& SrcBitSize
< DstBitSize
;
3208 case Instruction::UIToFP
:
3209 case Instruction::SIToFP
:
3210 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isFPOrFPVectorTy() &&
3211 SrcLength
== DstLength
;
3212 case Instruction::FPToUI
:
3213 case Instruction::FPToSI
:
3214 return SrcTy
->isFPOrFPVectorTy() && DstTy
->isIntOrIntVectorTy() &&
3215 SrcLength
== DstLength
;
3216 case Instruction::PtrToInt
:
3217 if (isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(DstTy
))
3219 if (VectorType
*VT
= dyn_cast
<VectorType
>(SrcTy
))
3220 if (VT
->getNumElements() != cast
<VectorType
>(DstTy
)->getNumElements())
3222 return SrcTy
->isPtrOrPtrVectorTy() && DstTy
->isIntOrIntVectorTy();
3223 case Instruction::IntToPtr
:
3224 if (isa
<VectorType
>(SrcTy
) != isa
<VectorType
>(DstTy
))
3226 if (VectorType
*VT
= dyn_cast
<VectorType
>(SrcTy
))
3227 if (VT
->getNumElements() != cast
<VectorType
>(DstTy
)->getNumElements())
3229 return SrcTy
->isIntOrIntVectorTy() && DstTy
->isPtrOrPtrVectorTy();
3230 case Instruction::BitCast
: {
3231 PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
->getScalarType());
3232 PointerType
*DstPtrTy
= dyn_cast
<PointerType
>(DstTy
->getScalarType());
3234 // BitCast implies a no-op cast of type only. No bits change.
3235 // However, you can't cast pointers to anything but pointers.
3236 if (!SrcPtrTy
!= !DstPtrTy
)
3239 // For non-pointer cases, the cast is okay if the source and destination bit
3240 // widths are identical.
3242 return SrcTy
->getPrimitiveSizeInBits() == DstTy
->getPrimitiveSizeInBits();
3244 // If both are pointers then the address spaces must match.
3245 if (SrcPtrTy
->getAddressSpace() != DstPtrTy
->getAddressSpace())
3248 // A vector of pointers must have the same number of elements.
3249 VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
);
3250 VectorType
*DstVecTy
= dyn_cast
<VectorType
>(DstTy
);
3251 if (SrcVecTy
&& DstVecTy
)
3252 return (SrcVecTy
->getNumElements() == DstVecTy
->getNumElements());
3254 return SrcVecTy
->getNumElements() == 1;
3256 return DstVecTy
->getNumElements() == 1;
3260 case Instruction::AddrSpaceCast
: {
3261 PointerType
*SrcPtrTy
= dyn_cast
<PointerType
>(SrcTy
->getScalarType());
3265 PointerType
*DstPtrTy
= dyn_cast
<PointerType
>(DstTy
->getScalarType());
3269 if (SrcPtrTy
->getAddressSpace() == DstPtrTy
->getAddressSpace())
3272 if (VectorType
*SrcVecTy
= dyn_cast
<VectorType
>(SrcTy
)) {
3273 if (VectorType
*DstVecTy
= dyn_cast
<VectorType
>(DstTy
))
3274 return (SrcVecTy
->getNumElements() == DstVecTy
->getNumElements());
3284 TruncInst::TruncInst(
3285 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3286 ) : CastInst(Ty
, Trunc
, S
, Name
, InsertBefore
) {
3287 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal Trunc");
3290 TruncInst::TruncInst(
3291 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3292 ) : CastInst(Ty
, Trunc
, S
, Name
, InsertAtEnd
) {
3293 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal Trunc");
3297 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3298 ) : CastInst(Ty
, ZExt
, S
, Name
, InsertBefore
) {
3299 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal ZExt");
3303 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3304 ) : CastInst(Ty
, ZExt
, S
, Name
, InsertAtEnd
) {
3305 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal ZExt");
3308 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3309 ) : CastInst(Ty
, SExt
, S
, Name
, InsertBefore
) {
3310 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SExt");
3314 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3315 ) : CastInst(Ty
, SExt
, S
, Name
, InsertAtEnd
) {
3316 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SExt");
3319 FPTruncInst::FPTruncInst(
3320 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3321 ) : CastInst(Ty
, FPTrunc
, S
, Name
, InsertBefore
) {
3322 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPTrunc");
3325 FPTruncInst::FPTruncInst(
3326 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3327 ) : CastInst(Ty
, FPTrunc
, S
, Name
, InsertAtEnd
) {
3328 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPTrunc");
3331 FPExtInst::FPExtInst(
3332 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3333 ) : CastInst(Ty
, FPExt
, S
, Name
, InsertBefore
) {
3334 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPExt");
3337 FPExtInst::FPExtInst(
3338 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3339 ) : CastInst(Ty
, FPExt
, S
, Name
, InsertAtEnd
) {
3340 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPExt");
3343 UIToFPInst::UIToFPInst(
3344 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3345 ) : CastInst(Ty
, UIToFP
, S
, Name
, InsertBefore
) {
3346 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal UIToFP");
3349 UIToFPInst::UIToFPInst(
3350 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3351 ) : CastInst(Ty
, UIToFP
, S
, Name
, InsertAtEnd
) {
3352 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal UIToFP");
3355 SIToFPInst::SIToFPInst(
3356 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3357 ) : CastInst(Ty
, SIToFP
, S
, Name
, InsertBefore
) {
3358 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SIToFP");
3361 SIToFPInst::SIToFPInst(
3362 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3363 ) : CastInst(Ty
, SIToFP
, S
, Name
, InsertAtEnd
) {
3364 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal SIToFP");
3367 FPToUIInst::FPToUIInst(
3368 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3369 ) : CastInst(Ty
, FPToUI
, S
, Name
, InsertBefore
) {
3370 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToUI");
3373 FPToUIInst::FPToUIInst(
3374 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3375 ) : CastInst(Ty
, FPToUI
, S
, Name
, InsertAtEnd
) {
3376 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToUI");
3379 FPToSIInst::FPToSIInst(
3380 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3381 ) : CastInst(Ty
, FPToSI
, S
, Name
, InsertBefore
) {
3382 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToSI");
3385 FPToSIInst::FPToSIInst(
3386 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3387 ) : CastInst(Ty
, FPToSI
, S
, Name
, InsertAtEnd
) {
3388 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal FPToSI");
3391 PtrToIntInst::PtrToIntInst(
3392 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3393 ) : CastInst(Ty
, PtrToInt
, S
, Name
, InsertBefore
) {
3394 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal PtrToInt");
3397 PtrToIntInst::PtrToIntInst(
3398 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3399 ) : CastInst(Ty
, PtrToInt
, S
, Name
, InsertAtEnd
) {
3400 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal PtrToInt");
3403 IntToPtrInst::IntToPtrInst(
3404 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3405 ) : CastInst(Ty
, IntToPtr
, S
, Name
, InsertBefore
) {
3406 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal IntToPtr");
3409 IntToPtrInst::IntToPtrInst(
3410 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3411 ) : CastInst(Ty
, IntToPtr
, S
, Name
, InsertAtEnd
) {
3412 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal IntToPtr");
3415 BitCastInst::BitCastInst(
3416 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3417 ) : CastInst(Ty
, BitCast
, S
, Name
, InsertBefore
) {
3418 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal BitCast");
3421 BitCastInst::BitCastInst(
3422 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3423 ) : CastInst(Ty
, BitCast
, S
, Name
, InsertAtEnd
) {
3424 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal BitCast");
3427 AddrSpaceCastInst::AddrSpaceCastInst(
3428 Value
*S
, Type
*Ty
, const Twine
&Name
, Instruction
*InsertBefore
3429 ) : CastInst(Ty
, AddrSpaceCast
, S
, Name
, InsertBefore
) {
3430 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal AddrSpaceCast");
3433 AddrSpaceCastInst::AddrSpaceCastInst(
3434 Value
*S
, Type
*Ty
, const Twine
&Name
, BasicBlock
*InsertAtEnd
3435 ) : CastInst(Ty
, AddrSpaceCast
, S
, Name
, InsertAtEnd
) {
3436 assert(castIsValid(getOpcode(), S
, Ty
) && "Illegal AddrSpaceCast");
3439 //===----------------------------------------------------------------------===//
3441 //===----------------------------------------------------------------------===//
3443 CmpInst::CmpInst(Type
*ty
, OtherOps op
, Predicate predicate
, Value
*LHS
,
3444 Value
*RHS
, const Twine
&Name
, Instruction
*InsertBefore
,
3445 Instruction
*FlagsSource
)
3446 : Instruction(ty
, op
,
3447 OperandTraits
<CmpInst
>::op_begin(this),
3448 OperandTraits
<CmpInst
>::operands(this),
3452 setPredicate((Predicate
)predicate
);
3455 copyIRFlags(FlagsSource
);
3458 CmpInst::CmpInst(Type
*ty
, OtherOps op
, Predicate predicate
, Value
*LHS
,
3459 Value
*RHS
, const Twine
&Name
, BasicBlock
*InsertAtEnd
)
3460 : Instruction(ty
, op
,
3461 OperandTraits
<CmpInst
>::op_begin(this),
3462 OperandTraits
<CmpInst
>::operands(this),
3466 setPredicate((Predicate
)predicate
);
3471 CmpInst::Create(OtherOps Op
, Predicate predicate
, Value
*S1
, Value
*S2
,
3472 const Twine
&Name
, Instruction
*InsertBefore
) {
3473 if (Op
== Instruction::ICmp
) {
3475 return new ICmpInst(InsertBefore
, CmpInst::Predicate(predicate
),
3478 return new ICmpInst(CmpInst::Predicate(predicate
),
3483 return new FCmpInst(InsertBefore
, CmpInst::Predicate(predicate
),
3486 return new FCmpInst(CmpInst::Predicate(predicate
),
3491 CmpInst::Create(OtherOps Op
, Predicate predicate
, Value
*S1
, Value
*S2
,
3492 const Twine
&Name
, BasicBlock
*InsertAtEnd
) {
3493 if (Op
== Instruction::ICmp
) {
3494 return new ICmpInst(*InsertAtEnd
, CmpInst::Predicate(predicate
),
3497 return new FCmpInst(*InsertAtEnd
, CmpInst::Predicate(predicate
),
3501 void CmpInst::swapOperands() {
3502 if (ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3505 cast
<FCmpInst
>(this)->swapOperands();
3508 bool CmpInst::isCommutative() const {
3509 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3510 return IC
->isCommutative();
3511 return cast
<FCmpInst
>(this)->isCommutative();
3514 bool CmpInst::isEquality() const {
3515 if (const ICmpInst
*IC
= dyn_cast
<ICmpInst
>(this))
3516 return IC
->isEquality();
3517 return cast
<FCmpInst
>(this)->isEquality();
3520 CmpInst::Predicate
CmpInst::getInversePredicate(Predicate pred
) {
3522 default: llvm_unreachable("Unknown cmp predicate!");
3523 case ICMP_EQ
: return ICMP_NE
;
3524 case ICMP_NE
: return ICMP_EQ
;
3525 case ICMP_UGT
: return ICMP_ULE
;
3526 case ICMP_ULT
: return ICMP_UGE
;
3527 case ICMP_UGE
: return ICMP_ULT
;
3528 case ICMP_ULE
: return ICMP_UGT
;
3529 case ICMP_SGT
: return ICMP_SLE
;
3530 case ICMP_SLT
: return ICMP_SGE
;
3531 case ICMP_SGE
: return ICMP_SLT
;
3532 case ICMP_SLE
: return ICMP_SGT
;
3534 case FCMP_OEQ
: return FCMP_UNE
;
3535 case FCMP_ONE
: return FCMP_UEQ
;
3536 case FCMP_OGT
: return FCMP_ULE
;
3537 case FCMP_OLT
: return FCMP_UGE
;
3538 case FCMP_OGE
: return FCMP_ULT
;
3539 case FCMP_OLE
: return FCMP_UGT
;
3540 case FCMP_UEQ
: return FCMP_ONE
;
3541 case FCMP_UNE
: return FCMP_OEQ
;
3542 case FCMP_UGT
: return FCMP_OLE
;
3543 case FCMP_ULT
: return FCMP_OGE
;
3544 case FCMP_UGE
: return FCMP_OLT
;
3545 case FCMP_ULE
: return FCMP_OGT
;
3546 case FCMP_ORD
: return FCMP_UNO
;
3547 case FCMP_UNO
: return FCMP_ORD
;
3548 case FCMP_TRUE
: return FCMP_FALSE
;
3549 case FCMP_FALSE
: return FCMP_TRUE
;
3553 StringRef
CmpInst::getPredicateName(Predicate Pred
) {
3555 default: return "unknown";
3556 case FCmpInst::FCMP_FALSE
: return "false";
3557 case FCmpInst::FCMP_OEQ
: return "oeq";
3558 case FCmpInst::FCMP_OGT
: return "ogt";
3559 case FCmpInst::FCMP_OGE
: return "oge";
3560 case FCmpInst::FCMP_OLT
: return "olt";
3561 case FCmpInst::FCMP_OLE
: return "ole";
3562 case FCmpInst::FCMP_ONE
: return "one";
3563 case FCmpInst::FCMP_ORD
: return "ord";
3564 case FCmpInst::FCMP_UNO
: return "uno";
3565 case FCmpInst::FCMP_UEQ
: return "ueq";
3566 case FCmpInst::FCMP_UGT
: return "ugt";
3567 case FCmpInst::FCMP_UGE
: return "uge";
3568 case FCmpInst::FCMP_ULT
: return "ult";
3569 case FCmpInst::FCMP_ULE
: return "ule";
3570 case FCmpInst::FCMP_UNE
: return "une";
3571 case FCmpInst::FCMP_TRUE
: return "true";
3572 case ICmpInst::ICMP_EQ
: return "eq";
3573 case ICmpInst::ICMP_NE
: return "ne";
3574 case ICmpInst::ICMP_SGT
: return "sgt";
3575 case ICmpInst::ICMP_SGE
: return "sge";
3576 case ICmpInst::ICMP_SLT
: return "slt";
3577 case ICmpInst::ICMP_SLE
: return "sle";
3578 case ICmpInst::ICMP_UGT
: return "ugt";
3579 case ICmpInst::ICMP_UGE
: return "uge";
3580 case ICmpInst::ICMP_ULT
: return "ult";
3581 case ICmpInst::ICMP_ULE
: return "ule";
3585 ICmpInst::Predicate
ICmpInst::getSignedPredicate(Predicate pred
) {
3587 default: llvm_unreachable("Unknown icmp predicate!");
3588 case ICMP_EQ
: case ICMP_NE
:
3589 case ICMP_SGT
: case ICMP_SLT
: case ICMP_SGE
: case ICMP_SLE
:
3591 case ICMP_UGT
: return ICMP_SGT
;
3592 case ICMP_ULT
: return ICMP_SLT
;
3593 case ICMP_UGE
: return ICMP_SGE
;
3594 case ICMP_ULE
: return ICMP_SLE
;
3598 ICmpInst::Predicate
ICmpInst::getUnsignedPredicate(Predicate pred
) {
3600 default: llvm_unreachable("Unknown icmp predicate!");
3601 case ICMP_EQ
: case ICMP_NE
:
3602 case ICMP_UGT
: case ICMP_ULT
: case ICMP_UGE
: case ICMP_ULE
:
3604 case ICMP_SGT
: return ICMP_UGT
;
3605 case ICMP_SLT
: return ICMP_ULT
;
3606 case ICMP_SGE
: return ICMP_UGE
;
3607 case ICMP_SLE
: return ICMP_ULE
;
3611 CmpInst::Predicate
CmpInst::getFlippedStrictnessPredicate(Predicate pred
) {
3613 default: llvm_unreachable("Unknown or unsupported cmp predicate!");
3614 case ICMP_SGT
: return ICMP_SGE
;
3615 case ICMP_SLT
: return ICMP_SLE
;
3616 case ICMP_SGE
: return ICMP_SGT
;
3617 case ICMP_SLE
: return ICMP_SLT
;
3618 case ICMP_UGT
: return ICMP_UGE
;
3619 case ICMP_ULT
: return ICMP_ULE
;
3620 case ICMP_UGE
: return ICMP_UGT
;
3621 case ICMP_ULE
: return ICMP_ULT
;
3623 case FCMP_OGT
: return FCMP_OGE
;
3624 case FCMP_OLT
: return FCMP_OLE
;
3625 case FCMP_OGE
: return FCMP_OGT
;
3626 case FCMP_OLE
: return FCMP_OLT
;
3627 case FCMP_UGT
: return FCMP_UGE
;
3628 case FCMP_ULT
: return FCMP_ULE
;
3629 case FCMP_UGE
: return FCMP_UGT
;
3630 case FCMP_ULE
: return FCMP_ULT
;
3634 CmpInst::Predicate
CmpInst::getSwappedPredicate(Predicate pred
) {
3636 default: llvm_unreachable("Unknown cmp predicate!");
3637 case ICMP_EQ
: case ICMP_NE
:
3639 case ICMP_SGT
: return ICMP_SLT
;
3640 case ICMP_SLT
: return ICMP_SGT
;
3641 case ICMP_SGE
: return ICMP_SLE
;
3642 case ICMP_SLE
: return ICMP_SGE
;
3643 case ICMP_UGT
: return ICMP_ULT
;
3644 case ICMP_ULT
: return ICMP_UGT
;
3645 case ICMP_UGE
: return ICMP_ULE
;
3646 case ICMP_ULE
: return ICMP_UGE
;
3648 case FCMP_FALSE
: case FCMP_TRUE
:
3649 case FCMP_OEQ
: case FCMP_ONE
:
3650 case FCMP_UEQ
: case FCMP_UNE
:
3651 case FCMP_ORD
: case FCMP_UNO
:
3653 case FCMP_OGT
: return FCMP_OLT
;
3654 case FCMP_OLT
: return FCMP_OGT
;
3655 case FCMP_OGE
: return FCMP_OLE
;
3656 case FCMP_OLE
: return FCMP_OGE
;
3657 case FCMP_UGT
: return FCMP_ULT
;
3658 case FCMP_ULT
: return FCMP_UGT
;
3659 case FCMP_UGE
: return FCMP_ULE
;
3660 case FCMP_ULE
: return FCMP_UGE
;
3664 CmpInst::Predicate
CmpInst::getNonStrictPredicate(Predicate pred
) {
3666 case ICMP_SGT
: return ICMP_SGE
;
3667 case ICMP_SLT
: return ICMP_SLE
;
3668 case ICMP_UGT
: return ICMP_UGE
;
3669 case ICMP_ULT
: return ICMP_ULE
;
3670 case FCMP_OGT
: return FCMP_OGE
;
3671 case FCMP_OLT
: return FCMP_OLE
;
3672 case FCMP_UGT
: return FCMP_UGE
;
3673 case FCMP_ULT
: return FCMP_ULE
;
3674 default: return pred
;
3678 CmpInst::Predicate
CmpInst::getSignedPredicate(Predicate pred
) {
3679 assert(CmpInst::isUnsigned(pred
) && "Call only with signed predicates!");
3683 llvm_unreachable("Unknown predicate!");
3684 case CmpInst::ICMP_ULT
:
3685 return CmpInst::ICMP_SLT
;
3686 case CmpInst::ICMP_ULE
:
3687 return CmpInst::ICMP_SLE
;
3688 case CmpInst::ICMP_UGT
:
3689 return CmpInst::ICMP_SGT
;
3690 case CmpInst::ICMP_UGE
:
3691 return CmpInst::ICMP_SGE
;
3695 bool CmpInst::isUnsigned(Predicate predicate
) {
3696 switch (predicate
) {
3697 default: return false;
3698 case ICmpInst::ICMP_ULT
: case ICmpInst::ICMP_ULE
: case ICmpInst::ICMP_UGT
:
3699 case ICmpInst::ICMP_UGE
: return true;
3703 bool CmpInst::isSigned(Predicate predicate
) {
3704 switch (predicate
) {
3705 default: return false;
3706 case ICmpInst::ICMP_SLT
: case ICmpInst::ICMP_SLE
: case ICmpInst::ICMP_SGT
:
3707 case ICmpInst::ICMP_SGE
: return true;
3711 bool CmpInst::isOrdered(Predicate predicate
) {
3712 switch (predicate
) {
3713 default: return false;
3714 case FCmpInst::FCMP_OEQ
: case FCmpInst::FCMP_ONE
: case FCmpInst::FCMP_OGT
:
3715 case FCmpInst::FCMP_OLT
: case FCmpInst::FCMP_OGE
: case FCmpInst::FCMP_OLE
:
3716 case FCmpInst::FCMP_ORD
: return true;
3720 bool CmpInst::isUnordered(Predicate predicate
) {
3721 switch (predicate
) {
3722 default: return false;
3723 case FCmpInst::FCMP_UEQ
: case FCmpInst::FCMP_UNE
: case FCmpInst::FCMP_UGT
:
3724 case FCmpInst::FCMP_ULT
: case FCmpInst::FCMP_UGE
: case FCmpInst::FCMP_ULE
:
3725 case FCmpInst::FCMP_UNO
: return true;
3729 bool CmpInst::isTrueWhenEqual(Predicate predicate
) {
3731 default: return false;
3732 case ICMP_EQ
: case ICMP_UGE
: case ICMP_ULE
: case ICMP_SGE
: case ICMP_SLE
:
3733 case FCMP_TRUE
: case FCMP_UEQ
: case FCMP_UGE
: case FCMP_ULE
: return true;
3737 bool CmpInst::isFalseWhenEqual(Predicate predicate
) {
3739 case ICMP_NE
: case ICMP_UGT
: case ICMP_ULT
: case ICMP_SGT
: case ICMP_SLT
:
3740 case FCMP_FALSE
: case FCMP_ONE
: case FCMP_OGT
: case FCMP_OLT
: return true;
3741 default: return false;
3745 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1
, Predicate Pred2
) {
3746 // If the predicates match, then we know the first condition implies the
3755 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
3756 return Pred2
== ICMP_UGE
|| Pred2
== ICMP_ULE
|| Pred2
== ICMP_SGE
||
3758 case ICMP_UGT
: // A >u B implies A != B and A >=u B are true.
3759 return Pred2
== ICMP_NE
|| Pred2
== ICMP_UGE
;
3760 case ICMP_ULT
: // A <u B implies A != B and A <=u B are true.
3761 return Pred2
== ICMP_NE
|| Pred2
== ICMP_ULE
;
3762 case ICMP_SGT
: // A >s B implies A != B and A >=s B are true.
3763 return Pred2
== ICMP_NE
|| Pred2
== ICMP_SGE
;
3764 case ICMP_SLT
: // A <s B implies A != B and A <=s B are true.
3765 return Pred2
== ICMP_NE
|| Pred2
== ICMP_SLE
;
3770 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1
, Predicate Pred2
) {
3771 return isImpliedTrueByMatchingCmp(Pred1
, getInversePredicate(Pred2
));
3774 //===----------------------------------------------------------------------===//
3775 // SwitchInst Implementation
3776 //===----------------------------------------------------------------------===//
3778 void SwitchInst::init(Value
*Value
, BasicBlock
*Default
, unsigned NumReserved
) {
3779 assert(Value
&& Default
&& NumReserved
);
3780 ReservedSpace
= NumReserved
;
3781 setNumHungOffUseOperands(2);
3782 allocHungoffUses(ReservedSpace
);
3788 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3789 /// switch on and a default destination. The number of additional cases can
3790 /// be specified here to make memory allocation more efficient. This
3791 /// constructor can also autoinsert before another instruction.
3792 SwitchInst::SwitchInst(Value
*Value
, BasicBlock
*Default
, unsigned NumCases
,
3793 Instruction
*InsertBefore
)
3794 : Instruction(Type::getVoidTy(Value
->getContext()), Instruction::Switch
,
3795 nullptr, 0, InsertBefore
) {
3796 init(Value
, Default
, 2+NumCases
*2);
3799 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3800 /// switch on and a default destination. The number of additional cases can
3801 /// be specified here to make memory allocation more efficient. This
3802 /// constructor also autoinserts at the end of the specified BasicBlock.
3803 SwitchInst::SwitchInst(Value
*Value
, BasicBlock
*Default
, unsigned NumCases
,
3804 BasicBlock
*InsertAtEnd
)
3805 : Instruction(Type::getVoidTy(Value
->getContext()), Instruction::Switch
,
3806 nullptr, 0, InsertAtEnd
) {
3807 init(Value
, Default
, 2+NumCases
*2);
3810 SwitchInst::SwitchInst(const SwitchInst
&SI
)
3811 : Instruction(SI
.getType(), Instruction::Switch
, nullptr, 0) {
3812 init(SI
.getCondition(), SI
.getDefaultDest(), SI
.getNumOperands());
3813 setNumHungOffUseOperands(SI
.getNumOperands());
3814 Use
*OL
= getOperandList();
3815 const Use
*InOL
= SI
.getOperandList();
3816 for (unsigned i
= 2, E
= SI
.getNumOperands(); i
!= E
; i
+= 2) {
3818 OL
[i
+1] = InOL
[i
+1];
3820 SubclassOptionalData
= SI
.SubclassOptionalData
;
3823 /// addCase - Add an entry to the switch instruction...
3825 void SwitchInst::addCase(ConstantInt
*OnVal
, BasicBlock
*Dest
) {
3826 unsigned NewCaseIdx
= getNumCases();
3827 unsigned OpNo
= getNumOperands();
3828 if (OpNo
+2 > ReservedSpace
)
3829 growOperands(); // Get more space!
3830 // Initialize some new operands.
3831 assert(OpNo
+1 < ReservedSpace
&& "Growing didn't work!");
3832 setNumHungOffUseOperands(OpNo
+2);
3833 CaseHandle
Case(this, NewCaseIdx
);
3834 Case
.setValue(OnVal
);
3835 Case
.setSuccessor(Dest
);
3838 /// removeCase - This method removes the specified case and its successor
3839 /// from the switch instruction.
3840 SwitchInst::CaseIt
SwitchInst::removeCase(CaseIt I
) {
3841 unsigned idx
= I
->getCaseIndex();
3843 assert(2 + idx
*2 < getNumOperands() && "Case index out of range!!!");
3845 unsigned NumOps
= getNumOperands();
3846 Use
*OL
= getOperandList();
3848 // Overwrite this case with the end of the list.
3849 if (2 + (idx
+ 1) * 2 != NumOps
) {
3850 OL
[2 + idx
* 2] = OL
[NumOps
- 2];
3851 OL
[2 + idx
* 2 + 1] = OL
[NumOps
- 1];
3854 // Nuke the last value.
3855 OL
[NumOps
-2].set(nullptr);
3856 OL
[NumOps
-2+1].set(nullptr);
3857 setNumHungOffUseOperands(NumOps
-2);
3859 return CaseIt(this, idx
);
3862 /// growOperands - grow operands - This grows the operand list in response
3863 /// to a push_back style of operation. This grows the number of ops by 3 times.
3865 void SwitchInst::growOperands() {
3866 unsigned e
= getNumOperands();
3867 unsigned NumOps
= e
*3;
3869 ReservedSpace
= NumOps
;
3870 growHungoffUses(ReservedSpace
);
3873 //===----------------------------------------------------------------------===//
3874 // IndirectBrInst Implementation
3875 //===----------------------------------------------------------------------===//
3877 void IndirectBrInst::init(Value
*Address
, unsigned NumDests
) {
3878 assert(Address
&& Address
->getType()->isPointerTy() &&
3879 "Address of indirectbr must be a pointer");
3880 ReservedSpace
= 1+NumDests
;
3881 setNumHungOffUseOperands(1);
3882 allocHungoffUses(ReservedSpace
);
3888 /// growOperands - grow operands - This grows the operand list in response
3889 /// to a push_back style of operation. This grows the number of ops by 2 times.
3891 void IndirectBrInst::growOperands() {
3892 unsigned e
= getNumOperands();
3893 unsigned NumOps
= e
*2;
3895 ReservedSpace
= NumOps
;
3896 growHungoffUses(ReservedSpace
);
3899 IndirectBrInst::IndirectBrInst(Value
*Address
, unsigned NumCases
,
3900 Instruction
*InsertBefore
)
3901 : Instruction(Type::getVoidTy(Address
->getContext()),
3902 Instruction::IndirectBr
, nullptr, 0, InsertBefore
) {
3903 init(Address
, NumCases
);
3906 IndirectBrInst::IndirectBrInst(Value
*Address
, unsigned NumCases
,
3907 BasicBlock
*InsertAtEnd
)
3908 : Instruction(Type::getVoidTy(Address
->getContext()),
3909 Instruction::IndirectBr
, nullptr, 0, InsertAtEnd
) {
3910 init(Address
, NumCases
);
3913 IndirectBrInst::IndirectBrInst(const IndirectBrInst
&IBI
)
3914 : Instruction(Type::getVoidTy(IBI
.getContext()), Instruction::IndirectBr
,
3915 nullptr, IBI
.getNumOperands()) {
3916 allocHungoffUses(IBI
.getNumOperands());
3917 Use
*OL
= getOperandList();
3918 const Use
*InOL
= IBI
.getOperandList();
3919 for (unsigned i
= 0, E
= IBI
.getNumOperands(); i
!= E
; ++i
)
3921 SubclassOptionalData
= IBI
.SubclassOptionalData
;
3924 /// addDestination - Add a destination.
3926 void IndirectBrInst::addDestination(BasicBlock
*DestBB
) {
3927 unsigned OpNo
= getNumOperands();
3928 if (OpNo
+1 > ReservedSpace
)
3929 growOperands(); // Get more space!
3930 // Initialize some new operands.
3931 assert(OpNo
< ReservedSpace
&& "Growing didn't work!");
3932 setNumHungOffUseOperands(OpNo
+1);
3933 getOperandList()[OpNo
] = DestBB
;
3936 /// removeDestination - This method removes the specified successor from the
3937 /// indirectbr instruction.
3938 void IndirectBrInst::removeDestination(unsigned idx
) {
3939 assert(idx
< getNumOperands()-1 && "Successor index out of range!");
3941 unsigned NumOps
= getNumOperands();
3942 Use
*OL
= getOperandList();
3944 // Replace this value with the last one.
3945 OL
[idx
+1] = OL
[NumOps
-1];
3947 // Nuke the last value.
3948 OL
[NumOps
-1].set(nullptr);
3949 setNumHungOffUseOperands(NumOps
-1);
3952 //===----------------------------------------------------------------------===//
3953 // cloneImpl() implementations
3954 //===----------------------------------------------------------------------===//
3956 // Define these methods here so vtables don't get emitted into every translation
3957 // unit that uses these classes.
3959 GetElementPtrInst
*GetElementPtrInst::cloneImpl() const {
3960 return new (getNumOperands()) GetElementPtrInst(*this);
3963 UnaryOperator
*UnaryOperator::cloneImpl() const {
3964 return Create(getOpcode(), Op
<0>());
3967 BinaryOperator
*BinaryOperator::cloneImpl() const {
3968 return Create(getOpcode(), Op
<0>(), Op
<1>());
3971 FCmpInst
*FCmpInst::cloneImpl() const {
3972 return new FCmpInst(getPredicate(), Op
<0>(), Op
<1>());
3975 ICmpInst
*ICmpInst::cloneImpl() const {
3976 return new ICmpInst(getPredicate(), Op
<0>(), Op
<1>());
3979 ExtractValueInst
*ExtractValueInst::cloneImpl() const {
3980 return new ExtractValueInst(*this);
3983 InsertValueInst
*InsertValueInst::cloneImpl() const {
3984 return new InsertValueInst(*this);
3987 AllocaInst
*AllocaInst::cloneImpl() const {
3988 AllocaInst
*Result
= new AllocaInst(getAllocatedType(),
3989 getType()->getAddressSpace(),
3990 (Value
*)getOperand(0), getAlignment());
3991 Result
->setUsedWithInAlloca(isUsedWithInAlloca());
3992 Result
->setSwiftError(isSwiftError());
3996 LoadInst
*LoadInst::cloneImpl() const {
3997 return new LoadInst(getType(), getOperand(0), Twine(), isVolatile(),
3998 getAlignment(), getOrdering(), getSyncScopeID());
4001 StoreInst
*StoreInst::cloneImpl() const {
4002 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
4003 getAlignment(), getOrdering(), getSyncScopeID());
4007 AtomicCmpXchgInst
*AtomicCmpXchgInst::cloneImpl() const {
4008 AtomicCmpXchgInst
*Result
=
4009 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
4010 getSuccessOrdering(), getFailureOrdering(),
4012 Result
->setVolatile(isVolatile());
4013 Result
->setWeak(isWeak());
4017 AtomicRMWInst
*AtomicRMWInst::cloneImpl() const {
4018 AtomicRMWInst
*Result
=
4019 new AtomicRMWInst(getOperation(), getOperand(0), getOperand(1),
4020 getOrdering(), getSyncScopeID());
4021 Result
->setVolatile(isVolatile());
4025 FenceInst
*FenceInst::cloneImpl() const {
4026 return new FenceInst(getContext(), getOrdering(), getSyncScopeID());
4029 TruncInst
*TruncInst::cloneImpl() const {
4030 return new TruncInst(getOperand(0), getType());
4033 ZExtInst
*ZExtInst::cloneImpl() const {
4034 return new ZExtInst(getOperand(0), getType());
4037 SExtInst
*SExtInst::cloneImpl() const {
4038 return new SExtInst(getOperand(0), getType());
4041 FPTruncInst
*FPTruncInst::cloneImpl() const {
4042 return new FPTruncInst(getOperand(0), getType());
4045 FPExtInst
*FPExtInst::cloneImpl() const {
4046 return new FPExtInst(getOperand(0), getType());
4049 UIToFPInst
*UIToFPInst::cloneImpl() const {
4050 return new UIToFPInst(getOperand(0), getType());
4053 SIToFPInst
*SIToFPInst::cloneImpl() const {
4054 return new SIToFPInst(getOperand(0), getType());
4057 FPToUIInst
*FPToUIInst::cloneImpl() const {
4058 return new FPToUIInst(getOperand(0), getType());
4061 FPToSIInst
*FPToSIInst::cloneImpl() const {
4062 return new FPToSIInst(getOperand(0), getType());
4065 PtrToIntInst
*PtrToIntInst::cloneImpl() const {
4066 return new PtrToIntInst(getOperand(0), getType());
4069 IntToPtrInst
*IntToPtrInst::cloneImpl() const {
4070 return new IntToPtrInst(getOperand(0), getType());
4073 BitCastInst
*BitCastInst::cloneImpl() const {
4074 return new BitCastInst(getOperand(0), getType());
4077 AddrSpaceCastInst
*AddrSpaceCastInst::cloneImpl() const {
4078 return new AddrSpaceCastInst(getOperand(0), getType());
4081 CallInst
*CallInst::cloneImpl() const {
4082 if (hasOperandBundles()) {
4083 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4084 return new(getNumOperands(), DescriptorBytes
) CallInst(*this);
4086 return new(getNumOperands()) CallInst(*this);
4089 SelectInst
*SelectInst::cloneImpl() const {
4090 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
4093 VAArgInst
*VAArgInst::cloneImpl() const {
4094 return new VAArgInst(getOperand(0), getType());
4097 ExtractElementInst
*ExtractElementInst::cloneImpl() const {
4098 return ExtractElementInst::Create(getOperand(0), getOperand(1));
4101 InsertElementInst
*InsertElementInst::cloneImpl() const {
4102 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4105 ShuffleVectorInst
*ShuffleVectorInst::cloneImpl() const {
4106 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4109 PHINode
*PHINode::cloneImpl() const { return new PHINode(*this); }
4111 LandingPadInst
*LandingPadInst::cloneImpl() const {
4112 return new LandingPadInst(*this);
4115 ReturnInst
*ReturnInst::cloneImpl() const {
4116 return new(getNumOperands()) ReturnInst(*this);
4119 BranchInst
*BranchInst::cloneImpl() const {
4120 return new(getNumOperands()) BranchInst(*this);
4123 SwitchInst
*SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4125 IndirectBrInst
*IndirectBrInst::cloneImpl() const {
4126 return new IndirectBrInst(*this);
4129 InvokeInst
*InvokeInst::cloneImpl() const {
4130 if (hasOperandBundles()) {
4131 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4132 return new(getNumOperands(), DescriptorBytes
) InvokeInst(*this);
4134 return new(getNumOperands()) InvokeInst(*this);
4137 CallBrInst
*CallBrInst::cloneImpl() const {
4138 if (hasOperandBundles()) {
4139 unsigned DescriptorBytes
= getNumOperandBundles() * sizeof(BundleOpInfo
);
4140 return new (getNumOperands(), DescriptorBytes
) CallBrInst(*this);
4142 return new (getNumOperands()) CallBrInst(*this);
4145 ResumeInst
*ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4147 CleanupReturnInst
*CleanupReturnInst::cloneImpl() const {
4148 return new (getNumOperands()) CleanupReturnInst(*this);
4151 CatchReturnInst
*CatchReturnInst::cloneImpl() const {
4152 return new (getNumOperands()) CatchReturnInst(*this);
4155 CatchSwitchInst
*CatchSwitchInst::cloneImpl() const {
4156 return new CatchSwitchInst(*this);
4159 FuncletPadInst
*FuncletPadInst::cloneImpl() const {
4160 return new (getNumOperands()) FuncletPadInst(*this);
4163 UnreachableInst
*UnreachableInst::cloneImpl() const {
4164 LLVMContext
&Context
= getContext();
4165 return new UnreachableInst(Context
);