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 void PHINode::anchor() {}
92 PHINode::PHINode(const PHINode &PN)
93 : Instruction(PN.getType(), Instruction::PHI, nullptr, PN.getNumOperands()),
94 ReservedSpace(PN.getNumOperands()) {
95 allocHungoffUses(PN.getNumOperands());
96 std::copy(PN.op_begin(), PN.op_end(), op_begin());
97 std::copy(PN.block_begin(), PN.block_end(), block_begin());
98 SubclassOptionalData = PN.SubclassOptionalData;
101 // removeIncomingValue - Remove an incoming value. This is useful if a
102 // predecessor basic block is deleted.
103 Value *PHINode::removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty) {
104 Value *Removed = getIncomingValue(Idx);
106 // Move everything after this operand down.
108 // FIXME: we could just swap with the end of the list, then erase. However,
109 // clients might not expect this to happen. The code as it is thrashes the
110 // use/def lists, which is kinda lame.
111 std::copy(op_begin() + Idx + 1, op_end(), op_begin() + Idx);
112 std::copy(block_begin() + Idx + 1, block_end(), block_begin() + Idx);
114 // Nuke the last value.
115 Op<-1>().set(nullptr);
116 setNumHungOffUseOperands(getNumOperands() - 1);
118 // If the PHI node is dead, because it has zero entries, nuke it now.
119 if (getNumOperands() == 0 && DeletePHIIfEmpty) {
120 // If anyone is using this PHI, make them use a dummy value instead...
121 replaceAllUsesWith(UndefValue::get(getType()));
127 /// growOperands - grow operands - This grows the operand list in response
128 /// to a push_back style of operation. This grows the number of ops by 1.5
131 void PHINode::growOperands() {
132 unsigned e = getNumOperands();
133 unsigned NumOps = e + e / 2;
134 if (NumOps < 2) NumOps = 2; // 2 op PHI nodes are VERY common.
136 ReservedSpace = NumOps;
137 growHungoffUses(ReservedSpace, /* IsPhi */ true);
140 /// hasConstantValue - If the specified PHI node always merges together the same
141 /// value, return the value, otherwise return null.
142 Value *PHINode::hasConstantValue() const {
143 // Exploit the fact that phi nodes always have at least one entry.
144 Value *ConstantValue = getIncomingValue(0);
145 for (unsigned i = 1, e = getNumIncomingValues(); i != e; ++i)
146 if (getIncomingValue(i) != ConstantValue && getIncomingValue(i) != this) {
147 if (ConstantValue != this)
148 return nullptr; // Incoming values not all the same.
149 // The case where the first value is this PHI.
150 ConstantValue = getIncomingValue(i);
152 if (ConstantValue == this)
153 return UndefValue::get(getType());
154 return ConstantValue;
157 /// hasConstantOrUndefValue - Whether the specified PHI node always merges
158 /// together the same value, assuming that undefs result in the same value as
160 /// Unlike \ref hasConstantValue, this does not return a value because the
161 /// unique non-undef incoming value need not dominate the PHI node.
162 bool PHINode::hasConstantOrUndefValue() const {
163 Value *ConstantValue = nullptr;
164 for (unsigned i = 0, e = getNumIncomingValues(); i != e; ++i) {
165 Value *Incoming = getIncomingValue(i);
166 if (Incoming != this && !isa<UndefValue>(Incoming)) {
167 if (ConstantValue && ConstantValue != Incoming)
169 ConstantValue = Incoming;
175 //===----------------------------------------------------------------------===//
176 // LandingPadInst Implementation
177 //===----------------------------------------------------------------------===//
179 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
180 const Twine &NameStr, Instruction *InsertBefore)
181 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertBefore) {
182 init(NumReservedValues, NameStr);
185 LandingPadInst::LandingPadInst(Type *RetTy, unsigned NumReservedValues,
186 const Twine &NameStr, BasicBlock *InsertAtEnd)
187 : Instruction(RetTy, Instruction::LandingPad, nullptr, 0, InsertAtEnd) {
188 init(NumReservedValues, NameStr);
191 LandingPadInst::LandingPadInst(const LandingPadInst &LP)
192 : Instruction(LP.getType(), Instruction::LandingPad, nullptr,
193 LP.getNumOperands()),
194 ReservedSpace(LP.getNumOperands()) {
195 allocHungoffUses(LP.getNumOperands());
196 Use *OL = getOperandList();
197 const Use *InOL = LP.getOperandList();
198 for (unsigned I = 0, E = ReservedSpace; I != E; ++I)
201 setCleanup(LP.isCleanup());
204 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
205 const Twine &NameStr,
206 Instruction *InsertBefore) {
207 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertBefore);
210 LandingPadInst *LandingPadInst::Create(Type *RetTy, unsigned NumReservedClauses,
211 const Twine &NameStr,
212 BasicBlock *InsertAtEnd) {
213 return new LandingPadInst(RetTy, NumReservedClauses, NameStr, InsertAtEnd);
216 void LandingPadInst::init(unsigned NumReservedValues, const Twine &NameStr) {
217 ReservedSpace = NumReservedValues;
218 setNumHungOffUseOperands(0);
219 allocHungoffUses(ReservedSpace);
224 /// growOperands - grow operands - This grows the operand list in response to a
225 /// push_back style of operation. This grows the number of ops by 2 times.
226 void LandingPadInst::growOperands(unsigned Size) {
227 unsigned e = getNumOperands();
228 if (ReservedSpace >= e + Size) return;
229 ReservedSpace = (std::max(e, 1U) + Size / 2) * 2;
230 growHungoffUses(ReservedSpace);
233 void LandingPadInst::addClause(Constant *Val) {
234 unsigned OpNo = getNumOperands();
236 assert(OpNo < ReservedSpace && "Growing didn't work!");
237 setNumHungOffUseOperands(getNumOperands() + 1);
238 getOperandList()[OpNo] = Val;
241 //===----------------------------------------------------------------------===//
242 // CallInst Implementation
243 //===----------------------------------------------------------------------===//
245 CallInst::~CallInst() {
248 void CallInst::init(FunctionType *FTy, Value *Func, ArrayRef<Value *> Args,
249 ArrayRef<OperandBundleDef> Bundles, const Twine &NameStr) {
251 assert(getNumOperands() == Args.size() + CountBundleInputs(Bundles) + 1 &&
252 "NumOperands not set up?");
256 assert((Args.size() == FTy->getNumParams() ||
257 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
258 "Calling a function with bad signature!");
260 for (unsigned i = 0; i != Args.size(); ++i)
261 assert((i >= FTy->getNumParams() ||
262 FTy->getParamType(i) == Args[i]->getType()) &&
263 "Calling a function with a bad signature!");
266 std::copy(Args.begin(), Args.end(), op_begin());
268 auto It = populateBundleOperandInfos(Bundles, Args.size());
270 assert(It + 1 == op_end() && "Should add up!");
275 void CallInst::init(Value *Func, const Twine &NameStr) {
277 cast<FunctionType>(cast<PointerType>(Func->getType())->getElementType());
278 assert(getNumOperands() == 1 && "NumOperands not set up?");
281 assert(FTy->getNumParams() == 0 && "Calling a function with bad signature");
286 CallInst::CallInst(Value *Func, const Twine &Name,
287 Instruction *InsertBefore)
288 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
289 ->getElementType())->getReturnType(),
291 OperandTraits<CallInst>::op_end(this) - 1,
296 CallInst::CallInst(Value *Func, const Twine &Name,
297 BasicBlock *InsertAtEnd)
298 : Instruction(cast<FunctionType>(cast<PointerType>(Func->getType())
299 ->getElementType())->getReturnType(),
301 OperandTraits<CallInst>::op_end(this) - 1,
306 CallInst::CallInst(const CallInst &CI)
307 : Instruction(CI.getType(), Instruction::Call,
308 OperandTraits<CallInst>::op_end(this) - CI.getNumOperands(),
309 CI.getNumOperands()),
310 Attrs(CI.Attrs), FTy(CI.FTy) {
311 setTailCallKind(CI.getTailCallKind());
312 setCallingConv(CI.getCallingConv());
314 std::copy(CI.op_begin(), CI.op_end(), op_begin());
315 std::copy(CI.bundle_op_info_begin(), CI.bundle_op_info_end(),
316 bundle_op_info_begin());
317 SubclassOptionalData = CI.SubclassOptionalData;
320 CallInst *CallInst::Create(CallInst *CI, ArrayRef<OperandBundleDef> OpB,
321 Instruction *InsertPt) {
322 std::vector<Value *> Args(CI->arg_begin(), CI->arg_end());
324 auto *NewCI = CallInst::Create(CI->getCalledValue(), Args, OpB, CI->getName(),
326 NewCI->setTailCallKind(CI->getTailCallKind());
327 NewCI->setCallingConv(CI->getCallingConv());
328 NewCI->SubclassOptionalData = CI->SubclassOptionalData;
329 NewCI->setAttributes(CI->getAttributes());
330 NewCI->setDebugLoc(CI->getDebugLoc());
334 Value *CallInst::getReturnedArgOperand() const {
337 if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index)
338 return getArgOperand(Index-1);
339 if (const Function *F = getCalledFunction())
340 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) &&
342 return getArgOperand(Index-1);
347 void CallInst::addAttribute(unsigned i, Attribute::AttrKind Kind) {
348 AttributeList PAL = getAttributes();
349 PAL = PAL.addAttribute(getContext(), i, Kind);
353 void CallInst::addAttribute(unsigned i, Attribute Attr) {
354 AttributeList PAL = getAttributes();
355 PAL = PAL.addAttribute(getContext(), i, Attr);
359 void CallInst::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
360 AttributeList PAL = getAttributes();
361 PAL = PAL.removeAttribute(getContext(), i, Kind);
365 void CallInst::removeAttribute(unsigned i, StringRef Kind) {
366 AttributeList PAL = getAttributes();
367 PAL = PAL.removeAttribute(getContext(), i, Kind);
371 void CallInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
372 AttributeList PAL = getAttributes();
373 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
377 void CallInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
378 AttributeList PAL = getAttributes();
379 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
383 bool CallInst::hasRetAttr(Attribute::AttrKind Kind) const {
384 if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind))
387 // Look at the callee, if available.
388 if (const Function *F = getCalledFunction())
389 return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind);
393 bool CallInst::paramHasAttr(unsigned i, Attribute::AttrKind Kind) const {
394 assert(i < getNumArgOperands() && "Param index out of bounds!");
396 if (Attrs.hasParamAttribute(i, Kind))
398 if (const Function *F = getCalledFunction())
399 return F->getAttributes().hasParamAttribute(i, Kind);
403 bool CallInst::dataOperandHasImpliedAttr(unsigned i,
404 Attribute::AttrKind Kind) const {
405 // There are getNumOperands() - 1 data operands. The last operand is the
407 assert(i < getNumOperands() && "Data operand index out of bounds!");
409 // The attribute A can either be directly specified, if the operand in
410 // question is a call argument; or be indirectly implied by the kind of its
411 // containing operand bundle, if the operand is a bundle operand.
413 // FIXME: Avoid these i - 1 calculations and update the API to use zero-based
415 if (i < (getNumArgOperands() + 1))
416 return paramHasAttr(i - 1, Kind);
418 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
419 "Must be either a call argument or an operand bundle!");
420 return bundleOperandHasAttr(i - 1, Kind);
423 /// IsConstantOne - Return true only if val is constant int 1
424 static bool IsConstantOne(Value *val) {
425 assert(val && "IsConstantOne does not work with nullptr val");
426 const ConstantInt *CVal = dyn_cast<ConstantInt>(val);
427 return CVal && CVal->isOne();
430 static Instruction *createMalloc(Instruction *InsertBefore,
431 BasicBlock *InsertAtEnd, Type *IntPtrTy,
432 Type *AllocTy, Value *AllocSize,
434 ArrayRef<OperandBundleDef> OpB,
435 Function *MallocF, const Twine &Name) {
436 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
437 "createMalloc needs either InsertBefore or InsertAtEnd");
439 // malloc(type) becomes:
440 // bitcast (i8* malloc(typeSize)) to type*
441 // malloc(type, arraySize) becomes:
442 // bitcast (i8* malloc(typeSize*arraySize)) to type*
444 ArraySize = ConstantInt::get(IntPtrTy, 1);
445 else if (ArraySize->getType() != IntPtrTy) {
447 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
450 ArraySize = CastInst::CreateIntegerCast(ArraySize, IntPtrTy, false,
454 if (!IsConstantOne(ArraySize)) {
455 if (IsConstantOne(AllocSize)) {
456 AllocSize = ArraySize; // Operand * 1 = Operand
457 } else if (Constant *CO = dyn_cast<Constant>(ArraySize)) {
458 Constant *Scale = ConstantExpr::getIntegerCast(CO, IntPtrTy,
460 // Malloc arg is constant product of type size and array size
461 AllocSize = ConstantExpr::getMul(Scale, cast<Constant>(AllocSize));
463 // Multiply type size by the array size...
465 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
466 "mallocsize", InsertBefore);
468 AllocSize = BinaryOperator::CreateMul(ArraySize, AllocSize,
469 "mallocsize", InsertAtEnd);
473 assert(AllocSize->getType() == IntPtrTy && "malloc arg is wrong size");
474 // Create the call to Malloc.
475 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
476 Module *M = BB->getParent()->getParent();
477 Type *BPTy = Type::getInt8PtrTy(BB->getContext());
478 Value *MallocFunc = MallocF;
480 // prototype malloc as "void *malloc(size_t)"
481 MallocFunc = M->getOrInsertFunction("malloc", BPTy, IntPtrTy);
482 PointerType *AllocPtrType = PointerType::getUnqual(AllocTy);
483 CallInst *MCall = nullptr;
484 Instruction *Result = nullptr;
486 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall",
489 if (Result->getType() != AllocPtrType)
490 // Create a cast instruction to convert to the right type...
491 Result = new BitCastInst(MCall, AllocPtrType, Name, InsertBefore);
493 MCall = CallInst::Create(MallocFunc, AllocSize, OpB, "malloccall");
495 if (Result->getType() != AllocPtrType) {
496 InsertAtEnd->getInstList().push_back(MCall);
497 // Create a cast instruction to convert to the right type...
498 Result = new BitCastInst(MCall, AllocPtrType, Name);
501 MCall->setTailCall();
502 if (Function *F = dyn_cast<Function>(MallocFunc)) {
503 MCall->setCallingConv(F->getCallingConv());
504 if (!F->doesNotAlias(0)) F->setDoesNotAlias(0);
506 assert(!MCall->getType()->isVoidTy() && "Malloc has void return type");
511 /// CreateMalloc - Generate the IR for a call to malloc:
512 /// 1. Compute the malloc call's argument as the specified type's size,
513 /// possibly multiplied by the array size if the array size is not
515 /// 2. Call malloc with that argument.
516 /// 3. Bitcast the result of the malloc call to the specified type.
517 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
518 Type *IntPtrTy, Type *AllocTy,
519 Value *AllocSize, Value *ArraySize,
522 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
523 ArraySize, None, MallocF, Name);
525 Instruction *CallInst::CreateMalloc(Instruction *InsertBefore,
526 Type *IntPtrTy, Type *AllocTy,
527 Value *AllocSize, Value *ArraySize,
528 ArrayRef<OperandBundleDef> OpB,
531 return createMalloc(InsertBefore, nullptr, IntPtrTy, AllocTy, AllocSize,
532 ArraySize, OpB, MallocF, Name);
536 /// CreateMalloc - Generate the IR for a call to malloc:
537 /// 1. Compute the malloc call's argument as the specified type's size,
538 /// possibly multiplied by the array size if the array size is not
540 /// 2. Call malloc with that argument.
541 /// 3. Bitcast the result of the malloc call to the specified type.
542 /// Note: This function does not add the bitcast to the basic block, that is the
543 /// responsibility of the caller.
544 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
545 Type *IntPtrTy, Type *AllocTy,
546 Value *AllocSize, Value *ArraySize,
547 Function *MallocF, const Twine &Name) {
548 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
549 ArraySize, None, MallocF, Name);
551 Instruction *CallInst::CreateMalloc(BasicBlock *InsertAtEnd,
552 Type *IntPtrTy, Type *AllocTy,
553 Value *AllocSize, Value *ArraySize,
554 ArrayRef<OperandBundleDef> OpB,
555 Function *MallocF, const Twine &Name) {
556 return createMalloc(nullptr, InsertAtEnd, IntPtrTy, AllocTy, AllocSize,
557 ArraySize, OpB, MallocF, Name);
560 static Instruction *createFree(Value *Source,
561 ArrayRef<OperandBundleDef> Bundles,
562 Instruction *InsertBefore,
563 BasicBlock *InsertAtEnd) {
564 assert(((!InsertBefore && InsertAtEnd) || (InsertBefore && !InsertAtEnd)) &&
565 "createFree needs either InsertBefore or InsertAtEnd");
566 assert(Source->getType()->isPointerTy() &&
567 "Can not free something of nonpointer type!");
569 BasicBlock *BB = InsertBefore ? InsertBefore->getParent() : InsertAtEnd;
570 Module *M = BB->getParent()->getParent();
572 Type *VoidTy = Type::getVoidTy(M->getContext());
573 Type *IntPtrTy = Type::getInt8PtrTy(M->getContext());
574 // prototype free as "void free(void*)"
575 Value *FreeFunc = M->getOrInsertFunction("free", VoidTy, IntPtrTy);
576 CallInst *Result = nullptr;
577 Value *PtrCast = Source;
579 if (Source->getType() != IntPtrTy)
580 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertBefore);
581 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "", InsertBefore);
583 if (Source->getType() != IntPtrTy)
584 PtrCast = new BitCastInst(Source, IntPtrTy, "", InsertAtEnd);
585 Result = CallInst::Create(FreeFunc, PtrCast, Bundles, "");
587 Result->setTailCall();
588 if (Function *F = dyn_cast<Function>(FreeFunc))
589 Result->setCallingConv(F->getCallingConv());
594 /// CreateFree - Generate the IR for a call to the builtin free function.
595 Instruction *CallInst::CreateFree(Value *Source, Instruction *InsertBefore) {
596 return createFree(Source, None, InsertBefore, nullptr);
598 Instruction *CallInst::CreateFree(Value *Source,
599 ArrayRef<OperandBundleDef> Bundles,
600 Instruction *InsertBefore) {
601 return createFree(Source, Bundles, InsertBefore, nullptr);
604 /// CreateFree - Generate the IR for a call to the builtin free function.
605 /// Note: This function does not add the call to the basic block, that is the
606 /// responsibility of the caller.
607 Instruction *CallInst::CreateFree(Value *Source, BasicBlock *InsertAtEnd) {
608 Instruction *FreeCall = createFree(Source, None, nullptr, InsertAtEnd);
609 assert(FreeCall && "CreateFree did not create a CallInst");
612 Instruction *CallInst::CreateFree(Value *Source,
613 ArrayRef<OperandBundleDef> Bundles,
614 BasicBlock *InsertAtEnd) {
615 Instruction *FreeCall = createFree(Source, Bundles, nullptr, InsertAtEnd);
616 assert(FreeCall && "CreateFree did not create a CallInst");
620 //===----------------------------------------------------------------------===//
621 // InvokeInst Implementation
622 //===----------------------------------------------------------------------===//
624 void InvokeInst::init(FunctionType *FTy, Value *Fn, BasicBlock *IfNormal,
625 BasicBlock *IfException, ArrayRef<Value *> Args,
626 ArrayRef<OperandBundleDef> Bundles,
627 const Twine &NameStr) {
630 assert(getNumOperands() == 3 + Args.size() + CountBundleInputs(Bundles) &&
631 "NumOperands not set up?");
634 Op<-1>() = IfException;
637 assert(((Args.size() == FTy->getNumParams()) ||
638 (FTy->isVarArg() && Args.size() > FTy->getNumParams())) &&
639 "Invoking a function with bad signature");
641 for (unsigned i = 0, e = Args.size(); i != e; i++)
642 assert((i >= FTy->getNumParams() ||
643 FTy->getParamType(i) == Args[i]->getType()) &&
644 "Invoking a function with a bad signature!");
647 std::copy(Args.begin(), Args.end(), op_begin());
649 auto It = populateBundleOperandInfos(Bundles, Args.size());
651 assert(It + 3 == op_end() && "Should add up!");
656 InvokeInst::InvokeInst(const InvokeInst &II)
657 : TerminatorInst(II.getType(), Instruction::Invoke,
658 OperandTraits<InvokeInst>::op_end(this) -
660 II.getNumOperands()),
661 Attrs(II.Attrs), FTy(II.FTy) {
662 setCallingConv(II.getCallingConv());
663 std::copy(II.op_begin(), II.op_end(), op_begin());
664 std::copy(II.bundle_op_info_begin(), II.bundle_op_info_end(),
665 bundle_op_info_begin());
666 SubclassOptionalData = II.SubclassOptionalData;
669 InvokeInst *InvokeInst::Create(InvokeInst *II, ArrayRef<OperandBundleDef> OpB,
670 Instruction *InsertPt) {
671 std::vector<Value *> Args(II->arg_begin(), II->arg_end());
673 auto *NewII = InvokeInst::Create(II->getCalledValue(), II->getNormalDest(),
674 II->getUnwindDest(), Args, OpB,
675 II->getName(), InsertPt);
676 NewII->setCallingConv(II->getCallingConv());
677 NewII->SubclassOptionalData = II->SubclassOptionalData;
678 NewII->setAttributes(II->getAttributes());
679 NewII->setDebugLoc(II->getDebugLoc());
683 BasicBlock *InvokeInst::getSuccessorV(unsigned idx) const {
684 return getSuccessor(idx);
686 unsigned InvokeInst::getNumSuccessorsV() const {
687 return getNumSuccessors();
689 void InvokeInst::setSuccessorV(unsigned idx, BasicBlock *B) {
690 return setSuccessor(idx, B);
693 Value *InvokeInst::getReturnedArgOperand() const {
696 if (Attrs.hasAttrSomewhere(Attribute::Returned, &Index) && Index)
697 return getArgOperand(Index-1);
698 if (const Function *F = getCalledFunction())
699 if (F->getAttributes().hasAttrSomewhere(Attribute::Returned, &Index) &&
701 return getArgOperand(Index-1);
706 bool InvokeInst::hasRetAttr(Attribute::AttrKind Kind) const {
707 if (Attrs.hasAttribute(AttributeList::ReturnIndex, Kind))
710 // Look at the callee, if available.
711 if (const Function *F = getCalledFunction())
712 return F->getAttributes().hasAttribute(AttributeList::ReturnIndex, Kind);
716 bool InvokeInst::paramHasAttr(unsigned i, Attribute::AttrKind Kind) const {
717 assert(i < getNumArgOperands() && "Param index out of bounds!");
719 if (Attrs.hasParamAttribute(i, Kind))
721 if (const Function *F = getCalledFunction())
722 return F->getAttributes().hasParamAttribute(i, Kind);
726 bool InvokeInst::dataOperandHasImpliedAttr(unsigned i,
727 Attribute::AttrKind Kind) const {
728 // There are getNumOperands() - 3 data operands. The last three operands are
729 // the callee and the two successor basic blocks.
730 assert(i < (getNumOperands() - 2) && "Data operand index out of bounds!");
732 // The attribute A can either be directly specified, if the operand in
733 // question is an invoke argument; or be indirectly implied by the kind of its
734 // containing operand bundle, if the operand is a bundle operand.
736 // FIXME: Avoid these i - 1 calculations and update the API to use zero-based
738 if (i < (getNumArgOperands() + 1))
739 return paramHasAttr(i - 1, Kind);
741 assert(hasOperandBundles() && i >= (getBundleOperandsStartIndex() + 1) &&
742 "Must be either an invoke argument or an operand bundle!");
743 return bundleOperandHasAttr(i - 1, Kind);
746 void InvokeInst::addAttribute(unsigned i, Attribute::AttrKind Kind) {
747 AttributeList PAL = getAttributes();
748 PAL = PAL.addAttribute(getContext(), i, Kind);
752 void InvokeInst::addAttribute(unsigned i, Attribute Attr) {
753 AttributeList PAL = getAttributes();
754 PAL = PAL.addAttribute(getContext(), i, Attr);
758 void InvokeInst::removeAttribute(unsigned i, Attribute::AttrKind Kind) {
759 AttributeList PAL = getAttributes();
760 PAL = PAL.removeAttribute(getContext(), i, Kind);
764 void InvokeInst::removeAttribute(unsigned i, StringRef Kind) {
765 AttributeList PAL = getAttributes();
766 PAL = PAL.removeAttribute(getContext(), i, Kind);
770 void InvokeInst::addDereferenceableAttr(unsigned i, uint64_t Bytes) {
771 AttributeList PAL = getAttributes();
772 PAL = PAL.addDereferenceableAttr(getContext(), i, Bytes);
776 void InvokeInst::addDereferenceableOrNullAttr(unsigned i, uint64_t Bytes) {
777 AttributeList PAL = getAttributes();
778 PAL = PAL.addDereferenceableOrNullAttr(getContext(), i, Bytes);
782 LandingPadInst *InvokeInst::getLandingPadInst() const {
783 return cast<LandingPadInst>(getUnwindDest()->getFirstNonPHI());
786 //===----------------------------------------------------------------------===//
787 // ReturnInst Implementation
788 //===----------------------------------------------------------------------===//
790 ReturnInst::ReturnInst(const ReturnInst &RI)
791 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Ret,
792 OperandTraits<ReturnInst>::op_end(this) -
794 RI.getNumOperands()) {
795 if (RI.getNumOperands())
796 Op<0>() = RI.Op<0>();
797 SubclassOptionalData = RI.SubclassOptionalData;
800 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, Instruction *InsertBefore)
801 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
802 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
807 ReturnInst::ReturnInst(LLVMContext &C, Value *retVal, BasicBlock *InsertAtEnd)
808 : TerminatorInst(Type::getVoidTy(C), Instruction::Ret,
809 OperandTraits<ReturnInst>::op_end(this) - !!retVal, !!retVal,
814 ReturnInst::ReturnInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
815 : TerminatorInst(Type::getVoidTy(Context), Instruction::Ret,
816 OperandTraits<ReturnInst>::op_end(this), 0, InsertAtEnd) {
819 unsigned ReturnInst::getNumSuccessorsV() const {
820 return getNumSuccessors();
823 /// Out-of-line ReturnInst method, put here so the C++ compiler can choose to
824 /// emit the vtable for the class in this translation unit.
825 void ReturnInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
826 llvm_unreachable("ReturnInst has no successors!");
829 BasicBlock *ReturnInst::getSuccessorV(unsigned idx) const {
830 llvm_unreachable("ReturnInst has no successors!");
833 ReturnInst::~ReturnInst() {
836 //===----------------------------------------------------------------------===//
837 // ResumeInst Implementation
838 //===----------------------------------------------------------------------===//
840 ResumeInst::ResumeInst(const ResumeInst &RI)
841 : TerminatorInst(Type::getVoidTy(RI.getContext()), Instruction::Resume,
842 OperandTraits<ResumeInst>::op_begin(this), 1) {
843 Op<0>() = RI.Op<0>();
846 ResumeInst::ResumeInst(Value *Exn, Instruction *InsertBefore)
847 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
848 OperandTraits<ResumeInst>::op_begin(this), 1, InsertBefore) {
852 ResumeInst::ResumeInst(Value *Exn, BasicBlock *InsertAtEnd)
853 : TerminatorInst(Type::getVoidTy(Exn->getContext()), Instruction::Resume,
854 OperandTraits<ResumeInst>::op_begin(this), 1, InsertAtEnd) {
858 unsigned ResumeInst::getNumSuccessorsV() const {
859 return getNumSuccessors();
862 void ResumeInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
863 llvm_unreachable("ResumeInst has no successors!");
866 BasicBlock *ResumeInst::getSuccessorV(unsigned idx) const {
867 llvm_unreachable("ResumeInst has no successors!");
870 //===----------------------------------------------------------------------===//
871 // CleanupReturnInst Implementation
872 //===----------------------------------------------------------------------===//
874 CleanupReturnInst::CleanupReturnInst(const CleanupReturnInst &CRI)
875 : TerminatorInst(CRI.getType(), Instruction::CleanupRet,
876 OperandTraits<CleanupReturnInst>::op_end(this) -
877 CRI.getNumOperands(),
878 CRI.getNumOperands()) {
879 setInstructionSubclassData(CRI.getSubclassDataFromInstruction());
880 Op<0>() = CRI.Op<0>();
881 if (CRI.hasUnwindDest())
882 Op<1>() = CRI.Op<1>();
885 void CleanupReturnInst::init(Value *CleanupPad, BasicBlock *UnwindBB) {
887 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
889 Op<0>() = CleanupPad;
894 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
895 unsigned Values, Instruction *InsertBefore)
896 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
897 Instruction::CleanupRet,
898 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
899 Values, InsertBefore) {
900 init(CleanupPad, UnwindBB);
903 CleanupReturnInst::CleanupReturnInst(Value *CleanupPad, BasicBlock *UnwindBB,
904 unsigned Values, BasicBlock *InsertAtEnd)
905 : TerminatorInst(Type::getVoidTy(CleanupPad->getContext()),
906 Instruction::CleanupRet,
907 OperandTraits<CleanupReturnInst>::op_end(this) - Values,
908 Values, InsertAtEnd) {
909 init(CleanupPad, UnwindBB);
912 BasicBlock *CleanupReturnInst::getSuccessorV(unsigned Idx) const {
914 return getUnwindDest();
916 unsigned CleanupReturnInst::getNumSuccessorsV() const {
917 return getNumSuccessors();
919 void CleanupReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
924 //===----------------------------------------------------------------------===//
925 // CatchReturnInst Implementation
926 //===----------------------------------------------------------------------===//
927 void CatchReturnInst::init(Value *CatchPad, BasicBlock *BB) {
932 CatchReturnInst::CatchReturnInst(const CatchReturnInst &CRI)
933 : TerminatorInst(Type::getVoidTy(CRI.getContext()), Instruction::CatchRet,
934 OperandTraits<CatchReturnInst>::op_begin(this), 2) {
935 Op<0>() = CRI.Op<0>();
936 Op<1>() = CRI.Op<1>();
939 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
940 Instruction *InsertBefore)
941 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
942 OperandTraits<CatchReturnInst>::op_begin(this), 2,
947 CatchReturnInst::CatchReturnInst(Value *CatchPad, BasicBlock *BB,
948 BasicBlock *InsertAtEnd)
949 : TerminatorInst(Type::getVoidTy(BB->getContext()), Instruction::CatchRet,
950 OperandTraits<CatchReturnInst>::op_begin(this), 2,
955 BasicBlock *CatchReturnInst::getSuccessorV(unsigned Idx) const {
956 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
957 return getSuccessor();
959 unsigned CatchReturnInst::getNumSuccessorsV() const {
960 return getNumSuccessors();
962 void CatchReturnInst::setSuccessorV(unsigned Idx, BasicBlock *B) {
963 assert(Idx < getNumSuccessors() && "Successor # out of range for catchret!");
967 //===----------------------------------------------------------------------===//
968 // CatchSwitchInst Implementation
969 //===----------------------------------------------------------------------===//
971 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
972 unsigned NumReservedValues,
973 const Twine &NameStr,
974 Instruction *InsertBefore)
975 : TerminatorInst(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
979 init(ParentPad, UnwindDest, NumReservedValues + 1);
983 CatchSwitchInst::CatchSwitchInst(Value *ParentPad, BasicBlock *UnwindDest,
984 unsigned NumReservedValues,
985 const Twine &NameStr, BasicBlock *InsertAtEnd)
986 : TerminatorInst(ParentPad->getType(), Instruction::CatchSwitch, nullptr, 0,
990 init(ParentPad, UnwindDest, NumReservedValues + 1);
994 CatchSwitchInst::CatchSwitchInst(const CatchSwitchInst &CSI)
995 : TerminatorInst(CSI.getType(), Instruction::CatchSwitch, nullptr,
996 CSI.getNumOperands()) {
997 init(CSI.getParentPad(), CSI.getUnwindDest(), CSI.getNumOperands());
998 setNumHungOffUseOperands(ReservedSpace);
999 Use *OL = getOperandList();
1000 const Use *InOL = CSI.getOperandList();
1001 for (unsigned I = 1, E = ReservedSpace; I != E; ++I)
1005 void CatchSwitchInst::init(Value *ParentPad, BasicBlock *UnwindDest,
1006 unsigned NumReservedValues) {
1007 assert(ParentPad && NumReservedValues);
1009 ReservedSpace = NumReservedValues;
1010 setNumHungOffUseOperands(UnwindDest ? 2 : 1);
1011 allocHungoffUses(ReservedSpace);
1013 Op<0>() = ParentPad;
1015 setInstructionSubclassData(getSubclassDataFromInstruction() | 1);
1016 setUnwindDest(UnwindDest);
1020 /// growOperands - grow operands - This grows the operand list in response to a
1021 /// push_back style of operation. This grows the number of ops by 2 times.
1022 void CatchSwitchInst::growOperands(unsigned Size) {
1023 unsigned NumOperands = getNumOperands();
1024 assert(NumOperands >= 1);
1025 if (ReservedSpace >= NumOperands + Size)
1027 ReservedSpace = (NumOperands + Size / 2) * 2;
1028 growHungoffUses(ReservedSpace);
1031 void CatchSwitchInst::addHandler(BasicBlock *Handler) {
1032 unsigned OpNo = getNumOperands();
1034 assert(OpNo < ReservedSpace && "Growing didn't work!");
1035 setNumHungOffUseOperands(getNumOperands() + 1);
1036 getOperandList()[OpNo] = Handler;
1039 void CatchSwitchInst::removeHandler(handler_iterator HI) {
1040 // Move all subsequent handlers up one.
1041 Use *EndDst = op_end() - 1;
1042 for (Use *CurDst = HI.getCurrent(); CurDst != EndDst; ++CurDst)
1043 *CurDst = *(CurDst + 1);
1044 // Null out the last handler use.
1047 setNumHungOffUseOperands(getNumOperands() - 1);
1050 BasicBlock *CatchSwitchInst::getSuccessorV(unsigned idx) const {
1051 return getSuccessor(idx);
1053 unsigned CatchSwitchInst::getNumSuccessorsV() const {
1054 return getNumSuccessors();
1056 void CatchSwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1057 setSuccessor(idx, B);
1060 //===----------------------------------------------------------------------===//
1061 // FuncletPadInst Implementation
1062 //===----------------------------------------------------------------------===//
1063 void FuncletPadInst::init(Value *ParentPad, ArrayRef<Value *> Args,
1064 const Twine &NameStr) {
1065 assert(getNumOperands() == 1 + Args.size() && "NumOperands not set up?");
1066 std::copy(Args.begin(), Args.end(), op_begin());
1067 setParentPad(ParentPad);
1071 FuncletPadInst::FuncletPadInst(const FuncletPadInst &FPI)
1072 : Instruction(FPI.getType(), FPI.getOpcode(),
1073 OperandTraits<FuncletPadInst>::op_end(this) -
1074 FPI.getNumOperands(),
1075 FPI.getNumOperands()) {
1076 std::copy(FPI.op_begin(), FPI.op_end(), op_begin());
1077 setParentPad(FPI.getParentPad());
1080 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1081 ArrayRef<Value *> Args, unsigned Values,
1082 const Twine &NameStr, Instruction *InsertBefore)
1083 : Instruction(ParentPad->getType(), Op,
1084 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
1086 init(ParentPad, Args, NameStr);
1089 FuncletPadInst::FuncletPadInst(Instruction::FuncletPadOps Op, Value *ParentPad,
1090 ArrayRef<Value *> Args, unsigned Values,
1091 const Twine &NameStr, BasicBlock *InsertAtEnd)
1092 : Instruction(ParentPad->getType(), Op,
1093 OperandTraits<FuncletPadInst>::op_end(this) - Values, Values,
1095 init(ParentPad, Args, NameStr);
1098 //===----------------------------------------------------------------------===//
1099 // UnreachableInst Implementation
1100 //===----------------------------------------------------------------------===//
1102 UnreachableInst::UnreachableInst(LLVMContext &Context,
1103 Instruction *InsertBefore)
1104 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1105 nullptr, 0, InsertBefore) {
1107 UnreachableInst::UnreachableInst(LLVMContext &Context, BasicBlock *InsertAtEnd)
1108 : TerminatorInst(Type::getVoidTy(Context), Instruction::Unreachable,
1109 nullptr, 0, InsertAtEnd) {
1112 unsigned UnreachableInst::getNumSuccessorsV() const {
1113 return getNumSuccessors();
1116 void UnreachableInst::setSuccessorV(unsigned idx, BasicBlock *NewSucc) {
1117 llvm_unreachable("UnreachableInst has no successors!");
1120 BasicBlock *UnreachableInst::getSuccessorV(unsigned idx) const {
1121 llvm_unreachable("UnreachableInst has no successors!");
1124 //===----------------------------------------------------------------------===//
1125 // BranchInst Implementation
1126 //===----------------------------------------------------------------------===//
1128 void BranchInst::AssertOK() {
1129 if (isConditional())
1130 assert(getCondition()->getType()->isIntegerTy(1) &&
1131 "May only branch on boolean predicates!");
1134 BranchInst::BranchInst(BasicBlock *IfTrue, Instruction *InsertBefore)
1135 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1136 OperandTraits<BranchInst>::op_end(this) - 1,
1138 assert(IfTrue && "Branch destination may not be null!");
1141 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1142 Instruction *InsertBefore)
1143 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1144 OperandTraits<BranchInst>::op_end(this) - 3,
1154 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *InsertAtEnd)
1155 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1156 OperandTraits<BranchInst>::op_end(this) - 1,
1158 assert(IfTrue && "Branch destination may not be null!");
1162 BranchInst::BranchInst(BasicBlock *IfTrue, BasicBlock *IfFalse, Value *Cond,
1163 BasicBlock *InsertAtEnd)
1164 : TerminatorInst(Type::getVoidTy(IfTrue->getContext()), Instruction::Br,
1165 OperandTraits<BranchInst>::op_end(this) - 3,
1176 BranchInst::BranchInst(const BranchInst &BI) :
1177 TerminatorInst(Type::getVoidTy(BI.getContext()), Instruction::Br,
1178 OperandTraits<BranchInst>::op_end(this) - BI.getNumOperands(),
1179 BI.getNumOperands()) {
1180 Op<-1>() = BI.Op<-1>();
1181 if (BI.getNumOperands() != 1) {
1182 assert(BI.getNumOperands() == 3 && "BR can have 1 or 3 operands!");
1183 Op<-3>() = BI.Op<-3>();
1184 Op<-2>() = BI.Op<-2>();
1186 SubclassOptionalData = BI.SubclassOptionalData;
1189 void BranchInst::swapSuccessors() {
1190 assert(isConditional() &&
1191 "Cannot swap successors of an unconditional branch");
1192 Op<-1>().swap(Op<-2>());
1194 // Update profile metadata if present and it matches our structural
1199 BasicBlock *BranchInst::getSuccessorV(unsigned idx) const {
1200 return getSuccessor(idx);
1202 unsigned BranchInst::getNumSuccessorsV() const {
1203 return getNumSuccessors();
1205 void BranchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
1206 setSuccessor(idx, B);
1210 //===----------------------------------------------------------------------===//
1211 // AllocaInst Implementation
1212 //===----------------------------------------------------------------------===//
1214 static Value *getAISize(LLVMContext &Context, Value *Amt) {
1216 Amt = ConstantInt::get(Type::getInt32Ty(Context), 1);
1218 assert(!isa<BasicBlock>(Amt) &&
1219 "Passed basic block into allocation size parameter! Use other ctor");
1220 assert(Amt->getType()->isIntegerTy() &&
1221 "Allocation array size is not an integer!");
1226 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1227 Instruction *InsertBefore)
1228 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertBefore) {}
1230 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, const Twine &Name,
1231 BasicBlock *InsertAtEnd)
1232 : AllocaInst(Ty, AddrSpace, /*ArraySize=*/nullptr, Name, InsertAtEnd) {}
1234 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1235 const Twine &Name, Instruction *InsertBefore)
1236 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertBefore) {}
1238 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1239 const Twine &Name, BasicBlock *InsertAtEnd)
1240 : AllocaInst(Ty, AddrSpace, ArraySize, /*Align=*/0, Name, InsertAtEnd) {}
1242 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1243 unsigned Align, const Twine &Name,
1244 Instruction *InsertBefore)
1245 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1246 getAISize(Ty->getContext(), ArraySize), InsertBefore),
1248 setAlignment(Align);
1249 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1253 AllocaInst::AllocaInst(Type *Ty, unsigned AddrSpace, Value *ArraySize,
1254 unsigned Align, const Twine &Name,
1255 BasicBlock *InsertAtEnd)
1256 : UnaryInstruction(PointerType::get(Ty, AddrSpace), Alloca,
1257 getAISize(Ty->getContext(), ArraySize), InsertAtEnd),
1259 setAlignment(Align);
1260 assert(!Ty->isVoidTy() && "Cannot allocate void!");
1264 // Out of line virtual method, so the vtable, etc has a home.
1265 AllocaInst::~AllocaInst() {
1268 void AllocaInst::setAlignment(unsigned Align) {
1269 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1270 assert(Align <= MaximumAlignment &&
1271 "Alignment is greater than MaximumAlignment!");
1272 setInstructionSubclassData((getSubclassDataFromInstruction() & ~31) |
1273 (Log2_32(Align) + 1));
1274 assert(getAlignment() == Align && "Alignment representation error!");
1277 bool AllocaInst::isArrayAllocation() const {
1278 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(0)))
1279 return !CI->isOne();
1283 /// isStaticAlloca - Return true if this alloca is in the entry block of the
1284 /// function and is a constant size. If so, the code generator will fold it
1285 /// into the prolog/epilog code, so it is basically free.
1286 bool AllocaInst::isStaticAlloca() const {
1287 // Must be constant size.
1288 if (!isa<ConstantInt>(getArraySize())) return false;
1290 // Must be in the entry block.
1291 const BasicBlock *Parent = getParent();
1292 return Parent == &Parent->getParent()->front() && !isUsedWithInAlloca();
1295 //===----------------------------------------------------------------------===//
1296 // LoadInst Implementation
1297 //===----------------------------------------------------------------------===//
1299 void LoadInst::AssertOK() {
1300 assert(getOperand(0)->getType()->isPointerTy() &&
1301 "Ptr must have pointer type.");
1302 assert(!(isAtomic() && getAlignment() == 0) &&
1303 "Alignment required for atomic load");
1306 LoadInst::LoadInst(Value *Ptr, const Twine &Name, Instruction *InsertBef)
1307 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertBef) {}
1309 LoadInst::LoadInst(Value *Ptr, const Twine &Name, BasicBlock *InsertAE)
1310 : LoadInst(Ptr, Name, /*isVolatile=*/false, InsertAE) {}
1312 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1313 Instruction *InsertBef)
1314 : LoadInst(Ty, Ptr, Name, isVolatile, /*Align=*/0, InsertBef) {}
1316 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1317 BasicBlock *InsertAE)
1318 : LoadInst(Ptr, Name, isVolatile, /*Align=*/0, InsertAE) {}
1320 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1321 unsigned Align, Instruction *InsertBef)
1322 : LoadInst(Ty, Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1323 CrossThread, InsertBef) {}
1325 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1326 unsigned Align, BasicBlock *InsertAE)
1327 : LoadInst(Ptr, Name, isVolatile, Align, AtomicOrdering::NotAtomic,
1328 CrossThread, InsertAE) {}
1330 LoadInst::LoadInst(Type *Ty, Value *Ptr, const Twine &Name, bool isVolatile,
1331 unsigned Align, AtomicOrdering Order,
1332 SynchronizationScope SynchScope, Instruction *InsertBef)
1333 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1334 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1335 setVolatile(isVolatile);
1336 setAlignment(Align);
1337 setAtomic(Order, SynchScope);
1342 LoadInst::LoadInst(Value *Ptr, const Twine &Name, bool isVolatile,
1343 unsigned Align, AtomicOrdering Order,
1344 SynchronizationScope SynchScope,
1345 BasicBlock *InsertAE)
1346 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1347 Load, Ptr, InsertAE) {
1348 setVolatile(isVolatile);
1349 setAlignment(Align);
1350 setAtomic(Order, SynchScope);
1355 LoadInst::LoadInst(Value *Ptr, const char *Name, Instruction *InsertBef)
1356 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1357 Load, Ptr, InsertBef) {
1360 setAtomic(AtomicOrdering::NotAtomic);
1362 if (Name && Name[0]) setName(Name);
1365 LoadInst::LoadInst(Value *Ptr, const char *Name, BasicBlock *InsertAE)
1366 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1367 Load, Ptr, InsertAE) {
1370 setAtomic(AtomicOrdering::NotAtomic);
1372 if (Name && Name[0]) setName(Name);
1375 LoadInst::LoadInst(Type *Ty, Value *Ptr, const char *Name, bool isVolatile,
1376 Instruction *InsertBef)
1377 : UnaryInstruction(Ty, Load, Ptr, InsertBef) {
1378 assert(Ty == cast<PointerType>(Ptr->getType())->getElementType());
1379 setVolatile(isVolatile);
1381 setAtomic(AtomicOrdering::NotAtomic);
1383 if (Name && Name[0]) setName(Name);
1386 LoadInst::LoadInst(Value *Ptr, const char *Name, bool isVolatile,
1387 BasicBlock *InsertAE)
1388 : UnaryInstruction(cast<PointerType>(Ptr->getType())->getElementType(),
1389 Load, Ptr, InsertAE) {
1390 setVolatile(isVolatile);
1392 setAtomic(AtomicOrdering::NotAtomic);
1394 if (Name && Name[0]) setName(Name);
1397 void LoadInst::setAlignment(unsigned Align) {
1398 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1399 assert(Align <= MaximumAlignment &&
1400 "Alignment is greater than MaximumAlignment!");
1401 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1402 ((Log2_32(Align)+1)<<1));
1403 assert(getAlignment() == Align && "Alignment representation error!");
1406 //===----------------------------------------------------------------------===//
1407 // StoreInst Implementation
1408 //===----------------------------------------------------------------------===//
1410 void StoreInst::AssertOK() {
1411 assert(getOperand(0) && getOperand(1) && "Both operands must be non-null!");
1412 assert(getOperand(1)->getType()->isPointerTy() &&
1413 "Ptr must have pointer type!");
1414 assert(getOperand(0)->getType() ==
1415 cast<PointerType>(getOperand(1)->getType())->getElementType()
1416 && "Ptr must be a pointer to Val type!");
1417 assert(!(isAtomic() && getAlignment() == 0) &&
1418 "Alignment required for atomic store");
1421 StoreInst::StoreInst(Value *val, Value *addr, Instruction *InsertBefore)
1422 : StoreInst(val, addr, /*isVolatile=*/false, InsertBefore) {}
1424 StoreInst::StoreInst(Value *val, Value *addr, BasicBlock *InsertAtEnd)
1425 : StoreInst(val, addr, /*isVolatile=*/false, InsertAtEnd) {}
1427 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1428 Instruction *InsertBefore)
1429 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertBefore) {}
1431 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1432 BasicBlock *InsertAtEnd)
1433 : StoreInst(val, addr, isVolatile, /*Align=*/0, InsertAtEnd) {}
1435 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1436 Instruction *InsertBefore)
1437 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1438 CrossThread, InsertBefore) {}
1440 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile, unsigned Align,
1441 BasicBlock *InsertAtEnd)
1442 : StoreInst(val, addr, isVolatile, Align, AtomicOrdering::NotAtomic,
1443 CrossThread, InsertAtEnd) {}
1445 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1446 unsigned Align, AtomicOrdering Order,
1447 SynchronizationScope SynchScope,
1448 Instruction *InsertBefore)
1449 : Instruction(Type::getVoidTy(val->getContext()), Store,
1450 OperandTraits<StoreInst>::op_begin(this),
1451 OperandTraits<StoreInst>::operands(this),
1455 setVolatile(isVolatile);
1456 setAlignment(Align);
1457 setAtomic(Order, SynchScope);
1461 StoreInst::StoreInst(Value *val, Value *addr, bool isVolatile,
1462 unsigned Align, AtomicOrdering Order,
1463 SynchronizationScope SynchScope,
1464 BasicBlock *InsertAtEnd)
1465 : Instruction(Type::getVoidTy(val->getContext()), Store,
1466 OperandTraits<StoreInst>::op_begin(this),
1467 OperandTraits<StoreInst>::operands(this),
1471 setVolatile(isVolatile);
1472 setAlignment(Align);
1473 setAtomic(Order, SynchScope);
1477 void StoreInst::setAlignment(unsigned Align) {
1478 assert((Align & (Align-1)) == 0 && "Alignment is not a power of 2!");
1479 assert(Align <= MaximumAlignment &&
1480 "Alignment is greater than MaximumAlignment!");
1481 setInstructionSubclassData((getSubclassDataFromInstruction() & ~(31 << 1)) |
1482 ((Log2_32(Align)+1) << 1));
1483 assert(getAlignment() == Align && "Alignment representation error!");
1486 //===----------------------------------------------------------------------===//
1487 // AtomicCmpXchgInst Implementation
1488 //===----------------------------------------------------------------------===//
1490 void AtomicCmpXchgInst::Init(Value *Ptr, Value *Cmp, Value *NewVal,
1491 AtomicOrdering SuccessOrdering,
1492 AtomicOrdering FailureOrdering,
1493 SynchronizationScope SynchScope) {
1497 setSuccessOrdering(SuccessOrdering);
1498 setFailureOrdering(FailureOrdering);
1499 setSynchScope(SynchScope);
1501 assert(getOperand(0) && getOperand(1) && getOperand(2) &&
1502 "All operands must be non-null!");
1503 assert(getOperand(0)->getType()->isPointerTy() &&
1504 "Ptr must have pointer type!");
1505 assert(getOperand(1)->getType() ==
1506 cast<PointerType>(getOperand(0)->getType())->getElementType()
1507 && "Ptr must be a pointer to Cmp type!");
1508 assert(getOperand(2)->getType() ==
1509 cast<PointerType>(getOperand(0)->getType())->getElementType()
1510 && "Ptr must be a pointer to NewVal type!");
1511 assert(SuccessOrdering != AtomicOrdering::NotAtomic &&
1512 "AtomicCmpXchg instructions must be atomic!");
1513 assert(FailureOrdering != AtomicOrdering::NotAtomic &&
1514 "AtomicCmpXchg instructions must be atomic!");
1515 assert(!isStrongerThan(FailureOrdering, SuccessOrdering) &&
1516 "AtomicCmpXchg failure argument shall be no stronger than the success "
1518 assert(FailureOrdering != AtomicOrdering::Release &&
1519 FailureOrdering != AtomicOrdering::AcquireRelease &&
1520 "AtomicCmpXchg failure ordering cannot include release semantics");
1523 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1524 AtomicOrdering SuccessOrdering,
1525 AtomicOrdering FailureOrdering,
1526 SynchronizationScope SynchScope,
1527 Instruction *InsertBefore)
1529 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1531 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1532 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertBefore) {
1533 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1536 AtomicCmpXchgInst::AtomicCmpXchgInst(Value *Ptr, Value *Cmp, Value *NewVal,
1537 AtomicOrdering SuccessOrdering,
1538 AtomicOrdering FailureOrdering,
1539 SynchronizationScope SynchScope,
1540 BasicBlock *InsertAtEnd)
1542 StructType::get(Cmp->getType(), Type::getInt1Ty(Cmp->getContext()),
1544 AtomicCmpXchg, OperandTraits<AtomicCmpXchgInst>::op_begin(this),
1545 OperandTraits<AtomicCmpXchgInst>::operands(this), InsertAtEnd) {
1546 Init(Ptr, Cmp, NewVal, SuccessOrdering, FailureOrdering, SynchScope);
1549 //===----------------------------------------------------------------------===//
1550 // AtomicRMWInst Implementation
1551 //===----------------------------------------------------------------------===//
1553 void AtomicRMWInst::Init(BinOp Operation, Value *Ptr, Value *Val,
1554 AtomicOrdering Ordering,
1555 SynchronizationScope SynchScope) {
1558 setOperation(Operation);
1559 setOrdering(Ordering);
1560 setSynchScope(SynchScope);
1562 assert(getOperand(0) && getOperand(1) &&
1563 "All operands must be non-null!");
1564 assert(getOperand(0)->getType()->isPointerTy() &&
1565 "Ptr must have pointer type!");
1566 assert(getOperand(1)->getType() ==
1567 cast<PointerType>(getOperand(0)->getType())->getElementType()
1568 && "Ptr must be a pointer to Val type!");
1569 assert(Ordering != AtomicOrdering::NotAtomic &&
1570 "AtomicRMW instructions must be atomic!");
1573 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1574 AtomicOrdering Ordering,
1575 SynchronizationScope SynchScope,
1576 Instruction *InsertBefore)
1577 : Instruction(Val->getType(), AtomicRMW,
1578 OperandTraits<AtomicRMWInst>::op_begin(this),
1579 OperandTraits<AtomicRMWInst>::operands(this),
1581 Init(Operation, Ptr, Val, Ordering, SynchScope);
1584 AtomicRMWInst::AtomicRMWInst(BinOp Operation, Value *Ptr, Value *Val,
1585 AtomicOrdering Ordering,
1586 SynchronizationScope SynchScope,
1587 BasicBlock *InsertAtEnd)
1588 : Instruction(Val->getType(), AtomicRMW,
1589 OperandTraits<AtomicRMWInst>::op_begin(this),
1590 OperandTraits<AtomicRMWInst>::operands(this),
1592 Init(Operation, Ptr, Val, Ordering, SynchScope);
1595 //===----------------------------------------------------------------------===//
1596 // FenceInst Implementation
1597 //===----------------------------------------------------------------------===//
1599 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1600 SynchronizationScope SynchScope,
1601 Instruction *InsertBefore)
1602 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertBefore) {
1603 setOrdering(Ordering);
1604 setSynchScope(SynchScope);
1607 FenceInst::FenceInst(LLVMContext &C, AtomicOrdering Ordering,
1608 SynchronizationScope SynchScope,
1609 BasicBlock *InsertAtEnd)
1610 : Instruction(Type::getVoidTy(C), Fence, nullptr, 0, InsertAtEnd) {
1611 setOrdering(Ordering);
1612 setSynchScope(SynchScope);
1615 //===----------------------------------------------------------------------===//
1616 // GetElementPtrInst Implementation
1617 //===----------------------------------------------------------------------===//
1619 void GetElementPtrInst::anchor() {}
1621 void GetElementPtrInst::init(Value *Ptr, ArrayRef<Value *> IdxList,
1622 const Twine &Name) {
1623 assert(getNumOperands() == 1 + IdxList.size() &&
1624 "NumOperands not initialized?");
1626 std::copy(IdxList.begin(), IdxList.end(), op_begin() + 1);
1630 GetElementPtrInst::GetElementPtrInst(const GetElementPtrInst &GEPI)
1631 : Instruction(GEPI.getType(), GetElementPtr,
1632 OperandTraits<GetElementPtrInst>::op_end(this) -
1633 GEPI.getNumOperands(),
1634 GEPI.getNumOperands()),
1635 SourceElementType(GEPI.SourceElementType),
1636 ResultElementType(GEPI.ResultElementType) {
1637 std::copy(GEPI.op_begin(), GEPI.op_end(), op_begin());
1638 SubclassOptionalData = GEPI.SubclassOptionalData;
1641 /// getIndexedType - Returns the type of the element that would be accessed with
1642 /// a gep instruction with the specified parameters.
1644 /// The Idxs pointer should point to a continuous piece of memory containing the
1645 /// indices, either as Value* or uint64_t.
1647 /// A null type is returned if the indices are invalid for the specified
1650 template <typename IndexTy>
1651 static Type *getIndexedTypeInternal(Type *Agg, ArrayRef<IndexTy> IdxList) {
1652 // Handle the special case of the empty set index set, which is always valid.
1653 if (IdxList.empty())
1656 // If there is at least one index, the top level type must be sized, otherwise
1657 // it cannot be 'stepped over'.
1658 if (!Agg->isSized())
1661 unsigned CurIdx = 1;
1662 for (; CurIdx != IdxList.size(); ++CurIdx) {
1663 CompositeType *CT = dyn_cast<CompositeType>(Agg);
1664 if (!CT || CT->isPointerTy()) return nullptr;
1665 IndexTy Index = IdxList[CurIdx];
1666 if (!CT->indexValid(Index)) return nullptr;
1667 Agg = CT->getTypeAtIndex(Index);
1669 return CurIdx == IdxList.size() ? Agg : nullptr;
1672 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<Value *> IdxList) {
1673 return getIndexedTypeInternal(Ty, IdxList);
1676 Type *GetElementPtrInst::getIndexedType(Type *Ty,
1677 ArrayRef<Constant *> IdxList) {
1678 return getIndexedTypeInternal(Ty, IdxList);
1681 Type *GetElementPtrInst::getIndexedType(Type *Ty, ArrayRef<uint64_t> IdxList) {
1682 return getIndexedTypeInternal(Ty, IdxList);
1685 /// hasAllZeroIndices - Return true if all of the indices of this GEP are
1686 /// zeros. If so, the result pointer and the first operand have the same
1687 /// value, just potentially different types.
1688 bool GetElementPtrInst::hasAllZeroIndices() const {
1689 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1690 if (ConstantInt *CI = dyn_cast<ConstantInt>(getOperand(i))) {
1691 if (!CI->isZero()) return false;
1699 /// hasAllConstantIndices - Return true if all of the indices of this GEP are
1700 /// constant integers. If so, the result pointer and the first operand have
1701 /// a constant offset between them.
1702 bool GetElementPtrInst::hasAllConstantIndices() const {
1703 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
1704 if (!isa<ConstantInt>(getOperand(i)))
1710 void GetElementPtrInst::setIsInBounds(bool B) {
1711 cast<GEPOperator>(this)->setIsInBounds(B);
1714 bool GetElementPtrInst::isInBounds() const {
1715 return cast<GEPOperator>(this)->isInBounds();
1718 bool GetElementPtrInst::accumulateConstantOffset(const DataLayout &DL,
1719 APInt &Offset) const {
1720 // Delegate to the generic GEPOperator implementation.
1721 return cast<GEPOperator>(this)->accumulateConstantOffset(DL, Offset);
1724 //===----------------------------------------------------------------------===//
1725 // ExtractElementInst Implementation
1726 //===----------------------------------------------------------------------===//
1728 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1730 Instruction *InsertBef)
1731 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1733 OperandTraits<ExtractElementInst>::op_begin(this),
1735 assert(isValidOperands(Val, Index) &&
1736 "Invalid extractelement instruction operands!");
1742 ExtractElementInst::ExtractElementInst(Value *Val, Value *Index,
1744 BasicBlock *InsertAE)
1745 : Instruction(cast<VectorType>(Val->getType())->getElementType(),
1747 OperandTraits<ExtractElementInst>::op_begin(this),
1749 assert(isValidOperands(Val, Index) &&
1750 "Invalid extractelement instruction operands!");
1758 bool ExtractElementInst::isValidOperands(const Value *Val, const Value *Index) {
1759 if (!Val->getType()->isVectorTy() || !Index->getType()->isIntegerTy())
1765 //===----------------------------------------------------------------------===//
1766 // InsertElementInst Implementation
1767 //===----------------------------------------------------------------------===//
1769 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1771 Instruction *InsertBef)
1772 : Instruction(Vec->getType(), InsertElement,
1773 OperandTraits<InsertElementInst>::op_begin(this),
1775 assert(isValidOperands(Vec, Elt, Index) &&
1776 "Invalid insertelement instruction operands!");
1783 InsertElementInst::InsertElementInst(Value *Vec, Value *Elt, Value *Index,
1785 BasicBlock *InsertAE)
1786 : Instruction(Vec->getType(), InsertElement,
1787 OperandTraits<InsertElementInst>::op_begin(this),
1789 assert(isValidOperands(Vec, Elt, Index) &&
1790 "Invalid insertelement instruction operands!");
1798 bool InsertElementInst::isValidOperands(const Value *Vec, const Value *Elt,
1799 const Value *Index) {
1800 if (!Vec->getType()->isVectorTy())
1801 return false; // First operand of insertelement must be vector type.
1803 if (Elt->getType() != cast<VectorType>(Vec->getType())->getElementType())
1804 return false;// Second operand of insertelement must be vector element type.
1806 if (!Index->getType()->isIntegerTy())
1807 return false; // Third operand of insertelement must be i32.
1812 //===----------------------------------------------------------------------===//
1813 // ShuffleVectorInst Implementation
1814 //===----------------------------------------------------------------------===//
1816 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1818 Instruction *InsertBefore)
1819 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1820 cast<VectorType>(Mask->getType())->getNumElements()),
1822 OperandTraits<ShuffleVectorInst>::op_begin(this),
1823 OperandTraits<ShuffleVectorInst>::operands(this),
1825 assert(isValidOperands(V1, V2, Mask) &&
1826 "Invalid shuffle vector instruction operands!");
1833 ShuffleVectorInst::ShuffleVectorInst(Value *V1, Value *V2, Value *Mask,
1835 BasicBlock *InsertAtEnd)
1836 : Instruction(VectorType::get(cast<VectorType>(V1->getType())->getElementType(),
1837 cast<VectorType>(Mask->getType())->getNumElements()),
1839 OperandTraits<ShuffleVectorInst>::op_begin(this),
1840 OperandTraits<ShuffleVectorInst>::operands(this),
1842 assert(isValidOperands(V1, V2, Mask) &&
1843 "Invalid shuffle vector instruction operands!");
1851 bool ShuffleVectorInst::isValidOperands(const Value *V1, const Value *V2,
1852 const Value *Mask) {
1853 // V1 and V2 must be vectors of the same type.
1854 if (!V1->getType()->isVectorTy() || V1->getType() != V2->getType())
1857 // Mask must be vector of i32.
1858 auto *MaskTy = dyn_cast<VectorType>(Mask->getType());
1859 if (!MaskTy || !MaskTy->getElementType()->isIntegerTy(32))
1862 // Check to see if Mask is valid.
1863 if (isa<UndefValue>(Mask) || isa<ConstantAggregateZero>(Mask))
1866 if (const auto *MV = dyn_cast<ConstantVector>(Mask)) {
1867 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1868 for (Value *Op : MV->operands()) {
1869 if (auto *CI = dyn_cast<ConstantInt>(Op)) {
1870 if (CI->uge(V1Size*2))
1872 } else if (!isa<UndefValue>(Op)) {
1879 if (const auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1880 unsigned V1Size = cast<VectorType>(V1->getType())->getNumElements();
1881 for (unsigned i = 0, e = MaskTy->getNumElements(); i != e; ++i)
1882 if (CDS->getElementAsInteger(i) >= V1Size*2)
1887 // The bitcode reader can create a place holder for a forward reference
1888 // used as the shuffle mask. When this occurs, the shuffle mask will
1889 // fall into this case and fail. To avoid this error, do this bit of
1890 // ugliness to allow such a mask pass.
1891 if (const auto *CE = dyn_cast<ConstantExpr>(Mask))
1892 if (CE->getOpcode() == Instruction::UserOp1)
1898 int ShuffleVectorInst::getMaskValue(Constant *Mask, unsigned i) {
1899 assert(i < Mask->getType()->getVectorNumElements() && "Index out of range");
1900 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask))
1901 return CDS->getElementAsInteger(i);
1902 Constant *C = Mask->getAggregateElement(i);
1903 if (isa<UndefValue>(C))
1905 return cast<ConstantInt>(C)->getZExtValue();
1908 void ShuffleVectorInst::getShuffleMask(Constant *Mask,
1909 SmallVectorImpl<int> &Result) {
1910 unsigned NumElts = Mask->getType()->getVectorNumElements();
1912 if (auto *CDS = dyn_cast<ConstantDataSequential>(Mask)) {
1913 for (unsigned i = 0; i != NumElts; ++i)
1914 Result.push_back(CDS->getElementAsInteger(i));
1917 for (unsigned i = 0; i != NumElts; ++i) {
1918 Constant *C = Mask->getAggregateElement(i);
1919 Result.push_back(isa<UndefValue>(C) ? -1 :
1920 cast<ConstantInt>(C)->getZExtValue());
1925 //===----------------------------------------------------------------------===//
1926 // InsertValueInst Class
1927 //===----------------------------------------------------------------------===//
1929 void InsertValueInst::init(Value *Agg, Value *Val, ArrayRef<unsigned> Idxs,
1930 const Twine &Name) {
1931 assert(getNumOperands() == 2 && "NumOperands not initialized?");
1933 // There's no fundamental reason why we require at least one index
1934 // (other than weirdness with &*IdxBegin being invalid; see
1935 // getelementptr's init routine for example). But there's no
1936 // present need to support it.
1937 assert(Idxs.size() > 0 && "InsertValueInst must have at least one index");
1939 assert(ExtractValueInst::getIndexedType(Agg->getType(), Idxs) ==
1940 Val->getType() && "Inserted value must match indexed type!");
1944 Indices.append(Idxs.begin(), Idxs.end());
1948 InsertValueInst::InsertValueInst(const InsertValueInst &IVI)
1949 : Instruction(IVI.getType(), InsertValue,
1950 OperandTraits<InsertValueInst>::op_begin(this), 2),
1951 Indices(IVI.Indices) {
1952 Op<0>() = IVI.getOperand(0);
1953 Op<1>() = IVI.getOperand(1);
1954 SubclassOptionalData = IVI.SubclassOptionalData;
1957 //===----------------------------------------------------------------------===//
1958 // ExtractValueInst Class
1959 //===----------------------------------------------------------------------===//
1961 void ExtractValueInst::init(ArrayRef<unsigned> Idxs, const Twine &Name) {
1962 assert(getNumOperands() == 1 && "NumOperands not initialized?");
1964 // There's no fundamental reason why we require at least one index.
1965 // But there's no present need to support it.
1966 assert(Idxs.size() > 0 && "ExtractValueInst must have at least one index");
1968 Indices.append(Idxs.begin(), Idxs.end());
1972 ExtractValueInst::ExtractValueInst(const ExtractValueInst &EVI)
1973 : UnaryInstruction(EVI.getType(), ExtractValue, EVI.getOperand(0)),
1974 Indices(EVI.Indices) {
1975 SubclassOptionalData = EVI.SubclassOptionalData;
1978 // getIndexedType - Returns the type of the element that would be extracted
1979 // with an extractvalue instruction with the specified parameters.
1981 // A null type is returned if the indices are invalid for the specified
1984 Type *ExtractValueInst::getIndexedType(Type *Agg,
1985 ArrayRef<unsigned> Idxs) {
1986 for (unsigned Index : Idxs) {
1987 // We can't use CompositeType::indexValid(Index) here.
1988 // indexValid() always returns true for arrays because getelementptr allows
1989 // out-of-bounds indices. Since we don't allow those for extractvalue and
1990 // insertvalue we need to check array indexing manually.
1991 // Since the only other types we can index into are struct types it's just
1992 // as easy to check those manually as well.
1993 if (ArrayType *AT = dyn_cast<ArrayType>(Agg)) {
1994 if (Index >= AT->getNumElements())
1996 } else if (StructType *ST = dyn_cast<StructType>(Agg)) {
1997 if (Index >= ST->getNumElements())
2000 // Not a valid type to index into.
2004 Agg = cast<CompositeType>(Agg)->getTypeAtIndex(Index);
2006 return const_cast<Type*>(Agg);
2009 //===----------------------------------------------------------------------===//
2010 // BinaryOperator Class
2011 //===----------------------------------------------------------------------===//
2013 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2014 Type *Ty, const Twine &Name,
2015 Instruction *InsertBefore)
2016 : Instruction(Ty, iType,
2017 OperandTraits<BinaryOperator>::op_begin(this),
2018 OperandTraits<BinaryOperator>::operands(this),
2026 BinaryOperator::BinaryOperator(BinaryOps iType, Value *S1, Value *S2,
2027 Type *Ty, const Twine &Name,
2028 BasicBlock *InsertAtEnd)
2029 : Instruction(Ty, iType,
2030 OperandTraits<BinaryOperator>::op_begin(this),
2031 OperandTraits<BinaryOperator>::operands(this),
2040 void BinaryOperator::init(BinaryOps iType) {
2041 Value *LHS = getOperand(0), *RHS = getOperand(1);
2042 (void)LHS; (void)RHS; // Silence warnings.
2043 assert(LHS->getType() == RHS->getType() &&
2044 "Binary operator operand types must match!");
2049 assert(getType() == LHS->getType() &&
2050 "Arithmetic operation should return same type as operands!");
2051 assert(getType()->isIntOrIntVectorTy() &&
2052 "Tried to create an integer operation on a non-integer type!");
2054 case FAdd: case FSub:
2056 assert(getType() == LHS->getType() &&
2057 "Arithmetic operation should return same type as operands!");
2058 assert(getType()->isFPOrFPVectorTy() &&
2059 "Tried to create a floating-point operation on a "
2060 "non-floating-point type!");
2064 assert(getType() == LHS->getType() &&
2065 "Arithmetic operation should return same type as operands!");
2066 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2067 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2068 "Incorrect operand type (not integer) for S/UDIV");
2071 assert(getType() == LHS->getType() &&
2072 "Arithmetic operation should return same type as operands!");
2073 assert(getType()->isFPOrFPVectorTy() &&
2074 "Incorrect operand type (not floating point) for FDIV");
2078 assert(getType() == LHS->getType() &&
2079 "Arithmetic operation should return same type as operands!");
2080 assert((getType()->isIntegerTy() || (getType()->isVectorTy() &&
2081 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2082 "Incorrect operand type (not integer) for S/UREM");
2085 assert(getType() == LHS->getType() &&
2086 "Arithmetic operation should return same type as operands!");
2087 assert(getType()->isFPOrFPVectorTy() &&
2088 "Incorrect operand type (not floating point) for FREM");
2093 assert(getType() == LHS->getType() &&
2094 "Shift operation should return same type as operands!");
2095 assert((getType()->isIntegerTy() ||
2096 (getType()->isVectorTy() &&
2097 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2098 "Tried to create a shift operation on a non-integral type!");
2102 assert(getType() == LHS->getType() &&
2103 "Logical operation should return same type as operands!");
2104 assert((getType()->isIntegerTy() ||
2105 (getType()->isVectorTy() &&
2106 cast<VectorType>(getType())->getElementType()->isIntegerTy())) &&
2107 "Tried to create a logical operation on a non-integral type!");
2115 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2117 Instruction *InsertBefore) {
2118 assert(S1->getType() == S2->getType() &&
2119 "Cannot create binary operator with two operands of differing type!");
2120 return new BinaryOperator(Op, S1, S2, S1->getType(), Name, InsertBefore);
2123 BinaryOperator *BinaryOperator::Create(BinaryOps Op, Value *S1, Value *S2,
2125 BasicBlock *InsertAtEnd) {
2126 BinaryOperator *Res = Create(Op, S1, S2, Name);
2127 InsertAtEnd->getInstList().push_back(Res);
2131 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2132 Instruction *InsertBefore) {
2133 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2134 return new BinaryOperator(Instruction::Sub,
2136 Op->getType(), Name, InsertBefore);
2139 BinaryOperator *BinaryOperator::CreateNeg(Value *Op, const Twine &Name,
2140 BasicBlock *InsertAtEnd) {
2141 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2142 return new BinaryOperator(Instruction::Sub,
2144 Op->getType(), Name, InsertAtEnd);
2147 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2148 Instruction *InsertBefore) {
2149 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2150 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertBefore);
2153 BinaryOperator *BinaryOperator::CreateNSWNeg(Value *Op, const Twine &Name,
2154 BasicBlock *InsertAtEnd) {
2155 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2156 return BinaryOperator::CreateNSWSub(zero, Op, Name, InsertAtEnd);
2159 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2160 Instruction *InsertBefore) {
2161 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2162 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertBefore);
2165 BinaryOperator *BinaryOperator::CreateNUWNeg(Value *Op, const Twine &Name,
2166 BasicBlock *InsertAtEnd) {
2167 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2168 return BinaryOperator::CreateNUWSub(zero, Op, Name, InsertAtEnd);
2171 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2172 Instruction *InsertBefore) {
2173 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2174 return new BinaryOperator(Instruction::FSub, zero, Op,
2175 Op->getType(), Name, InsertBefore);
2178 BinaryOperator *BinaryOperator::CreateFNeg(Value *Op, const Twine &Name,
2179 BasicBlock *InsertAtEnd) {
2180 Value *zero = ConstantFP::getZeroValueForNegation(Op->getType());
2181 return new BinaryOperator(Instruction::FSub, zero, Op,
2182 Op->getType(), Name, InsertAtEnd);
2185 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2186 Instruction *InsertBefore) {
2187 Constant *C = Constant::getAllOnesValue(Op->getType());
2188 return new BinaryOperator(Instruction::Xor, Op, C,
2189 Op->getType(), Name, InsertBefore);
2192 BinaryOperator *BinaryOperator::CreateNot(Value *Op, const Twine &Name,
2193 BasicBlock *InsertAtEnd) {
2194 Constant *AllOnes = Constant::getAllOnesValue(Op->getType());
2195 return new BinaryOperator(Instruction::Xor, Op, AllOnes,
2196 Op->getType(), Name, InsertAtEnd);
2200 // isConstantAllOnes - Helper function for several functions below
2201 static inline bool isConstantAllOnes(const Value *V) {
2202 if (const Constant *C = dyn_cast<Constant>(V))
2203 return C->isAllOnesValue();
2207 bool BinaryOperator::isNeg(const Value *V) {
2208 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2209 if (Bop->getOpcode() == Instruction::Sub)
2210 if (Constant *C = dyn_cast<Constant>(Bop->getOperand(0)))
2211 return C->isNegativeZeroValue();
2215 bool BinaryOperator::isFNeg(const Value *V, bool IgnoreZeroSign) {
2216 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2217 if (Bop->getOpcode() == Instruction::FSub)
2218 if (Constant *C = dyn_cast<Constant>(Bop->getOperand(0))) {
2219 if (!IgnoreZeroSign)
2220 IgnoreZeroSign = cast<Instruction>(V)->hasNoSignedZeros();
2221 return !IgnoreZeroSign ? C->isNegativeZeroValue() : C->isZeroValue();
2226 bool BinaryOperator::isNot(const Value *V) {
2227 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(V))
2228 return (Bop->getOpcode() == Instruction::Xor &&
2229 (isConstantAllOnes(Bop->getOperand(1)) ||
2230 isConstantAllOnes(Bop->getOperand(0))));
2234 Value *BinaryOperator::getNegArgument(Value *BinOp) {
2235 return cast<BinaryOperator>(BinOp)->getOperand(1);
2238 const Value *BinaryOperator::getNegArgument(const Value *BinOp) {
2239 return getNegArgument(const_cast<Value*>(BinOp));
2242 Value *BinaryOperator::getFNegArgument(Value *BinOp) {
2243 return cast<BinaryOperator>(BinOp)->getOperand(1);
2246 const Value *BinaryOperator::getFNegArgument(const Value *BinOp) {
2247 return getFNegArgument(const_cast<Value*>(BinOp));
2250 Value *BinaryOperator::getNotArgument(Value *BinOp) {
2251 assert(isNot(BinOp) && "getNotArgument on non-'not' instruction!");
2252 BinaryOperator *BO = cast<BinaryOperator>(BinOp);
2253 Value *Op0 = BO->getOperand(0);
2254 Value *Op1 = BO->getOperand(1);
2255 if (isConstantAllOnes(Op0)) return Op1;
2257 assert(isConstantAllOnes(Op1));
2261 const Value *BinaryOperator::getNotArgument(const Value *BinOp) {
2262 return getNotArgument(const_cast<Value*>(BinOp));
2266 // Exchange the two operands to this instruction. This instruction is safe to
2267 // use on any binary instruction and does not modify the semantics of the
2268 // instruction. If the instruction is order-dependent (SetLT f.e.), the opcode
2270 bool BinaryOperator::swapOperands() {
2271 if (!isCommutative())
2272 return true; // Can't commute operands
2273 Op<0>().swap(Op<1>());
2278 //===----------------------------------------------------------------------===//
2279 // FPMathOperator Class
2280 //===----------------------------------------------------------------------===//
2282 float FPMathOperator::getFPAccuracy() const {
2284 cast<Instruction>(this)->getMetadata(LLVMContext::MD_fpmath);
2287 ConstantFP *Accuracy = mdconst::extract<ConstantFP>(MD->getOperand(0));
2288 return Accuracy->getValueAPF().convertToFloat();
2292 //===----------------------------------------------------------------------===//
2294 //===----------------------------------------------------------------------===//
2296 void CastInst::anchor() {}
2298 // Just determine if this cast only deals with integral->integral conversion.
2299 bool CastInst::isIntegerCast() const {
2300 switch (getOpcode()) {
2301 default: return false;
2302 case Instruction::ZExt:
2303 case Instruction::SExt:
2304 case Instruction::Trunc:
2306 case Instruction::BitCast:
2307 return getOperand(0)->getType()->isIntegerTy() &&
2308 getType()->isIntegerTy();
2312 bool CastInst::isLosslessCast() const {
2313 // Only BitCast can be lossless, exit fast if we're not BitCast
2314 if (getOpcode() != Instruction::BitCast)
2317 // Identity cast is always lossless
2318 Type *SrcTy = getOperand(0)->getType();
2319 Type *DstTy = getType();
2323 // Pointer to pointer is always lossless.
2324 if (SrcTy->isPointerTy())
2325 return DstTy->isPointerTy();
2326 return false; // Other types have no identity values
2329 /// This function determines if the CastInst does not require any bits to be
2330 /// changed in order to effect the cast. Essentially, it identifies cases where
2331 /// no code gen is necessary for the cast, hence the name no-op cast. For
2332 /// example, the following are all no-op casts:
2333 /// # bitcast i32* %x to i8*
2334 /// # bitcast <2 x i32> %x to <4 x i16>
2335 /// # ptrtoint i32* %x to i32 ; on 32-bit plaforms only
2336 /// @brief Determine if the described cast is a no-op.
2337 bool CastInst::isNoopCast(Instruction::CastOps Opcode,
2342 default: llvm_unreachable("Invalid CastOp");
2343 case Instruction::Trunc:
2344 case Instruction::ZExt:
2345 case Instruction::SExt:
2346 case Instruction::FPTrunc:
2347 case Instruction::FPExt:
2348 case Instruction::UIToFP:
2349 case Instruction::SIToFP:
2350 case Instruction::FPToUI:
2351 case Instruction::FPToSI:
2352 case Instruction::AddrSpaceCast:
2353 // TODO: Target informations may give a more accurate answer here.
2355 case Instruction::BitCast:
2356 return true; // BitCast never modifies bits.
2357 case Instruction::PtrToInt:
2358 return IntPtrTy->getScalarSizeInBits() ==
2359 DestTy->getScalarSizeInBits();
2360 case Instruction::IntToPtr:
2361 return IntPtrTy->getScalarSizeInBits() ==
2362 SrcTy->getScalarSizeInBits();
2366 /// @brief Determine if a cast is a no-op.
2367 bool CastInst::isNoopCast(Type *IntPtrTy) const {
2368 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2371 bool CastInst::isNoopCast(const DataLayout &DL) const {
2372 Type *PtrOpTy = nullptr;
2373 if (getOpcode() == Instruction::PtrToInt)
2374 PtrOpTy = getOperand(0)->getType();
2375 else if (getOpcode() == Instruction::IntToPtr)
2376 PtrOpTy = getType();
2379 PtrOpTy ? DL.getIntPtrType(PtrOpTy) : DL.getIntPtrType(getContext(), 0);
2381 return isNoopCast(getOpcode(), getOperand(0)->getType(), getType(), IntPtrTy);
2384 /// This function determines if a pair of casts can be eliminated and what
2385 /// opcode should be used in the elimination. This assumes that there are two
2386 /// instructions like this:
2387 /// * %F = firstOpcode SrcTy %x to MidTy
2388 /// * %S = secondOpcode MidTy %F to DstTy
2389 /// The function returns a resultOpcode so these two casts can be replaced with:
2390 /// * %Replacement = resultOpcode %SrcTy %x to DstTy
2391 /// If no such cast is permitted, the function returns 0.
2392 unsigned CastInst::isEliminableCastPair(
2393 Instruction::CastOps firstOp, Instruction::CastOps secondOp,
2394 Type *SrcTy, Type *MidTy, Type *DstTy, Type *SrcIntPtrTy, Type *MidIntPtrTy,
2395 Type *DstIntPtrTy) {
2396 // Define the 144 possibilities for these two cast instructions. The values
2397 // in this matrix determine what to do in a given situation and select the
2398 // case in the switch below. The rows correspond to firstOp, the columns
2399 // correspond to secondOp. In looking at the table below, keep in mind
2400 // the following cast properties:
2402 // Size Compare Source Destination
2403 // Operator Src ? Size Type Sign Type Sign
2404 // -------- ------------ ------------------- ---------------------
2405 // TRUNC > Integer Any Integral Any
2406 // ZEXT < Integral Unsigned Integer Any
2407 // SEXT < Integral Signed Integer Any
2408 // FPTOUI n/a FloatPt n/a Integral Unsigned
2409 // FPTOSI n/a FloatPt n/a Integral Signed
2410 // UITOFP n/a Integral Unsigned FloatPt n/a
2411 // SITOFP n/a Integral Signed FloatPt n/a
2412 // FPTRUNC > FloatPt n/a FloatPt n/a
2413 // FPEXT < FloatPt n/a FloatPt n/a
2414 // PTRTOINT n/a Pointer n/a Integral Unsigned
2415 // INTTOPTR n/a Integral Unsigned Pointer n/a
2416 // BITCAST = FirstClass n/a FirstClass n/a
2417 // ADDRSPCST n/a Pointer n/a Pointer n/a
2419 // NOTE: some transforms are safe, but we consider them to be non-profitable.
2420 // For example, we could merge "fptoui double to i32" + "zext i32 to i64",
2421 // into "fptoui double to i64", but this loses information about the range
2422 // of the produced value (we no longer know the top-part is all zeros).
2423 // Further this conversion is often much more expensive for typical hardware,
2424 // and causes issues when building libgcc. We disallow fptosi+sext for the
2426 const unsigned numCastOps =
2427 Instruction::CastOpsEnd - Instruction::CastOpsBegin;
2428 static const uint8_t CastResults[numCastOps][numCastOps] = {
2429 // T F F U S F F P I B A -+
2430 // R Z S P P I I T P 2 N T S |
2431 // U E E 2 2 2 2 R E I T C C +- secondOp
2432 // N X X U S F F N X N 2 V V |
2433 // C T T I I P P C T T P T T -+
2434 { 1, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // Trunc -+
2435 { 8, 1, 9,99,99, 2,17,99,99,99, 2, 3, 0}, // ZExt |
2436 { 8, 0, 1,99,99, 0, 2,99,99,99, 0, 3, 0}, // SExt |
2437 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToUI |
2438 { 0, 0, 0,99,99, 0, 0,99,99,99, 0, 3, 0}, // FPToSI |
2439 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // UIToFP +- firstOp
2440 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // SIToFP |
2441 { 99,99,99, 0, 0,99,99, 0, 0,99,99, 4, 0}, // FPTrunc |
2442 { 99,99,99, 2, 2,99,99,10, 2,99,99, 4, 0}, // FPExt |
2443 { 1, 0, 0,99,99, 0, 0,99,99,99, 7, 3, 0}, // PtrToInt |
2444 { 99,99,99,99,99,99,99,99,99,11,99,15, 0}, // IntToPtr |
2445 { 5, 5, 5, 6, 6, 5, 5, 6, 6,16, 5, 1,14}, // BitCast |
2446 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,13,12}, // AddrSpaceCast -+
2449 // TODO: This logic could be encoded into the table above and handled in the
2451 // If either of the casts are a bitcast from scalar to vector, disallow the
2452 // merging. However, any pair of bitcasts are allowed.
2453 bool IsFirstBitcast = (firstOp == Instruction::BitCast);
2454 bool IsSecondBitcast = (secondOp == Instruction::BitCast);
2455 bool AreBothBitcasts = IsFirstBitcast && IsSecondBitcast;
2457 // Check if any of the casts convert scalars <-> vectors.
2458 if ((IsFirstBitcast && isa<VectorType>(SrcTy) != isa<VectorType>(MidTy)) ||
2459 (IsSecondBitcast && isa<VectorType>(MidTy) != isa<VectorType>(DstTy)))
2460 if (!AreBothBitcasts)
2463 int ElimCase = CastResults[firstOp-Instruction::CastOpsBegin]
2464 [secondOp-Instruction::CastOpsBegin];
2467 // Categorically disallowed.
2470 // Allowed, use first cast's opcode.
2473 // Allowed, use second cast's opcode.
2476 // No-op cast in second op implies firstOp as long as the DestTy
2477 // is integer and we are not converting between a vector and a
2479 if (!SrcTy->isVectorTy() && DstTy->isIntegerTy())
2483 // No-op cast in second op implies firstOp as long as the DestTy
2484 // is floating point.
2485 if (DstTy->isFloatingPointTy())
2489 // No-op cast in first op implies secondOp as long as the SrcTy
2491 if (SrcTy->isIntegerTy())
2495 // No-op cast in first op implies secondOp as long as the SrcTy
2496 // is a floating point.
2497 if (SrcTy->isFloatingPointTy())
2501 // Cannot simplify if address spaces are different!
2502 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2505 unsigned MidSize = MidTy->getScalarSizeInBits();
2506 // We can still fold this without knowing the actual sizes as long we
2507 // know that the intermediate pointer is the largest possible
2509 // FIXME: Is this always true?
2511 return Instruction::BitCast;
2513 // ptrtoint, inttoptr -> bitcast (ptr -> ptr) if int size is >= ptr size.
2514 if (!SrcIntPtrTy || DstIntPtrTy != SrcIntPtrTy)
2516 unsigned PtrSize = SrcIntPtrTy->getScalarSizeInBits();
2517 if (MidSize >= PtrSize)
2518 return Instruction::BitCast;
2522 // ext, trunc -> bitcast, if the SrcTy and DstTy are same size
2523 // ext, trunc -> ext, if sizeof(SrcTy) < sizeof(DstTy)
2524 // ext, trunc -> trunc, if sizeof(SrcTy) > sizeof(DstTy)
2525 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2526 unsigned DstSize = DstTy->getScalarSizeInBits();
2527 if (SrcSize == DstSize)
2528 return Instruction::BitCast;
2529 else if (SrcSize < DstSize)
2534 // zext, sext -> zext, because sext can't sign extend after zext
2535 return Instruction::ZExt;
2537 // fpext followed by ftrunc is allowed if the bit size returned to is
2538 // the same as the original, in which case its just a bitcast
2540 return Instruction::BitCast;
2541 return 0; // If the types are not the same we can't eliminate it.
2543 // inttoptr, ptrtoint -> bitcast if SrcSize<=PtrSize and SrcSize==DstSize
2546 unsigned PtrSize = MidIntPtrTy->getScalarSizeInBits();
2547 unsigned SrcSize = SrcTy->getScalarSizeInBits();
2548 unsigned DstSize = DstTy->getScalarSizeInBits();
2549 if (SrcSize <= PtrSize && SrcSize == DstSize)
2550 return Instruction::BitCast;
2554 // addrspacecast, addrspacecast -> bitcast, if SrcAS == DstAS
2555 // addrspacecast, addrspacecast -> addrspacecast, if SrcAS != DstAS
2556 if (SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace())
2557 return Instruction::AddrSpaceCast;
2558 return Instruction::BitCast;
2561 // FIXME: this state can be merged with (1), but the following assert
2562 // is useful to check the correcteness of the sequence due to semantic
2563 // change of bitcast.
2565 SrcTy->isPtrOrPtrVectorTy() &&
2566 MidTy->isPtrOrPtrVectorTy() &&
2567 DstTy->isPtrOrPtrVectorTy() &&
2568 SrcTy->getPointerAddressSpace() != MidTy->getPointerAddressSpace() &&
2569 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2570 "Illegal addrspacecast, bitcast sequence!");
2571 // Allowed, use first cast's opcode
2574 // bitcast, addrspacecast -> addrspacecast if the element type of
2575 // bitcast's source is the same as that of addrspacecast's destination.
2576 if (SrcTy->getScalarType()->getPointerElementType() ==
2577 DstTy->getScalarType()->getPointerElementType())
2578 return Instruction::AddrSpaceCast;
2582 // FIXME: this state can be merged with (1), but the following assert
2583 // is useful to check the correcteness of the sequence due to semantic
2584 // change of bitcast.
2586 SrcTy->isIntOrIntVectorTy() &&
2587 MidTy->isPtrOrPtrVectorTy() &&
2588 DstTy->isPtrOrPtrVectorTy() &&
2589 MidTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace() &&
2590 "Illegal inttoptr, bitcast sequence!");
2591 // Allowed, use first cast's opcode
2594 // FIXME: this state can be merged with (2), but the following assert
2595 // is useful to check the correcteness of the sequence due to semantic
2596 // change of bitcast.
2598 SrcTy->isPtrOrPtrVectorTy() &&
2599 MidTy->isPtrOrPtrVectorTy() &&
2600 DstTy->isIntOrIntVectorTy() &&
2601 SrcTy->getPointerAddressSpace() == MidTy->getPointerAddressSpace() &&
2602 "Illegal bitcast, ptrtoint sequence!");
2603 // Allowed, use second cast's opcode
2606 // (sitofp (zext x)) -> (uitofp x)
2607 return Instruction::UIToFP;
2609 // Cast combination can't happen (error in input). This is for all cases
2610 // where the MidTy is not the same for the two cast instructions.
2611 llvm_unreachable("Invalid Cast Combination");
2613 llvm_unreachable("Error in CastResults table!!!");
2617 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2618 const Twine &Name, Instruction *InsertBefore) {
2619 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2620 // Construct and return the appropriate CastInst subclass
2622 case Trunc: return new TruncInst (S, Ty, Name, InsertBefore);
2623 case ZExt: return new ZExtInst (S, Ty, Name, InsertBefore);
2624 case SExt: return new SExtInst (S, Ty, Name, InsertBefore);
2625 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertBefore);
2626 case FPExt: return new FPExtInst (S, Ty, Name, InsertBefore);
2627 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertBefore);
2628 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertBefore);
2629 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertBefore);
2630 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertBefore);
2631 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertBefore);
2632 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertBefore);
2633 case BitCast: return new BitCastInst (S, Ty, Name, InsertBefore);
2634 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertBefore);
2635 default: llvm_unreachable("Invalid opcode provided");
2639 CastInst *CastInst::Create(Instruction::CastOps op, Value *S, Type *Ty,
2640 const Twine &Name, BasicBlock *InsertAtEnd) {
2641 assert(castIsValid(op, S, Ty) && "Invalid cast!");
2642 // Construct and return the appropriate CastInst subclass
2644 case Trunc: return new TruncInst (S, Ty, Name, InsertAtEnd);
2645 case ZExt: return new ZExtInst (S, Ty, Name, InsertAtEnd);
2646 case SExt: return new SExtInst (S, Ty, Name, InsertAtEnd);
2647 case FPTrunc: return new FPTruncInst (S, Ty, Name, InsertAtEnd);
2648 case FPExt: return new FPExtInst (S, Ty, Name, InsertAtEnd);
2649 case UIToFP: return new UIToFPInst (S, Ty, Name, InsertAtEnd);
2650 case SIToFP: return new SIToFPInst (S, Ty, Name, InsertAtEnd);
2651 case FPToUI: return new FPToUIInst (S, Ty, Name, InsertAtEnd);
2652 case FPToSI: return new FPToSIInst (S, Ty, Name, InsertAtEnd);
2653 case PtrToInt: return new PtrToIntInst (S, Ty, Name, InsertAtEnd);
2654 case IntToPtr: return new IntToPtrInst (S, Ty, Name, InsertAtEnd);
2655 case BitCast: return new BitCastInst (S, Ty, Name, InsertAtEnd);
2656 case AddrSpaceCast: return new AddrSpaceCastInst (S, Ty, Name, InsertAtEnd);
2657 default: llvm_unreachable("Invalid opcode provided");
2661 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2663 Instruction *InsertBefore) {
2664 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2665 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2666 return Create(Instruction::ZExt, S, Ty, Name, InsertBefore);
2669 CastInst *CastInst::CreateZExtOrBitCast(Value *S, Type *Ty,
2671 BasicBlock *InsertAtEnd) {
2672 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2673 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2674 return Create(Instruction::ZExt, S, Ty, Name, InsertAtEnd);
2677 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2679 Instruction *InsertBefore) {
2680 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2681 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2682 return Create(Instruction::SExt, S, Ty, Name, InsertBefore);
2685 CastInst *CastInst::CreateSExtOrBitCast(Value *S, Type *Ty,
2687 BasicBlock *InsertAtEnd) {
2688 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2689 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2690 return Create(Instruction::SExt, S, Ty, Name, InsertAtEnd);
2693 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2695 Instruction *InsertBefore) {
2696 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2697 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2698 return Create(Instruction::Trunc, S, Ty, Name, InsertBefore);
2701 CastInst *CastInst::CreateTruncOrBitCast(Value *S, Type *Ty,
2703 BasicBlock *InsertAtEnd) {
2704 if (S->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
2705 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2706 return Create(Instruction::Trunc, S, Ty, Name, InsertAtEnd);
2709 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2711 BasicBlock *InsertAtEnd) {
2712 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2713 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2715 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2716 assert((!Ty->isVectorTy() ||
2717 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2720 if (Ty->isIntOrIntVectorTy())
2721 return Create(Instruction::PtrToInt, S, Ty, Name, InsertAtEnd);
2723 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertAtEnd);
2726 /// @brief Create a BitCast or a PtrToInt cast instruction
2727 CastInst *CastInst::CreatePointerCast(Value *S, Type *Ty,
2729 Instruction *InsertBefore) {
2730 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2731 assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
2733 assert(Ty->isVectorTy() == S->getType()->isVectorTy() && "Invalid cast");
2734 assert((!Ty->isVectorTy() ||
2735 Ty->getVectorNumElements() == S->getType()->getVectorNumElements()) &&
2738 if (Ty->isIntOrIntVectorTy())
2739 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2741 return CreatePointerBitCastOrAddrSpaceCast(S, Ty, Name, InsertBefore);
2744 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2747 BasicBlock *InsertAtEnd) {
2748 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2749 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2751 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2752 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertAtEnd);
2754 return Create(Instruction::BitCast, S, Ty, Name, InsertAtEnd);
2757 CastInst *CastInst::CreatePointerBitCastOrAddrSpaceCast(
2760 Instruction *InsertBefore) {
2761 assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
2762 assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
2764 if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
2765 return Create(Instruction::AddrSpaceCast, S, Ty, Name, InsertBefore);
2767 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2770 CastInst *CastInst::CreateBitOrPointerCast(Value *S, Type *Ty,
2772 Instruction *InsertBefore) {
2773 if (S->getType()->isPointerTy() && Ty->isIntegerTy())
2774 return Create(Instruction::PtrToInt, S, Ty, Name, InsertBefore);
2775 if (S->getType()->isIntegerTy() && Ty->isPointerTy())
2776 return Create(Instruction::IntToPtr, S, Ty, Name, InsertBefore);
2778 return Create(Instruction::BitCast, S, Ty, Name, InsertBefore);
2781 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2782 bool isSigned, const Twine &Name,
2783 Instruction *InsertBefore) {
2784 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2785 "Invalid integer cast");
2786 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2787 unsigned DstBits = Ty->getScalarSizeInBits();
2788 Instruction::CastOps opcode =
2789 (SrcBits == DstBits ? Instruction::BitCast :
2790 (SrcBits > DstBits ? Instruction::Trunc :
2791 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2792 return Create(opcode, C, Ty, Name, InsertBefore);
2795 CastInst *CastInst::CreateIntegerCast(Value *C, Type *Ty,
2796 bool isSigned, const Twine &Name,
2797 BasicBlock *InsertAtEnd) {
2798 assert(C->getType()->isIntOrIntVectorTy() && Ty->isIntOrIntVectorTy() &&
2800 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2801 unsigned DstBits = Ty->getScalarSizeInBits();
2802 Instruction::CastOps opcode =
2803 (SrcBits == DstBits ? Instruction::BitCast :
2804 (SrcBits > DstBits ? Instruction::Trunc :
2805 (isSigned ? Instruction::SExt : Instruction::ZExt)));
2806 return Create(opcode, C, Ty, Name, InsertAtEnd);
2809 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2811 Instruction *InsertBefore) {
2812 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2814 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2815 unsigned DstBits = Ty->getScalarSizeInBits();
2816 Instruction::CastOps opcode =
2817 (SrcBits == DstBits ? Instruction::BitCast :
2818 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2819 return Create(opcode, C, Ty, Name, InsertBefore);
2822 CastInst *CastInst::CreateFPCast(Value *C, Type *Ty,
2824 BasicBlock *InsertAtEnd) {
2825 assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
2827 unsigned SrcBits = C->getType()->getScalarSizeInBits();
2828 unsigned DstBits = Ty->getScalarSizeInBits();
2829 Instruction::CastOps opcode =
2830 (SrcBits == DstBits ? Instruction::BitCast :
2831 (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt));
2832 return Create(opcode, C, Ty, Name, InsertAtEnd);
2835 // Check whether it is valid to call getCastOpcode for these types.
2836 // This routine must be kept in sync with getCastOpcode.
2837 bool CastInst::isCastable(Type *SrcTy, Type *DestTy) {
2838 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2841 if (SrcTy == DestTy)
2844 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2845 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2846 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2847 // An element by element cast. Valid if casting the elements is valid.
2848 SrcTy = SrcVecTy->getElementType();
2849 DestTy = DestVecTy->getElementType();
2852 // Get the bit sizes, we'll need these
2853 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2854 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2856 // Run through the possibilities ...
2857 if (DestTy->isIntegerTy()) { // Casting to integral
2858 if (SrcTy->isIntegerTy()) // Casting from integral
2860 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2862 if (SrcTy->isVectorTy()) // Casting from vector
2863 return DestBits == SrcBits;
2864 // Casting from something else
2865 return SrcTy->isPointerTy();
2867 if (DestTy->isFloatingPointTy()) { // Casting to floating pt
2868 if (SrcTy->isIntegerTy()) // Casting from integral
2870 if (SrcTy->isFloatingPointTy()) // Casting from floating pt
2872 if (SrcTy->isVectorTy()) // Casting from vector
2873 return DestBits == SrcBits;
2874 // Casting from something else
2877 if (DestTy->isVectorTy()) // Casting to vector
2878 return DestBits == SrcBits;
2879 if (DestTy->isPointerTy()) { // Casting to pointer
2880 if (SrcTy->isPointerTy()) // Casting from pointer
2882 return SrcTy->isIntegerTy(); // Casting from integral
2884 if (DestTy->isX86_MMXTy()) {
2885 if (SrcTy->isVectorTy())
2886 return DestBits == SrcBits; // 64-bit vector to MMX
2888 } // Casting to something else
2892 bool CastInst::isBitCastable(Type *SrcTy, Type *DestTy) {
2893 if (!SrcTy->isFirstClassType() || !DestTy->isFirstClassType())
2896 if (SrcTy == DestTy)
2899 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
2900 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy)) {
2901 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2902 // An element by element cast. Valid if casting the elements is valid.
2903 SrcTy = SrcVecTy->getElementType();
2904 DestTy = DestVecTy->getElementType();
2909 if (PointerType *DestPtrTy = dyn_cast<PointerType>(DestTy)) {
2910 if (PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy)) {
2911 return SrcPtrTy->getAddressSpace() == DestPtrTy->getAddressSpace();
2915 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2916 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2918 // Could still have vectors of pointers if the number of elements doesn't
2920 if (SrcBits == 0 || DestBits == 0)
2923 if (SrcBits != DestBits)
2926 if (DestTy->isX86_MMXTy() || SrcTy->isX86_MMXTy())
2932 bool CastInst::isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy,
2933 const DataLayout &DL) {
2934 if (auto *PtrTy = dyn_cast<PointerType>(SrcTy))
2935 if (auto *IntTy = dyn_cast<IntegerType>(DestTy))
2936 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2937 if (auto *PtrTy = dyn_cast<PointerType>(DestTy))
2938 if (auto *IntTy = dyn_cast<IntegerType>(SrcTy))
2939 return IntTy->getBitWidth() == DL.getPointerTypeSizeInBits(PtrTy);
2941 return isBitCastable(SrcTy, DestTy);
2944 // Provide a way to get a "cast" where the cast opcode is inferred from the
2945 // types and size of the operand. This, basically, is a parallel of the
2946 // logic in the castIsValid function below. This axiom should hold:
2947 // castIsValid( getCastOpcode(Val, Ty), Val, Ty)
2948 // should not assert in castIsValid. In other words, this produces a "correct"
2949 // casting opcode for the arguments passed to it.
2950 // This routine must be kept in sync with isCastable.
2951 Instruction::CastOps
2952 CastInst::getCastOpcode(
2953 const Value *Src, bool SrcIsSigned, Type *DestTy, bool DestIsSigned) {
2954 Type *SrcTy = Src->getType();
2956 assert(SrcTy->isFirstClassType() && DestTy->isFirstClassType() &&
2957 "Only first class types are castable!");
2959 if (SrcTy == DestTy)
2962 // FIXME: Check address space sizes here
2963 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy))
2964 if (VectorType *DestVecTy = dyn_cast<VectorType>(DestTy))
2965 if (SrcVecTy->getNumElements() == DestVecTy->getNumElements()) {
2966 // An element by element cast. Find the appropriate opcode based on the
2968 SrcTy = SrcVecTy->getElementType();
2969 DestTy = DestVecTy->getElementType();
2972 // Get the bit sizes, we'll need these
2973 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); // 0 for ptr
2974 unsigned DestBits = DestTy->getPrimitiveSizeInBits(); // 0 for ptr
2976 // Run through the possibilities ...
2977 if (DestTy->isIntegerTy()) { // Casting to integral
2978 if (SrcTy->isIntegerTy()) { // Casting from integral
2979 if (DestBits < SrcBits)
2980 return Trunc; // int -> smaller int
2981 else if (DestBits > SrcBits) { // its an extension
2983 return SExt; // signed -> SEXT
2985 return ZExt; // unsigned -> ZEXT
2987 return BitCast; // Same size, No-op cast
2989 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
2991 return FPToSI; // FP -> sint
2993 return FPToUI; // FP -> uint
2994 } else if (SrcTy->isVectorTy()) {
2995 assert(DestBits == SrcBits &&
2996 "Casting vector to integer of different width");
2997 return BitCast; // Same size, no-op cast
2999 assert(SrcTy->isPointerTy() &&
3000 "Casting from a value that is not first-class type");
3001 return PtrToInt; // ptr -> int
3003 } else if (DestTy->isFloatingPointTy()) { // Casting to floating pt
3004 if (SrcTy->isIntegerTy()) { // Casting from integral
3006 return SIToFP; // sint -> FP
3008 return UIToFP; // uint -> FP
3009 } else if (SrcTy->isFloatingPointTy()) { // Casting from floating pt
3010 if (DestBits < SrcBits) {
3011 return FPTrunc; // FP -> smaller FP
3012 } else if (DestBits > SrcBits) {
3013 return FPExt; // FP -> larger FP
3015 return BitCast; // same size, no-op cast
3017 } else if (SrcTy->isVectorTy()) {
3018 assert(DestBits == SrcBits &&
3019 "Casting vector to floating point of different width");
3020 return BitCast; // same size, no-op cast
3022 llvm_unreachable("Casting pointer or non-first class to float");
3023 } else if (DestTy->isVectorTy()) {
3024 assert(DestBits == SrcBits &&
3025 "Illegal cast to vector (wrong type or size)");
3027 } else if (DestTy->isPointerTy()) {
3028 if (SrcTy->isPointerTy()) {
3029 if (DestTy->getPointerAddressSpace() != SrcTy->getPointerAddressSpace())
3030 return AddrSpaceCast;
3031 return BitCast; // ptr -> ptr
3032 } else if (SrcTy->isIntegerTy()) {
3033 return IntToPtr; // int -> ptr
3035 llvm_unreachable("Casting pointer to other than pointer or int");
3036 } else if (DestTy->isX86_MMXTy()) {
3037 if (SrcTy->isVectorTy()) {
3038 assert(DestBits == SrcBits && "Casting vector of wrong width to X86_MMX");
3039 return BitCast; // 64-bit vector to MMX
3041 llvm_unreachable("Illegal cast to X86_MMX");
3043 llvm_unreachable("Casting to type that is not first-class");
3046 //===----------------------------------------------------------------------===//
3047 // CastInst SubClass Constructors
3048 //===----------------------------------------------------------------------===//
3050 /// Check that the construction parameters for a CastInst are correct. This
3051 /// could be broken out into the separate constructors but it is useful to have
3052 /// it in one place and to eliminate the redundant code for getting the sizes
3053 /// of the types involved.
3055 CastInst::castIsValid(Instruction::CastOps op, Value *S, Type *DstTy) {
3057 // Check for type sanity on the arguments
3058 Type *SrcTy = S->getType();
3060 if (!SrcTy->isFirstClassType() || !DstTy->isFirstClassType() ||
3061 SrcTy->isAggregateType() || DstTy->isAggregateType())
3064 // Get the size of the types in bits, we'll need this later
3065 unsigned SrcBitSize = SrcTy->getScalarSizeInBits();
3066 unsigned DstBitSize = DstTy->getScalarSizeInBits();
3068 // If these are vector types, get the lengths of the vectors (using zero for
3069 // scalar types means that checking that vector lengths match also checks that
3070 // scalars are not being converted to vectors or vectors to scalars).
3071 unsigned SrcLength = SrcTy->isVectorTy() ?
3072 cast<VectorType>(SrcTy)->getNumElements() : 0;
3073 unsigned DstLength = DstTy->isVectorTy() ?
3074 cast<VectorType>(DstTy)->getNumElements() : 0;
3076 // Switch on the opcode provided
3078 default: return false; // This is an input error
3079 case Instruction::Trunc:
3080 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3081 SrcLength == DstLength && SrcBitSize > DstBitSize;
3082 case Instruction::ZExt:
3083 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3084 SrcLength == DstLength && SrcBitSize < DstBitSize;
3085 case Instruction::SExt:
3086 return SrcTy->isIntOrIntVectorTy() && DstTy->isIntOrIntVectorTy() &&
3087 SrcLength == DstLength && SrcBitSize < DstBitSize;
3088 case Instruction::FPTrunc:
3089 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3090 SrcLength == DstLength && SrcBitSize > DstBitSize;
3091 case Instruction::FPExt:
3092 return SrcTy->isFPOrFPVectorTy() && DstTy->isFPOrFPVectorTy() &&
3093 SrcLength == DstLength && SrcBitSize < DstBitSize;
3094 case Instruction::UIToFP:
3095 case Instruction::SIToFP:
3096 return SrcTy->isIntOrIntVectorTy() && DstTy->isFPOrFPVectorTy() &&
3097 SrcLength == DstLength;
3098 case Instruction::FPToUI:
3099 case Instruction::FPToSI:
3100 return SrcTy->isFPOrFPVectorTy() && DstTy->isIntOrIntVectorTy() &&
3101 SrcLength == DstLength;
3102 case Instruction::PtrToInt:
3103 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3105 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3106 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3108 return SrcTy->getScalarType()->isPointerTy() &&
3109 DstTy->getScalarType()->isIntegerTy();
3110 case Instruction::IntToPtr:
3111 if (isa<VectorType>(SrcTy) != isa<VectorType>(DstTy))
3113 if (VectorType *VT = dyn_cast<VectorType>(SrcTy))
3114 if (VT->getNumElements() != cast<VectorType>(DstTy)->getNumElements())
3116 return SrcTy->getScalarType()->isIntegerTy() &&
3117 DstTy->getScalarType()->isPointerTy();
3118 case Instruction::BitCast: {
3119 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3120 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3122 // BitCast implies a no-op cast of type only. No bits change.
3123 // However, you can't cast pointers to anything but pointers.
3124 if (!SrcPtrTy != !DstPtrTy)
3127 // For non-pointer cases, the cast is okay if the source and destination bit
3128 // widths are identical.
3130 return SrcTy->getPrimitiveSizeInBits() == DstTy->getPrimitiveSizeInBits();
3132 // If both are pointers then the address spaces must match.
3133 if (SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace())
3136 // A vector of pointers must have the same number of elements.
3137 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3138 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3139 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3146 case Instruction::AddrSpaceCast: {
3147 PointerType *SrcPtrTy = dyn_cast<PointerType>(SrcTy->getScalarType());
3151 PointerType *DstPtrTy = dyn_cast<PointerType>(DstTy->getScalarType());
3155 if (SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
3158 if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcTy)) {
3159 if (VectorType *DstVecTy = dyn_cast<VectorType>(DstTy))
3160 return (SrcVecTy->getNumElements() == DstVecTy->getNumElements());
3170 TruncInst::TruncInst(
3171 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3172 ) : CastInst(Ty, Trunc, S, Name, InsertBefore) {
3173 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3176 TruncInst::TruncInst(
3177 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3178 ) : CastInst(Ty, Trunc, S, Name, InsertAtEnd) {
3179 assert(castIsValid(getOpcode(), S, Ty) && "Illegal Trunc");
3183 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3184 ) : CastInst(Ty, ZExt, S, Name, InsertBefore) {
3185 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3189 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3190 ) : CastInst(Ty, ZExt, S, Name, InsertAtEnd) {
3191 assert(castIsValid(getOpcode(), S, Ty) && "Illegal ZExt");
3194 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3195 ) : CastInst(Ty, SExt, S, Name, InsertBefore) {
3196 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3200 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3201 ) : CastInst(Ty, SExt, S, Name, InsertAtEnd) {
3202 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SExt");
3205 FPTruncInst::FPTruncInst(
3206 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3207 ) : CastInst(Ty, FPTrunc, S, Name, InsertBefore) {
3208 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3211 FPTruncInst::FPTruncInst(
3212 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3213 ) : CastInst(Ty, FPTrunc, S, Name, InsertAtEnd) {
3214 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPTrunc");
3217 FPExtInst::FPExtInst(
3218 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3219 ) : CastInst(Ty, FPExt, S, Name, InsertBefore) {
3220 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3223 FPExtInst::FPExtInst(
3224 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3225 ) : CastInst(Ty, FPExt, S, Name, InsertAtEnd) {
3226 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPExt");
3229 UIToFPInst::UIToFPInst(
3230 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3231 ) : CastInst(Ty, UIToFP, S, Name, InsertBefore) {
3232 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3235 UIToFPInst::UIToFPInst(
3236 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3237 ) : CastInst(Ty, UIToFP, S, Name, InsertAtEnd) {
3238 assert(castIsValid(getOpcode(), S, Ty) && "Illegal UIToFP");
3241 SIToFPInst::SIToFPInst(
3242 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3243 ) : CastInst(Ty, SIToFP, S, Name, InsertBefore) {
3244 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3247 SIToFPInst::SIToFPInst(
3248 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3249 ) : CastInst(Ty, SIToFP, S, Name, InsertAtEnd) {
3250 assert(castIsValid(getOpcode(), S, Ty) && "Illegal SIToFP");
3253 FPToUIInst::FPToUIInst(
3254 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3255 ) : CastInst(Ty, FPToUI, S, Name, InsertBefore) {
3256 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3259 FPToUIInst::FPToUIInst(
3260 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3261 ) : CastInst(Ty, FPToUI, S, Name, InsertAtEnd) {
3262 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToUI");
3265 FPToSIInst::FPToSIInst(
3266 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3267 ) : CastInst(Ty, FPToSI, S, Name, InsertBefore) {
3268 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3271 FPToSIInst::FPToSIInst(
3272 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3273 ) : CastInst(Ty, FPToSI, S, Name, InsertAtEnd) {
3274 assert(castIsValid(getOpcode(), S, Ty) && "Illegal FPToSI");
3277 PtrToIntInst::PtrToIntInst(
3278 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3279 ) : CastInst(Ty, PtrToInt, S, Name, InsertBefore) {
3280 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3283 PtrToIntInst::PtrToIntInst(
3284 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3285 ) : CastInst(Ty, PtrToInt, S, Name, InsertAtEnd) {
3286 assert(castIsValid(getOpcode(), S, Ty) && "Illegal PtrToInt");
3289 IntToPtrInst::IntToPtrInst(
3290 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3291 ) : CastInst(Ty, IntToPtr, S, Name, InsertBefore) {
3292 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3295 IntToPtrInst::IntToPtrInst(
3296 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3297 ) : CastInst(Ty, IntToPtr, S, Name, InsertAtEnd) {
3298 assert(castIsValid(getOpcode(), S, Ty) && "Illegal IntToPtr");
3301 BitCastInst::BitCastInst(
3302 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3303 ) : CastInst(Ty, BitCast, S, Name, InsertBefore) {
3304 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3307 BitCastInst::BitCastInst(
3308 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3309 ) : CastInst(Ty, BitCast, S, Name, InsertAtEnd) {
3310 assert(castIsValid(getOpcode(), S, Ty) && "Illegal BitCast");
3313 AddrSpaceCastInst::AddrSpaceCastInst(
3314 Value *S, Type *Ty, const Twine &Name, Instruction *InsertBefore
3315 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertBefore) {
3316 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3319 AddrSpaceCastInst::AddrSpaceCastInst(
3320 Value *S, Type *Ty, const Twine &Name, BasicBlock *InsertAtEnd
3321 ) : CastInst(Ty, AddrSpaceCast, S, Name, InsertAtEnd) {
3322 assert(castIsValid(getOpcode(), S, Ty) && "Illegal AddrSpaceCast");
3325 //===----------------------------------------------------------------------===//
3327 //===----------------------------------------------------------------------===//
3329 void CmpInst::anchor() {}
3331 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3332 Value *RHS, const Twine &Name, Instruction *InsertBefore)
3333 : Instruction(ty, op,
3334 OperandTraits<CmpInst>::op_begin(this),
3335 OperandTraits<CmpInst>::operands(this),
3339 setPredicate((Predicate)predicate);
3343 CmpInst::CmpInst(Type *ty, OtherOps op, Predicate predicate, Value *LHS,
3344 Value *RHS, const Twine &Name, BasicBlock *InsertAtEnd)
3345 : Instruction(ty, op,
3346 OperandTraits<CmpInst>::op_begin(this),
3347 OperandTraits<CmpInst>::operands(this),
3351 setPredicate((Predicate)predicate);
3356 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3357 const Twine &Name, Instruction *InsertBefore) {
3358 if (Op == Instruction::ICmp) {
3360 return new ICmpInst(InsertBefore, CmpInst::Predicate(predicate),
3363 return new ICmpInst(CmpInst::Predicate(predicate),
3368 return new FCmpInst(InsertBefore, CmpInst::Predicate(predicate),
3371 return new FCmpInst(CmpInst::Predicate(predicate),
3376 CmpInst::Create(OtherOps Op, Predicate predicate, Value *S1, Value *S2,
3377 const Twine &Name, BasicBlock *InsertAtEnd) {
3378 if (Op == Instruction::ICmp) {
3379 return new ICmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3382 return new FCmpInst(*InsertAtEnd, CmpInst::Predicate(predicate),
3386 void CmpInst::swapOperands() {
3387 if (ICmpInst *IC = dyn_cast<ICmpInst>(this))
3390 cast<FCmpInst>(this)->swapOperands();
3393 bool CmpInst::isCommutative() const {
3394 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3395 return IC->isCommutative();
3396 return cast<FCmpInst>(this)->isCommutative();
3399 bool CmpInst::isEquality() const {
3400 if (const ICmpInst *IC = dyn_cast<ICmpInst>(this))
3401 return IC->isEquality();
3402 return cast<FCmpInst>(this)->isEquality();
3406 CmpInst::Predicate CmpInst::getInversePredicate(Predicate pred) {
3408 default: llvm_unreachable("Unknown cmp predicate!");
3409 case ICMP_EQ: return ICMP_NE;
3410 case ICMP_NE: return ICMP_EQ;
3411 case ICMP_UGT: return ICMP_ULE;
3412 case ICMP_ULT: return ICMP_UGE;
3413 case ICMP_UGE: return ICMP_ULT;
3414 case ICMP_ULE: return ICMP_UGT;
3415 case ICMP_SGT: return ICMP_SLE;
3416 case ICMP_SLT: return ICMP_SGE;
3417 case ICMP_SGE: return ICMP_SLT;
3418 case ICMP_SLE: return ICMP_SGT;
3420 case FCMP_OEQ: return FCMP_UNE;
3421 case FCMP_ONE: return FCMP_UEQ;
3422 case FCMP_OGT: return FCMP_ULE;
3423 case FCMP_OLT: return FCMP_UGE;
3424 case FCMP_OGE: return FCMP_ULT;
3425 case FCMP_OLE: return FCMP_UGT;
3426 case FCMP_UEQ: return FCMP_ONE;
3427 case FCMP_UNE: return FCMP_OEQ;
3428 case FCMP_UGT: return FCMP_OLE;
3429 case FCMP_ULT: return FCMP_OGE;
3430 case FCMP_UGE: return FCMP_OLT;
3431 case FCMP_ULE: return FCMP_OGT;
3432 case FCMP_ORD: return FCMP_UNO;
3433 case FCMP_UNO: return FCMP_ORD;
3434 case FCMP_TRUE: return FCMP_FALSE;
3435 case FCMP_FALSE: return FCMP_TRUE;
3439 StringRef CmpInst::getPredicateName(Predicate Pred) {
3441 default: return "unknown";
3442 case FCmpInst::FCMP_FALSE: return "false";
3443 case FCmpInst::FCMP_OEQ: return "oeq";
3444 case FCmpInst::FCMP_OGT: return "ogt";
3445 case FCmpInst::FCMP_OGE: return "oge";
3446 case FCmpInst::FCMP_OLT: return "olt";
3447 case FCmpInst::FCMP_OLE: return "ole";
3448 case FCmpInst::FCMP_ONE: return "one";
3449 case FCmpInst::FCMP_ORD: return "ord";
3450 case FCmpInst::FCMP_UNO: return "uno";
3451 case FCmpInst::FCMP_UEQ: return "ueq";
3452 case FCmpInst::FCMP_UGT: return "ugt";
3453 case FCmpInst::FCMP_UGE: return "uge";
3454 case FCmpInst::FCMP_ULT: return "ult";
3455 case FCmpInst::FCMP_ULE: return "ule";
3456 case FCmpInst::FCMP_UNE: return "une";
3457 case FCmpInst::FCMP_TRUE: return "true";
3458 case ICmpInst::ICMP_EQ: return "eq";
3459 case ICmpInst::ICMP_NE: return "ne";
3460 case ICmpInst::ICMP_SGT: return "sgt";
3461 case ICmpInst::ICMP_SGE: return "sge";
3462 case ICmpInst::ICMP_SLT: return "slt";
3463 case ICmpInst::ICMP_SLE: return "sle";
3464 case ICmpInst::ICMP_UGT: return "ugt";
3465 case ICmpInst::ICMP_UGE: return "uge";
3466 case ICmpInst::ICMP_ULT: return "ult";
3467 case ICmpInst::ICMP_ULE: return "ule";
3471 void ICmpInst::anchor() {}
3473 ICmpInst::Predicate ICmpInst::getSignedPredicate(Predicate pred) {
3475 default: llvm_unreachable("Unknown icmp predicate!");
3476 case ICMP_EQ: case ICMP_NE:
3477 case ICMP_SGT: case ICMP_SLT: case ICMP_SGE: case ICMP_SLE:
3479 case ICMP_UGT: return ICMP_SGT;
3480 case ICMP_ULT: return ICMP_SLT;
3481 case ICMP_UGE: return ICMP_SGE;
3482 case ICMP_ULE: return ICMP_SLE;
3486 ICmpInst::Predicate ICmpInst::getUnsignedPredicate(Predicate pred) {
3488 default: llvm_unreachable("Unknown icmp predicate!");
3489 case ICMP_EQ: case ICMP_NE:
3490 case ICMP_UGT: case ICMP_ULT: case ICMP_UGE: case ICMP_ULE:
3492 case ICMP_SGT: return ICMP_UGT;
3493 case ICMP_SLT: return ICMP_ULT;
3494 case ICMP_SGE: return ICMP_UGE;
3495 case ICMP_SLE: return ICMP_ULE;
3499 CmpInst::Predicate CmpInst::getSwappedPredicate(Predicate pred) {
3501 default: llvm_unreachable("Unknown cmp predicate!");
3502 case ICMP_EQ: case ICMP_NE:
3504 case ICMP_SGT: return ICMP_SLT;
3505 case ICMP_SLT: return ICMP_SGT;
3506 case ICMP_SGE: return ICMP_SLE;
3507 case ICMP_SLE: return ICMP_SGE;
3508 case ICMP_UGT: return ICMP_ULT;
3509 case ICMP_ULT: return ICMP_UGT;
3510 case ICMP_UGE: return ICMP_ULE;
3511 case ICMP_ULE: return ICMP_UGE;
3513 case FCMP_FALSE: case FCMP_TRUE:
3514 case FCMP_OEQ: case FCMP_ONE:
3515 case FCMP_UEQ: case FCMP_UNE:
3516 case FCMP_ORD: case FCMP_UNO:
3518 case FCMP_OGT: return FCMP_OLT;
3519 case FCMP_OLT: return FCMP_OGT;
3520 case FCMP_OGE: return FCMP_OLE;
3521 case FCMP_OLE: return FCMP_OGE;
3522 case FCMP_UGT: return FCMP_ULT;
3523 case FCMP_ULT: return FCMP_UGT;
3524 case FCMP_UGE: return FCMP_ULE;
3525 case FCMP_ULE: return FCMP_UGE;
3529 CmpInst::Predicate CmpInst::getSignedPredicate(Predicate pred) {
3530 assert(CmpInst::isUnsigned(pred) && "Call only with signed predicates!");
3534 llvm_unreachable("Unknown predicate!");
3535 case CmpInst::ICMP_ULT:
3536 return CmpInst::ICMP_SLT;
3537 case CmpInst::ICMP_ULE:
3538 return CmpInst::ICMP_SLE;
3539 case CmpInst::ICMP_UGT:
3540 return CmpInst::ICMP_SGT;
3541 case CmpInst::ICMP_UGE:
3542 return CmpInst::ICMP_SGE;
3546 bool CmpInst::isUnsigned(Predicate predicate) {
3547 switch (predicate) {
3548 default: return false;
3549 case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_ULE: case ICmpInst::ICMP_UGT:
3550 case ICmpInst::ICMP_UGE: return true;
3554 bool CmpInst::isSigned(Predicate predicate) {
3555 switch (predicate) {
3556 default: return false;
3557 case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_SLE: case ICmpInst::ICMP_SGT:
3558 case ICmpInst::ICMP_SGE: return true;
3562 bool CmpInst::isOrdered(Predicate predicate) {
3563 switch (predicate) {
3564 default: return false;
3565 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_OGT:
3566 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_OLE:
3567 case FCmpInst::FCMP_ORD: return true;
3571 bool CmpInst::isUnordered(Predicate predicate) {
3572 switch (predicate) {
3573 default: return false;
3574 case FCmpInst::FCMP_UEQ: case FCmpInst::FCMP_UNE: case FCmpInst::FCMP_UGT:
3575 case FCmpInst::FCMP_ULT: case FCmpInst::FCMP_UGE: case FCmpInst::FCMP_ULE:
3576 case FCmpInst::FCMP_UNO: return true;
3580 bool CmpInst::isTrueWhenEqual(Predicate predicate) {
3582 default: return false;
3583 case ICMP_EQ: case ICMP_UGE: case ICMP_ULE: case ICMP_SGE: case ICMP_SLE:
3584 case FCMP_TRUE: case FCMP_UEQ: case FCMP_UGE: case FCMP_ULE: return true;
3588 bool CmpInst::isFalseWhenEqual(Predicate predicate) {
3590 case ICMP_NE: case ICMP_UGT: case ICMP_ULT: case ICMP_SGT: case ICMP_SLT:
3591 case FCMP_FALSE: case FCMP_ONE: case FCMP_OGT: case FCMP_OLT: return true;
3592 default: return false;
3596 bool CmpInst::isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3597 // If the predicates match, then we know the first condition implies the
3606 // A == B implies A >=u B, A <=u B, A >=s B, and A <=s B are true.
3607 return Pred2 == ICMP_UGE || Pred2 == ICMP_ULE || Pred2 == ICMP_SGE ||
3609 case ICMP_UGT: // A >u B implies A != B and A >=u B are true.
3610 return Pred2 == ICMP_NE || Pred2 == ICMP_UGE;
3611 case ICMP_ULT: // A <u B implies A != B and A <=u B are true.
3612 return Pred2 == ICMP_NE || Pred2 == ICMP_ULE;
3613 case ICMP_SGT: // A >s B implies A != B and A >=s B are true.
3614 return Pred2 == ICMP_NE || Pred2 == ICMP_SGE;
3615 case ICMP_SLT: // A <s B implies A != B and A <=s B are true.
3616 return Pred2 == ICMP_NE || Pred2 == ICMP_SLE;
3621 bool CmpInst::isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2) {
3622 return isImpliedTrueByMatchingCmp(Pred1, getInversePredicate(Pred2));
3625 //===----------------------------------------------------------------------===//
3626 // SwitchInst Implementation
3627 //===----------------------------------------------------------------------===//
3629 void SwitchInst::init(Value *Value, BasicBlock *Default, unsigned NumReserved) {
3630 assert(Value && Default && NumReserved);
3631 ReservedSpace = NumReserved;
3632 setNumHungOffUseOperands(2);
3633 allocHungoffUses(ReservedSpace);
3639 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3640 /// switch on and a default destination. The number of additional cases can
3641 /// be specified here to make memory allocation more efficient. This
3642 /// constructor can also autoinsert before another instruction.
3643 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3644 Instruction *InsertBefore)
3645 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3646 nullptr, 0, InsertBefore) {
3647 init(Value, Default, 2+NumCases*2);
3650 /// SwitchInst ctor - Create a new switch instruction, specifying a value to
3651 /// switch on and a default destination. The number of additional cases can
3652 /// be specified here to make memory allocation more efficient. This
3653 /// constructor also autoinserts at the end of the specified BasicBlock.
3654 SwitchInst::SwitchInst(Value *Value, BasicBlock *Default, unsigned NumCases,
3655 BasicBlock *InsertAtEnd)
3656 : TerminatorInst(Type::getVoidTy(Value->getContext()), Instruction::Switch,
3657 nullptr, 0, InsertAtEnd) {
3658 init(Value, Default, 2+NumCases*2);
3661 SwitchInst::SwitchInst(const SwitchInst &SI)
3662 : TerminatorInst(SI.getType(), Instruction::Switch, nullptr, 0) {
3663 init(SI.getCondition(), SI.getDefaultDest(), SI.getNumOperands());
3664 setNumHungOffUseOperands(SI.getNumOperands());
3665 Use *OL = getOperandList();
3666 const Use *InOL = SI.getOperandList();
3667 for (unsigned i = 2, E = SI.getNumOperands(); i != E; i += 2) {
3669 OL[i+1] = InOL[i+1];
3671 SubclassOptionalData = SI.SubclassOptionalData;
3675 /// addCase - Add an entry to the switch instruction...
3677 void SwitchInst::addCase(ConstantInt *OnVal, BasicBlock *Dest) {
3678 unsigned NewCaseIdx = getNumCases();
3679 unsigned OpNo = getNumOperands();
3680 if (OpNo+2 > ReservedSpace)
3681 growOperands(); // Get more space!
3682 // Initialize some new operands.
3683 assert(OpNo+1 < ReservedSpace && "Growing didn't work!");
3684 setNumHungOffUseOperands(OpNo+2);
3685 CaseHandle Case(this, NewCaseIdx);
3686 Case.setValue(OnVal);
3687 Case.setSuccessor(Dest);
3690 /// removeCase - This method removes the specified case and its successor
3691 /// from the switch instruction.
3692 SwitchInst::CaseIt SwitchInst::removeCase(CaseIt I) {
3693 unsigned idx = I->getCaseIndex();
3695 assert(2 + idx*2 < getNumOperands() && "Case index out of range!!!");
3697 unsigned NumOps = getNumOperands();
3698 Use *OL = getOperandList();
3700 // Overwrite this case with the end of the list.
3701 if (2 + (idx + 1) * 2 != NumOps) {
3702 OL[2 + idx * 2] = OL[NumOps - 2];
3703 OL[2 + idx * 2 + 1] = OL[NumOps - 1];
3706 // Nuke the last value.
3707 OL[NumOps-2].set(nullptr);
3708 OL[NumOps-2+1].set(nullptr);
3709 setNumHungOffUseOperands(NumOps-2);
3711 return CaseIt(this, idx);
3714 /// growOperands - grow operands - This grows the operand list in response
3715 /// to a push_back style of operation. This grows the number of ops by 3 times.
3717 void SwitchInst::growOperands() {
3718 unsigned e = getNumOperands();
3719 unsigned NumOps = e*3;
3721 ReservedSpace = NumOps;
3722 growHungoffUses(ReservedSpace);
3726 BasicBlock *SwitchInst::getSuccessorV(unsigned idx) const {
3727 return getSuccessor(idx);
3729 unsigned SwitchInst::getNumSuccessorsV() const {
3730 return getNumSuccessors();
3732 void SwitchInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3733 setSuccessor(idx, B);
3736 //===----------------------------------------------------------------------===//
3737 // IndirectBrInst Implementation
3738 //===----------------------------------------------------------------------===//
3740 void IndirectBrInst::init(Value *Address, unsigned NumDests) {
3741 assert(Address && Address->getType()->isPointerTy() &&
3742 "Address of indirectbr must be a pointer");
3743 ReservedSpace = 1+NumDests;
3744 setNumHungOffUseOperands(1);
3745 allocHungoffUses(ReservedSpace);
3751 /// growOperands - grow operands - This grows the operand list in response
3752 /// to a push_back style of operation. This grows the number of ops by 2 times.
3754 void IndirectBrInst::growOperands() {
3755 unsigned e = getNumOperands();
3756 unsigned NumOps = e*2;
3758 ReservedSpace = NumOps;
3759 growHungoffUses(ReservedSpace);
3762 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3763 Instruction *InsertBefore)
3764 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3765 nullptr, 0, InsertBefore) {
3766 init(Address, NumCases);
3769 IndirectBrInst::IndirectBrInst(Value *Address, unsigned NumCases,
3770 BasicBlock *InsertAtEnd)
3771 : TerminatorInst(Type::getVoidTy(Address->getContext()),Instruction::IndirectBr,
3772 nullptr, 0, InsertAtEnd) {
3773 init(Address, NumCases);
3776 IndirectBrInst::IndirectBrInst(const IndirectBrInst &IBI)
3777 : TerminatorInst(Type::getVoidTy(IBI.getContext()), Instruction::IndirectBr,
3778 nullptr, IBI.getNumOperands()) {
3779 allocHungoffUses(IBI.getNumOperands());
3780 Use *OL = getOperandList();
3781 const Use *InOL = IBI.getOperandList();
3782 for (unsigned i = 0, E = IBI.getNumOperands(); i != E; ++i)
3784 SubclassOptionalData = IBI.SubclassOptionalData;
3787 /// addDestination - Add a destination.
3789 void IndirectBrInst::addDestination(BasicBlock *DestBB) {
3790 unsigned OpNo = getNumOperands();
3791 if (OpNo+1 > ReservedSpace)
3792 growOperands(); // Get more space!
3793 // Initialize some new operands.
3794 assert(OpNo < ReservedSpace && "Growing didn't work!");
3795 setNumHungOffUseOperands(OpNo+1);
3796 getOperandList()[OpNo] = DestBB;
3799 /// removeDestination - This method removes the specified successor from the
3800 /// indirectbr instruction.
3801 void IndirectBrInst::removeDestination(unsigned idx) {
3802 assert(idx < getNumOperands()-1 && "Successor index out of range!");
3804 unsigned NumOps = getNumOperands();
3805 Use *OL = getOperandList();
3807 // Replace this value with the last one.
3808 OL[idx+1] = OL[NumOps-1];
3810 // Nuke the last value.
3811 OL[NumOps-1].set(nullptr);
3812 setNumHungOffUseOperands(NumOps-1);
3815 BasicBlock *IndirectBrInst::getSuccessorV(unsigned idx) const {
3816 return getSuccessor(idx);
3818 unsigned IndirectBrInst::getNumSuccessorsV() const {
3819 return getNumSuccessors();
3821 void IndirectBrInst::setSuccessorV(unsigned idx, BasicBlock *B) {
3822 setSuccessor(idx, B);
3825 //===----------------------------------------------------------------------===//
3826 // cloneImpl() implementations
3827 //===----------------------------------------------------------------------===//
3829 // Define these methods here so vtables don't get emitted into every translation
3830 // unit that uses these classes.
3832 GetElementPtrInst *GetElementPtrInst::cloneImpl() const {
3833 return new (getNumOperands()) GetElementPtrInst(*this);
3836 BinaryOperator *BinaryOperator::cloneImpl() const {
3837 return Create(getOpcode(), Op<0>(), Op<1>());
3840 FCmpInst *FCmpInst::cloneImpl() const {
3841 return new FCmpInst(getPredicate(), Op<0>(), Op<1>());
3844 ICmpInst *ICmpInst::cloneImpl() const {
3845 return new ICmpInst(getPredicate(), Op<0>(), Op<1>());
3848 ExtractValueInst *ExtractValueInst::cloneImpl() const {
3849 return new ExtractValueInst(*this);
3852 InsertValueInst *InsertValueInst::cloneImpl() const {
3853 return new InsertValueInst(*this);
3856 AllocaInst *AllocaInst::cloneImpl() const {
3857 AllocaInst *Result = new AllocaInst(getAllocatedType(),
3858 getType()->getAddressSpace(),
3859 (Value *)getOperand(0), getAlignment());
3860 Result->setUsedWithInAlloca(isUsedWithInAlloca());
3861 Result->setSwiftError(isSwiftError());
3865 LoadInst *LoadInst::cloneImpl() const {
3866 return new LoadInst(getOperand(0), Twine(), isVolatile(),
3867 getAlignment(), getOrdering(), getSynchScope());
3870 StoreInst *StoreInst::cloneImpl() const {
3871 return new StoreInst(getOperand(0), getOperand(1), isVolatile(),
3872 getAlignment(), getOrdering(), getSynchScope());
3876 AtomicCmpXchgInst *AtomicCmpXchgInst::cloneImpl() const {
3877 AtomicCmpXchgInst *Result =
3878 new AtomicCmpXchgInst(getOperand(0), getOperand(1), getOperand(2),
3879 getSuccessOrdering(), getFailureOrdering(),
3881 Result->setVolatile(isVolatile());
3882 Result->setWeak(isWeak());
3886 AtomicRMWInst *AtomicRMWInst::cloneImpl() const {
3887 AtomicRMWInst *Result =
3888 new AtomicRMWInst(getOperation(),getOperand(0), getOperand(1),
3889 getOrdering(), getSynchScope());
3890 Result->setVolatile(isVolatile());
3894 FenceInst *FenceInst::cloneImpl() const {
3895 return new FenceInst(getContext(), getOrdering(), getSynchScope());
3898 TruncInst *TruncInst::cloneImpl() const {
3899 return new TruncInst(getOperand(0), getType());
3902 ZExtInst *ZExtInst::cloneImpl() const {
3903 return new ZExtInst(getOperand(0), getType());
3906 SExtInst *SExtInst::cloneImpl() const {
3907 return new SExtInst(getOperand(0), getType());
3910 FPTruncInst *FPTruncInst::cloneImpl() const {
3911 return new FPTruncInst(getOperand(0), getType());
3914 FPExtInst *FPExtInst::cloneImpl() const {
3915 return new FPExtInst(getOperand(0), getType());
3918 UIToFPInst *UIToFPInst::cloneImpl() const {
3919 return new UIToFPInst(getOperand(0), getType());
3922 SIToFPInst *SIToFPInst::cloneImpl() const {
3923 return new SIToFPInst(getOperand(0), getType());
3926 FPToUIInst *FPToUIInst::cloneImpl() const {
3927 return new FPToUIInst(getOperand(0), getType());
3930 FPToSIInst *FPToSIInst::cloneImpl() const {
3931 return new FPToSIInst(getOperand(0), getType());
3934 PtrToIntInst *PtrToIntInst::cloneImpl() const {
3935 return new PtrToIntInst(getOperand(0), getType());
3938 IntToPtrInst *IntToPtrInst::cloneImpl() const {
3939 return new IntToPtrInst(getOperand(0), getType());
3942 BitCastInst *BitCastInst::cloneImpl() const {
3943 return new BitCastInst(getOperand(0), getType());
3946 AddrSpaceCastInst *AddrSpaceCastInst::cloneImpl() const {
3947 return new AddrSpaceCastInst(getOperand(0), getType());
3950 CallInst *CallInst::cloneImpl() const {
3951 if (hasOperandBundles()) {
3952 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
3953 return new(getNumOperands(), DescriptorBytes) CallInst(*this);
3955 return new(getNumOperands()) CallInst(*this);
3958 SelectInst *SelectInst::cloneImpl() const {
3959 return SelectInst::Create(getOperand(0), getOperand(1), getOperand(2));
3962 VAArgInst *VAArgInst::cloneImpl() const {
3963 return new VAArgInst(getOperand(0), getType());
3966 ExtractElementInst *ExtractElementInst::cloneImpl() const {
3967 return ExtractElementInst::Create(getOperand(0), getOperand(1));
3970 InsertElementInst *InsertElementInst::cloneImpl() const {
3971 return InsertElementInst::Create(getOperand(0), getOperand(1), getOperand(2));
3974 ShuffleVectorInst *ShuffleVectorInst::cloneImpl() const {
3975 return new ShuffleVectorInst(getOperand(0), getOperand(1), getOperand(2));
3978 PHINode *PHINode::cloneImpl() const { return new PHINode(*this); }
3980 LandingPadInst *LandingPadInst::cloneImpl() const {
3981 return new LandingPadInst(*this);
3984 ReturnInst *ReturnInst::cloneImpl() const {
3985 return new(getNumOperands()) ReturnInst(*this);
3988 BranchInst *BranchInst::cloneImpl() const {
3989 return new(getNumOperands()) BranchInst(*this);
3992 SwitchInst *SwitchInst::cloneImpl() const { return new SwitchInst(*this); }
3994 IndirectBrInst *IndirectBrInst::cloneImpl() const {
3995 return new IndirectBrInst(*this);
3998 InvokeInst *InvokeInst::cloneImpl() const {
3999 if (hasOperandBundles()) {
4000 unsigned DescriptorBytes = getNumOperandBundles() * sizeof(BundleOpInfo);
4001 return new(getNumOperands(), DescriptorBytes) InvokeInst(*this);
4003 return new(getNumOperands()) InvokeInst(*this);
4006 ResumeInst *ResumeInst::cloneImpl() const { return new (1) ResumeInst(*this); }
4008 CleanupReturnInst *CleanupReturnInst::cloneImpl() const {
4009 return new (getNumOperands()) CleanupReturnInst(*this);
4012 CatchReturnInst *CatchReturnInst::cloneImpl() const {
4013 return new (getNumOperands()) CatchReturnInst(*this);
4016 CatchSwitchInst *CatchSwitchInst::cloneImpl() const {
4017 return new CatchSwitchInst(*this);
4020 FuncletPadInst *FuncletPadInst::cloneImpl() const {
4021 return new (getNumOperands()) FuncletPadInst(*this);
4024 UnreachableInst *UnreachableInst::cloneImpl() const {
4025 LLVMContext &Context = getContext();
4026 return new UnreachableInst(Context);