1 //===-- Instructions.cpp - Implement the LLVM instructions ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements all of the non-inline methods for the LLVM instruction
13 //===----------------------------------------------------------------------===//
15 #include "llvm/IR/Instructions.h"
16 #include "LLVMContextImpl.h"
17 #include "llvm/IR/CallSite.h"
18 #include "llvm/IR/ConstantRange.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Operator.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/MathExtras.h"
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 User::op_iterator CallSite::getCallee() const {
34 Instruction *II(getInstruction());
36 ? cast<CallInst>(II)->op_end() - 1 // Skip Callee
37 : cast<InvokeInst>(II)->op_end() - 3; // Skip BB, BB, Callee
40 //===----------------------------------------------------------------------===//
41 // TerminatorInst Class
42 //===----------------------------------------------------------------------===//
44 // Out of line virtual method, so the vtable, etc has a home.
45 TerminatorInst::~TerminatorInst() {
48 //===----------------------------------------------------------------------===//
49 // UnaryInstruction Class
50 //===----------------------------------------------------------------------===//
52 // Out of line virtual method, so the vtable, etc has a home.
53 UnaryInstruction::~UnaryInstruction() {
56 //===----------------------------------------------------------------------===//
58 //===----------------------------------------------------------------------===//
60 /// areInvalidOperands - Return a string if the specified operands are invalid
61 /// for a select operation, otherwise return null.
62 const char *SelectInst::areInvalidOperands(Value *Op0, Value *Op1, Value *Op2) {
63 if (Op1->getType() != Op2->getType())
64 return "both values to select must have same type";
66 if (Op1->getType()->isTokenTy())
67 return "select values cannot have token type";
69 if (VectorType *VT = dyn_cast<VectorType>(Op0->getType())) {
71 if (VT->getElementType() != Type::getInt1Ty(Op0->getContext()))
72 return "vector select condition element type must be i1";
73 VectorType *ET = dyn_cast<VectorType>(Op1->getType());
75 return "selected values for vector select must be vectors";
76 if (ET->getNumElements() != VT->getNumElements())
77 return "vector select requires selected vectors to have "
78 "the same vector length as select condition";
79 } else if (Op0->getType() != Type::getInt1Ty(Op0->getContext())) {
80 return "select condition must be i1 or <n x i1>";
86 //===----------------------------------------------------------------------===//
88 //===----------------------------------------------------------------------===//
90 PHINode::PHINode(const PHINode &PN)
91 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
92 ReservedSpace(PN.getNumOperands()) {
93 allocHungoffUses(PN.getNumOperands());
94 std::copy(PN.op_begin(), PN.op_end(), op_begin());
95 std::copy(PN.block_begin(), PN.block_end(), block_begin());
96 SubclassOptionalData = PN.SubclassOptionalData;
99 // removeIncomingValue - Remove an incoming value. This is useful if a
100 // predecessor basic block is deleted.
101 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
102 Value *Removed = getIncomingValue(Idx);
104 // Move everything after this operand down.
106 // FIXME: we could just swap with the end of the list, then erase. However,
107 // clients might not expect this to happen. The code as it is thrashes the
108 // use/def lists, which is kinda lame.
109 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
110 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
112 // Nuke the last value.
113 Op<-1>().set(nullptr);
114 setNumHungOffUseOperands(getNumOperands() - 1);
116 // If the PHI node is dead, because it has zero entries, nuke it now.
117 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
118 // If anyone is using this PHI, make them use a dummy value instead...
119 replaceAllUsesWith(UndefValue::get(getType()));
125 /// growOperands - grow operands - This grows the operand list in response
126 /// to a push_back style of operation. This grows the number of ops by 1.5
129 void PHINode::growOperands() {
130 unsigned e = getNumOperands();
131 unsigned NumOps = e + e / 2;
132 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
134 ReservedSpace = NumOps;
135 growHungoffUses(ReservedSpace, /* IsPhi */ true);
138 /// hasConstantValue - If the specified PHI node always merges together the same
139 /// value, return the value, otherwise return null.
140 Value *PHINode::hasConstantValue() const {
141 // Exploit the fact that phi nodes always have at least one entry.
142 Value *ConstantValue = getIncomingValue(0);
143 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
144 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
145 if (ConstantValue != this)
146 return nullptr; // Incoming values not all the same.
147 // The case where the first value is this PHI.
148 ConstantValue = getIncomingValue(i);
150 if (ConstantValue == this)
151 return UndefValue::get(getType());
152 return ConstantValue;
155 //===----------------------------------------------------------------------===//
156 // LandingPadInst Implementation
157 //===----------------------------------------------------------------------===//
159 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
160 const Twine &NameStr, Instruction *InsertBefore)
161 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
162 init(NumReservedValues, NameStr);
165 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
166 const Twine &NameStr, BasicBlock *InsertAtEnd)
167 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
168 init(NumReservedValues, NameStr);
171 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
172 : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
173 LP.getNumOperands()),
174 ReservedSpace(LP.getNumOperands()) {
175 allocHungoffUses(LP.getNumOperands());
176 Use *OL = getOperandList();
177 const Use *InOL = LP.getOperandList();
178 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
181 setCleanup(LP.isCleanup());
184 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
185 const Twine &NameStr,
186 Instruction *InsertBefore) {
187 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
190 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
191 const Twine &NameStr,
192 BasicBlock *InsertAtEnd) {
193 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
196 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
197 ReservedSpace = NumReservedValues;
198 setNumHungOffUseOperands(0);
199 allocHungoffUses(ReservedSpace);
204 /// growOperands - grow operands - This grows the operand list in response to a
205 /// push_back style of operation. This grows the number of ops by 2 times.
206 void LandingPadInst::growOperands(unsigned Size) {
207 unsigned e = getNumOperands();
208 if (ReservedSpace >= e + Size) return;
209 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
210 growHungoffUses(ReservedSpace);
213 void LandingPadInst::addClause(Constant *Val) {
214 unsigned OpNo = getNumOperands();
216 assert(OpNo < ReservedSpace && "Growing didn't work!");
217 setNumHungOffUseOperands(getNumOperands() + 1);
218 getOperandList()[OpNo] = Val;
221 //===----------------------------------------------------------------------===//
222 // CallInst Implementation
223 //===----------------------------------------------------------------------===//
225 CallInst::~CallInst() {
228 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
229 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
231 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
232 "NumOperands not set up?");
236 assert((Args.size() == FTy->getNumParams() ||
237 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
238 "Calling a function with bad signature!");
240 for (unsigned i = 0; i != Args.size(); ++i)
241 assert((i >= FTy->getNumParams() ||
242 FTy->getParamType(i) == Args[i]->getType()) &&
243 "Calling a function with a bad signature!");
246 std::copy(Args.begin(), Args.end(), op_begin());
248 auto It = populateBundleOperandInfos(Bundles, Args.size());
250 assert(It + 1 == op_end() && "Should add up!");
255 void CallInst::init(Value *Func, const Twine &NameStr) {
257 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
258 assert(getNumOperands() == 1 && "NumOperands not set up?");
261 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
266 CallInst::CallInst(Value *Func, const Twine &Name,
267 Instruction *InsertBefore)
268 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
269 ->getElementType())->getReturnType(),
271 OperandTraits<CallInst>::op_end(this) - 1,
276 CallInst::CallInst(Value *Func, const Twine &Name,
277 BasicBlock *InsertAtEnd)
278 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
279 ->getElementType())->getReturnType(),
281 OperandTraits<CallInst>::op_end(this) - 1,
286 CallInst::CallInst(const CallInst &CI)
287 : Instruction(CI.getType(), Instruction::Call,
288 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
289 CI.getNumOperands()),
290 AttributeList(CI.AttributeList), FTy(CI.FTy) {
291 setTailCallKind(CI.getTailCallKind());
292 setCallingConv(CI.getCallingConv());
294 std::copy(CI.op_begin(), CI.op_end(), op_begin());
295 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
296 bundle_op_info_begin());
297 SubclassOptionalData = CI.SubclassOptionalData;
300 void CallInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
301 AttributeSet PAL = getAttributes();
302 PAL = PAL.addAttribute(getContext(), i, attr);
306 void CallInst::addAttribute(unsigned i, StringRef Kind, StringRef Value) {
307 AttributeSet PAL = getAttributes();
308 PAL = PAL.addAttribute(getContext(), i, Kind, Value);
312 void CallInst::removeAttribute(unsigned i, Attribute attr) {
313 AttributeSet PAL = getAttributes();
315 LLVMContext &Context = getContext();
316 PAL = PAL.removeAttributes(Context, i,
317 AttributeSet::get(Context, i, B));
321 void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
322 AttributeSet PAL = getAttributes();
323 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
327 void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
328 AttributeSet PAL = getAttributes();
329 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
333 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
334 if (AttributeList.hasAttribute(i, A))
336 if (const Function *F = getCalledFunction())
337 return F->getAttributes().hasAttribute(i, A);
341 /// IsConstantOne - Return true only if val is constant int 1
342 static bool IsConstantOne(Value *val) {
343 assert(val && "IsConstantOne does not work with nullptr val");
344 const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
345 return CVal && CVal->isOne();
348 static Instruction *createMalloc(Instruction *InsertBefore,
349 BasicBlock *InsertAtEnd, Type *IntPtrTy,
350 Type *AllocTy, Value *AllocSize,
351 Value *ArraySize, Function *MallocF,
353 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
354 "createMalloc needs either InsertBefore or InsertAtEnd");
356 // malloc(type) becomes:
357 // bitcast (i8* malloc(typeSize)) to type*
358 // malloc(type, arraySize) becomes:
359 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
361 ArraySize = ConstantInt::get(IntPtrTy, 1);
362 else if (ArraySize->getType() != IntPtrTy) {
364 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
367 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
371 if (!IsConstantOne(ArraySize)) {
372 if (IsConstantOne(AllocSize)) {
373 AllocSize = ArraySize; // Operand * 1 = Operand
374 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
375 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
377 // Malloc arg is constant product of type size and array size
378 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
380 // Multiply type size by the array size...
382 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
383 "mallocsize", InsertBefore);
385 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
386 "mallocsize", InsertAtEnd);
390 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
391 // Create the call to Malloc.
392 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
393 Module* M = BB->getParent()->getParent();
394 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
395 Value *MallocFunc = MallocF;
397 // prototype malloc as "void *malloc(size_t)"
398 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr);
399 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
400 CallInst *MCall = nullptr;
401 Instruction *Result = nullptr;
403 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
405 if (Result->getType() != AllocPtrType)
406 // Create a cast instruction to convert to the right type...
407 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
409 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
411 if (Result->getType() != AllocPtrType) {
412 InsertAtEnd->getInstList().push_back(MCall);
413 // Create a cast instruction to convert to the right type...
414 Result = new BitCastInst(MCall, AllocPtrType, Name);
417 MCall->setTailCall();
418 if (Function *F = dyn_cast<Function>(MallocFunc)) {
419 MCall->setCallingConv(F->getCallingConv());
420 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
422 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
427 /// CreateMalloc - Generate the IR for a call to malloc:
428 /// 1. Compute the malloc call's argument as the specified type's size,
429 /// possibly multiplied by the array size if the array size is not
431 /// 2. Call malloc with that argument.
432 /// 3. Bitcast the result of the malloc call to the specified type.
433 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
434 Type *IntPtrTy, Type *AllocTy,
435 Value *AllocSize, Value *ArraySize,
438 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
439 ArraySize, MallocF, Name);
442 /// CreateMalloc - Generate the IR for a call to malloc:
443 /// 1. Compute the malloc call's argument as the specified type's size,
444 /// possibly multiplied by the array size if the array size is not
446 /// 2. Call malloc with that argument.
447 /// 3. Bitcast the result of the malloc call to the specified type.
448 /// Note: This function does not add the bitcast to the basic block, that is the
449 /// responsibility of the caller.
450 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
451 Type *IntPtrTy, Type *AllocTy,
452 Value *AllocSize, Value *ArraySize,
453 Function *MallocF, const Twine &Name) {
454 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
455 ArraySize, MallocF, Name);
458 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
459 BasicBlock *InsertAtEnd) {
460 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
461 "createFree needs either InsertBefore or InsertAtEnd");
462 assert(Source->getType()->isPointerTy() &&
463 "Can not free something of nonpointer type!");
465 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
466 Module* M = BB->getParent()->getParent();
468 Type *VoidTy = Type::getVoidTy(M->getContext());
469 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
470 // prototype free as "void free(void*)"
471 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr);
472 CallInst* Result = nullptr;
473 Value *PtrCast = Source;
475 if (Source->getType() != IntPtrTy)
476 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
477 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
479 if (Source->getType() != IntPtrTy)
480 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
481 Result = CallInst::Create(FreeFunc, PtrCast, "");
483 Result->setTailCall();
484 if (Function *F = dyn_cast<Function>(FreeFunc))
485 Result->setCallingConv(F->getCallingConv());
490 /// CreateFree - Generate the IR for a call to the builtin free function.
491 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
492 return createFree(Source, InsertBefore, nullptr);
495 /// CreateFree - Generate the IR for a call to the builtin free function.
496 /// Note: This function does not add the call to the basic block, that is the
497 /// responsibility of the caller.
498 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
499 Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd);
500 assert(FreeCall && "CreateFree did not create a CallInst");
504 //===----------------------------------------------------------------------===//
505 // InvokeInst Implementation
506 //===----------------------------------------------------------------------===//
508 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
509 BasicBlock *IfException, ArrayRef<Value *> Args,
510 ArrayRef<OperandBundleDef> Bundles,
511 const Twine &NameStr) {
514 assert(getNumOperands() == 3 + Args.size() + CountBundleInputs(Bundles) &&
515 "NumOperands not set up?");
518 Op<-1>() = IfException;
521 assert(((Args.size() == FTy->getNumParams()) ||
522 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
523 "Invoking a function with bad signature");
525 for (unsigned i = 0, e = Args.size(); i != e; i++)
526 assert((i >= FTy->getNumParams() ||
527 FTy->getParamType(i) == Args[i]->getType()) &&
528 "Invoking a function with a bad signature!");
531 std::copy(Args.begin(), Args.end(), op_begin());
533 auto It = populateBundleOperandInfos(Bundles, Args.size());
535 assert(It + 3 == op_end() && "Should add up!");
540 InvokeInst::InvokeInst(const InvokeInst &II)
541 : TerminatorInst(II.getType(), Instruction::Invoke,
542 OperandTraits<InvokeInst>::op_end(this) -
544 II.getNumOperands()),
545 AttributeList(II.AttributeList), FTy(II.FTy) {
546 setCallingConv(II.getCallingConv());
547 std::copy(II.op_begin(), II.op_end(), op_begin());
548 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
549 bundle_op_info_begin());
550 SubclassOptionalData = II.SubclassOptionalData;
553 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
554 return getSuccessor(idx);
556 unsigned InvokeInst::getNumSuccessorsV() const {
557 return getNumSuccessors();
559 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
560 return setSuccessor(idx, B);
563 bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const {
564 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
566 if (const Function *F = getCalledFunction())
567 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
571 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
572 if (AttributeList.hasAttribute(i, A))
574 if (const Function *F = getCalledFunction())
575 return F->getAttributes().hasAttribute(i, A);
579 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
580 AttributeSet PAL = getAttributes();
581 PAL = PAL.addAttribute(getContext(), i, attr);
585 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
586 AttributeSet PAL = getAttributes();
588 PAL = PAL.removeAttributes(getContext(), i,
589 AttributeSet::get(getContext(), i, B));
593 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
594 AttributeSet PAL = getAttributes();
595 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
599 void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
600 AttributeSet PAL = getAttributes();
601 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
605 LandingPadInst *InvokeInst::getLandingPadInst() const {
606 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
609 //===----------------------------------------------------------------------===//
610 // ReturnInst Implementation
611 //===----------------------------------------------------------------------===//
613 ReturnInst::ReturnInst(const ReturnInst &RI)
614 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
615 OperandTraits<ReturnInst>::op_end(this) -
617 RI.getNumOperands()) {
618 if (RI.getNumOperands())
619 Op<0>() = RI.Op<0>();
620 SubclassOptionalData = RI.SubclassOptionalData;
623 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
624 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
625 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
630 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
631 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
632 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
637 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
638 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
639 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
642 unsigned ReturnInst::getNumSuccessorsV() const {
643 return getNumSuccessors();
646 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
647 /// emit the vtable for the class in this translation unit.
648 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
649 llvm_unreachable("ReturnInst has no successors!");
652 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
653 llvm_unreachable("ReturnInst has no successors!");
656 ReturnInst::~ReturnInst() {
659 //===----------------------------------------------------------------------===//
660 // ResumeInst Implementation
661 //===----------------------------------------------------------------------===//
663 ResumeInst::ResumeInst(const ResumeInst &RI)
664 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
665 OperandTraits<ResumeInst>::op_begin(this), 1) {
666 Op<0>() = RI.Op<0>();
669 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
670 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
671 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
675 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
676 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
677 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
681 unsigned ResumeInst::getNumSuccessorsV() const {
682 return getNumSuccessors();
685 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
686 llvm_unreachable("ResumeInst has no successors!");
689 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
690 llvm_unreachable("ResumeInst has no successors!");
693 //===----------------------------------------------------------------------===//
694 // CleanupEndPadInst Implementation
695 //===----------------------------------------------------------------------===//
697 CleanupEndPadInst::CleanupEndPadInst(const CleanupEndPadInst &CEPI)
698 : TerminatorInst(CEPI.getType(), Instruction::CleanupEndPad,
699 OperandTraits<CleanupEndPadInst>::op_end(this) -
700 CEPI.getNumOperands(),
701 CEPI.getNumOperands()) {
702 setInstructionSubclassData(CEPI.getSubclassDataFromInstruction());
703 setCleanupPad(CEPI.getCleanupPad());
704 if (BasicBlock *UnwindDest = CEPI.getUnwindDest())
705 setUnwindDest(UnwindDest);
708 void CleanupEndPadInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) {
709 setCleanupPad(CleanupPad);
711 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
712 setUnwindDest(UnwindBB);
716 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad,
717 BasicBlock *UnwindBB, unsigned Values,
718 Instruction *InsertBefore)
719 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
720 Instruction::CleanupEndPad,
721 OperandTraits<CleanupEndPadInst>::op_end(this) - Values,
722 Values, InsertBefore) {
723 init(CleanupPad, UnwindBB);
726 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad,
727 BasicBlock *UnwindBB, unsigned Values,
728 BasicBlock *InsertAtEnd)
729 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
730 Instruction::CleanupEndPad,
731 OperandTraits<CleanupEndPadInst>::op_end(this) - Values,
732 Values, InsertAtEnd) {
733 init(CleanupPad, UnwindBB);
736 BasicBlock *CleanupEndPadInst::getSuccessorV(unsigned Idx) const {
738 return getUnwindDest();
740 unsigned CleanupEndPadInst::getNumSuccessorsV() const {
741 return getNumSuccessors();
743 void CleanupEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
748 //===----------------------------------------------------------------------===//
749 // CleanupReturnInst Implementation
750 //===----------------------------------------------------------------------===//
752 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
753 : TerminatorInst(CRI.getType(), Instruction::CleanupRet,
754 OperandTraits<CleanupReturnInst>::op_end(this) -
755 CRI.getNumOperands(),
756 CRI.getNumOperands()) {
757 setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
758 Op<-1>() = CRI.Op<-1>();
759 if (CRI.hasUnwindDest())
760 Op<-2>() = CRI.Op<-2>();
763 void CleanupReturnInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) {
765 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
767 Op<-1>() = CleanupPad;
772 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad,
773 BasicBlock *UnwindBB, unsigned Values,
774 Instruction *InsertBefore)
775 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
776 Instruction::CleanupRet,
777 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
778 Values, InsertBefore) {
779 init(CleanupPad, UnwindBB);
782 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad,
783 BasicBlock *UnwindBB, unsigned Values,
784 BasicBlock *InsertAtEnd)
785 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
786 Instruction::CleanupRet,
787 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
788 Values, InsertAtEnd) {
789 init(CleanupPad, UnwindBB);
792 BasicBlock *CleanupReturnInst::getSuccessorV(unsigned Idx) const {
794 return getUnwindDest();
796 unsigned CleanupReturnInst::getNumSuccessorsV() const {
797 return getNumSuccessors();
799 void CleanupReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
804 //===----------------------------------------------------------------------===//
805 // CatchEndPadInst Implementation
806 //===----------------------------------------------------------------------===//
808 CatchEndPadInst::CatchEndPadInst(const CatchEndPadInst &CRI)
809 : TerminatorInst(CRI.getType(), Instruction::CatchEndPad,
810 OperandTraits<CatchEndPadInst>::op_end(this) -
811 CRI.getNumOperands(),
812 CRI.getNumOperands()) {
813 setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
814 if (BasicBlock *UnwindDest = CRI.getUnwindDest())
815 setUnwindDest(UnwindDest);
818 void CatchEndPadInst::init(BasicBlock *UnwindBB) {
820 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
821 setUnwindDest(UnwindBB);
825 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB,
826 unsigned Values, Instruction *InsertBefore)
827 : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad,
828 OperandTraits<CatchEndPadInst>::op_end(this) - Values,
829 Values, InsertBefore) {
833 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB,
834 unsigned Values, BasicBlock *InsertAtEnd)
835 : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad,
836 OperandTraits<CatchEndPadInst>::op_end(this) - Values,
837 Values, InsertAtEnd) {
841 BasicBlock *CatchEndPadInst::getSuccessorV(unsigned Idx) const {
843 return getUnwindDest();
845 unsigned CatchEndPadInst::getNumSuccessorsV() const {
846 return getNumSuccessors();
848 void CatchEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
853 //===----------------------------------------------------------------------===//
854 // CatchReturnInst Implementation
855 //===----------------------------------------------------------------------===//
856 void CatchReturnInst::init(CatchPadInst *CatchPad, BasicBlock *BB) {
861 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
862 : TerminatorInst(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
863 OperandTraits<CatchReturnInst>::op_begin(this), 2) {
864 Op<0>() = CRI.Op<0>();
865 Op<1>() = CRI.Op<1>();
868 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
869 Instruction *InsertBefore)
870 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
871 OperandTraits<CatchReturnInst>::op_begin(this), 2,
876 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
877 BasicBlock *InsertAtEnd)
878 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
879 OperandTraits<CatchReturnInst>::op_begin(this), 2,
884 BasicBlock *CatchReturnInst::getSuccessorV(unsigned Idx) const {
885 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
886 return getSuccessor();
888 unsigned CatchReturnInst::getNumSuccessorsV() const {
889 return getNumSuccessors();
891 void CatchReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
892 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
896 //===----------------------------------------------------------------------===//
897 // CatchPadInst Implementation
898 //===----------------------------------------------------------------------===//
899 void CatchPadInst::init(BasicBlock *IfNormal, BasicBlock *IfException,
900 ArrayRef<Value *> Args, const Twine &NameStr) {
901 assert(getNumOperands() == 2 + Args.size() && "NumOperands not set up?");
903 Op<-1>() = IfException;
904 std::copy(Args.begin(), Args.end(), op_begin());
908 CatchPadInst::CatchPadInst(const CatchPadInst &CPI)
909 : TerminatorInst(CPI.getType(), Instruction::CatchPad,
910 OperandTraits<CatchPadInst>::op_end(this) -
911 CPI.getNumOperands(),
912 CPI.getNumOperands()) {
913 std::copy(CPI.op_begin(), CPI.op_end(), op_begin());
916 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
917 ArrayRef<Value *> Args, unsigned Values,
918 const Twine &NameStr, Instruction *InsertBefore)
919 : TerminatorInst(Type::getTokenTy(IfNormal->getContext()),
920 Instruction::CatchPad,
921 OperandTraits<CatchPadInst>::op_end(this) - Values, Values,
923 init(IfNormal, IfException, Args, NameStr);
926 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
927 ArrayRef<Value *> Args, unsigned Values,
928 const Twine &NameStr, BasicBlock *InsertAtEnd)
929 : TerminatorInst(Type::getTokenTy(IfNormal->getContext()),
930 Instruction::CatchPad,
931 OperandTraits<CatchPadInst>::op_end(this) - Values, Values,
933 init(IfNormal, IfException, Args, NameStr);
936 BasicBlock *CatchPadInst::getSuccessorV(unsigned Idx) const {
937 return getSuccessor(Idx);
939 unsigned CatchPadInst::getNumSuccessorsV() const {
940 return getNumSuccessors();
942 void CatchPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
943 return setSuccessor(Idx, B);
946 //===----------------------------------------------------------------------===//
947 // TerminatePadInst Implementation
948 //===----------------------------------------------------------------------===//
949 void TerminatePadInst::init(BasicBlock *BB, ArrayRef<Value *> Args) {
951 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
954 std::copy(Args.begin(), Args.end(), op_begin());
957 TerminatePadInst::TerminatePadInst(const TerminatePadInst &TPI)
958 : TerminatorInst(TPI.getType(), Instruction::TerminatePad,
959 OperandTraits<TerminatePadInst>::op_end(this) -
960 TPI.getNumOperands(),
961 TPI.getNumOperands()) {
962 setInstructionSubclassData(TPI.getSubclassDataFromInstruction());
963 std::copy(TPI.op_begin(), TPI.op_end(), op_begin());
966 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB,
967 ArrayRef<Value *> Args, unsigned Values,
968 Instruction *InsertBefore)
969 : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad,
970 OperandTraits<TerminatePadInst>::op_end(this) - Values,
971 Values, InsertBefore) {
975 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB,
976 ArrayRef<Value *> Args, unsigned Values,
977 BasicBlock *InsertAtEnd)
978 : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad,
979 OperandTraits<TerminatePadInst>::op_end(this) - Values,
980 Values, InsertAtEnd) {
984 BasicBlock *TerminatePadInst::getSuccessorV(unsigned Idx) const {
986 return getUnwindDest();
988 unsigned TerminatePadInst::getNumSuccessorsV() const {
989 return getNumSuccessors();
991 void TerminatePadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
993 return setUnwindDest(B);
996 //===----------------------------------------------------------------------===//
997 // CleanupPadInst Implementation
998 //===----------------------------------------------------------------------===//
999 void CleanupPadInst::init(ArrayRef<Value *> Args, const Twine &NameStr) {
1000 assert(getNumOperands() == Args.size() && "NumOperands not set up?");
1001 std::copy(Args.begin(), Args.end(), op_begin());
1005 CleanupPadInst::CleanupPadInst(const CleanupPadInst &CPI)
1006 : Instruction(CPI.getType(), Instruction::CleanupPad,
1007 OperandTraits<CleanupPadInst>::op_end(this) -
1008 CPI.getNumOperands(),
1009 CPI.getNumOperands()) {
1010 std::copy(CPI.op_begin(), CPI.op_end(), op_begin());
1013 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
1014 const Twine &NameStr, Instruction *InsertBefore)
1015 : Instruction(Type::getTokenTy(C), Instruction::CleanupPad,
1016 OperandTraits<CleanupPadInst>::op_end(this) - Args.size(),
1017 Args.size(), InsertBefore) {
1018 init(Args, NameStr);
1021 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
1022 const Twine &NameStr, BasicBlock *InsertAtEnd)
1023 : Instruction(Type::getTokenTy(C), Instruction::CleanupPad,
1024 OperandTraits<CleanupPadInst>::op_end(this) - Args.size(),
1025 Args.size(), InsertAtEnd) {
1026 init(Args, NameStr);
1029 //===----------------------------------------------------------------------===//
1030 // UnreachableInst Implementation
1031 //===----------------------------------------------------------------------===//
1033 UnreachableInst::UnreachableInst(LLVMContext &Context,
1034 Instruction *InsertBefore)
1035 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1036 nullptr, 0, InsertBefore) {
1038 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1039 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1040 nullptr, 0, InsertAtEnd) {
1043 unsigned UnreachableInst::getNumSuccessorsV() const {
1044 return getNumSuccessors();
1047 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
1048 llvm_unreachable("UnreachableInst has no successors!");
1051 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
1052 llvm_unreachable("UnreachableInst has no successors!");
1055 //===----------------------------------------------------------------------===//
1056 // BranchInst Implementation
1057 //===----------------------------------------------------------------------===//
1059 void BranchInst::AssertOK() {
1060 if (isConditional())
1061 assert(getCondition()->getType()->isIntegerTy(1) &&
1062 "May only branch on boolean predicates!");
1065 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
1066 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1067 OperandTraits<BranchInst>::op_end(this) - 1,
1069 assert(IfTrue && "Branch destination may not be null!");
1072 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1073 Instruction *InsertBefore)
1074 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1075 OperandTraits<BranchInst>::op_end(this) - 3,
1085 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
1086 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1087 OperandTraits<BranchInst>::op_end(this) - 1,
1089 assert(IfTrue && "Branch destination may not be null!");
1093 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1094 BasicBlock *InsertAtEnd)
1095 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1096 OperandTraits<BranchInst>::op_end(this) - 3,
1107 BranchInst::BranchInst(const BranchInst &BI) :
1108 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
1109 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
1110 BI.getNumOperands()) {
1111 Op<-1>() = BI.Op<-1>();
1112 if (BI.getNumOperands() != 1) {
1113 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1114 Op<-3>() = BI.Op<-3>();
1115 Op<-2>() = BI.Op<-2>();
1117 SubclassOptionalData = BI.SubclassOptionalData;
1120 void BranchInst::swapSuccessors() {
1121 assert(isConditional() &&
1122 "Cannot swap successors of an unconditional branch");
1123 Op<-1>().swap(Op<-2>());
1125 // Update profile metadata if present and it matches our structural
1127 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
1128 if (!ProfileData || ProfileData->getNumOperands() != 3)
1131 // The first operand is the name. Fetch them backwards and build a new one.
1132 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
1133 ProfileData->getOperand(1)};
1134 setMetadata(LLVMContext::MD_prof,
1135 MDNode::get(ProfileData->getContext(), Ops));
1138 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
1139 return getSuccessor(idx);
1141 unsigned BranchInst::getNumSuccessorsV() const {
1142 return getNumSuccessors();
1144 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1145 setSuccessor(idx, B);
1149 //===----------------------------------------------------------------------===//
1150 // AllocaInst Implementation
1151 //===----------------------------------------------------------------------===//
1153 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1155 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1157 assert(!isa<BasicBlock>(Amt) &&
1158 "Passed basic block into allocation size parameter! Use other ctor");
1159 assert(Amt->getType()->isIntegerTy() &&
1160 "Allocation array size is not an integer!");
1165 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore)
1166 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1168 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
1169 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
1171 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
1172 Instruction *InsertBefore)
1173 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertBefore) {}
1175 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
1176 BasicBlock *InsertAtEnd)
1177 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
1179 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1180 const Twine &Name, Instruction *InsertBefore)
1181 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1182 getAISize(Ty->getContext(), ArraySize), InsertBefore),
1184 setAlignment(Align);
1185 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1189 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1190 const Twine &Name, BasicBlock *InsertAtEnd)
1191 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1192 getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
1194 setAlignment(Align);
1195 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1199 // Out of line virtual method, so the vtable, etc has a home.
1200 AllocaInst::~AllocaInst() {
1203 void AllocaInst::setAlignment(unsigned Align) {
1204 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1205 assert(Align <= MaximumAlignment &&
1206 "Alignment is greater than MaximumAlignment!");
1207 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1208 (Log2_32(Align) + 1));
1209 assert(getAlignment() == Align && "Alignment representation error!");
1212 bool AllocaInst::isArrayAllocation() const {
1213 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1214 return !CI->isOne();
1218 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1219 /// function and is a constant size. If so, the code generator will fold it
1220 /// into the prolog/epilog code, so it is basically free.
1221 bool AllocaInst::isStaticAlloca() const {
1222 // Must be constant size.
1223 if (!isa<ConstantInt>(getArraySize())) return false;
1225 // Must be in the entry block.
1226 const BasicBlock *Parent = getParent();
1227 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1230 //===----------------------------------------------------------------------===//
1231 // LoadInst Implementation
1232 //===----------------------------------------------------------------------===//
1234 void LoadInst::AssertOK() {
1235 assert(getOperand(0)->getType()->isPointerTy() &&
1236 "Ptr must have pointer type.");
1237 assert(!(isAtomic() && getAlignment() == 0) &&
1238 "Alignment required for atomic load");
1241 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1242 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1244 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1245 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1247 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1248 Instruction *InsertBef)
1249 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {}
1251 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1252 BasicBlock *InsertAE)
1253 : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {}
1255 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1256 unsigned Align, Instruction *InsertBef)
1257 : LoadInst(Ty, Ptr, Name, isVolatile, Align, NotAtomic, CrossThread,
1260 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1261 unsigned Align, BasicBlock *InsertAE)
1262 : LoadInst(Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertAE) {
1265 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1266 unsigned Align, AtomicOrdering Order,
1267 SynchronizationScope SynchScope, Instruction *InsertBef)
1268 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1269 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1270 setVolatile(isVolatile);
1271 setAlignment(Align);
1272 setAtomic(Order, SynchScope);
1277 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1278 unsigned Align, AtomicOrdering Order,
1279 SynchronizationScope SynchScope,
1280 BasicBlock *InsertAE)
1281 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1282 Load, Ptr, InsertAE) {
1283 setVolatile(isVolatile);
1284 setAlignment(Align);
1285 setAtomic(Order, SynchScope);
1290 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1291 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1292 Load, Ptr, InsertBef) {
1295 setAtomic(NotAtomic);
1297 if (Name && Name[0]) setName(Name);
1300 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1301 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1302 Load, Ptr, InsertAE) {
1305 setAtomic(NotAtomic);
1307 if (Name && Name[0]) setName(Name);
1310 LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile,
1311 Instruction *InsertBef)
1312 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1313 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1314 setVolatile(isVolatile);
1316 setAtomic(NotAtomic);
1318 if (Name && Name[0]) setName(Name);
1321 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1322 BasicBlock *InsertAE)
1323 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1324 Load, Ptr, InsertAE) {
1325 setVolatile(isVolatile);
1327 setAtomic(NotAtomic);
1329 if (Name && Name[0]) setName(Name);
1332 void LoadInst::setAlignment(unsigned Align) {
1333 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1334 assert(Align <= MaximumAlignment &&
1335 "Alignment is greater than MaximumAlignment!");
1336 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1337 ((Log2_32(Align)+1)<<1));
1338 assert(getAlignment() == Align && "Alignment representation error!");
1341 //===----------------------------------------------------------------------===//
1342 // StoreInst Implementation
1343 //===----------------------------------------------------------------------===//
1345 void StoreInst::AssertOK() {
1346 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1347 assert(getOperand(1)->getType()->isPointerTy() &&
1348 "Ptr must have pointer type!");
1349 assert(getOperand(0)->getType() ==
1350 cast<PointerType>(getOperand(1)->getType())->getElementType()
1351 && "Ptr must be a pointer to Val type!");
1352 assert(!(isAtomic() && getAlignment() == 0) &&
1353 "Alignment required for atomic store");
1356 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1357 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1359 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1360 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1362 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1363 Instruction *InsertBefore)
1364 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
1366 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1367 BasicBlock *InsertAtEnd)
1368 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
1370 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1371 Instruction *InsertBefore)
1372 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1375 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1376 BasicBlock *InsertAtEnd)
1377 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1380 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1381 unsigned Align, AtomicOrdering Order,
1382 SynchronizationScope SynchScope,
1383 Instruction *InsertBefore)
1384 : Instruction(Type::getVoidTy(val->getContext()), Store,
1385 OperandTraits<StoreInst>::op_begin(this),
1386 OperandTraits<StoreInst>::operands(this),
1390 setVolatile(isVolatile);
1391 setAlignment(Align);
1392 setAtomic(Order, SynchScope);
1396 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1397 unsigned Align, AtomicOrdering Order,
1398 SynchronizationScope SynchScope,
1399 BasicBlock *InsertAtEnd)
1400 : Instruction(Type::getVoidTy(val->getContext()), Store,
1401 OperandTraits<StoreInst>::op_begin(this),
1402 OperandTraits<StoreInst>::operands(this),
1406 setVolatile(isVolatile);
1407 setAlignment(Align);
1408 setAtomic(Order, SynchScope);
1412 void StoreInst::setAlignment(unsigned Align) {
1413 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1414 assert(Align <= MaximumAlignment &&
1415 "Alignment is greater than MaximumAlignment!");
1416 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1417 ((Log2_32(Align)+1) << 1));
1418 assert(getAlignment() == Align && "Alignment representation error!");
1421 //===----------------------------------------------------------------------===//
1422 // AtomicCmpXchgInst Implementation
1423 //===----------------------------------------------------------------------===//
1425 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1426 AtomicOrdering SuccessOrdering,
1427 AtomicOrdering FailureOrdering,
1428 SynchronizationScope SynchScope) {
1432 setSuccessOrdering(SuccessOrdering);
1433 setFailureOrdering(FailureOrdering);
1434 setSynchScope(SynchScope);
1436 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1437 "All operands must be non-null!");
1438 assert(getOperand(0)->getType()->isPointerTy() &&
1439 "Ptr must have pointer type!");
1440 assert(getOperand(1)->getType() ==
1441 cast<PointerType>(getOperand(0)->getType())->getElementType()
1442 && "Ptr must be a pointer to Cmp type!");
1443 assert(getOperand(2)->getType() ==
1444 cast<PointerType>(getOperand(0)->getType())->getElementType()
1445 && "Ptr must be a pointer to NewVal type!");
1446 assert(SuccessOrdering != NotAtomic &&
1447 "AtomicCmpXchg instructions must be atomic!");
1448 assert(FailureOrdering != NotAtomic &&
1449 "AtomicCmpXchg instructions must be atomic!");
1450 assert(SuccessOrdering >= FailureOrdering &&
1451 "AtomicCmpXchg success ordering must be at least as strong as fail");
1452 assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
1453 "AtomicCmpXchg failure ordering cannot include release semantics");
1456 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1457 AtomicOrdering SuccessOrdering,
1458 AtomicOrdering FailureOrdering,
1459 SynchronizationScope SynchScope,
1460 Instruction *InsertBefore)
1462 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1464 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1465 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1466 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1469 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1470 AtomicOrdering SuccessOrdering,
1471 AtomicOrdering FailureOrdering,
1472 SynchronizationScope SynchScope,
1473 BasicBlock *InsertAtEnd)
1475 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1477 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1478 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1479 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1482 //===----------------------------------------------------------------------===//
1483 // AtomicRMWInst Implementation
1484 //===----------------------------------------------------------------------===//
1486 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1487 AtomicOrdering Ordering,
1488 SynchronizationScope SynchScope) {
1491 setOperation(Operation);
1492 setOrdering(Ordering);
1493 setSynchScope(SynchScope);
1495 assert(getOperand(0) && getOperand(1) &&
1496 "All operands must be non-null!");
1497 assert(getOperand(0)->getType()->isPointerTy() &&
1498 "Ptr must have pointer type!");
1499 assert(getOperand(1)->getType() ==
1500 cast<PointerType>(getOperand(0)->getType())->getElementType()
1501 && "Ptr must be a pointer to Val type!");
1502 assert(Ordering != NotAtomic &&
1503 "AtomicRMW instructions must be atomic!");
1506 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1507 AtomicOrdering Ordering,
1508 SynchronizationScope SynchScope,
1509 Instruction *InsertBefore)
1510 : Instruction(Val->getType(), AtomicRMW,
1511 OperandTraits<AtomicRMWInst>::op_begin(this),
1512 OperandTraits<AtomicRMWInst>::operands(this),
1514 Init(Operation, Ptr, Val, Ordering, SynchScope);
1517 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1518 AtomicOrdering Ordering,
1519 SynchronizationScope SynchScope,
1520 BasicBlock *InsertAtEnd)
1521 : Instruction(Val->getType(), AtomicRMW,
1522 OperandTraits<AtomicRMWInst>::op_begin(this),
1523 OperandTraits<AtomicRMWInst>::operands(this),
1525 Init(Operation, Ptr, Val, Ordering, SynchScope);
1528 //===----------------------------------------------------------------------===//
1529 // FenceInst Implementation
1530 //===----------------------------------------------------------------------===//
1532 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1533 SynchronizationScope SynchScope,
1534 Instruction *InsertBefore)
1535 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1536 setOrdering(Ordering);
1537 setSynchScope(SynchScope);
1540 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1541 SynchronizationScope SynchScope,
1542 BasicBlock *InsertAtEnd)
1543 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1544 setOrdering(Ordering);
1545 setSynchScope(SynchScope);
1548 //===----------------------------------------------------------------------===//
1549 // GetElementPtrInst Implementation
1550 //===----------------------------------------------------------------------===//
1552 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1553 const Twine &Name) {
1554 assert(getNumOperands() == 1 + IdxList.size() &&
1555 "NumOperands not initialized?");
1557 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1561 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1562 : Instruction(GEPI.getType(), GetElementPtr,
1563 OperandTraits<GetElementPtrInst>::op_end(this) -
1564 GEPI.getNumOperands(),
1565 GEPI.getNumOperands()),
1566 SourceElementType(GEPI.SourceElementType),
1567 ResultElementType(GEPI.ResultElementType) {
1568 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1569 SubclassOptionalData = GEPI.SubclassOptionalData;
1572 /// getIndexedType - Returns the type of the element that would be accessed with
1573 /// a gep instruction with the specified parameters.
1575 /// The Idxs pointer should point to a continuous piece of memory containing the
1576 /// indices, either as Value* or uint64_t.
1578 /// A null type is returned if the indices are invalid for the specified
1581 template <typename IndexTy>
1582 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1583 // Handle the special case of the empty set index set, which is always valid.
1584 if (IdxList.empty())
1587 // If there is at least one index, the top level type must be sized, otherwise
1588 // it cannot be 'stepped over'.
1589 if (!Agg->isSized())
1592 unsigned CurIdx = 1;
1593 for (; CurIdx != IdxList.size(); ++CurIdx) {
1594 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1595 if (!CT || CT->isPointerTy()) return nullptr;
1596 IndexTy Index = IdxList[CurIdx];
1597 if (!CT->indexValid(Index)) return nullptr;
1598 Agg = CT->getTypeAtIndex(Index);
1600 return CurIdx == IdxList.size() ? Agg : nullptr;
1603 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1604 return getIndexedTypeInternal(Ty, IdxList);
1607 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1608 ArrayRef<Constant *> IdxList) {
1609 return getIndexedTypeInternal(Ty, IdxList);
1612 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1613 return getIndexedTypeInternal(Ty, IdxList);
1616 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1617 /// zeros. If so, the result pointer and the first operand have the same
1618 /// value, just potentially different types.
1619 bool GetElementPtrInst::hasAllZeroIndices() const {
1620 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1621 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1622 if (!CI->isZero()) return false;
1630 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1631 /// constant integers. If so, the result pointer and the first operand have
1632 /// a constant offset between them.
1633 bool GetElementPtrInst::hasAllConstantIndices() const {
1634 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1635 if (!isa<ConstantInt>(getOperand(i)))
1641 void GetElementPtrInst::setIsInBounds(bool B) {
1642 cast<GEPOperator>(this)->setIsInBounds(B);
1645 bool GetElementPtrInst::isInBounds() const {
1646 return cast<GEPOperator>(this)->isInBounds();
1649 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1650 APInt &Offset) const {
1651 // Delegate to the generic GEPOperator implementation.
1652 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1655 //===----------------------------------------------------------------------===//
1656 // ExtractElementInst Implementation
1657 //===----------------------------------------------------------------------===//
1659 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1661 Instruction *InsertBef)
1662 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1664 OperandTraits<ExtractElementInst>::op_begin(this),
1666 assert(isValidOperands(Val, Index) &&
1667 "Invalid extractelement instruction operands!");
1673 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1675 BasicBlock *InsertAE)
1676 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1678 OperandTraits<ExtractElementInst>::op_begin(this),
1680 assert(isValidOperands(Val, Index) &&
1681 "Invalid extractelement instruction operands!");
1689 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1690 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1696 //===----------------------------------------------------------------------===//
1697 // InsertElementInst Implementation
1698 //===----------------------------------------------------------------------===//
1700 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1702 Instruction *InsertBef)
1703 : Instruction(Vec->getType(), InsertElement,
1704 OperandTraits<InsertElementInst>::op_begin(this),
1706 assert(isValidOperands(Vec, Elt, Index) &&
1707 "Invalid insertelement instruction operands!");
1714 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1716 BasicBlock *InsertAE)
1717 : Instruction(Vec->getType(), InsertElement,
1718 OperandTraits<InsertElementInst>::op_begin(this),
1720 assert(isValidOperands(Vec, Elt, Index) &&
1721 "Invalid insertelement instruction operands!");
1729 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1730 const Value *Index) {
1731 if (!Vec->getType()->isVectorTy())
1732 return false; // First operand of insertelement must be vector type.
1734 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1735 return false;// Second operand of insertelement must be vector element type.
1737 if (!Index->getType()->isIntegerTy())
1738 return false; // Third operand of insertelement must be i32.
1743 //===----------------------------------------------------------------------===//
1744 // ShuffleVectorInst Implementation
1745 //===----------------------------------------------------------------------===//
1747 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1749 Instruction *InsertBefore)
1750 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1751 cast<VectorType>(Mask->getType())->getNumElements()),
1753 OperandTraits<ShuffleVectorInst>::op_begin(this),
1754 OperandTraits<ShuffleVectorInst>::operands(this),
1756 assert(isValidOperands(V1, V2, Mask) &&
1757 "Invalid shuffle vector instruction operands!");
1764 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1766 BasicBlock *InsertAtEnd)
1767 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1768 cast<VectorType>(Mask->getType())->getNumElements()),
1770 OperandTraits<ShuffleVectorInst>::op_begin(this),
1771 OperandTraits<ShuffleVectorInst>::operands(this),
1773 assert(isValidOperands(V1, V2, Mask) &&
1774 "Invalid shuffle vector instruction operands!");
1782 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1783 const Value *Mask) {
1784 // V1 and V2 must be vectors of the same type.
1785 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1788 // Mask must be vector of i32.
1789 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1790 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1793 // Check to see if Mask is valid.
1794 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1797 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1798 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1799 for (Value *Op : MV->operands()) {
1800 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1801 if (CI->uge(V1Size*2))
1803 } else if (!isa<UndefValue>(Op)) {
1810 if (const ConstantDataSequential *CDS =
1811 dyn_cast<ConstantDataSequential>(Mask)) {
1812 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1813 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1814 if (CDS->getElementAsInteger(i) >= V1Size*2)
1819 // The bitcode reader can create a place holder for a forward reference
1820 // used as the shuffle mask. When this occurs, the shuffle mask will
1821 // fall into this case and fail. To avoid this error, do this bit of
1822 // ugliness to allow such a mask pass.
1823 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1824 if (CE->getOpcode() == Instruction::UserOp1)
1830 /// getMaskValue - Return the index from the shuffle mask for the specified
1831 /// output result. This is either -1 if the element is undef or a number less
1832 /// than 2*numelements.
1833 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1834 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1835 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1836 return CDS->getElementAsInteger(i);
1837 Constant *C = Mask->getAggregateElement(i);
1838 if (isa<UndefValue>(C))
1840 return cast<ConstantInt>(C)->getZExtValue();
1843 /// getShuffleMask - Return the full mask for this instruction, where each
1844 /// element is the element number and undef's are returned as -1.
1845 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1846 SmallVectorImpl<int> &Result) {
1847 unsigned NumElts = Mask->getType()->getVectorNumElements();
1849 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1850 for (unsigned i = 0; i != NumElts; ++i)
1851 Result.push_back(CDS->getElementAsInteger(i));
1854 for (unsigned i = 0; i != NumElts; ++i) {
1855 Constant *C = Mask->getAggregateElement(i);
1856 Result.push_back(isa<UndefValue>(C) ? -1 :
1857 cast<ConstantInt>(C)->getZExtValue());
1862 //===----------------------------------------------------------------------===//
1863 // InsertValueInst Class
1864 //===----------------------------------------------------------------------===//
1866 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1867 const Twine &Name) {
1868 assert(getNumOperands() == 2 && "NumOperands not initialized?");
1870 // There's no fundamental reason why we require at least one index
1871 // (other than weirdness with &*IdxBegin being invalid; see
1872 // getelementptr's init routine for example). But there's no
1873 // present need to support it.
1874 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1876 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1877 Val->getType() && "Inserted value must match indexed type!");
1881 Indices.append(Idxs.begin(), Idxs.end());
1885 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1886 : Instruction(IVI.getType(), InsertValue,
1887 OperandTraits<InsertValueInst>::op_begin(this), 2),
1888 Indices(IVI.Indices) {
1889 Op<0>() = IVI.getOperand(0);
1890 Op<1>() = IVI.getOperand(1);
1891 SubclassOptionalData = IVI.SubclassOptionalData;
1894 //===----------------------------------------------------------------------===//
1895 // ExtractValueInst Class
1896 //===----------------------------------------------------------------------===//
1898 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1899 assert(getNumOperands() == 1 && "NumOperands not initialized?");
1901 // There's no fundamental reason why we require at least one index.
1902 // But there's no present need to support it.
1903 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1905 Indices.append(Idxs.begin(), Idxs.end());
1909 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1910 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1911 Indices(EVI.Indices) {
1912 SubclassOptionalData = EVI.SubclassOptionalData;
1915 // getIndexedType - Returns the type of the element that would be extracted
1916 // with an extractvalue instruction with the specified parameters.
1918 // A null type is returned if the indices are invalid for the specified
1921 Type *ExtractValueInst::getIndexedType(Type *Agg,
1922 ArrayRef<unsigned> Idxs) {
1923 for (unsigned Index : Idxs) {
1924 // We can't use CompositeType::indexValid(Index) here.
1925 // indexValid() always returns true for arrays because getelementptr allows
1926 // out-of-bounds indices. Since we don't allow those for extractvalue and
1927 // insertvalue we need to check array indexing manually.
1928 // Since the only other types we can index into are struct types it's just
1929 // as easy to check those manually as well.
1930 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1931 if (Index >= AT->getNumElements())
1933 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1934 if (Index >= ST->getNumElements())
1937 // Not a valid type to index into.
1941 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1943 return const_cast<Type*>(Agg);
1946 //===----------------------------------------------------------------------===//
1947 // BinaryOperator Class
1948 //===----------------------------------------------------------------------===//
1950 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1951 Type *Ty, const Twine &Name,
1952 Instruction *InsertBefore)
1953 : Instruction(Ty, iType,
1954 OperandTraits<BinaryOperator>::op_begin(this),
1955 OperandTraits<BinaryOperator>::operands(this),
1963 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1964 Type *Ty, const Twine &Name,
1965 BasicBlock *InsertAtEnd)
1966 : Instruction(Ty, iType,
1967 OperandTraits<BinaryOperator>::op_begin(this),
1968 OperandTraits<BinaryOperator>::operands(this),
1977 void BinaryOperator::init(BinaryOps iType) {
1978 Value *LHS = getOperand(0), *RHS = getOperand(1);
1979 (void)LHS; (void)RHS; // Silence warnings.
1980 assert(LHS->getType() == RHS->getType() &&
1981 "Binary operator operand types must match!");
1986 assert(getType() == LHS->getType() &&
1987 "Arithmetic operation should return same type as operands!");
1988 assert(getType()->isIntOrIntVectorTy() &&
1989 "Tried to create an integer operation on a non-integer type!");
1991 case FAdd: case FSub:
1993 assert(getType() == LHS->getType() &&
1994 "Arithmetic operation should return same type as operands!");
1995 assert(getType()->isFPOrFPVectorTy() &&
1996 "Tried to create a floating-point operation on a "
1997 "non-floating-point type!");
2001 assert(getType() == LHS->getType() &&
2002 "Arithmetic operation should return same type as operands!");
2003 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2004 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2005 "Incorrect operand type (not integer) for S/UDIV");
2008 assert(getType() == LHS->getType() &&
2009 "Arithmetic operation should return same type as operands!");
2010 assert(getType()->isFPOrFPVectorTy() &&
2011 "Incorrect operand type (not floating point) for FDIV");
2015 assert(getType() == LHS->getType() &&
2016 "Arithmetic operation should return same type as operands!");
2017 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2018 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2019 "Incorrect operand type (not integer) for S/UREM");
2022 assert(getType() == LHS->getType() &&
2023 "Arithmetic operation should return same type as operands!");
2024 assert(getType()->isFPOrFPVectorTy() &&
2025 "Incorrect operand type (not floating point) for FREM");
2030 assert(getType() == LHS->getType() &&
2031 "Shift operation should return same type as operands!");
2032 assert((getType()->isIntegerTy() ||
2033 (getType()->isVectorTy() &&
2034 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2035 "Tried to create a shift operation on a non-integral type!");
2039 assert(getType() == LHS->getType() &&
2040 "Logical operation should return same type as operands!");
2041 assert((getType()->isIntegerTy() ||
2042 (getType()->isVectorTy() &&
2043 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2044 "Tried to create a logical operation on a non-integral type!");
2052 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2054 Instruction *InsertBefore) {
2055 assert(S1->getType() == S2->getType() &&
2056 "Cannot create binary operator with two operands of differing type!");
2057 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2060 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2062 BasicBlock *InsertAtEnd) {
2063 BinaryOperator *Res = Create(Op, S1, S2, Name);
2064 InsertAtEnd->getInstList().push_back(Res);
2068 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2069 Instruction *InsertBefore) {
2070 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2071 return new BinaryOperator(Instruction::Sub,
2073 Op->getType(), Name, InsertBefore);
2076 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2077 BasicBlock *InsertAtEnd) {
2078 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2079 return new BinaryOperator(Instruction::Sub,
2081 Op->getType(), Name, InsertAtEnd);
2084 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2085 Instruction *InsertBefore) {
2086 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2087 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2090 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2091 BasicBlock *InsertAtEnd) {
2092 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2093 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2096 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2097 Instruction *InsertBefore) {
2098 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2099 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2102 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2103 BasicBlock *InsertAtEnd) {
2104 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2105 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2108 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2109 Instruction *InsertBefore) {
2110 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2111 return new BinaryOperator(Instruction::FSub, zero, Op,
2112 Op->getType(), Name, InsertBefore);
2115 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2116 BasicBlock *InsertAtEnd) {
2117 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2118 return new BinaryOperator(Instruction::FSub, zero, Op,
2119 Op->getType(), Name, InsertAtEnd);
2122 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2123 Instruction *InsertBefore) {
2124 Constant *C = Constant::getAllOnesValue(Op->getType());
2125 return new BinaryOperator(Instruction::Xor, Op, C,
2126 Op->getType(), Name, InsertBefore);
2129 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2130 BasicBlock *InsertAtEnd) {
2131 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2132 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2133 Op->getType(), Name, InsertAtEnd);
2137 // isConstantAllOnes - Helper function for several functions below
2138 static inline bool isConstantAllOnes(const Value *V) {
2139 if (const Constant *C = dyn_cast<Constant>(V))
2140 return C->isAllOnesValue();
2144 bool BinaryOperator::isNeg(const Value *V) {
2145 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2146 if (Bop->getOpcode() == Instruction::Sub)
2147 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2148 return C->isNegativeZeroValue();
2152 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
2153 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2154 if (Bop->getOpcode() == Instruction::FSub)
2155 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
2156 if (!IgnoreZeroSign)
2157 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
2158 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
2163 bool BinaryOperator::isNot(const Value *V) {
2164 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2165 return (Bop->getOpcode() == Instruction::Xor &&
2166 (isConstantAllOnes(Bop->getOperand(1)) ||
2167 isConstantAllOnes(Bop->getOperand(0))));
2171 Value *BinaryOperator::getNegArgument(Value *BinOp) {
2172 return cast<BinaryOperator>(BinOp)->getOperand(1);
2175 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
2176 return getNegArgument(const_cast<Value*>(BinOp));
2179 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
2180 return cast<BinaryOperator>(BinOp)->getOperand(1);
2183 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
2184 return getFNegArgument(const_cast<Value*>(BinOp));
2187 Value *BinaryOperator::getNotArgument(Value *BinOp) {
2188 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
2189 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
2190 Value *Op0 = BO->getOperand(0);
2191 Value *Op1 = BO->getOperand(1);
2192 if (isConstantAllOnes(Op0)) return Op1;
2194 assert(isConstantAllOnes(Op1));
2198 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2199 return getNotArgument(const_cast<Value*>(BinOp));
2203 // swapOperands - Exchange the two operands to this instruction. This
2204 // instruction is safe to use on any binary instruction and does not
2205 // modify the semantics of the instruction. If the instruction is
2206 // order dependent (SetLT f.e.) the opcode is changed.
2208 bool BinaryOperator::swapOperands() {
2209 if (!isCommutative())
2210 return true; // Can't commute operands
2211 Op<0>().swap(Op<1>());
2215 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2216 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2219 void BinaryOperator::setHasNoSignedWrap(bool b) {
2220 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2223 void BinaryOperator::setIsExact(bool b) {
2224 cast<PossiblyExactOperator>(this)->setIsExact(b);
2227 bool BinaryOperator::hasNoUnsignedWrap() const {
2228 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2231 bool BinaryOperator::hasNoSignedWrap() const {
2232 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2235 bool BinaryOperator::isExact() const {
2236 return cast<PossiblyExactOperator>(this)->isExact();
2239 void BinaryOperator::copyIRFlags(const Value *V) {
2240 // Copy the wrapping flags.
2241 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2242 setHasNoSignedWrap(OB->hasNoSignedWrap());
2243 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
2246 // Copy the exact flag.
2247 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2248 setIsExact(PE->isExact());
2250 // Copy the fast-math flags.
2251 if (auto *FP = dyn_cast<FPMathOperator>(V))
2252 copyFastMathFlags(FP->getFastMathFlags());
2255 void BinaryOperator::andIRFlags(const Value *V) {
2256 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2257 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
2258 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
2261 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2262 setIsExact(isExact() & PE->isExact());
2264 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
2265 FastMathFlags FM = getFastMathFlags();
2266 FM &= FP->getFastMathFlags();
2267 copyFastMathFlags(FM);
2272 //===----------------------------------------------------------------------===//
2273 // FPMathOperator Class
2274 //===----------------------------------------------------------------------===//
2276 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2277 /// An accuracy of 0.0 means that the operation should be performed with the
2278 /// default precision.
2279 float FPMathOperator::getFPAccuracy() const {
2281 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2284 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2285 return Accuracy->getValueAPF().convertToFloat();
2289 //===----------------------------------------------------------------------===//
2291 //===----------------------------------------------------------------------===//
2293 void CastInst::anchor() {}
2295 // Just determine if this cast only deals with integral->integral conversion.
2296 bool CastInst::isIntegerCast() const {
2297 switch (getOpcode()) {
2298 default: return false;
2299 case Instruction::ZExt:
2300 case Instruction::SExt:
2301 case Instruction::Trunc:
2303 case Instruction::BitCast:
2304 return getOperand(0)->getType()->isIntegerTy() &&
2305 getType()->isIntegerTy();
2309 bool CastInst::isLosslessCast() const {
2310 // Only BitCast can be lossless, exit fast if we're not BitCast
2311 if (getOpcode() != Instruction::BitCast)
2314 // Identity cast is always lossless
2315 Type* SrcTy = getOperand(0)->getType();
2316 Type* DstTy = getType();
2320 // Pointer to pointer is always lossless.
2321 if (SrcTy->isPointerTy())
2322 return DstTy->isPointerTy();
2323 return false; // Other types have no identity values
2326 /// This function determines if the CastInst does not require any bits to be
2327 /// changed in order to effect the cast. Essentially, it identifies cases where
2328 /// no code gen is necessary for the cast, hence the name no-op cast. For
2329 /// example, the following are all no-op casts:
2330 /// # bitcast i32* %x to i8*
2331 /// # bitcast <2 x i32> %x to <4 x i16>
2332 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2333 /// @brief Determine if the described cast is a no-op.
2334 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2339 default: llvm_unreachable("Invalid CastOp");
2340 case Instruction::Trunc:
2341 case Instruction::ZExt:
2342 case Instruction::SExt:
2343 case Instruction::FPTrunc:
2344 case Instruction::FPExt:
2345 case Instruction::UIToFP:
2346 case Instruction::SIToFP:
2347 case Instruction::FPToUI:
2348 case Instruction::FPToSI:
2349 case Instruction::AddrSpaceCast:
2350 // TODO: Target informations may give a more accurate answer here.
2352 case Instruction::BitCast:
2353 return true; // BitCast never modifies bits.
2354 case Instruction::PtrToInt:
2355 return IntPtrTy->getScalarSizeInBits() ==
2356 DestTy->getScalarSizeInBits();
2357 case Instruction::IntToPtr:
2358 return IntPtrTy->getScalarSizeInBits() ==
2359 SrcTy->getScalarSizeInBits();
2363 /// @brief Determine if a cast is a no-op.
2364 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2365 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2368 bool CastInst::isNoopCast(const DataLayout &DL) const {
2369 Type *PtrOpTy = nullptr;
2370 if (getOpcode() == Instruction::PtrToInt)
2371 PtrOpTy = getOperand(0)->getType();
2372 else if (getOpcode() == Instruction::IntToPtr)
2373 PtrOpTy = getType();
2376 PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0);
2378 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2381 /// This function determines if a pair of casts can be eliminated and what
2382 /// opcode should be used in the elimination. This assumes that there are two
2383 /// instructions like this:
2384 /// * %F = firstOpcode SrcTy %x to MidTy
2385 /// * %S = secondOpcode MidTy %F to DstTy
2386 /// The function returns a resultOpcode so these two casts can be replaced with:
2387 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2388 /// If no such cast is permited, the function returns 0.
2389 unsigned CastInst::isEliminableCastPair(
2390 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2391 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2392 Type *DstIntPtrTy) {
2393 // Define the 144 possibilities for these two cast instructions. The values
2394 // in this matrix determine what to do in a given situation and select the
2395 // case in the switch below. The rows correspond to firstOp, the columns
2396 // correspond to secondOp. In looking at the table below, keep in mind
2397 // the following cast properties:
2399 // Size Compare Source Destination
2400 // Operator Src ? Size Type Sign Type Sign
2401 // -------- ------------ ------------------- ---------------------
2402 // TRUNC > Integer Any Integral Any
2403 // ZEXT < Integral Unsigned Integer Any
2404 // SEXT < Integral Signed Integer Any
2405 // FPTOUI n/a FloatPt n/a Integral Unsigned
2406 // FPTOSI n/a FloatPt n/a Integral Signed
2407 // UITOFP n/a Integral Unsigned FloatPt n/a
2408 // SITOFP n/a Integral Signed FloatPt n/a
2409 // FPTRUNC > FloatPt n/a FloatPt n/a
2410 // FPEXT < FloatPt n/a FloatPt n/a
2411 // PTRTOINT n/a Pointer n/a Integral Unsigned
2412 // INTTOPTR n/a Integral Unsigned Pointer n/a
2413 // BITCAST = FirstClass n/a FirstClass n/a
2414 // ADDRSPCST n/a Pointer n/a Pointer n/a
2416 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2417 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2418 // into "fptoui double to i64", but this loses information about the range
2419 // of the produced value (we no longer know the top-part is all zeros).
2420 // Further this conversion is often much more expensive for typical hardware,
2421 // and causes issues when building libgcc. We disallow fptosi+sext for the
2423 const unsigned numCastOps =
2424 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2425 static const uint8_t CastResults[numCastOps][numCastOps] = {
2426 // T F F U S F F P I B A -+
2427 // R Z S P P I I T P 2 N T S |
2428 // U E E 2 2 2 2 R E I T C C +- secondOp
2429 // N X X U S F F N X N 2 V V |
2430 // C T T I I P P C T T P T T -+
2431 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2432 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2433 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2434 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2435 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2436 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2437 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2438 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2439 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt |
2440 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2441 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2442 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2443 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2446 // If either of the casts are a bitcast from scalar to vector, disallow the
2447 // merging. However, bitcast of A->B->A are allowed.
2448 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2449 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2450 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2452 // Check if any of the bitcasts convert scalars<->vectors.
2453 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2454 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2455 // Unless we are bitcasing to the original type, disallow optimizations.
2456 if (!chainedBitcast) return 0;
2458 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2459 [secondOp-Instruction::CastOpsBegin];
2462 // Categorically disallowed.
2465 // Allowed, use first cast's opcode.
2468 // Allowed, use second cast's opcode.
2471 // No-op cast in second op implies firstOp as long as the DestTy
2472 // is integer and we are not converting between a vector and a
2474 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2478 // No-op cast in second op implies firstOp as long as the DestTy
2479 // is floating point.
2480 if (DstTy->isFloatingPointTy())
2484 // No-op cast in first op implies secondOp as long as the SrcTy
2486 if (SrcTy->isIntegerTy())
2490 // No-op cast in first op implies secondOp as long as the SrcTy
2491 // is a floating point.
2492 if (SrcTy->isFloatingPointTy())
2496 // Cannot simplify if address spaces are different!
2497 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2500 unsigned MidSize = MidTy->getScalarSizeInBits();
2501 // We can still fold this without knowing the actual sizes as long we
2502 // know that the intermediate pointer is the largest possible
2504 // FIXME: Is this always true?
2506 return Instruction::BitCast;
2508 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2509 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2511 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2512 if (MidSize >= PtrSize)
2513 return Instruction::BitCast;
2517 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2518 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2519 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2520 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2521 unsigned DstSize = DstTy->getScalarSizeInBits();
2522 if (SrcSize == DstSize)
2523 return Instruction::BitCast;
2524 else if (SrcSize < DstSize)
2529 // zext, sext -> zext, because sext can't sign extend after zext
2530 return Instruction::ZExt;
2532 // fpext followed by ftrunc is allowed if the bit size returned to is
2533 // the same as the original, in which case its just a bitcast
2535 return Instruction::BitCast;
2536 return 0; // If the types are not the same we can't eliminate it.
2538 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2541 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2542 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2543 unsigned DstSize = DstTy->getScalarSizeInBits();
2544 if (SrcSize <= PtrSize && SrcSize == DstSize)
2545 return Instruction::BitCast;
2549 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2550 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2551 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2552 return Instruction::AddrSpaceCast;
2553 return Instruction::BitCast;
2556 // FIXME: this state can be merged with (1), but the following assert
2557 // is useful to check the correcteness of the sequence due to semantic
2558 // change of bitcast.
2560 SrcTy->isPtrOrPtrVectorTy() &&
2561 MidTy->isPtrOrPtrVectorTy() &&
2562 DstTy->isPtrOrPtrVectorTy() &&
2563 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2564 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2565 "Illegal addrspacecast, bitcast sequence!");
2566 // Allowed, use first cast's opcode
2569 // bitcast, addrspacecast -> addrspacecast if the element type of
2570 // bitcast's source is the same as that of addrspacecast's destination.
2571 if (SrcTy->getPointerElementType() == DstTy->getPointerElementType())
2572 return Instruction::AddrSpaceCast;
2576 // FIXME: this state can be merged with (1), but the following assert
2577 // is useful to check the correcteness of the sequence due to semantic
2578 // change of bitcast.
2580 SrcTy->isIntOrIntVectorTy() &&
2581 MidTy->isPtrOrPtrVectorTy() &&
2582 DstTy->isPtrOrPtrVectorTy() &&
2583 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2584 "Illegal inttoptr, bitcast sequence!");
2585 // Allowed, use first cast's opcode
2588 // FIXME: this state can be merged with (2), but the following assert
2589 // is useful to check the correcteness of the sequence due to semantic
2590 // change of bitcast.
2592 SrcTy->isPtrOrPtrVectorTy() &&
2593 MidTy->isPtrOrPtrVectorTy() &&
2594 DstTy->isIntOrIntVectorTy() &&
2595 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2596 "Illegal bitcast, ptrtoint sequence!");
2597 // Allowed, use second cast's opcode
2600 // (sitofp (zext x)) -> (uitofp x)
2601 return Instruction::UIToFP;
2603 // Cast combination can't happen (error in input). This is for all cases
2604 // where the MidTy is not the same for the two cast instructions.
2605 llvm_unreachable("Invalid Cast Combination");
2607 llvm_unreachable("Error in CastResults table!!!");
2611 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2612 const Twine &Name, Instruction *InsertBefore) {
2613 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2614 // Construct and return the appropriate CastInst subclass
2616 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2617 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2618 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2619 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2620 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2621 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2622 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2623 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2624 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2625 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2626 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2627 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2628 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2629 default: llvm_unreachable("Invalid opcode provided");
2633 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2634 const Twine &Name, BasicBlock *InsertAtEnd) {
2635 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2636 // Construct and return the appropriate CastInst subclass
2638 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2639 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2640 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2641 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2642 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2643 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2644 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2645 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2646 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2647 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2648 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2649 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2650 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2651 default: llvm_unreachable("Invalid opcode provided");
2655 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2657 Instruction *InsertBefore) {
2658 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2659 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2660 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2663 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2665 BasicBlock *InsertAtEnd) {
2666 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2667 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2668 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2671 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2673 Instruction *InsertBefore) {
2674 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2675 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2676 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2679 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2681 BasicBlock *InsertAtEnd) {
2682 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2683 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2684 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2687 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2689 Instruction *InsertBefore) {
2690 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2691 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2692 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2695 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2697 BasicBlock *InsertAtEnd) {
2698 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2699 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2700 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2703 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2705 BasicBlock *InsertAtEnd) {
2706 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2707 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2709 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2710 assert((!Ty->isVectorTy() ||
2711 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2714 if (Ty->isIntOrIntVectorTy())
2715 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2717 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2720 /// @brief Create a BitCast or a PtrToInt cast instruction
2721 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2723 Instruction *InsertBefore) {
2724 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2725 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2727 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2728 assert((!Ty->isVectorTy() ||
2729 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2732 if (Ty->isIntOrIntVectorTy())
2733 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2735 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2738 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2741 BasicBlock *InsertAtEnd) {
2742 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2743 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2745 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2746 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2748 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2751 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2754 Instruction *InsertBefore) {
2755 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2756 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2758 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2759 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2761 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2764 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2766 Instruction *InsertBefore) {
2767 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2768 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2769 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2770 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2772 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2775 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2776 bool isSigned, const Twine &Name,
2777 Instruction *InsertBefore) {
2778 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2779 "Invalid integer cast");
2780 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2781 unsigned DstBits = Ty->getScalarSizeInBits();
2782 Instruction::CastOps opcode =
2783 (SrcBits == DstBits ? Instruction::BitCast :
2784 (SrcBits > DstBits ? Instruction::Trunc :
2785 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2786 return Create(opcode, C, Ty, Name, InsertBefore);
2789 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2790 bool isSigned, const Twine &Name,
2791 BasicBlock *InsertAtEnd) {
2792 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2794 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2795 unsigned DstBits = Ty->getScalarSizeInBits();
2796 Instruction::CastOps opcode =
2797 (SrcBits == DstBits ? Instruction::BitCast :
2798 (SrcBits > DstBits ? Instruction::Trunc :
2799 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2800 return Create(opcode, C, Ty, Name, InsertAtEnd);
2803 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2805 Instruction *InsertBefore) {
2806 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2808 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2809 unsigned DstBits = Ty->getScalarSizeInBits();
2810 Instruction::CastOps opcode =
2811 (SrcBits == DstBits ? Instruction::BitCast :
2812 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2813 return Create(opcode, C, Ty, Name, InsertBefore);
2816 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2818 BasicBlock *InsertAtEnd) {
2819 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2821 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2822 unsigned DstBits = Ty->getScalarSizeInBits();
2823 Instruction::CastOps opcode =
2824 (SrcBits == DstBits ? Instruction::BitCast :
2825 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2826 return Create(opcode, C, Ty, Name, InsertAtEnd);
2829 // Check whether it is valid to call getCastOpcode for these types.
2830 // This routine must be kept in sync with getCastOpcode.
2831 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2832 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2835 if (SrcTy == DestTy)
2838 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2839 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2840 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2841 // An element by element cast. Valid if casting the elements is valid.
2842 SrcTy = SrcVecTy->getElementType();
2843 DestTy = DestVecTy->getElementType();
2846 // Get the bit sizes, we'll need these
2847 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2848 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2850 // Run through the possibilities ...
2851 if (DestTy->isIntegerTy()) { // Casting to integral
2852 if (SrcTy->isIntegerTy()) // Casting from integral
2854 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2856 if (SrcTy->isVectorTy()) // Casting from vector
2857 return DestBits == SrcBits;
2858 // Casting from something else
2859 return SrcTy->isPointerTy();
2861 if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2862 if (SrcTy->isIntegerTy()) // Casting from integral
2864 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2866 if (SrcTy->isVectorTy()) // Casting from vector
2867 return DestBits == SrcBits;
2868 // Casting from something else
2871 if (DestTy->isVectorTy()) // Casting to vector
2872 return DestBits == SrcBits;
2873 if (DestTy->isPointerTy()) { // Casting to pointer
2874 if (SrcTy->isPointerTy()) // Casting from pointer
2876 return SrcTy->isIntegerTy(); // Casting from integral
2878 if (DestTy->isX86_MMXTy()) {
2879 if (SrcTy->isVectorTy())
2880 return DestBits == SrcBits; // 64-bit vector to MMX
2882 } // Casting to something else
2886 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
2887 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2890 if (SrcTy == DestTy)
2893 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2894 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
2895 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2896 // An element by element cast. Valid if casting the elements is valid.
2897 SrcTy = SrcVecTy->getElementType();
2898 DestTy = DestVecTy->getElementType();
2903 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
2904 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
2905 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
2909 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2910 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2912 // Could still have vectors of pointers if the number of elements doesn't
2914 if (SrcBits == 0 || DestBits == 0)
2917 if (SrcBits != DestBits)
2920 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
2926 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
2927 const DataLayout &DL) {
2928 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
2929 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
2930 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2931 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
2932 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
2933 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2935 return isBitCastable(SrcTy, DestTy);
2938 // Provide a way to get a "cast" where the cast opcode is inferred from the
2939 // types and size of the operand. This, basically, is a parallel of the
2940 // logic in the castIsValid function below. This axiom should hold:
2941 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2942 // should not assert in castIsValid. In other words, this produces a "correct"
2943 // casting opcode for the arguments passed to it.
2944 // This routine must be kept in sync with isCastable.
2945 Instruction::CastOps
2946 CastInst::getCastOpcode(
2947 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2948 Type *SrcTy = Src->getType();
2950 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2951 "Only first class types are castable!");
2953 if (SrcTy == DestTy)
2956 // FIXME: Check address space sizes here
2957 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2958 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2959 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2960 // An element by element cast. Find the appropriate opcode based on the
2962 SrcTy = SrcVecTy->getElementType();
2963 DestTy = DestVecTy->getElementType();
2966 // Get the bit sizes, we'll need these
2967 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2968 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2970 // Run through the possibilities ...
2971 if (DestTy->isIntegerTy()) { // Casting to integral
2972 if (SrcTy->isIntegerTy()) { // Casting from integral
2973 if (DestBits < SrcBits)
2974 return Trunc; // int -> smaller int
2975 else if (DestBits > SrcBits) { // its an extension
2977 return SExt; // signed -> SEXT
2979 return ZExt; // unsigned -> ZEXT
2981 return BitCast; // Same size, No-op cast
2983 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2985 return FPToSI; // FP -> sint
2987 return FPToUI; // FP -> uint
2988 } else if (SrcTy->isVectorTy()) {
2989 assert(DestBits == SrcBits &&
2990 "Casting vector to integer of different width");
2991 return BitCast; // Same size, no-op cast
2993 assert(SrcTy->isPointerTy() &&
2994 "Casting from a value that is not first-class type");
2995 return PtrToInt; // ptr -> int
2997 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2998 if (SrcTy->isIntegerTy()) { // Casting from integral
3000 return SIToFP; // sint -> FP
3002 return UIToFP; // uint -> FP
3003 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3004 if (DestBits < SrcBits) {
3005 return FPTrunc; // FP -> smaller FP
3006 } else if (DestBits > SrcBits) {
3007 return FPExt; // FP -> larger FP
3009 return BitCast; // same size, no-op cast
3011 } else if (SrcTy->isVectorTy()) {
3012 assert(DestBits == SrcBits &&
3013 "Casting vector to floating point of different width");
3014 return BitCast; // same size, no-op cast
3016 llvm_unreachable("Casting pointer or non-first class to float");
3017 } else if (DestTy->isVectorTy()) {
3018 assert(DestBits == SrcBits &&
3019 "Illegal cast to vector (wrong type or size)");
3021 } else if (DestTy->isPointerTy()) {
3022 if (SrcTy->isPointerTy()) {
3023 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3024 return AddrSpaceCast;
3025 return BitCast; // ptr -> ptr
3026 } else if (SrcTy->isIntegerTy()) {
3027 return IntToPtr; // int -> ptr
3029 llvm_unreachable("Casting pointer to other than pointer or int");
3030 } else if (DestTy->isX86_MMXTy()) {
3031 if (SrcTy->isVectorTy()) {
3032 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3033 return BitCast; // 64-bit vector to MMX
3035 llvm_unreachable("Illegal cast to X86_MMX");
3037 llvm_unreachable("Casting to type that is not first-class");
3040 //===----------------------------------------------------------------------===//
3041 // CastInst SubClass Constructors
3042 //===----------------------------------------------------------------------===//
3044 /// Check that the construction parameters for a CastInst are correct. This
3045 /// could be broken out into the separate constructors but it is useful to have
3046 /// it in one place and to eliminate the redundant code for getting the sizes
3047 /// of the types involved.
3049 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
3051 // Check for type sanity on the arguments
3052 Type *SrcTy = S->getType();
3054 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3055 SrcTy->isAggregateType() || DstTy->isAggregateType())
3058 // Get the size of the types in bits, we'll need this later
3059 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3060 unsigned DstBitSize = DstTy->getScalarSizeInBits();
3062 // If these are vector types, get the lengths of the vectors (using zero for
3063 // scalar types means that checking that vector lengths match also checks that
3064 // scalars are not being converted to vectors or vectors to scalars).
3065 unsigned SrcLength = SrcTy->isVectorTy() ?
3066 cast<VectorType>(SrcTy)->getNumElements() : 0;
3067 unsigned DstLength = DstTy->isVectorTy() ?
3068 cast<VectorType>(DstTy)->getNumElements() : 0;
3070 // Switch on the opcode provided
3072 default: return false; // This is an input error
3073 case Instruction::Trunc:
3074 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3075 SrcLength == DstLength && SrcBitSize > DstBitSize;
3076 case Instruction::ZExt:
3077 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3078 SrcLength == DstLength && SrcBitSize < DstBitSize;
3079 case Instruction::SExt:
3080 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3081 SrcLength == DstLength && SrcBitSize < DstBitSize;
3082 case Instruction::FPTrunc:
3083 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3084 SrcLength == DstLength && SrcBitSize > DstBitSize;
3085 case Instruction::FPExt:
3086 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3087 SrcLength == DstLength && SrcBitSize < DstBitSize;
3088 case Instruction::UIToFP:
3089 case Instruction::SIToFP:
3090 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3091 SrcLength == DstLength;
3092 case Instruction::FPToUI:
3093 case Instruction::FPToSI:
3094 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3095 SrcLength == DstLength;
3096 case Instruction::PtrToInt:
3097 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3099 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3100 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3102 return SrcTy->getScalarType()->isPointerTy() &&
3103 DstTy->getScalarType()->isIntegerTy();
3104 case Instruction::IntToPtr:
3105 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3107 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3108 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3110 return SrcTy->getScalarType()->isIntegerTy() &&
3111 DstTy->getScalarType()->isPointerTy();
3112 case Instruction::BitCast: {
3113 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3114 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3116 // BitCast implies a no-op cast of type only. No bits change.
3117 // However, you can't cast pointers to anything but pointers.
3118 if (!SrcPtrTy != !DstPtrTy)
3121 // For non-pointer cases, the cast is okay if the source and destination bit
3122 // widths are identical.
3124 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3126 // If both are pointers then the address spaces must match.
3127 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3130 // A vector of pointers must have the same number of elements.
3131 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3132 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3133 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3140 case Instruction::AddrSpaceCast: {
3141 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3145 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3149 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3152 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3153 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3154 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3164 TruncInst::TruncInst(
3165 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3166 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3167 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3170 TruncInst::TruncInst(
3171 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3172 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3173 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3177 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3178 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3179 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3183 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3184 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3185 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3188 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3189 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3190 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3194 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3195 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3196 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3199 FPTruncInst::FPTruncInst(
3200 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3201 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3202 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3205 FPTruncInst::FPTruncInst(
3206 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3207 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3208 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3211 FPExtInst::FPExtInst(
3212 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3213 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3214 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3217 FPExtInst::FPExtInst(
3218 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3219 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3220 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3223 UIToFPInst::UIToFPInst(
3224 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3225 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3226 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3229 UIToFPInst::UIToFPInst(
3230 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3231 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3232 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3235 SIToFPInst::SIToFPInst(
3236 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3237 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3238 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3241 SIToFPInst::SIToFPInst(
3242 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3243 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3244 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3247 FPToUIInst::FPToUIInst(
3248 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3249 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3250 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3253 FPToUIInst::FPToUIInst(
3254 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3255 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3256 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3259 FPToSIInst::FPToSIInst(
3260 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3261 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3262 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3265 FPToSIInst::FPToSIInst(
3266 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3267 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3268 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3271 PtrToIntInst::PtrToIntInst(
3272 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3273 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3274 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3277 PtrToIntInst::PtrToIntInst(
3278 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3279 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3280 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3283 IntToPtrInst::IntToPtrInst(
3284 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3285 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3286 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3289 IntToPtrInst::IntToPtrInst(
3290 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3291 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3292 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3295 BitCastInst::BitCastInst(
3296 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3297 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3298 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3301 BitCastInst::BitCastInst(
3302 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3303 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3304 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3307 AddrSpaceCastInst::AddrSpaceCastInst(
3308 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3309 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3310 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3313 AddrSpaceCastInst::AddrSpaceCastInst(
3314 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3315 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3316 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3319 //===----------------------------------------------------------------------===//
3321 //===----------------------------------------------------------------------===//
3323 void CmpInst::anchor() {}
3325 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3326 Value *LHS, Value *RHS, const Twine &Name,
3327 Instruction *InsertBefore)
3328 : Instruction(ty, op,
3329 OperandTraits<CmpInst>::op_begin(this),
3330 OperandTraits<CmpInst>::operands(this),
3334 setPredicate((Predicate)predicate);
3338 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3339 Value *LHS, Value *RHS, const Twine &Name,
3340 BasicBlock *InsertAtEnd)
3341 : Instruction(ty, op,
3342 OperandTraits<CmpInst>::op_begin(this),
3343 OperandTraits<CmpInst>::operands(this),
3347 setPredicate((Predicate)predicate);
3352 CmpInst::Create(OtherOps Op, unsigned short predicate,
3353 Value *S1, Value *S2,
3354 const Twine &Name, Instruction *InsertBefore) {
3355 if (Op == Instruction::ICmp) {
3357 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3360 return new ICmpInst(CmpInst::Predicate(predicate),
3365 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3368 return new FCmpInst(CmpInst::Predicate(predicate),
3373 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
3374 const Twine &Name, BasicBlock *InsertAtEnd) {
3375 if (Op == Instruction::ICmp) {
3376 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3379 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3383 void CmpInst::swapOperands() {
3384 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3387 cast<FCmpInst>(this)->swapOperands();
3390 bool CmpInst::isCommutative() const {
3391 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3392 return IC->isCommutative();
3393 return cast<FCmpInst>(this)->isCommutative();
3396 bool CmpInst::isEquality() const {
3397 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3398 return IC->isEquality();
3399 return cast<FCmpInst>(this)->isEquality();
3403 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3405 default: llvm_unreachable("Unknown cmp predicate!");
3406 case ICMP_EQ: return ICMP_NE;
3407 case ICMP_NE: return ICMP_EQ;
3408 case ICMP_UGT: return ICMP_ULE;
3409 case ICMP_ULT: return ICMP_UGE;
3410 case ICMP_UGE: return ICMP_ULT;
3411 case ICMP_ULE: return ICMP_UGT;
3412 case ICMP_SGT: return ICMP_SLE;
3413 case ICMP_SLT: return ICMP_SGE;
3414 case ICMP_SGE: return ICMP_SLT;
3415 case ICMP_SLE: return ICMP_SGT;
3417 case FCMP_OEQ: return FCMP_UNE;
3418 case FCMP_ONE: return FCMP_UEQ;
3419 case FCMP_OGT: return FCMP_ULE;
3420 case FCMP_OLT: return FCMP_UGE;
3421 case FCMP_OGE: return FCMP_ULT;
3422 case FCMP_OLE: return FCMP_UGT;
3423 case FCMP_UEQ: return FCMP_ONE;
3424 case FCMP_UNE: return FCMP_OEQ;
3425 case FCMP_UGT: return FCMP_OLE;
3426 case FCMP_ULT: return FCMP_OGE;
3427 case FCMP_UGE: return FCMP_OLT;
3428 case FCMP_ULE: return FCMP_OGT;
3429 case FCMP_ORD: return FCMP_UNO;
3430 case FCMP_UNO: return FCMP_ORD;
3431 case FCMP_TRUE: return FCMP_FALSE;
3432 case FCMP_FALSE: return FCMP_TRUE;
3436 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3438 default: llvm_unreachable("Unknown icmp predicate!");
3439 case ICMP_EQ: case ICMP_NE:
3440 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3442 case ICMP_UGT: return ICMP_SGT;
3443 case ICMP_ULT: return ICMP_SLT;
3444 case ICMP_UGE: return ICMP_SGE;
3445 case ICMP_ULE: return ICMP_SLE;
3449 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3451 default: llvm_unreachable("Unknown icmp predicate!");
3452 case ICMP_EQ: case ICMP_NE:
3453 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3455 case ICMP_SGT: return ICMP_UGT;
3456 case ICMP_SLT: return ICMP_ULT;
3457 case ICMP_SGE: return ICMP_UGE;
3458 case ICMP_SLE: return ICMP_ULE;
3462 /// Initialize a set of values that all satisfy the condition with C.
3465 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3468 uint32_t BitWidth = C.getBitWidth();
3470 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3471 case ICmpInst::ICMP_EQ: ++Upper; break;
3472 case ICmpInst::ICMP_NE: ++Lower; break;
3473 case ICmpInst::ICMP_ULT:
3474 Lower = APInt::getMinValue(BitWidth);
3475 // Check for an empty-set condition.
3477 return ConstantRange(BitWidth, /*isFullSet=*/false);
3479 case ICmpInst::ICMP_SLT:
3480 Lower = APInt::getSignedMinValue(BitWidth);
3481 // Check for an empty-set condition.
3483 return ConstantRange(BitWidth, /*isFullSet=*/false);
3485 case ICmpInst::ICMP_UGT:
3486 ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3487 // Check for an empty-set condition.
3489 return ConstantRange(BitWidth, /*isFullSet=*/false);
3491 case ICmpInst::ICMP_SGT:
3492 ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3493 // Check for an empty-set condition.
3495 return ConstantRange(BitWidth, /*isFullSet=*/false);
3497 case ICmpInst::ICMP_ULE:
3498 Lower = APInt::getMinValue(BitWidth); ++Upper;
3499 // Check for a full-set condition.
3501 return ConstantRange(BitWidth, /*isFullSet=*/true);
3503 case ICmpInst::ICMP_SLE:
3504 Lower = APInt::getSignedMinValue(BitWidth); ++Upper;
3505 // Check for a full-set condition.
3507 return ConstantRange(BitWidth, /*isFullSet=*/true);
3509 case ICmpInst::ICMP_UGE:
3510 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3511 // Check for a full-set condition.
3513 return ConstantRange(BitWidth, /*isFullSet=*/true);
3515 case ICmpInst::ICMP_SGE:
3516 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3517 // Check for a full-set condition.
3519 return ConstantRange(BitWidth, /*isFullSet=*/true);
3522 return ConstantRange(Lower, Upper);
3525 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3527 default: llvm_unreachable("Unknown cmp predicate!");
3528 case ICMP_EQ: case ICMP_NE:
3530 case ICMP_SGT: return ICMP_SLT;
3531 case ICMP_SLT: return ICMP_SGT;
3532 case ICMP_SGE: return ICMP_SLE;
3533 case ICMP_SLE: return ICMP_SGE;
3534 case ICMP_UGT: return ICMP_ULT;
3535 case ICMP_ULT: return ICMP_UGT;
3536 case ICMP_UGE: return ICMP_ULE;
3537 case ICMP_ULE: return ICMP_UGE;
3539 case FCMP_FALSE: case FCMP_TRUE:
3540 case FCMP_OEQ: case FCMP_ONE:
3541 case FCMP_UEQ: case FCMP_UNE:
3542 case FCMP_ORD: case FCMP_UNO:
3544 case FCMP_OGT: return FCMP_OLT;
3545 case FCMP_OLT: return FCMP_OGT;
3546 case FCMP_OGE: return FCMP_OLE;
3547 case FCMP_OLE: return FCMP_OGE;
3548 case FCMP_UGT: return FCMP_ULT;
3549 case FCMP_ULT: return FCMP_UGT;
3550 case FCMP_UGE: return FCMP_ULE;
3551 case FCMP_ULE: return FCMP_UGE;
3555 bool CmpInst::isUnsigned(unsigned short predicate) {
3556 switch (predicate) {
3557 default: return false;
3558 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3559 case ICmpInst::ICMP_UGE: return true;
3563 bool CmpInst::isSigned(unsigned short predicate) {
3564 switch (predicate) {
3565 default: return false;
3566 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3567 case ICmpInst::ICMP_SGE: return true;
3571 bool CmpInst::isOrdered(unsigned short predicate) {
3572 switch (predicate) {
3573 default: return false;
3574 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3575 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3576 case FCmpInst::FCMP_ORD: return true;
3580 bool CmpInst::isUnordered(unsigned short predicate) {
3581 switch (predicate) {
3582 default: return false;
3583 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3584 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3585 case FCmpInst::FCMP_UNO: return true;
3589 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3591 default: return false;
3592 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3593 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3597 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3599 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3600 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3601 default: return false;
3606 //===----------------------------------------------------------------------===//
3607 // SwitchInst Implementation
3608 //===----------------------------------------------------------------------===//
3610 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3611 assert(Value && Default && NumReserved);
3612 ReservedSpace = NumReserved;
3613 setNumHungOffUseOperands(2);
3614 allocHungoffUses(ReservedSpace);
3620 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3621 /// switch on and a default destination. The number of additional cases can
3622 /// be specified here to make memory allocation more efficient. This
3623 /// constructor can also autoinsert before another instruction.
3624 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3625 Instruction *InsertBefore)
3626 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3627 nullptr, 0, InsertBefore) {
3628 init(Value, Default, 2+NumCases*2);
3631 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3632 /// switch on and a default destination. The number of additional cases can
3633 /// be specified here to make memory allocation more efficient. This
3634 /// constructor also autoinserts at the end of the specified BasicBlock.
3635 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3636 BasicBlock *InsertAtEnd)
3637 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3638 nullptr, 0, InsertAtEnd) {
3639 init(Value, Default, 2+NumCases*2);
3642 SwitchInst::SwitchInst(const SwitchInst &SI)
3643 : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
3644 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3645 setNumHungOffUseOperands(SI.getNumOperands());
3646 Use *OL = getOperandList();
3647 const Use *InOL = SI.getOperandList();
3648 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3650 OL[i+1] = InOL[i+1];
3652 SubclassOptionalData = SI.SubclassOptionalData;
3656 /// addCase - Add an entry to the switch instruction...
3658 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3659 unsigned NewCaseIdx = getNumCases();
3660 unsigned OpNo = getNumOperands();
3661 if (OpNo+2 > ReservedSpace)
3662 growOperands(); // Get more space!
3663 // Initialize some new operands.
3664 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3665 setNumHungOffUseOperands(OpNo+2);
3666 CaseIt Case(this, NewCaseIdx);
3667 Case.setValue(OnVal);
3668 Case.setSuccessor(Dest);
3671 /// removeCase - This method removes the specified case and its successor
3672 /// from the switch instruction.
3673 void SwitchInst::removeCase(CaseIt i) {
3674 unsigned idx = i.getCaseIndex();
3676 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3678 unsigned NumOps = getNumOperands();
3679 Use *OL = getOperandList();
3681 // Overwrite this case with the end of the list.
3682 if (2 + (idx + 1) * 2 != NumOps) {
3683 OL[2 + idx * 2] = OL[NumOps - 2];
3684 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3687 // Nuke the last value.
3688 OL[NumOps-2].set(nullptr);
3689 OL[NumOps-2+1].set(nullptr);
3690 setNumHungOffUseOperands(NumOps-2);
3693 /// growOperands - grow operands - This grows the operand list in response
3694 /// to a push_back style of operation. This grows the number of ops by 3 times.
3696 void SwitchInst::growOperands() {
3697 unsigned e = getNumOperands();
3698 unsigned NumOps = e*3;
3700 ReservedSpace = NumOps;
3701 growHungoffUses(ReservedSpace);
3705 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3706 return getSuccessor(idx);
3708 unsigned SwitchInst::getNumSuccessorsV() const {
3709 return getNumSuccessors();
3711 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3712 setSuccessor(idx, B);
3715 //===----------------------------------------------------------------------===//
3716 // IndirectBrInst Implementation
3717 //===----------------------------------------------------------------------===//
3719 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3720 assert(Address && Address->getType()->isPointerTy() &&
3721 "Address of indirectbr must be a pointer");
3722 ReservedSpace = 1+NumDests;
3723 setNumHungOffUseOperands(1);
3724 allocHungoffUses(ReservedSpace);
3730 /// growOperands - grow operands - This grows the operand list in response
3731 /// to a push_back style of operation. This grows the number of ops by 2 times.
3733 void IndirectBrInst::growOperands() {
3734 unsigned e = getNumOperands();
3735 unsigned NumOps = e*2;
3737 ReservedSpace = NumOps;
3738 growHungoffUses(ReservedSpace);
3741 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3742 Instruction *InsertBefore)
3743 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3744 nullptr, 0, InsertBefore) {
3745 init(Address, NumCases);
3748 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3749 BasicBlock *InsertAtEnd)
3750 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3751 nullptr, 0, InsertAtEnd) {
3752 init(Address, NumCases);
3755 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3756 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3757 nullptr, IBI.getNumOperands()) {
3758 allocHungoffUses(IBI.getNumOperands());
3759 Use *OL = getOperandList();
3760 const Use *InOL = IBI.getOperandList();
3761 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3763 SubclassOptionalData = IBI.SubclassOptionalData;
3766 /// addDestination - Add a destination.
3768 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3769 unsigned OpNo = getNumOperands();
3770 if (OpNo+1 > ReservedSpace)
3771 growOperands(); // Get more space!
3772 // Initialize some new operands.
3773 assert(OpNo < ReservedSpace && "Growing didn't work!");
3774 setNumHungOffUseOperands(OpNo+1);
3775 getOperandList()[OpNo] = DestBB;
3778 /// removeDestination - This method removes the specified successor from the
3779 /// indirectbr instruction.
3780 void IndirectBrInst::removeDestination(unsigned idx) {
3781 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3783 unsigned NumOps = getNumOperands();
3784 Use *OL = getOperandList();
3786 // Replace this value with the last one.
3787 OL[idx+1] = OL[NumOps-1];
3789 // Nuke the last value.
3790 OL[NumOps-1].set(nullptr);
3791 setNumHungOffUseOperands(NumOps-1);
3794 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3795 return getSuccessor(idx);
3797 unsigned IndirectBrInst::getNumSuccessorsV() const {
3798 return getNumSuccessors();
3800 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3801 setSuccessor(idx, B);
3804 //===----------------------------------------------------------------------===//
3805 // cloneImpl() implementations
3806 //===----------------------------------------------------------------------===//
3808 // Define these methods here so vtables don't get emitted into every translation
3809 // unit that uses these classes.
3811 GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
3812 return new (getNumOperands()) GetElementPtrInst(*this);
3815 BinaryOperator *BinaryOperator::cloneImpl() const {
3816 return Create(getOpcode(), Op<0>(), Op<1>());
3819 FCmpInst *FCmpInst::cloneImpl() const {
3820 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3823 ICmpInst *ICmpInst::cloneImpl() const {
3824 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3827 ExtractValueInst *ExtractValueInst::cloneImpl() const {
3828 return new ExtractValueInst(*this);
3831 InsertValueInst *InsertValueInst::cloneImpl() const {
3832 return new InsertValueInst(*this);
3835 AllocaInst *AllocaInst::cloneImpl() const {
3836 AllocaInst *Result = new AllocaInst(getAllocatedType(),
3837 (Value *)getOperand(0), getAlignment());
3838 Result->setUsedWithInAlloca(isUsedWithInAlloca());
3842 LoadInst *LoadInst::cloneImpl() const {
3843 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3844 getAlignment(), getOrdering(), getSynchScope());
3847 StoreInst *StoreInst::cloneImpl() const {
3848 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3849 getAlignment(), getOrdering(), getSynchScope());
3853 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
3854 AtomicCmpXchgInst *Result =
3855 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3856 getSuccessOrdering(), getFailureOrdering(),
3858 Result->setVolatile(isVolatile());
3859 Result->setWeak(isWeak());
3863 AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
3864 AtomicRMWInst *Result =
3865 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3866 getOrdering(), getSynchScope());
3867 Result->setVolatile(isVolatile());
3871 FenceInst *FenceInst::cloneImpl() const {
3872 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3875 TruncInst *TruncInst::cloneImpl() const {
3876 return new TruncInst(getOperand(0), getType());
3879 ZExtInst *ZExtInst::cloneImpl() const {
3880 return new ZExtInst(getOperand(0), getType());
3883 SExtInst *SExtInst::cloneImpl() const {
3884 return new SExtInst(getOperand(0), getType());
3887 FPTruncInst *FPTruncInst::cloneImpl() const {
3888 return new FPTruncInst(getOperand(0), getType());
3891 FPExtInst *FPExtInst::cloneImpl() const {
3892 return new FPExtInst(getOperand(0), getType());
3895 UIToFPInst *UIToFPInst::cloneImpl() const {
3896 return new UIToFPInst(getOperand(0), getType());
3899 SIToFPInst *SIToFPInst::cloneImpl() const {
3900 return new SIToFPInst(getOperand(0), getType());
3903 FPToUIInst *FPToUIInst::cloneImpl() const {
3904 return new FPToUIInst(getOperand(0), getType());
3907 FPToSIInst *FPToSIInst::cloneImpl() const {
3908 return new FPToSIInst(getOperand(0), getType());
3911 PtrToIntInst *PtrToIntInst::cloneImpl() const {
3912 return new PtrToIntInst(getOperand(0), getType());
3915 IntToPtrInst *IntToPtrInst::cloneImpl() const {
3916 return new IntToPtrInst(getOperand(0), getType());
3919 BitCastInst *BitCastInst::cloneImpl() const {
3920 return new BitCastInst(getOperand(0), getType());
3923 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
3924 return new AddrSpaceCastInst(getOperand(0), getType());
3927 CallInst *CallInst::cloneImpl() const {
3928 return new(getNumOperands()) CallInst(*this);
3931 SelectInst *SelectInst::cloneImpl() const {
3932 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3935 VAArgInst *VAArgInst::cloneImpl() const {
3936 return new VAArgInst(getOperand(0), getType());
3939 ExtractElementInst *ExtractElementInst::cloneImpl() const {
3940 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3943 InsertElementInst *InsertElementInst::cloneImpl() const {
3944 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3947 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
3948 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3951 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
3953 LandingPadInst *LandingPadInst::cloneImpl() const {
3954 return new LandingPadInst(*this);
3957 ReturnInst *ReturnInst::cloneImpl() const {
3958 return new(getNumOperands()) ReturnInst(*this);
3961 BranchInst *BranchInst::cloneImpl() const {
3962 return new(getNumOperands()) BranchInst(*this);
3965 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
3967 IndirectBrInst *IndirectBrInst::cloneImpl() const {
3968 return new IndirectBrInst(*this);
3971 InvokeInst *InvokeInst::cloneImpl() const {
3972 return new(getNumOperands()) InvokeInst(*this);
3975 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
3977 CleanupEndPadInst *CleanupEndPadInst::cloneImpl() const {
3978 return new (getNumOperands()) CleanupEndPadInst(*this);
3981 CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
3982 return new (getNumOperands()) CleanupReturnInst(*this);
3985 CatchEndPadInst *CatchEndPadInst::cloneImpl() const {
3986 return new (getNumOperands()) CatchEndPadInst(*this);
3989 CatchReturnInst *CatchReturnInst::cloneImpl() const {
3990 return new (getNumOperands()) CatchReturnInst(*this);
3993 CatchPadInst *CatchPadInst::cloneImpl() const {
3994 return new (getNumOperands()) CatchPadInst(*this);
3997 TerminatePadInst *TerminatePadInst::cloneImpl() const {
3998 return new (getNumOperands()) TerminatePadInst(*this);
4001 CleanupPadInst *CleanupPadInst::cloneImpl() const {
4002 return new (getNumOperands()) CleanupPadInst(*this);
4005 UnreachableInst *UnreachableInst::cloneImpl() const {
4006 LLVMContext &Context = getContext();
4007 return new UnreachableInst(Context);