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 assert(i < (getNumArgOperands() + 1) && "Param index out of bounds!");
336 if (AttributeList.hasAttribute(i, A))
338 if (const Function *F = getCalledFunction())
339 return F->getAttributes().hasAttribute(i, A);
343 bool CallInst::dataOperandHasImpliedAttr(unsigned i,
344 Attribute::AttrKind A) const {
346 // The attribute A can either be directly specified, if the operand in
347 // question is a call argument; or be indirectly implied by the kind of its
348 // containing operand bundle, if the operand is a bundle operand.
350 if (i < (getNumArgOperands() + 1))
351 return paramHasAttr(i, A);
353 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
354 "Must be either a call argument or an operand bundle!");
355 return getOperandBundleForOperand(i - 1).operandsHaveAttr(A);
358 /// IsConstantOne - Return true only if val is constant int 1
359 static bool IsConstantOne(Value *val) {
360 assert(val && "IsConstantOne does not work with nullptr val");
361 const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
362 return CVal && CVal->isOne();
365 static Instruction *createMalloc(Instruction *InsertBefore,
366 BasicBlock *InsertAtEnd, Type *IntPtrTy,
367 Type *AllocTy, Value *AllocSize,
368 Value *ArraySize, Function *MallocF,
370 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
371 "createMalloc needs either InsertBefore or InsertAtEnd");
373 // malloc(type) becomes:
374 // bitcast (i8* malloc(typeSize)) to type*
375 // malloc(type, arraySize) becomes:
376 // bitcast (i8 *malloc(typeSize*arraySize)) to type*
378 ArraySize = ConstantInt::get(IntPtrTy, 1);
379 else if (ArraySize->getType() != IntPtrTy) {
381 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
384 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
388 if (!IsConstantOne(ArraySize)) {
389 if (IsConstantOne(AllocSize)) {
390 AllocSize = ArraySize; // Operand * 1 = Operand
391 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
392 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
394 // Malloc arg is constant product of type size and array size
395 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
397 // Multiply type size by the array size...
399 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
400 "mallocsize", InsertBefore);
402 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
403 "mallocsize", InsertAtEnd);
407 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
408 // Create the call to Malloc.
409 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
410 Module* M = BB->getParent()->getParent();
411 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
412 Value *MallocFunc = MallocF;
414 // prototype malloc as "void *malloc(size_t)"
415 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy, nullptr);
416 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
417 CallInst *MCall = nullptr;
418 Instruction *Result = nullptr;
420 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall", InsertBefore);
422 if (Result->getType() != AllocPtrType)
423 // Create a cast instruction to convert to the right type...
424 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
426 MCall = CallInst::Create(MallocFunc, AllocSize, "malloccall");
428 if (Result->getType() != AllocPtrType) {
429 InsertAtEnd->getInstList().push_back(MCall);
430 // Create a cast instruction to convert to the right type...
431 Result = new BitCastInst(MCall, AllocPtrType, Name);
434 MCall->setTailCall();
435 if (Function *F = dyn_cast<Function>(MallocFunc)) {
436 MCall->setCallingConv(F->getCallingConv());
437 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
439 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
444 /// CreateMalloc - Generate the IR for a call to malloc:
445 /// 1. Compute the malloc call's argument as the specified type's size,
446 /// possibly multiplied by the array size if the array size is not
448 /// 2. Call malloc with that argument.
449 /// 3. Bitcast the result of the malloc call to the specified type.
450 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
451 Type *IntPtrTy, Type *AllocTy,
452 Value *AllocSize, Value *ArraySize,
455 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
456 ArraySize, MallocF, Name);
459 /// CreateMalloc - Generate the IR for a call to malloc:
460 /// 1. Compute the malloc call's argument as the specified type's size,
461 /// possibly multiplied by the array size if the array size is not
463 /// 2. Call malloc with that argument.
464 /// 3. Bitcast the result of the malloc call to the specified type.
465 /// Note: This function does not add the bitcast to the basic block, that is the
466 /// responsibility of the caller.
467 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
468 Type *IntPtrTy, Type *AllocTy,
469 Value *AllocSize, Value *ArraySize,
470 Function *MallocF, const Twine &Name) {
471 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
472 ArraySize, MallocF, Name);
475 static Instruction* createFree(Value* Source, Instruction *InsertBefore,
476 BasicBlock *InsertAtEnd) {
477 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
478 "createFree needs either InsertBefore or InsertAtEnd");
479 assert(Source->getType()->isPointerTy() &&
480 "Can not free something of nonpointer type!");
482 BasicBlock* BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
483 Module* M = BB->getParent()->getParent();
485 Type *VoidTy = Type::getVoidTy(M->getContext());
486 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
487 // prototype free as "void free(void*)"
488 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy, nullptr);
489 CallInst* Result = nullptr;
490 Value *PtrCast = Source;
492 if (Source->getType() != IntPtrTy)
493 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
494 Result = CallInst::Create(FreeFunc, PtrCast, "", InsertBefore);
496 if (Source->getType() != IntPtrTy)
497 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
498 Result = CallInst::Create(FreeFunc, PtrCast, "");
500 Result->setTailCall();
501 if (Function *F = dyn_cast<Function>(FreeFunc))
502 Result->setCallingConv(F->getCallingConv());
507 /// CreateFree - Generate the IR for a call to the builtin free function.
508 Instruction * CallInst::CreateFree(Value* Source, Instruction *InsertBefore) {
509 return createFree(Source, InsertBefore, nullptr);
512 /// CreateFree - Generate the IR for a call to the builtin free function.
513 /// Note: This function does not add the call to the basic block, that is the
514 /// responsibility of the caller.
515 Instruction* CallInst::CreateFree(Value* Source, BasicBlock *InsertAtEnd) {
516 Instruction* FreeCall = createFree(Source, nullptr, InsertAtEnd);
517 assert(FreeCall && "CreateFree did not create a CallInst");
521 //===----------------------------------------------------------------------===//
522 // InvokeInst Implementation
523 //===----------------------------------------------------------------------===//
525 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
526 BasicBlock *IfException, ArrayRef<Value *> Args,
527 ArrayRef<OperandBundleDef> Bundles,
528 const Twine &NameStr) {
531 assert(getNumOperands() == 3 + Args.size() + CountBundleInputs(Bundles) &&
532 "NumOperands not set up?");
535 Op<-1>() = IfException;
538 assert(((Args.size() == FTy->getNumParams()) ||
539 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
540 "Invoking a function with bad signature");
542 for (unsigned i = 0, e = Args.size(); i != e; i++)
543 assert((i >= FTy->getNumParams() ||
544 FTy->getParamType(i) == Args[i]->getType()) &&
545 "Invoking a function with a bad signature!");
548 std::copy(Args.begin(), Args.end(), op_begin());
550 auto It = populateBundleOperandInfos(Bundles, Args.size());
552 assert(It + 3 == op_end() && "Should add up!");
557 InvokeInst::InvokeInst(const InvokeInst &II)
558 : TerminatorInst(II.getType(), Instruction::Invoke,
559 OperandTraits<InvokeInst>::op_end(this) -
561 II.getNumOperands()),
562 AttributeList(II.AttributeList), FTy(II.FTy) {
563 setCallingConv(II.getCallingConv());
564 std::copy(II.op_begin(), II.op_end(), op_begin());
565 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
566 bundle_op_info_begin());
567 SubclassOptionalData = II.SubclassOptionalData;
570 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
571 return getSuccessor(idx);
573 unsigned InvokeInst::getNumSuccessorsV() const {
574 return getNumSuccessors();
576 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
577 return setSuccessor(idx, B);
580 bool InvokeInst::hasFnAttrImpl(Attribute::AttrKind A) const {
581 if (AttributeList.hasAttribute(AttributeSet::FunctionIndex, A))
584 // Operand bundles override attributes on the called function, but don't
585 // override attributes directly present on the invoke instruction.
586 if (isFnAttrDisallowedByOpBundle(A))
589 if (const Function *F = getCalledFunction())
590 return F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, A);
594 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind A) const {
595 assert(i < (getNumArgOperands() + 1) && "Param index out of bounds!");
597 if (AttributeList.hasAttribute(i, A))
599 if (const Function *F = getCalledFunction())
600 return F->getAttributes().hasAttribute(i, A);
604 bool InvokeInst::dataOperandHasImpliedAttr(unsigned i,
605 Attribute::AttrKind A) const {
606 // The attribute A can either be directly specified, if the operand in
607 // question is an invoke argument; or be indirectly implied by the kind of its
608 // containing operand bundle, if the operand is a bundle operand.
610 if (i < (getNumArgOperands() + 1))
611 return paramHasAttr(i, A);
613 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
614 "Must be either an invoke argument or an operand bundle!");
615 return getOperandBundleForOperand(i - 1).operandsHaveAttr(A);
618 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind attr) {
619 AttributeSet PAL = getAttributes();
620 PAL = PAL.addAttribute(getContext(), i, attr);
624 void InvokeInst::removeAttribute(unsigned i, Attribute attr) {
625 AttributeSet PAL = getAttributes();
627 PAL = PAL.removeAttributes(getContext(), i,
628 AttributeSet::get(getContext(), i, B));
632 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
633 AttributeSet PAL = getAttributes();
634 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
638 void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
639 AttributeSet PAL = getAttributes();
640 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
644 LandingPadInst *InvokeInst::getLandingPadInst() const {
645 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
648 //===----------------------------------------------------------------------===//
649 // ReturnInst Implementation
650 //===----------------------------------------------------------------------===//
652 ReturnInst::ReturnInst(const ReturnInst &RI)
653 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
654 OperandTraits<ReturnInst>::op_end(this) -
656 RI.getNumOperands()) {
657 if (RI.getNumOperands())
658 Op<0>() = RI.Op<0>();
659 SubclassOptionalData = RI.SubclassOptionalData;
662 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
663 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
664 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
669 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
670 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
671 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
676 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
677 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
678 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
681 unsigned ReturnInst::getNumSuccessorsV() const {
682 return getNumSuccessors();
685 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
686 /// emit the vtable for the class in this translation unit.
687 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
688 llvm_unreachable("ReturnInst has no successors!");
691 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
692 llvm_unreachable("ReturnInst has no successors!");
695 ReturnInst::~ReturnInst() {
698 //===----------------------------------------------------------------------===//
699 // ResumeInst Implementation
700 //===----------------------------------------------------------------------===//
702 ResumeInst::ResumeInst(const ResumeInst &RI)
703 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
704 OperandTraits<ResumeInst>::op_begin(this), 1) {
705 Op<0>() = RI.Op<0>();
708 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
709 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
710 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
714 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
715 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
716 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
720 unsigned ResumeInst::getNumSuccessorsV() const {
721 return getNumSuccessors();
724 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
725 llvm_unreachable("ResumeInst has no successors!");
728 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
729 llvm_unreachable("ResumeInst has no successors!");
732 //===----------------------------------------------------------------------===//
733 // CleanupEndPadInst Implementation
734 //===----------------------------------------------------------------------===//
736 CleanupEndPadInst::CleanupEndPadInst(const CleanupEndPadInst &CEPI)
737 : TerminatorInst(CEPI.getType(), Instruction::CleanupEndPad,
738 OperandTraits<CleanupEndPadInst>::op_end(this) -
739 CEPI.getNumOperands(),
740 CEPI.getNumOperands()) {
741 setInstructionSubclassData(CEPI.getSubclassDataFromInstruction());
742 setCleanupPad(CEPI.getCleanupPad());
743 if (BasicBlock *UnwindDest = CEPI.getUnwindDest())
744 setUnwindDest(UnwindDest);
747 void CleanupEndPadInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) {
748 setCleanupPad(CleanupPad);
750 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
751 setUnwindDest(UnwindBB);
755 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad,
756 BasicBlock *UnwindBB, unsigned Values,
757 Instruction *InsertBefore)
758 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
759 Instruction::CleanupEndPad,
760 OperandTraits<CleanupEndPadInst>::op_end(this) - Values,
761 Values, InsertBefore) {
762 init(CleanupPad, UnwindBB);
765 CleanupEndPadInst::CleanupEndPadInst(CleanupPadInst *CleanupPad,
766 BasicBlock *UnwindBB, unsigned Values,
767 BasicBlock *InsertAtEnd)
768 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
769 Instruction::CleanupEndPad,
770 OperandTraits<CleanupEndPadInst>::op_end(this) - Values,
771 Values, InsertAtEnd) {
772 init(CleanupPad, UnwindBB);
775 BasicBlock *CleanupEndPadInst::getSuccessorV(unsigned Idx) const {
777 return getUnwindDest();
779 unsigned CleanupEndPadInst::getNumSuccessorsV() const {
780 return getNumSuccessors();
782 void CleanupEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
787 //===----------------------------------------------------------------------===//
788 // CleanupReturnInst Implementation
789 //===----------------------------------------------------------------------===//
791 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
792 : TerminatorInst(CRI.getType(), Instruction::CleanupRet,
793 OperandTraits<CleanupReturnInst>::op_end(this) -
794 CRI.getNumOperands(),
795 CRI.getNumOperands()) {
796 setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
797 Op<-1>() = CRI.Op<-1>();
798 if (CRI.hasUnwindDest())
799 Op<-2>() = CRI.Op<-2>();
802 void CleanupReturnInst::init(CleanupPadInst *CleanupPad, BasicBlock *UnwindBB) {
804 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
806 Op<-1>() = CleanupPad;
811 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad,
812 BasicBlock *UnwindBB, unsigned Values,
813 Instruction *InsertBefore)
814 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
815 Instruction::CleanupRet,
816 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
817 Values, InsertBefore) {
818 init(CleanupPad, UnwindBB);
821 CleanupReturnInst::CleanupReturnInst(CleanupPadInst *CleanupPad,
822 BasicBlock *UnwindBB, unsigned Values,
823 BasicBlock *InsertAtEnd)
824 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
825 Instruction::CleanupRet,
826 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
827 Values, InsertAtEnd) {
828 init(CleanupPad, UnwindBB);
831 BasicBlock *CleanupReturnInst::getSuccessorV(unsigned Idx) const {
833 return getUnwindDest();
835 unsigned CleanupReturnInst::getNumSuccessorsV() const {
836 return getNumSuccessors();
838 void CleanupReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
843 //===----------------------------------------------------------------------===//
844 // CatchEndPadInst Implementation
845 //===----------------------------------------------------------------------===//
847 CatchEndPadInst::CatchEndPadInst(const CatchEndPadInst &CRI)
848 : TerminatorInst(CRI.getType(), Instruction::CatchEndPad,
849 OperandTraits<CatchEndPadInst>::op_end(this) -
850 CRI.getNumOperands(),
851 CRI.getNumOperands()) {
852 setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
853 if (BasicBlock *UnwindDest = CRI.getUnwindDest())
854 setUnwindDest(UnwindDest);
857 void CatchEndPadInst::init(BasicBlock *UnwindBB) {
859 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
860 setUnwindDest(UnwindBB);
864 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB,
865 unsigned Values, Instruction *InsertBefore)
866 : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad,
867 OperandTraits<CatchEndPadInst>::op_end(this) - Values,
868 Values, InsertBefore) {
872 CatchEndPadInst::CatchEndPadInst(LLVMContext &C, BasicBlock *UnwindBB,
873 unsigned Values, BasicBlock *InsertAtEnd)
874 : TerminatorInst(Type::getVoidTy(C), Instruction::CatchEndPad,
875 OperandTraits<CatchEndPadInst>::op_end(this) - Values,
876 Values, InsertAtEnd) {
880 BasicBlock *CatchEndPadInst::getSuccessorV(unsigned Idx) const {
882 return getUnwindDest();
884 unsigned CatchEndPadInst::getNumSuccessorsV() const {
885 return getNumSuccessors();
887 void CatchEndPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
892 //===----------------------------------------------------------------------===//
893 // CatchReturnInst Implementation
894 //===----------------------------------------------------------------------===//
895 void CatchReturnInst::init(CatchPadInst *CatchPad, BasicBlock *BB) {
900 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
901 : TerminatorInst(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
902 OperandTraits<CatchReturnInst>::op_begin(this), 2) {
903 Op<0>() = CRI.Op<0>();
904 Op<1>() = CRI.Op<1>();
907 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
908 Instruction *InsertBefore)
909 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
910 OperandTraits<CatchReturnInst>::op_begin(this), 2,
915 CatchReturnInst::CatchReturnInst(CatchPadInst *CatchPad, BasicBlock *BB,
916 BasicBlock *InsertAtEnd)
917 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
918 OperandTraits<CatchReturnInst>::op_begin(this), 2,
923 BasicBlock *CatchReturnInst::getSuccessorV(unsigned Idx) const {
924 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
925 return getSuccessor();
927 unsigned CatchReturnInst::getNumSuccessorsV() const {
928 return getNumSuccessors();
930 void CatchReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
931 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
935 //===----------------------------------------------------------------------===//
936 // CatchPadInst Implementation
937 //===----------------------------------------------------------------------===//
938 void CatchPadInst::init(BasicBlock *IfNormal, BasicBlock *IfException,
939 ArrayRef<Value *> Args, const Twine &NameStr) {
940 assert(getNumOperands() == 2 + Args.size() && "NumOperands not set up?");
942 Op<-1>() = IfException;
943 std::copy(Args.begin(), Args.end(), op_begin());
947 CatchPadInst::CatchPadInst(const CatchPadInst &CPI)
948 : TerminatorInst(CPI.getType(), Instruction::CatchPad,
949 OperandTraits<CatchPadInst>::op_end(this) -
950 CPI.getNumOperands(),
951 CPI.getNumOperands()) {
952 std::copy(CPI.op_begin(), CPI.op_end(), op_begin());
955 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
956 ArrayRef<Value *> Args, unsigned Values,
957 const Twine &NameStr, Instruction *InsertBefore)
958 : TerminatorInst(Type::getTokenTy(IfNormal->getContext()),
959 Instruction::CatchPad,
960 OperandTraits<CatchPadInst>::op_end(this) - Values, Values,
962 init(IfNormal, IfException, Args, NameStr);
965 CatchPadInst::CatchPadInst(BasicBlock *IfNormal, BasicBlock *IfException,
966 ArrayRef<Value *> Args, unsigned Values,
967 const Twine &NameStr, BasicBlock *InsertAtEnd)
968 : TerminatorInst(Type::getTokenTy(IfNormal->getContext()),
969 Instruction::CatchPad,
970 OperandTraits<CatchPadInst>::op_end(this) - Values, Values,
972 init(IfNormal, IfException, Args, NameStr);
975 BasicBlock *CatchPadInst::getSuccessorV(unsigned Idx) const {
976 return getSuccessor(Idx);
978 unsigned CatchPadInst::getNumSuccessorsV() const {
979 return getNumSuccessors();
981 void CatchPadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
982 return setSuccessor(Idx, B);
985 //===----------------------------------------------------------------------===//
986 // TerminatePadInst Implementation
987 //===----------------------------------------------------------------------===//
988 void TerminatePadInst::init(BasicBlock *BB, ArrayRef<Value *> Args) {
990 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
993 std::copy(Args.begin(), Args.end(), op_begin());
996 TerminatePadInst::TerminatePadInst(const TerminatePadInst &TPI)
997 : TerminatorInst(TPI.getType(), Instruction::TerminatePad,
998 OperandTraits<TerminatePadInst>::op_end(this) -
999 TPI.getNumOperands(),
1000 TPI.getNumOperands()) {
1001 setInstructionSubclassData(TPI.getSubclassDataFromInstruction());
1002 std::copy(TPI.op_begin(), TPI.op_end(), op_begin());
1005 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB,
1006 ArrayRef<Value *> Args, unsigned Values,
1007 Instruction *InsertBefore)
1008 : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad,
1009 OperandTraits<TerminatePadInst>::op_end(this) - Values,
1010 Values, InsertBefore) {
1014 TerminatePadInst::TerminatePadInst(LLVMContext &C, BasicBlock *BB,
1015 ArrayRef<Value *> Args, unsigned Values,
1016 BasicBlock *InsertAtEnd)
1017 : TerminatorInst(Type::getVoidTy(C), Instruction::TerminatePad,
1018 OperandTraits<TerminatePadInst>::op_end(this) - Values,
1019 Values, InsertAtEnd) {
1023 BasicBlock *TerminatePadInst::getSuccessorV(unsigned Idx) const {
1025 return getUnwindDest();
1027 unsigned TerminatePadInst::getNumSuccessorsV() const {
1028 return getNumSuccessors();
1030 void TerminatePadInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
1032 return setUnwindDest(B);
1035 //===----------------------------------------------------------------------===//
1036 // CleanupPadInst Implementation
1037 //===----------------------------------------------------------------------===//
1038 void CleanupPadInst::init(ArrayRef<Value *> Args, const Twine &NameStr) {
1039 assert(getNumOperands() == Args.size() && "NumOperands not set up?");
1040 std::copy(Args.begin(), Args.end(), op_begin());
1044 CleanupPadInst::CleanupPadInst(const CleanupPadInst &CPI)
1045 : Instruction(CPI.getType(), Instruction::CleanupPad,
1046 OperandTraits<CleanupPadInst>::op_end(this) -
1047 CPI.getNumOperands(),
1048 CPI.getNumOperands()) {
1049 std::copy(CPI.op_begin(), CPI.op_end(), op_begin());
1052 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
1053 const Twine &NameStr, Instruction *InsertBefore)
1054 : Instruction(Type::getTokenTy(C), Instruction::CleanupPad,
1055 OperandTraits<CleanupPadInst>::op_end(this) - Args.size(),
1056 Args.size(), InsertBefore) {
1057 init(Args, NameStr);
1060 CleanupPadInst::CleanupPadInst(LLVMContext &C, ArrayRef<Value *> Args,
1061 const Twine &NameStr, BasicBlock *InsertAtEnd)
1062 : Instruction(Type::getTokenTy(C), Instruction::CleanupPad,
1063 OperandTraits<CleanupPadInst>::op_end(this) - Args.size(),
1064 Args.size(), InsertAtEnd) {
1065 init(Args, NameStr);
1068 //===----------------------------------------------------------------------===//
1069 // UnreachableInst Implementation
1070 //===----------------------------------------------------------------------===//
1072 UnreachableInst::UnreachableInst(LLVMContext &Context,
1073 Instruction *InsertBefore)
1074 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1075 nullptr, 0, InsertBefore) {
1077 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1078 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1079 nullptr, 0, InsertAtEnd) {
1082 unsigned UnreachableInst::getNumSuccessorsV() const {
1083 return getNumSuccessors();
1086 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
1087 llvm_unreachable("UnreachableInst has no successors!");
1090 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
1091 llvm_unreachable("UnreachableInst has no successors!");
1094 //===----------------------------------------------------------------------===//
1095 // BranchInst Implementation
1096 //===----------------------------------------------------------------------===//
1098 void BranchInst::AssertOK() {
1099 if (isConditional())
1100 assert(getCondition()->getType()->isIntegerTy(1) &&
1101 "May only branch on boolean predicates!");
1104 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
1105 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1106 OperandTraits<BranchInst>::op_end(this) - 1,
1108 assert(IfTrue && "Branch destination may not be null!");
1111 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1112 Instruction *InsertBefore)
1113 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1114 OperandTraits<BranchInst>::op_end(this) - 3,
1124 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
1125 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1126 OperandTraits<BranchInst>::op_end(this) - 1,
1128 assert(IfTrue && "Branch destination may not be null!");
1132 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1133 BasicBlock *InsertAtEnd)
1134 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1135 OperandTraits<BranchInst>::op_end(this) - 3,
1146 BranchInst::BranchInst(const BranchInst &BI) :
1147 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
1148 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
1149 BI.getNumOperands()) {
1150 Op<-1>() = BI.Op<-1>();
1151 if (BI.getNumOperands() != 1) {
1152 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1153 Op<-3>() = BI.Op<-3>();
1154 Op<-2>() = BI.Op<-2>();
1156 SubclassOptionalData = BI.SubclassOptionalData;
1159 void BranchInst::swapSuccessors() {
1160 assert(isConditional() &&
1161 "Cannot swap successors of an unconditional branch");
1162 Op<-1>().swap(Op<-2>());
1164 // Update profile metadata if present and it matches our structural
1166 MDNode *ProfileData = getMetadata(LLVMContext::MD_prof);
1167 if (!ProfileData || ProfileData->getNumOperands() != 3)
1170 // The first operand is the name. Fetch them backwards and build a new one.
1171 Metadata *Ops[] = {ProfileData->getOperand(0), ProfileData->getOperand(2),
1172 ProfileData->getOperand(1)};
1173 setMetadata(LLVMContext::MD_prof,
1174 MDNode::get(ProfileData->getContext(), Ops));
1177 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
1178 return getSuccessor(idx);
1180 unsigned BranchInst::getNumSuccessorsV() const {
1181 return getNumSuccessors();
1183 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1184 setSuccessor(idx, B);
1188 //===----------------------------------------------------------------------===//
1189 // AllocaInst Implementation
1190 //===----------------------------------------------------------------------===//
1192 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1194 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1196 assert(!isa<BasicBlock>(Amt) &&
1197 "Passed basic block into allocation size parameter! Use other ctor");
1198 assert(Amt->getType()->isIntegerTy() &&
1199 "Allocation array size is not an integer!");
1204 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, Instruction *InsertBefore)
1205 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1207 AllocaInst::AllocaInst(Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd)
1208 : AllocaInst(Ty, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
1210 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
1211 Instruction *InsertBefore)
1212 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertBefore) {}
1214 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, const Twine &Name,
1215 BasicBlock *InsertAtEnd)
1216 : AllocaInst(Ty, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
1218 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1219 const Twine &Name, Instruction *InsertBefore)
1220 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1221 getAISize(Ty->getContext(), ArraySize), InsertBefore),
1223 setAlignment(Align);
1224 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1228 AllocaInst::AllocaInst(Type *Ty, Value *ArraySize, unsigned Align,
1229 const Twine &Name, BasicBlock *InsertAtEnd)
1230 : UnaryInstruction(PointerType::getUnqual(Ty), Alloca,
1231 getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
1233 setAlignment(Align);
1234 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1238 // Out of line virtual method, so the vtable, etc has a home.
1239 AllocaInst::~AllocaInst() {
1242 void AllocaInst::setAlignment(unsigned Align) {
1243 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1244 assert(Align <= MaximumAlignment &&
1245 "Alignment is greater than MaximumAlignment!");
1246 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1247 (Log2_32(Align) + 1));
1248 assert(getAlignment() == Align && "Alignment representation error!");
1251 bool AllocaInst::isArrayAllocation() const {
1252 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1253 return !CI->isOne();
1257 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1258 /// function and is a constant size. If so, the code generator will fold it
1259 /// into the prolog/epilog code, so it is basically free.
1260 bool AllocaInst::isStaticAlloca() const {
1261 // Must be constant size.
1262 if (!isa<ConstantInt>(getArraySize())) return false;
1264 // Must be in the entry block.
1265 const BasicBlock *Parent = getParent();
1266 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1269 //===----------------------------------------------------------------------===//
1270 // LoadInst Implementation
1271 //===----------------------------------------------------------------------===//
1273 void LoadInst::AssertOK() {
1274 assert(getOperand(0)->getType()->isPointerTy() &&
1275 "Ptr must have pointer type.");
1276 assert(!(isAtomic() && getAlignment() == 0) &&
1277 "Alignment required for atomic load");
1280 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1281 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1283 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1284 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1286 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1287 Instruction *InsertBef)
1288 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {}
1290 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1291 BasicBlock *InsertAE)
1292 : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {}
1294 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1295 unsigned Align, Instruction *InsertBef)
1296 : LoadInst(Ty, Ptr, Name, isVolatile, Align, NotAtomic, CrossThread,
1299 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1300 unsigned Align, BasicBlock *InsertAE)
1301 : LoadInst(Ptr, Name, isVolatile, Align, NotAtomic, CrossThread, InsertAE) {
1304 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1305 unsigned Align, AtomicOrdering Order,
1306 SynchronizationScope SynchScope, Instruction *InsertBef)
1307 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1308 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1309 setVolatile(isVolatile);
1310 setAlignment(Align);
1311 setAtomic(Order, SynchScope);
1316 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1317 unsigned Align, AtomicOrdering Order,
1318 SynchronizationScope SynchScope,
1319 BasicBlock *InsertAE)
1320 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1321 Load, Ptr, InsertAE) {
1322 setVolatile(isVolatile);
1323 setAlignment(Align);
1324 setAtomic(Order, SynchScope);
1329 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1330 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1331 Load, Ptr, InsertBef) {
1334 setAtomic(NotAtomic);
1336 if (Name && Name[0]) setName(Name);
1339 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1340 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1341 Load, Ptr, InsertAE) {
1344 setAtomic(NotAtomic);
1346 if (Name && Name[0]) setName(Name);
1349 LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile,
1350 Instruction *InsertBef)
1351 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1352 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1353 setVolatile(isVolatile);
1355 setAtomic(NotAtomic);
1357 if (Name && Name[0]) setName(Name);
1360 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1361 BasicBlock *InsertAE)
1362 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1363 Load, Ptr, InsertAE) {
1364 setVolatile(isVolatile);
1366 setAtomic(NotAtomic);
1368 if (Name && Name[0]) setName(Name);
1371 void LoadInst::setAlignment(unsigned Align) {
1372 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1373 assert(Align <= MaximumAlignment &&
1374 "Alignment is greater than MaximumAlignment!");
1375 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1376 ((Log2_32(Align)+1)<<1));
1377 assert(getAlignment() == Align && "Alignment representation error!");
1380 //===----------------------------------------------------------------------===//
1381 // StoreInst Implementation
1382 //===----------------------------------------------------------------------===//
1384 void StoreInst::AssertOK() {
1385 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1386 assert(getOperand(1)->getType()->isPointerTy() &&
1387 "Ptr must have pointer type!");
1388 assert(getOperand(0)->getType() ==
1389 cast<PointerType>(getOperand(1)->getType())->getElementType()
1390 && "Ptr must be a pointer to Val type!");
1391 assert(!(isAtomic() && getAlignment() == 0) &&
1392 "Alignment required for atomic store");
1395 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1396 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1398 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1399 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1401 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1402 Instruction *InsertBefore)
1403 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
1405 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1406 BasicBlock *InsertAtEnd)
1407 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
1409 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1410 Instruction *InsertBefore)
1411 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1414 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1415 BasicBlock *InsertAtEnd)
1416 : StoreInst(val, addr, isVolatile, Align, NotAtomic, CrossThread,
1419 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1420 unsigned Align, AtomicOrdering Order,
1421 SynchronizationScope SynchScope,
1422 Instruction *InsertBefore)
1423 : Instruction(Type::getVoidTy(val->getContext()), Store,
1424 OperandTraits<StoreInst>::op_begin(this),
1425 OperandTraits<StoreInst>::operands(this),
1429 setVolatile(isVolatile);
1430 setAlignment(Align);
1431 setAtomic(Order, SynchScope);
1435 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1436 unsigned Align, AtomicOrdering Order,
1437 SynchronizationScope SynchScope,
1438 BasicBlock *InsertAtEnd)
1439 : Instruction(Type::getVoidTy(val->getContext()), Store,
1440 OperandTraits<StoreInst>::op_begin(this),
1441 OperandTraits<StoreInst>::operands(this),
1445 setVolatile(isVolatile);
1446 setAlignment(Align);
1447 setAtomic(Order, SynchScope);
1451 void StoreInst::setAlignment(unsigned Align) {
1452 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1453 assert(Align <= MaximumAlignment &&
1454 "Alignment is greater than MaximumAlignment!");
1455 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1456 ((Log2_32(Align)+1) << 1));
1457 assert(getAlignment() == Align && "Alignment representation error!");
1460 //===----------------------------------------------------------------------===//
1461 // AtomicCmpXchgInst Implementation
1462 //===----------------------------------------------------------------------===//
1464 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1465 AtomicOrdering SuccessOrdering,
1466 AtomicOrdering FailureOrdering,
1467 SynchronizationScope SynchScope) {
1471 setSuccessOrdering(SuccessOrdering);
1472 setFailureOrdering(FailureOrdering);
1473 setSynchScope(SynchScope);
1475 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1476 "All operands must be non-null!");
1477 assert(getOperand(0)->getType()->isPointerTy() &&
1478 "Ptr must have pointer type!");
1479 assert(getOperand(1)->getType() ==
1480 cast<PointerType>(getOperand(0)->getType())->getElementType()
1481 && "Ptr must be a pointer to Cmp type!");
1482 assert(getOperand(2)->getType() ==
1483 cast<PointerType>(getOperand(0)->getType())->getElementType()
1484 && "Ptr must be a pointer to NewVal type!");
1485 assert(SuccessOrdering != NotAtomic &&
1486 "AtomicCmpXchg instructions must be atomic!");
1487 assert(FailureOrdering != NotAtomic &&
1488 "AtomicCmpXchg instructions must be atomic!");
1489 assert(SuccessOrdering >= FailureOrdering &&
1490 "AtomicCmpXchg success ordering must be at least as strong as fail");
1491 assert(FailureOrdering != Release && FailureOrdering != AcquireRelease &&
1492 "AtomicCmpXchg failure ordering cannot include release semantics");
1495 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1496 AtomicOrdering SuccessOrdering,
1497 AtomicOrdering FailureOrdering,
1498 SynchronizationScope SynchScope,
1499 Instruction *InsertBefore)
1501 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1503 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1504 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1505 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1508 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1509 AtomicOrdering SuccessOrdering,
1510 AtomicOrdering FailureOrdering,
1511 SynchronizationScope SynchScope,
1512 BasicBlock *InsertAtEnd)
1514 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1516 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1517 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1518 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1521 //===----------------------------------------------------------------------===//
1522 // AtomicRMWInst Implementation
1523 //===----------------------------------------------------------------------===//
1525 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1526 AtomicOrdering Ordering,
1527 SynchronizationScope SynchScope) {
1530 setOperation(Operation);
1531 setOrdering(Ordering);
1532 setSynchScope(SynchScope);
1534 assert(getOperand(0) && getOperand(1) &&
1535 "All operands must be non-null!");
1536 assert(getOperand(0)->getType()->isPointerTy() &&
1537 "Ptr must have pointer type!");
1538 assert(getOperand(1)->getType() ==
1539 cast<PointerType>(getOperand(0)->getType())->getElementType()
1540 && "Ptr must be a pointer to Val type!");
1541 assert(Ordering != NotAtomic &&
1542 "AtomicRMW instructions must be atomic!");
1545 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1546 AtomicOrdering Ordering,
1547 SynchronizationScope SynchScope,
1548 Instruction *InsertBefore)
1549 : Instruction(Val->getType(), AtomicRMW,
1550 OperandTraits<AtomicRMWInst>::op_begin(this),
1551 OperandTraits<AtomicRMWInst>::operands(this),
1553 Init(Operation, Ptr, Val, Ordering, SynchScope);
1556 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1557 AtomicOrdering Ordering,
1558 SynchronizationScope SynchScope,
1559 BasicBlock *InsertAtEnd)
1560 : Instruction(Val->getType(), AtomicRMW,
1561 OperandTraits<AtomicRMWInst>::op_begin(this),
1562 OperandTraits<AtomicRMWInst>::operands(this),
1564 Init(Operation, Ptr, Val, Ordering, SynchScope);
1567 //===----------------------------------------------------------------------===//
1568 // FenceInst Implementation
1569 //===----------------------------------------------------------------------===//
1571 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1572 SynchronizationScope SynchScope,
1573 Instruction *InsertBefore)
1574 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1575 setOrdering(Ordering);
1576 setSynchScope(SynchScope);
1579 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1580 SynchronizationScope SynchScope,
1581 BasicBlock *InsertAtEnd)
1582 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1583 setOrdering(Ordering);
1584 setSynchScope(SynchScope);
1587 //===----------------------------------------------------------------------===//
1588 // GetElementPtrInst Implementation
1589 //===----------------------------------------------------------------------===//
1591 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1592 const Twine &Name) {
1593 assert(getNumOperands() == 1 + IdxList.size() &&
1594 "NumOperands not initialized?");
1596 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1600 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1601 : Instruction(GEPI.getType(), GetElementPtr,
1602 OperandTraits<GetElementPtrInst>::op_end(this) -
1603 GEPI.getNumOperands(),
1604 GEPI.getNumOperands()),
1605 SourceElementType(GEPI.SourceElementType),
1606 ResultElementType(GEPI.ResultElementType) {
1607 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1608 SubclassOptionalData = GEPI.SubclassOptionalData;
1611 /// getIndexedType - Returns the type of the element that would be accessed with
1612 /// a gep instruction with the specified parameters.
1614 /// The Idxs pointer should point to a continuous piece of memory containing the
1615 /// indices, either as Value* or uint64_t.
1617 /// A null type is returned if the indices are invalid for the specified
1620 template <typename IndexTy>
1621 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1622 // Handle the special case of the empty set index set, which is always valid.
1623 if (IdxList.empty())
1626 // If there is at least one index, the top level type must be sized, otherwise
1627 // it cannot be 'stepped over'.
1628 if (!Agg->isSized())
1631 unsigned CurIdx = 1;
1632 for (; CurIdx != IdxList.size(); ++CurIdx) {
1633 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1634 if (!CT || CT->isPointerTy()) return nullptr;
1635 IndexTy Index = IdxList[CurIdx];
1636 if (!CT->indexValid(Index)) return nullptr;
1637 Agg = CT->getTypeAtIndex(Index);
1639 return CurIdx == IdxList.size() ? Agg : nullptr;
1642 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1643 return getIndexedTypeInternal(Ty, IdxList);
1646 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1647 ArrayRef<Constant *> IdxList) {
1648 return getIndexedTypeInternal(Ty, IdxList);
1651 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1652 return getIndexedTypeInternal(Ty, IdxList);
1655 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1656 /// zeros. If so, the result pointer and the first operand have the same
1657 /// value, just potentially different types.
1658 bool GetElementPtrInst::hasAllZeroIndices() const {
1659 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1660 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1661 if (!CI->isZero()) return false;
1669 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1670 /// constant integers. If so, the result pointer and the first operand have
1671 /// a constant offset between them.
1672 bool GetElementPtrInst::hasAllConstantIndices() const {
1673 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1674 if (!isa<ConstantInt>(getOperand(i)))
1680 void GetElementPtrInst::setIsInBounds(bool B) {
1681 cast<GEPOperator>(this)->setIsInBounds(B);
1684 bool GetElementPtrInst::isInBounds() const {
1685 return cast<GEPOperator>(this)->isInBounds();
1688 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1689 APInt &Offset) const {
1690 // Delegate to the generic GEPOperator implementation.
1691 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1694 //===----------------------------------------------------------------------===//
1695 // ExtractElementInst Implementation
1696 //===----------------------------------------------------------------------===//
1698 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1700 Instruction *InsertBef)
1701 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1703 OperandTraits<ExtractElementInst>::op_begin(this),
1705 assert(isValidOperands(Val, Index) &&
1706 "Invalid extractelement instruction operands!");
1712 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1714 BasicBlock *InsertAE)
1715 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1717 OperandTraits<ExtractElementInst>::op_begin(this),
1719 assert(isValidOperands(Val, Index) &&
1720 "Invalid extractelement instruction operands!");
1728 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1729 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1735 //===----------------------------------------------------------------------===//
1736 // InsertElementInst Implementation
1737 //===----------------------------------------------------------------------===//
1739 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1741 Instruction *InsertBef)
1742 : Instruction(Vec->getType(), InsertElement,
1743 OperandTraits<InsertElementInst>::op_begin(this),
1745 assert(isValidOperands(Vec, Elt, Index) &&
1746 "Invalid insertelement instruction operands!");
1753 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1755 BasicBlock *InsertAE)
1756 : Instruction(Vec->getType(), InsertElement,
1757 OperandTraits<InsertElementInst>::op_begin(this),
1759 assert(isValidOperands(Vec, Elt, Index) &&
1760 "Invalid insertelement instruction operands!");
1768 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1769 const Value *Index) {
1770 if (!Vec->getType()->isVectorTy())
1771 return false; // First operand of insertelement must be vector type.
1773 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1774 return false;// Second operand of insertelement must be vector element type.
1776 if (!Index->getType()->isIntegerTy())
1777 return false; // Third operand of insertelement must be i32.
1782 //===----------------------------------------------------------------------===//
1783 // ShuffleVectorInst Implementation
1784 //===----------------------------------------------------------------------===//
1786 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1788 Instruction *InsertBefore)
1789 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1790 cast<VectorType>(Mask->getType())->getNumElements()),
1792 OperandTraits<ShuffleVectorInst>::op_begin(this),
1793 OperandTraits<ShuffleVectorInst>::operands(this),
1795 assert(isValidOperands(V1, V2, Mask) &&
1796 "Invalid shuffle vector instruction operands!");
1803 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1805 BasicBlock *InsertAtEnd)
1806 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1807 cast<VectorType>(Mask->getType())->getNumElements()),
1809 OperandTraits<ShuffleVectorInst>::op_begin(this),
1810 OperandTraits<ShuffleVectorInst>::operands(this),
1812 assert(isValidOperands(V1, V2, Mask) &&
1813 "Invalid shuffle vector instruction operands!");
1821 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1822 const Value *Mask) {
1823 // V1 and V2 must be vectors of the same type.
1824 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1827 // Mask must be vector of i32.
1828 VectorType *MaskTy = dyn_cast<VectorType>(Mask->getType());
1829 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1832 // Check to see if Mask is valid.
1833 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1836 if (const ConstantVector *MV = dyn_cast<ConstantVector>(Mask)) {
1837 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1838 for (Value *Op : MV->operands()) {
1839 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1840 if (CI->uge(V1Size*2))
1842 } else if (!isa<UndefValue>(Op)) {
1849 if (const ConstantDataSequential *CDS =
1850 dyn_cast<ConstantDataSequential>(Mask)) {
1851 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1852 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1853 if (CDS->getElementAsInteger(i) >= V1Size*2)
1858 // The bitcode reader can create a place holder for a forward reference
1859 // used as the shuffle mask. When this occurs, the shuffle mask will
1860 // fall into this case and fail. To avoid this error, do this bit of
1861 // ugliness to allow such a mask pass.
1862 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(Mask))
1863 if (CE->getOpcode() == Instruction::UserOp1)
1869 /// getMaskValue - Return the index from the shuffle mask for the specified
1870 /// output result. This is either -1 if the element is undef or a number less
1871 /// than 2*numelements.
1872 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1873 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1874 if (ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(Mask))
1875 return CDS->getElementAsInteger(i);
1876 Constant *C = Mask->getAggregateElement(i);
1877 if (isa<UndefValue>(C))
1879 return cast<ConstantInt>(C)->getZExtValue();
1882 /// getShuffleMask - Return the full mask for this instruction, where each
1883 /// element is the element number and undef's are returned as -1.
1884 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1885 SmallVectorImpl<int> &Result) {
1886 unsigned NumElts = Mask->getType()->getVectorNumElements();
1888 if (ConstantDataSequential *CDS=dyn_cast<ConstantDataSequential>(Mask)) {
1889 for (unsigned i = 0; i != NumElts; ++i)
1890 Result.push_back(CDS->getElementAsInteger(i));
1893 for (unsigned i = 0; i != NumElts; ++i) {
1894 Constant *C = Mask->getAggregateElement(i);
1895 Result.push_back(isa<UndefValue>(C) ? -1 :
1896 cast<ConstantInt>(C)->getZExtValue());
1901 //===----------------------------------------------------------------------===//
1902 // InsertValueInst Class
1903 //===----------------------------------------------------------------------===//
1905 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1906 const Twine &Name) {
1907 assert(getNumOperands() == 2 && "NumOperands not initialized?");
1909 // There's no fundamental reason why we require at least one index
1910 // (other than weirdness with &*IdxBegin being invalid; see
1911 // getelementptr's init routine for example). But there's no
1912 // present need to support it.
1913 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1915 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1916 Val->getType() && "Inserted value must match indexed type!");
1920 Indices.append(Idxs.begin(), Idxs.end());
1924 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1925 : Instruction(IVI.getType(), InsertValue,
1926 OperandTraits<InsertValueInst>::op_begin(this), 2),
1927 Indices(IVI.Indices) {
1928 Op<0>() = IVI.getOperand(0);
1929 Op<1>() = IVI.getOperand(1);
1930 SubclassOptionalData = IVI.SubclassOptionalData;
1933 //===----------------------------------------------------------------------===//
1934 // ExtractValueInst Class
1935 //===----------------------------------------------------------------------===//
1937 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1938 assert(getNumOperands() == 1 && "NumOperands not initialized?");
1940 // There's no fundamental reason why we require at least one index.
1941 // But there's no present need to support it.
1942 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1944 Indices.append(Idxs.begin(), Idxs.end());
1948 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1949 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1950 Indices(EVI.Indices) {
1951 SubclassOptionalData = EVI.SubclassOptionalData;
1954 // getIndexedType - Returns the type of the element that would be extracted
1955 // with an extractvalue instruction with the specified parameters.
1957 // A null type is returned if the indices are invalid for the specified
1960 Type *ExtractValueInst::getIndexedType(Type *Agg,
1961 ArrayRef<unsigned> Idxs) {
1962 for (unsigned Index : Idxs) {
1963 // We can't use CompositeType::indexValid(Index) here.
1964 // indexValid() always returns true for arrays because getelementptr allows
1965 // out-of-bounds indices. Since we don't allow those for extractvalue and
1966 // insertvalue we need to check array indexing manually.
1967 // Since the only other types we can index into are struct types it's just
1968 // as easy to check those manually as well.
1969 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1970 if (Index >= AT->getNumElements())
1972 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1973 if (Index >= ST->getNumElements())
1976 // Not a valid type to index into.
1980 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
1982 return const_cast<Type*>(Agg);
1985 //===----------------------------------------------------------------------===//
1986 // BinaryOperator Class
1987 //===----------------------------------------------------------------------===//
1989 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
1990 Type *Ty, const Twine &Name,
1991 Instruction *InsertBefore)
1992 : Instruction(Ty, iType,
1993 OperandTraits<BinaryOperator>::op_begin(this),
1994 OperandTraits<BinaryOperator>::operands(this),
2002 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2003 Type *Ty, const Twine &Name,
2004 BasicBlock *InsertAtEnd)
2005 : Instruction(Ty, iType,
2006 OperandTraits<BinaryOperator>::op_begin(this),
2007 OperandTraits<BinaryOperator>::operands(this),
2016 void BinaryOperator::init(BinaryOps iType) {
2017 Value *LHS = getOperand(0), *RHS = getOperand(1);
2018 (void)LHS; (void)RHS; // Silence warnings.
2019 assert(LHS->getType() == RHS->getType() &&
2020 "Binary operator operand types must match!");
2025 assert(getType() == LHS->getType() &&
2026 "Arithmetic operation should return same type as operands!");
2027 assert(getType()->isIntOrIntVectorTy() &&
2028 "Tried to create an integer operation on a non-integer type!");
2030 case FAdd: case FSub:
2032 assert(getType() == LHS->getType() &&
2033 "Arithmetic operation should return same type as operands!");
2034 assert(getType()->isFPOrFPVectorTy() &&
2035 "Tried to create a floating-point operation on a "
2036 "non-floating-point type!");
2040 assert(getType() == LHS->getType() &&
2041 "Arithmetic operation should return same type as operands!");
2042 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2043 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2044 "Incorrect operand type (not integer) for S/UDIV");
2047 assert(getType() == LHS->getType() &&
2048 "Arithmetic operation should return same type as operands!");
2049 assert(getType()->isFPOrFPVectorTy() &&
2050 "Incorrect operand type (not floating point) for FDIV");
2054 assert(getType() == LHS->getType() &&
2055 "Arithmetic operation should return same type as operands!");
2056 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2057 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2058 "Incorrect operand type (not integer) for S/UREM");
2061 assert(getType() == LHS->getType() &&
2062 "Arithmetic operation should return same type as operands!");
2063 assert(getType()->isFPOrFPVectorTy() &&
2064 "Incorrect operand type (not floating point) for FREM");
2069 assert(getType() == LHS->getType() &&
2070 "Shift operation should return same type as operands!");
2071 assert((getType()->isIntegerTy() ||
2072 (getType()->isVectorTy() &&
2073 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2074 "Tried to create a shift operation on a non-integral type!");
2078 assert(getType() == LHS->getType() &&
2079 "Logical operation should return same type as operands!");
2080 assert((getType()->isIntegerTy() ||
2081 (getType()->isVectorTy() &&
2082 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2083 "Tried to create a logical operation on a non-integral type!");
2091 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2093 Instruction *InsertBefore) {
2094 assert(S1->getType() == S2->getType() &&
2095 "Cannot create binary operator with two operands of differing type!");
2096 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2099 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2101 BasicBlock *InsertAtEnd) {
2102 BinaryOperator *Res = Create(Op, S1, S2, Name);
2103 InsertAtEnd->getInstList().push_back(Res);
2107 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2108 Instruction *InsertBefore) {
2109 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2110 return new BinaryOperator(Instruction::Sub,
2112 Op->getType(), Name, InsertBefore);
2115 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2116 BasicBlock *InsertAtEnd) {
2117 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2118 return new BinaryOperator(Instruction::Sub,
2120 Op->getType(), Name, InsertAtEnd);
2123 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2124 Instruction *InsertBefore) {
2125 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2126 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2129 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2130 BasicBlock *InsertAtEnd) {
2131 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2132 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2135 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2136 Instruction *InsertBefore) {
2137 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2138 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2141 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2142 BasicBlock *InsertAtEnd) {
2143 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2144 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2147 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2148 Instruction *InsertBefore) {
2149 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2150 return new BinaryOperator(Instruction::FSub, zero, Op,
2151 Op->getType(), Name, InsertBefore);
2154 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2155 BasicBlock *InsertAtEnd) {
2156 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2157 return new BinaryOperator(Instruction::FSub, zero, Op,
2158 Op->getType(), Name, InsertAtEnd);
2161 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2162 Instruction *InsertBefore) {
2163 Constant *C = Constant::getAllOnesValue(Op->getType());
2164 return new BinaryOperator(Instruction::Xor, Op, C,
2165 Op->getType(), Name, InsertBefore);
2168 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2169 BasicBlock *InsertAtEnd) {
2170 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2171 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2172 Op->getType(), Name, InsertAtEnd);
2176 // isConstantAllOnes - Helper function for several functions below
2177 static inline bool isConstantAllOnes(const Value *V) {
2178 if (const Constant *C = dyn_cast<Constant>(V))
2179 return C->isAllOnesValue();
2183 bool BinaryOperator::isNeg(const Value *V) {
2184 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2185 if (Bop->getOpcode() == Instruction::Sub)
2186 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0)))
2187 return C->isNegativeZeroValue();
2191 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
2192 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2193 if (Bop->getOpcode() == Instruction::FSub)
2194 if (Constant* C = dyn_cast<Constant>(Bop->getOperand(0))) {
2195 if (!IgnoreZeroSign)
2196 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
2197 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
2202 bool BinaryOperator::isNot(const Value *V) {
2203 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2204 return (Bop->getOpcode() == Instruction::Xor &&
2205 (isConstantAllOnes(Bop->getOperand(1)) ||
2206 isConstantAllOnes(Bop->getOperand(0))));
2210 Value *BinaryOperator::getNegArgument(Value *BinOp) {
2211 return cast<BinaryOperator>(BinOp)->getOperand(1);
2214 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
2215 return getNegArgument(const_cast<Value*>(BinOp));
2218 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
2219 return cast<BinaryOperator>(BinOp)->getOperand(1);
2222 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
2223 return getFNegArgument(const_cast<Value*>(BinOp));
2226 Value *BinaryOperator::getNotArgument(Value *BinOp) {
2227 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
2228 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
2229 Value *Op0 = BO->getOperand(0);
2230 Value *Op1 = BO->getOperand(1);
2231 if (isConstantAllOnes(Op0)) return Op1;
2233 assert(isConstantAllOnes(Op1));
2237 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2238 return getNotArgument(const_cast<Value*>(BinOp));
2242 // swapOperands - Exchange the two operands to this instruction. This
2243 // instruction is safe to use on any binary instruction and does not
2244 // modify the semantics of the instruction. If the instruction is
2245 // order dependent (SetLT f.e.) the opcode is changed.
2247 bool BinaryOperator::swapOperands() {
2248 if (!isCommutative())
2249 return true; // Can't commute operands
2250 Op<0>().swap(Op<1>());
2254 void BinaryOperator::setHasNoUnsignedWrap(bool b) {
2255 cast<OverflowingBinaryOperator>(this)->setHasNoUnsignedWrap(b);
2258 void BinaryOperator::setHasNoSignedWrap(bool b) {
2259 cast<OverflowingBinaryOperator>(this)->setHasNoSignedWrap(b);
2262 void BinaryOperator::setIsExact(bool b) {
2263 cast<PossiblyExactOperator>(this)->setIsExact(b);
2266 bool BinaryOperator::hasNoUnsignedWrap() const {
2267 return cast<OverflowingBinaryOperator>(this)->hasNoUnsignedWrap();
2270 bool BinaryOperator::hasNoSignedWrap() const {
2271 return cast<OverflowingBinaryOperator>(this)->hasNoSignedWrap();
2274 bool BinaryOperator::isExact() const {
2275 return cast<PossiblyExactOperator>(this)->isExact();
2278 void BinaryOperator::copyIRFlags(const Value *V) {
2279 // Copy the wrapping flags.
2280 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2281 setHasNoSignedWrap(OB->hasNoSignedWrap());
2282 setHasNoUnsignedWrap(OB->hasNoUnsignedWrap());
2285 // Copy the exact flag.
2286 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2287 setIsExact(PE->isExact());
2289 // Copy the fast-math flags.
2290 if (auto *FP = dyn_cast<FPMathOperator>(V))
2291 copyFastMathFlags(FP->getFastMathFlags());
2294 void BinaryOperator::andIRFlags(const Value *V) {
2295 if (auto *OB = dyn_cast<OverflowingBinaryOperator>(V)) {
2296 setHasNoSignedWrap(hasNoSignedWrap() & OB->hasNoSignedWrap());
2297 setHasNoUnsignedWrap(hasNoUnsignedWrap() & OB->hasNoUnsignedWrap());
2300 if (auto *PE = dyn_cast<PossiblyExactOperator>(V))
2301 setIsExact(isExact() & PE->isExact());
2303 if (auto *FP = dyn_cast<FPMathOperator>(V)) {
2304 FastMathFlags FM = getFastMathFlags();
2305 FM &= FP->getFastMathFlags();
2306 copyFastMathFlags(FM);
2311 //===----------------------------------------------------------------------===//
2312 // FPMathOperator Class
2313 //===----------------------------------------------------------------------===//
2315 /// getFPAccuracy - Get the maximum error permitted by this operation in ULPs.
2316 /// An accuracy of 0.0 means that the operation should be performed with the
2317 /// default precision.
2318 float FPMathOperator::getFPAccuracy() const {
2320 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2323 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2324 return Accuracy->getValueAPF().convertToFloat();
2328 //===----------------------------------------------------------------------===//
2330 //===----------------------------------------------------------------------===//
2332 void CastInst::anchor() {}
2334 // Just determine if this cast only deals with integral->integral conversion.
2335 bool CastInst::isIntegerCast() const {
2336 switch (getOpcode()) {
2337 default: return false;
2338 case Instruction::ZExt:
2339 case Instruction::SExt:
2340 case Instruction::Trunc:
2342 case Instruction::BitCast:
2343 return getOperand(0)->getType()->isIntegerTy() &&
2344 getType()->isIntegerTy();
2348 bool CastInst::isLosslessCast() const {
2349 // Only BitCast can be lossless, exit fast if we're not BitCast
2350 if (getOpcode() != Instruction::BitCast)
2353 // Identity cast is always lossless
2354 Type* SrcTy = getOperand(0)->getType();
2355 Type* DstTy = getType();
2359 // Pointer to pointer is always lossless.
2360 if (SrcTy->isPointerTy())
2361 return DstTy->isPointerTy();
2362 return false; // Other types have no identity values
2365 /// This function determines if the CastInst does not require any bits to be
2366 /// changed in order to effect the cast. Essentially, it identifies cases where
2367 /// no code gen is necessary for the cast, hence the name no-op cast. For
2368 /// example, the following are all no-op casts:
2369 /// # bitcast i32* %x to i8*
2370 /// # bitcast <2 x i32> %x to <4 x i16>
2371 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2372 /// @brief Determine if the described cast is a no-op.
2373 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2378 default: llvm_unreachable("Invalid CastOp");
2379 case Instruction::Trunc:
2380 case Instruction::ZExt:
2381 case Instruction::SExt:
2382 case Instruction::FPTrunc:
2383 case Instruction::FPExt:
2384 case Instruction::UIToFP:
2385 case Instruction::SIToFP:
2386 case Instruction::FPToUI:
2387 case Instruction::FPToSI:
2388 case Instruction::AddrSpaceCast:
2389 // TODO: Target informations may give a more accurate answer here.
2391 case Instruction::BitCast:
2392 return true; // BitCast never modifies bits.
2393 case Instruction::PtrToInt:
2394 return IntPtrTy->getScalarSizeInBits() ==
2395 DestTy->getScalarSizeInBits();
2396 case Instruction::IntToPtr:
2397 return IntPtrTy->getScalarSizeInBits() ==
2398 SrcTy->getScalarSizeInBits();
2402 /// @brief Determine if a cast is a no-op.
2403 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2404 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2407 bool CastInst::isNoopCast(const DataLayout &DL) const {
2408 Type *PtrOpTy = nullptr;
2409 if (getOpcode() == Instruction::PtrToInt)
2410 PtrOpTy = getOperand(0)->getType();
2411 else if (getOpcode() == Instruction::IntToPtr)
2412 PtrOpTy = getType();
2415 PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0);
2417 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2420 /// This function determines if a pair of casts can be eliminated and what
2421 /// opcode should be used in the elimination. This assumes that there are two
2422 /// instructions like this:
2423 /// * %F = firstOpcode SrcTy %x to MidTy
2424 /// * %S = secondOpcode MidTy %F to DstTy
2425 /// The function returns a resultOpcode so these two casts can be replaced with:
2426 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2427 /// If no such cast is permited, the function returns 0.
2428 unsigned CastInst::isEliminableCastPair(
2429 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2430 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2431 Type *DstIntPtrTy) {
2432 // Define the 144 possibilities for these two cast instructions. The values
2433 // in this matrix determine what to do in a given situation and select the
2434 // case in the switch below. The rows correspond to firstOp, the columns
2435 // correspond to secondOp. In looking at the table below, keep in mind
2436 // the following cast properties:
2438 // Size Compare Source Destination
2439 // Operator Src ? Size Type Sign Type Sign
2440 // -------- ------------ ------------------- ---------------------
2441 // TRUNC > Integer Any Integral Any
2442 // ZEXT < Integral Unsigned Integer Any
2443 // SEXT < Integral Signed Integer Any
2444 // FPTOUI n/a FloatPt n/a Integral Unsigned
2445 // FPTOSI n/a FloatPt n/a Integral Signed
2446 // UITOFP n/a Integral Unsigned FloatPt n/a
2447 // SITOFP n/a Integral Signed FloatPt n/a
2448 // FPTRUNC > FloatPt n/a FloatPt n/a
2449 // FPEXT < FloatPt n/a FloatPt n/a
2450 // PTRTOINT n/a Pointer n/a Integral Unsigned
2451 // INTTOPTR n/a Integral Unsigned Pointer n/a
2452 // BITCAST = FirstClass n/a FirstClass n/a
2453 // ADDRSPCST n/a Pointer n/a Pointer n/a
2455 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2456 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2457 // into "fptoui double to i64", but this loses information about the range
2458 // of the produced value (we no longer know the top-part is all zeros).
2459 // Further this conversion is often much more expensive for typical hardware,
2460 // and causes issues when building libgcc. We disallow fptosi+sext for the
2462 const unsigned numCastOps =
2463 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2464 static const uint8_t CastResults[numCastOps][numCastOps] = {
2465 // T F F U S F F P I B A -+
2466 // R Z S P P I I T P 2 N T S |
2467 // U E E 2 2 2 2 R E I T C C +- secondOp
2468 // N X X U S F F N X N 2 V V |
2469 // C T T I I P P C T T P T T -+
2470 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2471 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2472 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2473 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2474 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2475 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2476 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2477 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2478 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt |
2479 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2480 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2481 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2482 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2485 // If either of the casts are a bitcast from scalar to vector, disallow the
2486 // merging. However, bitcast of A->B->A are allowed.
2487 bool isFirstBitcast = (firstOp == Instruction::BitCast);
2488 bool isSecondBitcast = (secondOp == Instruction::BitCast);
2489 bool chainedBitcast = (SrcTy == DstTy && isFirstBitcast && isSecondBitcast);
2491 // Check if any of the bitcasts convert scalars<->vectors.
2492 if ((isFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2493 (isSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2494 // Unless we are bitcasing to the original type, disallow optimizations.
2495 if (!chainedBitcast) return 0;
2497 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2498 [secondOp-Instruction::CastOpsBegin];
2501 // Categorically disallowed.
2504 // Allowed, use first cast's opcode.
2507 // Allowed, use second cast's opcode.
2510 // No-op cast in second op implies firstOp as long as the DestTy
2511 // is integer and we are not converting between a vector and a
2513 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2517 // No-op cast in second op implies firstOp as long as the DestTy
2518 // is floating point.
2519 if (DstTy->isFloatingPointTy())
2523 // No-op cast in first op implies secondOp as long as the SrcTy
2525 if (SrcTy->isIntegerTy())
2529 // No-op cast in first op implies secondOp as long as the SrcTy
2530 // is a floating point.
2531 if (SrcTy->isFloatingPointTy())
2535 // Cannot simplify if address spaces are different!
2536 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2539 unsigned MidSize = MidTy->getScalarSizeInBits();
2540 // We can still fold this without knowing the actual sizes as long we
2541 // know that the intermediate pointer is the largest possible
2543 // FIXME: Is this always true?
2545 return Instruction::BitCast;
2547 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2548 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2550 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2551 if (MidSize >= PtrSize)
2552 return Instruction::BitCast;
2556 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2557 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2558 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2559 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2560 unsigned DstSize = DstTy->getScalarSizeInBits();
2561 if (SrcSize == DstSize)
2562 return Instruction::BitCast;
2563 else if (SrcSize < DstSize)
2568 // zext, sext -> zext, because sext can't sign extend after zext
2569 return Instruction::ZExt;
2571 // fpext followed by ftrunc is allowed if the bit size returned to is
2572 // the same as the original, in which case its just a bitcast
2574 return Instruction::BitCast;
2575 return 0; // If the types are not the same we can't eliminate it.
2577 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2580 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2581 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2582 unsigned DstSize = DstTy->getScalarSizeInBits();
2583 if (SrcSize <= PtrSize && SrcSize == DstSize)
2584 return Instruction::BitCast;
2588 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2589 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2590 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2591 return Instruction::AddrSpaceCast;
2592 return Instruction::BitCast;
2595 // FIXME: this state can be merged with (1), but the following assert
2596 // is useful to check the correcteness of the sequence due to semantic
2597 // change of bitcast.
2599 SrcTy->isPtrOrPtrVectorTy() &&
2600 MidTy->isPtrOrPtrVectorTy() &&
2601 DstTy->isPtrOrPtrVectorTy() &&
2602 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2603 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2604 "Illegal addrspacecast, bitcast sequence!");
2605 // Allowed, use first cast's opcode
2608 // bitcast, addrspacecast -> addrspacecast if the element type of
2609 // bitcast's source is the same as that of addrspacecast's destination.
2610 if (SrcTy->getPointerElementType() == DstTy->getPointerElementType())
2611 return Instruction::AddrSpaceCast;
2615 // FIXME: this state can be merged with (1), but the following assert
2616 // is useful to check the correcteness of the sequence due to semantic
2617 // change of bitcast.
2619 SrcTy->isIntOrIntVectorTy() &&
2620 MidTy->isPtrOrPtrVectorTy() &&
2621 DstTy->isPtrOrPtrVectorTy() &&
2622 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2623 "Illegal inttoptr, bitcast sequence!");
2624 // Allowed, use first cast's opcode
2627 // FIXME: this state can be merged with (2), but the following assert
2628 // is useful to check the correcteness of the sequence due to semantic
2629 // change of bitcast.
2631 SrcTy->isPtrOrPtrVectorTy() &&
2632 MidTy->isPtrOrPtrVectorTy() &&
2633 DstTy->isIntOrIntVectorTy() &&
2634 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2635 "Illegal bitcast, ptrtoint sequence!");
2636 // Allowed, use second cast's opcode
2639 // (sitofp (zext x)) -> (uitofp x)
2640 return Instruction::UIToFP;
2642 // Cast combination can't happen (error in input). This is for all cases
2643 // where the MidTy is not the same for the two cast instructions.
2644 llvm_unreachable("Invalid Cast Combination");
2646 llvm_unreachable("Error in CastResults table!!!");
2650 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2651 const Twine &Name, Instruction *InsertBefore) {
2652 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2653 // Construct and return the appropriate CastInst subclass
2655 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2656 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2657 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2658 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2659 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2660 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2661 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2662 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2663 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2664 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2665 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2666 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2667 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2668 default: llvm_unreachable("Invalid opcode provided");
2672 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2673 const Twine &Name, BasicBlock *InsertAtEnd) {
2674 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2675 // Construct and return the appropriate CastInst subclass
2677 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2678 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2679 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2680 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2681 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2682 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2683 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2684 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2685 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2686 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2687 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2688 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2689 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2690 default: llvm_unreachable("Invalid opcode provided");
2694 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2696 Instruction *InsertBefore) {
2697 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2698 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2699 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2702 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2704 BasicBlock *InsertAtEnd) {
2705 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2706 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2707 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2710 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2712 Instruction *InsertBefore) {
2713 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2714 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2715 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2718 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2720 BasicBlock *InsertAtEnd) {
2721 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2722 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2723 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2726 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2728 Instruction *InsertBefore) {
2729 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2730 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2731 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2734 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2736 BasicBlock *InsertAtEnd) {
2737 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2738 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2739 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2742 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2744 BasicBlock *InsertAtEnd) {
2745 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2746 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2748 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2749 assert((!Ty->isVectorTy() ||
2750 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2753 if (Ty->isIntOrIntVectorTy())
2754 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2756 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2759 /// @brief Create a BitCast or a PtrToInt cast instruction
2760 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2762 Instruction *InsertBefore) {
2763 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2764 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2766 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2767 assert((!Ty->isVectorTy() ||
2768 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2771 if (Ty->isIntOrIntVectorTy())
2772 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2774 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2777 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2780 BasicBlock *InsertAtEnd) {
2781 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2782 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2784 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2785 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2787 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2790 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2793 Instruction *InsertBefore) {
2794 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2795 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2797 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2798 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2800 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2803 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2805 Instruction *InsertBefore) {
2806 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2807 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2808 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2809 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2811 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2814 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2815 bool isSigned, const Twine &Name,
2816 Instruction *InsertBefore) {
2817 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2818 "Invalid integer cast");
2819 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2820 unsigned DstBits = Ty->getScalarSizeInBits();
2821 Instruction::CastOps opcode =
2822 (SrcBits == DstBits ? Instruction::BitCast :
2823 (SrcBits > DstBits ? Instruction::Trunc :
2824 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2825 return Create(opcode, C, Ty, Name, InsertBefore);
2828 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2829 bool isSigned, const Twine &Name,
2830 BasicBlock *InsertAtEnd) {
2831 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2833 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2834 unsigned DstBits = Ty->getScalarSizeInBits();
2835 Instruction::CastOps opcode =
2836 (SrcBits == DstBits ? Instruction::BitCast :
2837 (SrcBits > DstBits ? Instruction::Trunc :
2838 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2839 return Create(opcode, C, Ty, Name, InsertAtEnd);
2842 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2844 Instruction *InsertBefore) {
2845 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2847 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2848 unsigned DstBits = Ty->getScalarSizeInBits();
2849 Instruction::CastOps opcode =
2850 (SrcBits == DstBits ? Instruction::BitCast :
2851 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2852 return Create(opcode, C, Ty, Name, InsertBefore);
2855 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2857 BasicBlock *InsertAtEnd) {
2858 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2860 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2861 unsigned DstBits = Ty->getScalarSizeInBits();
2862 Instruction::CastOps opcode =
2863 (SrcBits == DstBits ? Instruction::BitCast :
2864 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2865 return Create(opcode, C, Ty, Name, InsertAtEnd);
2868 // Check whether it is valid to call getCastOpcode for these types.
2869 // This routine must be kept in sync with getCastOpcode.
2870 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2871 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2874 if (SrcTy == DestTy)
2877 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2878 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2879 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2880 // An element by element cast. Valid if casting the elements is valid.
2881 SrcTy = SrcVecTy->getElementType();
2882 DestTy = DestVecTy->getElementType();
2885 // Get the bit sizes, we'll need these
2886 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2887 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2889 // Run through the possibilities ...
2890 if (DestTy->isIntegerTy()) { // Casting to integral
2891 if (SrcTy->isIntegerTy()) // Casting from integral
2893 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2895 if (SrcTy->isVectorTy()) // Casting from vector
2896 return DestBits == SrcBits;
2897 // Casting from something else
2898 return SrcTy->isPointerTy();
2900 if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2901 if (SrcTy->isIntegerTy()) // Casting from integral
2903 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2905 if (SrcTy->isVectorTy()) // Casting from vector
2906 return DestBits == SrcBits;
2907 // Casting from something else
2910 if (DestTy->isVectorTy()) // Casting to vector
2911 return DestBits == SrcBits;
2912 if (DestTy->isPointerTy()) { // Casting to pointer
2913 if (SrcTy->isPointerTy()) // Casting from pointer
2915 return SrcTy->isIntegerTy(); // Casting from integral
2917 if (DestTy->isX86_MMXTy()) {
2918 if (SrcTy->isVectorTy())
2919 return DestBits == SrcBits; // 64-bit vector to MMX
2921 } // Casting to something else
2925 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
2926 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2929 if (SrcTy == DestTy)
2932 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2933 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
2934 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2935 // An element by element cast. Valid if casting the elements is valid.
2936 SrcTy = SrcVecTy->getElementType();
2937 DestTy = DestVecTy->getElementType();
2942 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
2943 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
2944 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
2948 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2949 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2951 // Could still have vectors of pointers if the number of elements doesn't
2953 if (SrcBits == 0 || DestBits == 0)
2956 if (SrcBits != DestBits)
2959 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
2965 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
2966 const DataLayout &DL) {
2967 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
2968 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
2969 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2970 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
2971 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
2972 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2974 return isBitCastable(SrcTy, DestTy);
2977 // Provide a way to get a "cast" where the cast opcode is inferred from the
2978 // types and size of the operand. This, basically, is a parallel of the
2979 // logic in the castIsValid function below. This axiom should hold:
2980 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2981 // should not assert in castIsValid. In other words, this produces a "correct"
2982 // casting opcode for the arguments passed to it.
2983 // This routine must be kept in sync with isCastable.
2984 Instruction::CastOps
2985 CastInst::getCastOpcode(
2986 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2987 Type *SrcTy = Src->getType();
2989 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2990 "Only first class types are castable!");
2992 if (SrcTy == DestTy)
2995 // FIXME: Check address space sizes here
2996 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2997 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2998 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2999 // An element by element cast. Find the appropriate opcode based on the
3001 SrcTy = SrcVecTy->getElementType();
3002 DestTy = DestVecTy->getElementType();
3005 // Get the bit sizes, we'll need these
3006 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
3007 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
3009 // Run through the possibilities ...
3010 if (DestTy->isIntegerTy()) { // Casting to integral
3011 if (SrcTy->isIntegerTy()) { // Casting from integral
3012 if (DestBits < SrcBits)
3013 return Trunc; // int -> smaller int
3014 else if (DestBits > SrcBits) { // its an extension
3016 return SExt; // signed -> SEXT
3018 return ZExt; // unsigned -> ZEXT
3020 return BitCast; // Same size, No-op cast
3022 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3024 return FPToSI; // FP -> sint
3026 return FPToUI; // FP -> uint
3027 } else if (SrcTy->isVectorTy()) {
3028 assert(DestBits == SrcBits &&
3029 "Casting vector to integer of different width");
3030 return BitCast; // Same size, no-op cast
3032 assert(SrcTy->isPointerTy() &&
3033 "Casting from a value that is not first-class type");
3034 return PtrToInt; // ptr -> int
3036 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3037 if (SrcTy->isIntegerTy()) { // Casting from integral
3039 return SIToFP; // sint -> FP
3041 return UIToFP; // uint -> FP
3042 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3043 if (DestBits < SrcBits) {
3044 return FPTrunc; // FP -> smaller FP
3045 } else if (DestBits > SrcBits) {
3046 return FPExt; // FP -> larger FP
3048 return BitCast; // same size, no-op cast
3050 } else if (SrcTy->isVectorTy()) {
3051 assert(DestBits == SrcBits &&
3052 "Casting vector to floating point of different width");
3053 return BitCast; // same size, no-op cast
3055 llvm_unreachable("Casting pointer or non-first class to float");
3056 } else if (DestTy->isVectorTy()) {
3057 assert(DestBits == SrcBits &&
3058 "Illegal cast to vector (wrong type or size)");
3060 } else if (DestTy->isPointerTy()) {
3061 if (SrcTy->isPointerTy()) {
3062 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3063 return AddrSpaceCast;
3064 return BitCast; // ptr -> ptr
3065 } else if (SrcTy->isIntegerTy()) {
3066 return IntToPtr; // int -> ptr
3068 llvm_unreachable("Casting pointer to other than pointer or int");
3069 } else if (DestTy->isX86_MMXTy()) {
3070 if (SrcTy->isVectorTy()) {
3071 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3072 return BitCast; // 64-bit vector to MMX
3074 llvm_unreachable("Illegal cast to X86_MMX");
3076 llvm_unreachable("Casting to type that is not first-class");
3079 //===----------------------------------------------------------------------===//
3080 // CastInst SubClass Constructors
3081 //===----------------------------------------------------------------------===//
3083 /// Check that the construction parameters for a CastInst are correct. This
3084 /// could be broken out into the separate constructors but it is useful to have
3085 /// it in one place and to eliminate the redundant code for getting the sizes
3086 /// of the types involved.
3088 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
3090 // Check for type sanity on the arguments
3091 Type *SrcTy = S->getType();
3093 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3094 SrcTy->isAggregateType() || DstTy->isAggregateType())
3097 // Get the size of the types in bits, we'll need this later
3098 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3099 unsigned DstBitSize = DstTy->getScalarSizeInBits();
3101 // If these are vector types, get the lengths of the vectors (using zero for
3102 // scalar types means that checking that vector lengths match also checks that
3103 // scalars are not being converted to vectors or vectors to scalars).
3104 unsigned SrcLength = SrcTy->isVectorTy() ?
3105 cast<VectorType>(SrcTy)->getNumElements() : 0;
3106 unsigned DstLength = DstTy->isVectorTy() ?
3107 cast<VectorType>(DstTy)->getNumElements() : 0;
3109 // Switch on the opcode provided
3111 default: return false; // This is an input error
3112 case Instruction::Trunc:
3113 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3114 SrcLength == DstLength && SrcBitSize > DstBitSize;
3115 case Instruction::ZExt:
3116 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3117 SrcLength == DstLength && SrcBitSize < DstBitSize;
3118 case Instruction::SExt:
3119 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3120 SrcLength == DstLength && SrcBitSize < DstBitSize;
3121 case Instruction::FPTrunc:
3122 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3123 SrcLength == DstLength && SrcBitSize > DstBitSize;
3124 case Instruction::FPExt:
3125 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3126 SrcLength == DstLength && SrcBitSize < DstBitSize;
3127 case Instruction::UIToFP:
3128 case Instruction::SIToFP:
3129 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3130 SrcLength == DstLength;
3131 case Instruction::FPToUI:
3132 case Instruction::FPToSI:
3133 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3134 SrcLength == DstLength;
3135 case Instruction::PtrToInt:
3136 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3138 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3139 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3141 return SrcTy->getScalarType()->isPointerTy() &&
3142 DstTy->getScalarType()->isIntegerTy();
3143 case Instruction::IntToPtr:
3144 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3146 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3147 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3149 return SrcTy->getScalarType()->isIntegerTy() &&
3150 DstTy->getScalarType()->isPointerTy();
3151 case Instruction::BitCast: {
3152 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3153 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3155 // BitCast implies a no-op cast of type only. No bits change.
3156 // However, you can't cast pointers to anything but pointers.
3157 if (!SrcPtrTy != !DstPtrTy)
3160 // For non-pointer cases, the cast is okay if the source and destination bit
3161 // widths are identical.
3163 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3165 // If both are pointers then the address spaces must match.
3166 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3169 // A vector of pointers must have the same number of elements.
3170 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3171 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3172 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3179 case Instruction::AddrSpaceCast: {
3180 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3184 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3188 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3191 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3192 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3193 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3203 TruncInst::TruncInst(
3204 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3205 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3206 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3209 TruncInst::TruncInst(
3210 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3211 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3212 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3216 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3217 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3218 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3222 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3223 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3224 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3227 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3228 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3229 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3233 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3234 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3235 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3238 FPTruncInst::FPTruncInst(
3239 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3240 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3241 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3244 FPTruncInst::FPTruncInst(
3245 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3246 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3247 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3250 FPExtInst::FPExtInst(
3251 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3252 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3253 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3256 FPExtInst::FPExtInst(
3257 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3258 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3259 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3262 UIToFPInst::UIToFPInst(
3263 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3264 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3265 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3268 UIToFPInst::UIToFPInst(
3269 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3270 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3271 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3274 SIToFPInst::SIToFPInst(
3275 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3276 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3277 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3280 SIToFPInst::SIToFPInst(
3281 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3282 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3283 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3286 FPToUIInst::FPToUIInst(
3287 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3288 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3289 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3292 FPToUIInst::FPToUIInst(
3293 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3294 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3295 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3298 FPToSIInst::FPToSIInst(
3299 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3300 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3301 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3304 FPToSIInst::FPToSIInst(
3305 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3306 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3307 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3310 PtrToIntInst::PtrToIntInst(
3311 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3312 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3313 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3316 PtrToIntInst::PtrToIntInst(
3317 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3318 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3319 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3322 IntToPtrInst::IntToPtrInst(
3323 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3324 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3325 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3328 IntToPtrInst::IntToPtrInst(
3329 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3330 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3331 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3334 BitCastInst::BitCastInst(
3335 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3336 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3337 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3340 BitCastInst::BitCastInst(
3341 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3342 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3343 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3346 AddrSpaceCastInst::AddrSpaceCastInst(
3347 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3348 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3349 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3352 AddrSpaceCastInst::AddrSpaceCastInst(
3353 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3354 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3355 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3358 //===----------------------------------------------------------------------===//
3360 //===----------------------------------------------------------------------===//
3362 void CmpInst::anchor() {}
3364 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3365 Value *LHS, Value *RHS, const Twine &Name,
3366 Instruction *InsertBefore)
3367 : Instruction(ty, op,
3368 OperandTraits<CmpInst>::op_begin(this),
3369 OperandTraits<CmpInst>::operands(this),
3373 setPredicate((Predicate)predicate);
3377 CmpInst::CmpInst(Type *ty, OtherOps op, unsigned short predicate,
3378 Value *LHS, Value *RHS, const Twine &Name,
3379 BasicBlock *InsertAtEnd)
3380 : Instruction(ty, op,
3381 OperandTraits<CmpInst>::op_begin(this),
3382 OperandTraits<CmpInst>::operands(this),
3386 setPredicate((Predicate)predicate);
3391 CmpInst::Create(OtherOps Op, unsigned short predicate,
3392 Value *S1, Value *S2,
3393 const Twine &Name, Instruction *InsertBefore) {
3394 if (Op == Instruction::ICmp) {
3396 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3399 return new ICmpInst(CmpInst::Predicate(predicate),
3404 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3407 return new FCmpInst(CmpInst::Predicate(predicate),
3412 CmpInst::Create(OtherOps Op, unsigned short predicate, Value *S1, Value *S2,
3413 const Twine &Name, BasicBlock *InsertAtEnd) {
3414 if (Op == Instruction::ICmp) {
3415 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3418 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3422 void CmpInst::swapOperands() {
3423 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3426 cast<FCmpInst>(this)->swapOperands();
3429 bool CmpInst::isCommutative() const {
3430 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3431 return IC->isCommutative();
3432 return cast<FCmpInst>(this)->isCommutative();
3435 bool CmpInst::isEquality() const {
3436 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3437 return IC->isEquality();
3438 return cast<FCmpInst>(this)->isEquality();
3442 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3444 default: llvm_unreachable("Unknown cmp predicate!");
3445 case ICMP_EQ: return ICMP_NE;
3446 case ICMP_NE: return ICMP_EQ;
3447 case ICMP_UGT: return ICMP_ULE;
3448 case ICMP_ULT: return ICMP_UGE;
3449 case ICMP_UGE: return ICMP_ULT;
3450 case ICMP_ULE: return ICMP_UGT;
3451 case ICMP_SGT: return ICMP_SLE;
3452 case ICMP_SLT: return ICMP_SGE;
3453 case ICMP_SGE: return ICMP_SLT;
3454 case ICMP_SLE: return ICMP_SGT;
3456 case FCMP_OEQ: return FCMP_UNE;
3457 case FCMP_ONE: return FCMP_UEQ;
3458 case FCMP_OGT: return FCMP_ULE;
3459 case FCMP_OLT: return FCMP_UGE;
3460 case FCMP_OGE: return FCMP_ULT;
3461 case FCMP_OLE: return FCMP_UGT;
3462 case FCMP_UEQ: return FCMP_ONE;
3463 case FCMP_UNE: return FCMP_OEQ;
3464 case FCMP_UGT: return FCMP_OLE;
3465 case FCMP_ULT: return FCMP_OGE;
3466 case FCMP_UGE: return FCMP_OLT;
3467 case FCMP_ULE: return FCMP_OGT;
3468 case FCMP_ORD: return FCMP_UNO;
3469 case FCMP_UNO: return FCMP_ORD;
3470 case FCMP_TRUE: return FCMP_FALSE;
3471 case FCMP_FALSE: return FCMP_TRUE;
3475 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3477 default: llvm_unreachable("Unknown icmp predicate!");
3478 case ICMP_EQ: case ICMP_NE:
3479 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3481 case ICMP_UGT: return ICMP_SGT;
3482 case ICMP_ULT: return ICMP_SLT;
3483 case ICMP_UGE: return ICMP_SGE;
3484 case ICMP_ULE: return ICMP_SLE;
3488 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3490 default: llvm_unreachable("Unknown icmp predicate!");
3491 case ICMP_EQ: case ICMP_NE:
3492 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3494 case ICMP_SGT: return ICMP_UGT;
3495 case ICMP_SLT: return ICMP_ULT;
3496 case ICMP_SGE: return ICMP_UGE;
3497 case ICMP_SLE: return ICMP_ULE;
3501 /// Initialize a set of values that all satisfy the condition with C.
3504 ICmpInst::makeConstantRange(Predicate pred, const APInt &C) {
3507 uint32_t BitWidth = C.getBitWidth();
3509 default: llvm_unreachable("Invalid ICmp opcode to ConstantRange ctor!");
3510 case ICmpInst::ICMP_EQ: ++Upper; break;
3511 case ICmpInst::ICMP_NE: ++Lower; break;
3512 case ICmpInst::ICMP_ULT:
3513 Lower = APInt::getMinValue(BitWidth);
3514 // Check for an empty-set condition.
3516 return ConstantRange(BitWidth, /*isFullSet=*/false);
3518 case ICmpInst::ICMP_SLT:
3519 Lower = APInt::getSignedMinValue(BitWidth);
3520 // Check for an empty-set condition.
3522 return ConstantRange(BitWidth, /*isFullSet=*/false);
3524 case ICmpInst::ICMP_UGT:
3525 ++Lower; Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3526 // Check for an empty-set condition.
3528 return ConstantRange(BitWidth, /*isFullSet=*/false);
3530 case ICmpInst::ICMP_SGT:
3531 ++Lower; Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3532 // Check for an empty-set condition.
3534 return ConstantRange(BitWidth, /*isFullSet=*/false);
3536 case ICmpInst::ICMP_ULE:
3537 Lower = APInt::getMinValue(BitWidth); ++Upper;
3538 // Check for a full-set condition.
3540 return ConstantRange(BitWidth, /*isFullSet=*/true);
3542 case ICmpInst::ICMP_SLE:
3543 Lower = APInt::getSignedMinValue(BitWidth); ++Upper;
3544 // Check for a full-set condition.
3546 return ConstantRange(BitWidth, /*isFullSet=*/true);
3548 case ICmpInst::ICMP_UGE:
3549 Upper = APInt::getMinValue(BitWidth); // Min = Next(Max)
3550 // Check for a full-set condition.
3552 return ConstantRange(BitWidth, /*isFullSet=*/true);
3554 case ICmpInst::ICMP_SGE:
3555 Upper = APInt::getSignedMinValue(BitWidth); // Min = Next(Max)
3556 // Check for a full-set condition.
3558 return ConstantRange(BitWidth, /*isFullSet=*/true);
3561 return ConstantRange(Lower, Upper);
3564 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3566 default: llvm_unreachable("Unknown cmp predicate!");
3567 case ICMP_EQ: case ICMP_NE:
3569 case ICMP_SGT: return ICMP_SLT;
3570 case ICMP_SLT: return ICMP_SGT;
3571 case ICMP_SGE: return ICMP_SLE;
3572 case ICMP_SLE: return ICMP_SGE;
3573 case ICMP_UGT: return ICMP_ULT;
3574 case ICMP_ULT: return ICMP_UGT;
3575 case ICMP_UGE: return ICMP_ULE;
3576 case ICMP_ULE: return ICMP_UGE;
3578 case FCMP_FALSE: case FCMP_TRUE:
3579 case FCMP_OEQ: case FCMP_ONE:
3580 case FCMP_UEQ: case FCMP_UNE:
3581 case FCMP_ORD: case FCMP_UNO:
3583 case FCMP_OGT: return FCMP_OLT;
3584 case FCMP_OLT: return FCMP_OGT;
3585 case FCMP_OGE: return FCMP_OLE;
3586 case FCMP_OLE: return FCMP_OGE;
3587 case FCMP_UGT: return FCMP_ULT;
3588 case FCMP_ULT: return FCMP_UGT;
3589 case FCMP_UGE: return FCMP_ULE;
3590 case FCMP_ULE: return FCMP_UGE;
3594 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
3595 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!");
3599 llvm_unreachable("Unknown predicate!");
3600 case CmpInst::ICMP_ULT:
3601 return CmpInst::ICMP_SLT;
3602 case CmpInst::ICMP_ULE:
3603 return CmpInst::ICMP_SLE;
3604 case CmpInst::ICMP_UGT:
3605 return CmpInst::ICMP_SGT;
3606 case CmpInst::ICMP_UGE:
3607 return CmpInst::ICMP_SGE;
3611 bool CmpInst::isUnsigned(unsigned short predicate) {
3612 switch (predicate) {
3613 default: return false;
3614 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3615 case ICmpInst::ICMP_UGE: return true;
3619 bool CmpInst::isSigned(unsigned short predicate) {
3620 switch (predicate) {
3621 default: return false;
3622 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3623 case ICmpInst::ICMP_SGE: return true;
3627 bool CmpInst::isOrdered(unsigned short predicate) {
3628 switch (predicate) {
3629 default: return false;
3630 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3631 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3632 case FCmpInst::FCMP_ORD: return true;
3636 bool CmpInst::isUnordered(unsigned short predicate) {
3637 switch (predicate) {
3638 default: return false;
3639 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3640 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3641 case FCmpInst::FCMP_UNO: return true;
3645 bool CmpInst::isTrueWhenEqual(unsigned short predicate) {
3647 default: return false;
3648 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3649 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3653 bool CmpInst::isFalseWhenEqual(unsigned short predicate) {
3655 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3656 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3657 default: return false;
3662 //===----------------------------------------------------------------------===//
3663 // SwitchInst Implementation
3664 //===----------------------------------------------------------------------===//
3666 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3667 assert(Value && Default && NumReserved);
3668 ReservedSpace = NumReserved;
3669 setNumHungOffUseOperands(2);
3670 allocHungoffUses(ReservedSpace);
3676 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3677 /// switch on and a default destination. The number of additional cases can
3678 /// be specified here to make memory allocation more efficient. This
3679 /// constructor can also autoinsert before another instruction.
3680 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3681 Instruction *InsertBefore)
3682 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3683 nullptr, 0, InsertBefore) {
3684 init(Value, Default, 2+NumCases*2);
3687 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3688 /// switch on and a default destination. The number of additional cases can
3689 /// be specified here to make memory allocation more efficient. This
3690 /// constructor also autoinserts at the end of the specified BasicBlock.
3691 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3692 BasicBlock *InsertAtEnd)
3693 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3694 nullptr, 0, InsertAtEnd) {
3695 init(Value, Default, 2+NumCases*2);
3698 SwitchInst::SwitchInst(const SwitchInst &SI)
3699 : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
3700 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3701 setNumHungOffUseOperands(SI.getNumOperands());
3702 Use *OL = getOperandList();
3703 const Use *InOL = SI.getOperandList();
3704 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3706 OL[i+1] = InOL[i+1];
3708 SubclassOptionalData = SI.SubclassOptionalData;
3712 /// addCase - Add an entry to the switch instruction...
3714 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3715 unsigned NewCaseIdx = getNumCases();
3716 unsigned OpNo = getNumOperands();
3717 if (OpNo+2 > ReservedSpace)
3718 growOperands(); // Get more space!
3719 // Initialize some new operands.
3720 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3721 setNumHungOffUseOperands(OpNo+2);
3722 CaseIt Case(this, NewCaseIdx);
3723 Case.setValue(OnVal);
3724 Case.setSuccessor(Dest);
3727 /// removeCase - This method removes the specified case and its successor
3728 /// from the switch instruction.
3729 void SwitchInst::removeCase(CaseIt i) {
3730 unsigned idx = i.getCaseIndex();
3732 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3734 unsigned NumOps = getNumOperands();
3735 Use *OL = getOperandList();
3737 // Overwrite this case with the end of the list.
3738 if (2 + (idx + 1) * 2 != NumOps) {
3739 OL[2 + idx * 2] = OL[NumOps - 2];
3740 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3743 // Nuke the last value.
3744 OL[NumOps-2].set(nullptr);
3745 OL[NumOps-2+1].set(nullptr);
3746 setNumHungOffUseOperands(NumOps-2);
3749 /// growOperands - grow operands - This grows the operand list in response
3750 /// to a push_back style of operation. This grows the number of ops by 3 times.
3752 void SwitchInst::growOperands() {
3753 unsigned e = getNumOperands();
3754 unsigned NumOps = e*3;
3756 ReservedSpace = NumOps;
3757 growHungoffUses(ReservedSpace);
3761 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3762 return getSuccessor(idx);
3764 unsigned SwitchInst::getNumSuccessorsV() const {
3765 return getNumSuccessors();
3767 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3768 setSuccessor(idx, B);
3771 //===----------------------------------------------------------------------===//
3772 // IndirectBrInst Implementation
3773 //===----------------------------------------------------------------------===//
3775 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3776 assert(Address && Address->getType()->isPointerTy() &&
3777 "Address of indirectbr must be a pointer");
3778 ReservedSpace = 1+NumDests;
3779 setNumHungOffUseOperands(1);
3780 allocHungoffUses(ReservedSpace);
3786 /// growOperands - grow operands - This grows the operand list in response
3787 /// to a push_back style of operation. This grows the number of ops by 2 times.
3789 void IndirectBrInst::growOperands() {
3790 unsigned e = getNumOperands();
3791 unsigned NumOps = e*2;
3793 ReservedSpace = NumOps;
3794 growHungoffUses(ReservedSpace);
3797 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3798 Instruction *InsertBefore)
3799 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3800 nullptr, 0, InsertBefore) {
3801 init(Address, NumCases);
3804 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3805 BasicBlock *InsertAtEnd)
3806 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3807 nullptr, 0, InsertAtEnd) {
3808 init(Address, NumCases);
3811 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3812 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3813 nullptr, IBI.getNumOperands()) {
3814 allocHungoffUses(IBI.getNumOperands());
3815 Use *OL = getOperandList();
3816 const Use *InOL = IBI.getOperandList();
3817 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3819 SubclassOptionalData = IBI.SubclassOptionalData;
3822 /// addDestination - Add a destination.
3824 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3825 unsigned OpNo = getNumOperands();
3826 if (OpNo+1 > ReservedSpace)
3827 growOperands(); // Get more space!
3828 // Initialize some new operands.
3829 assert(OpNo < ReservedSpace && "Growing didn't work!");
3830 setNumHungOffUseOperands(OpNo+1);
3831 getOperandList()[OpNo] = DestBB;
3834 /// removeDestination - This method removes the specified successor from the
3835 /// indirectbr instruction.
3836 void IndirectBrInst::removeDestination(unsigned idx) {
3837 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3839 unsigned NumOps = getNumOperands();
3840 Use *OL = getOperandList();
3842 // Replace this value with the last one.
3843 OL[idx+1] = OL[NumOps-1];
3845 // Nuke the last value.
3846 OL[NumOps-1].set(nullptr);
3847 setNumHungOffUseOperands(NumOps-1);
3850 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3851 return getSuccessor(idx);
3853 unsigned IndirectBrInst::getNumSuccessorsV() const {
3854 return getNumSuccessors();
3856 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3857 setSuccessor(idx, B);
3860 //===----------------------------------------------------------------------===//
3861 // cloneImpl() implementations
3862 //===----------------------------------------------------------------------===//
3864 // Define these methods here so vtables don't get emitted into every translation
3865 // unit that uses these classes.
3867 GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
3868 return new (getNumOperands()) GetElementPtrInst(*this);
3871 BinaryOperator *BinaryOperator::cloneImpl() const {
3872 return Create(getOpcode(), Op<0>(), Op<1>());
3875 FCmpInst *FCmpInst::cloneImpl() const {
3876 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3879 ICmpInst *ICmpInst::cloneImpl() const {
3880 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3883 ExtractValueInst *ExtractValueInst::cloneImpl() const {
3884 return new ExtractValueInst(*this);
3887 InsertValueInst *InsertValueInst::cloneImpl() const {
3888 return new InsertValueInst(*this);
3891 AllocaInst *AllocaInst::cloneImpl() const {
3892 AllocaInst *Result = new AllocaInst(getAllocatedType(),
3893 (Value *)getOperand(0), getAlignment());
3894 Result->setUsedWithInAlloca(isUsedWithInAlloca());
3898 LoadInst *LoadInst::cloneImpl() const {
3899 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3900 getAlignment(), getOrdering(), getSynchScope());
3903 StoreInst *StoreInst::cloneImpl() const {
3904 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3905 getAlignment(), getOrdering(), getSynchScope());
3909 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
3910 AtomicCmpXchgInst *Result =
3911 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3912 getSuccessOrdering(), getFailureOrdering(),
3914 Result->setVolatile(isVolatile());
3915 Result->setWeak(isWeak());
3919 AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
3920 AtomicRMWInst *Result =
3921 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3922 getOrdering(), getSynchScope());
3923 Result->setVolatile(isVolatile());
3927 FenceInst *FenceInst::cloneImpl() const {
3928 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3931 TruncInst *TruncInst::cloneImpl() const {
3932 return new TruncInst(getOperand(0), getType());
3935 ZExtInst *ZExtInst::cloneImpl() const {
3936 return new ZExtInst(getOperand(0), getType());
3939 SExtInst *SExtInst::cloneImpl() const {
3940 return new SExtInst(getOperand(0), getType());
3943 FPTruncInst *FPTruncInst::cloneImpl() const {
3944 return new FPTruncInst(getOperand(0), getType());
3947 FPExtInst *FPExtInst::cloneImpl() const {
3948 return new FPExtInst(getOperand(0), getType());
3951 UIToFPInst *UIToFPInst::cloneImpl() const {
3952 return new UIToFPInst(getOperand(0), getType());
3955 SIToFPInst *SIToFPInst::cloneImpl() const {
3956 return new SIToFPInst(getOperand(0), getType());
3959 FPToUIInst *FPToUIInst::cloneImpl() const {
3960 return new FPToUIInst(getOperand(0), getType());
3963 FPToSIInst *FPToSIInst::cloneImpl() const {
3964 return new FPToSIInst(getOperand(0), getType());
3967 PtrToIntInst *PtrToIntInst::cloneImpl() const {
3968 return new PtrToIntInst(getOperand(0), getType());
3971 IntToPtrInst *IntToPtrInst::cloneImpl() const {
3972 return new IntToPtrInst(getOperand(0), getType());
3975 BitCastInst *BitCastInst::cloneImpl() const {
3976 return new BitCastInst(getOperand(0), getType());
3979 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
3980 return new AddrSpaceCastInst(getOperand(0), getType());
3983 CallInst *CallInst::cloneImpl() const {
3984 return new(getNumOperands()) CallInst(*this);
3987 SelectInst *SelectInst::cloneImpl() const {
3988 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3991 VAArgInst *VAArgInst::cloneImpl() const {
3992 return new VAArgInst(getOperand(0), getType());
3995 ExtractElementInst *ExtractElementInst::cloneImpl() const {
3996 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3999 InsertElementInst *InsertElementInst::cloneImpl() const {
4000 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
4003 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
4004 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
4007 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
4009 LandingPadInst *LandingPadInst::cloneImpl() const {
4010 return new LandingPadInst(*this);
4013 ReturnInst *ReturnInst::cloneImpl() const {
4014 return new(getNumOperands()) ReturnInst(*this);
4017 BranchInst *BranchInst::cloneImpl() const {
4018 return new(getNumOperands()) BranchInst(*this);
4021 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
4023 IndirectBrInst *IndirectBrInst::cloneImpl() const {
4024 return new IndirectBrInst(*this);
4027 InvokeInst *InvokeInst::cloneImpl() const {
4028 return new(getNumOperands()) InvokeInst(*this);
4031 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4033 CleanupEndPadInst *CleanupEndPadInst::cloneImpl() const {
4034 return new (getNumOperands()) CleanupEndPadInst(*this);
4037 CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4038 return new (getNumOperands()) CleanupReturnInst(*this);
4041 CatchEndPadInst *CatchEndPadInst::cloneImpl() const {
4042 return new (getNumOperands()) CatchEndPadInst(*this);
4045 CatchReturnInst *CatchReturnInst::cloneImpl() const {
4046 return new (getNumOperands()) CatchReturnInst(*this);
4049 CatchPadInst *CatchPadInst::cloneImpl() const {
4050 return new (getNumOperands()) CatchPadInst(*this);
4053 TerminatePadInst *TerminatePadInst::cloneImpl() const {
4054 return new (getNumOperands()) TerminatePadInst(*this);
4057 CleanupPadInst *CleanupPadInst::cloneImpl() const {
4058 return new (getNumOperands()) CleanupPadInst(*this);
4061 UnreachableInst *UnreachableInst::cloneImpl() const {
4062 LLVMContext &Context = getContext();
4063 return new UnreachableInst(Context);