23 using namespace PatternMatch;
25 STATISTIC(NumSimplified,
"Number of library calls simplified");
31 if (ITy->getBitWidth() < 32)
41 if (
StructType *STy = dyn_cast<StructType>(T)) {
42 if (STy->getNumElements() == 1)
43 T = STy->getElementType(0);
46 }
else if (
ArrayType *ATy = dyn_cast<ArrayType>(T)) {
47 if (ATy->getNumElements() == 1)
48 T = ATy->getElementType();
61 unsigned MinAlign = std::min(DstAlign, SrcAlign);
64 if (CopyAlign < MinAlign) {
73 if (MemOpLength == 0)
return 0;
80 assert(Size &&
"0-sized memory transfering should be removed already.");
82 if (Size > 8 || (Size&(Size-1)))
104 Type *SrcETy = cast<PointerType>(StrippedDest->
getType())
106 if (
TD && SrcETy->
isSized() &&
TD->getTypeStoreSize(SrcETy) == Size) {
118 if (M->getNumOperands() == 3 &&
120 isa<ConstantInt>(M->getOperand(0)) &&
121 cast<ConstantInt>(M->getOperand(0))->isNullValue() &&
123 isa<ConstantInt>(M->getOperand(1)) &&
124 cast<ConstantInt>(M->getOperand(1))->getValue() == Size &&
126 isa<MDNode>(M->getOperand(2)))
127 CopyMD = cast<MDNode>(M->getOperand(2));
135 SrcAlign = std::max(SrcAlign, CopyAlign);
136 DstAlign = std::max(DstAlign, CopyAlign);
169 assert(Len &&
"0-sized memory setting should be removed already.");
176 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
178 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
181 if (Alignment == 0) Alignment = 1;
184 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
203 return visitFree(CI);
214 if (!II)
return visitCallSite(&CI);
219 bool Changed =
false;
223 if (NumBytes->isNullValue())
224 return EraseInstFromFunction(CI);
226 if (
ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
227 if (CI->getZExtValue() == 1) {
241 if (
MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
242 if (
GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
243 if (GVSrc->isConstant()) {
256 if (MTI->getSource() == MTI->getDest())
257 return EraseInstFromFunction(CI);
262 if (isa<MemTransferInst>(MI)) {
265 }
else if (
MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
270 if (Changed)
return II;
287 return ReplaceInstUsesWith(CI, X);
294 Value *V = Builder->CreateLShr(X, CV);
309 if (Power->isAllOnesValue())
321 APInt KnownZero(BitWidth, 0);
322 APInt KnownOne(BitWidth, 0);
326 if ((Mask & KnownZero) == Mask)
328 APInt(BitWidth, TrailingZeros)));
339 APInt KnownZero(BitWidth, 0);
340 APInt KnownOne(BitWidth, 0);
344 if ((Mask & KnownZero) == Mask)
346 APInt(BitWidth, LeadingZeros)));
354 APInt LHSKnownZero(BitWidth, 0);
355 APInt LHSKnownOne(BitWidth, 0);
357 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
358 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
360 if (LHSKnownNegative || LHSKnownPositive) {
361 APInt RHSKnownZero(BitWidth, 0);
362 APInt RHSKnownOne(BitWidth, 0);
364 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
365 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
366 if (LHSKnownNegative && RHSKnownNegative) {
369 Value *Add = Builder->CreateAdd(LHS, RHS);
380 if (LHSKnownPositive && RHSKnownPositive) {
383 Value *Add = Builder->CreateNUWAdd(LHS, RHS);
448 APInt LHSKnownZero(BitWidth, 0);
449 APInt LHSKnownOne(BitWidth, 0);
451 APInt RHSKnownZero(BitWidth, 0);
452 APInt RHSKnownOne(BitWidth, 0);
456 APInt LHSMax = ~LHSKnownZero;
457 APInt RHSMax = ~RHSKnownZero;
462 LHSMax.
umul_ov(RHSMax, Overflow);
464 Value *Mul = Builder->CreateNUWMul(LHS, RHS,
"umul_with_overflow");
493 if (RHSI->equalsInt(1)) {
547 APInt DemandedElts(VWidth, 1);
548 APInt UndefElts(VWidth, 0);
550 DemandedElts, UndefElts)) {
567 unsigned LowHalfElts = VWidth / 2;
569 APInt UndefElts(VWidth, 0);
582 assert(Mask->getType()->getVectorNumElements() == 16 &&
583 "Bad type for intrinsic!");
586 bool AllEltsOk =
true;
587 for (
unsigned i = 0; i != 16; ++i) {
590 !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
605 Value *ExtractedElts[32];
606 memset(ExtractedElts, 0,
sizeof(ExtractedElts));
608 for (
unsigned i = 0; i != 16; ++i) {
609 if (isa<UndefValue>(Mask->getAggregateElement(i)))
612 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
615 if (ExtractedElts[Idx] == 0) {
617 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
618 Builder->getInt32(Idx&15));
622 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
623 Builder->getInt32(i));
647 if (IntrAlign && IntrAlign->
getZExtValue() < MemAlign) {
662 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
672 VectorType* VT = cast<VectorType>(CV0->getType());
676 (cast<ConstantInt>(CV0->getAggregateElement(i)))->getValue();
677 CV0E = Zext ? CV0E.
zext(NewWidth) : CV0E.
sext(NewWidth);
679 (cast<ConstantInt>(CV1->getAggregateElement(i)))->getValue();
680 CV1E = Zext ? CV1E.
zext(NewWidth) : CV1E.
sext(NewWidth);
694 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) {
695 if (Splat->isOne()) {
714 return EraseInstFromFunction(CI);
722 bool CannotRemove =
false;
723 for (++BI; &*BI != TI; ++BI) {
724 if (isa<AllocaInst>(BI)) {
728 if (
CallInst *BCI = dyn_cast<CallInst>(BI)) {
732 return EraseInstFromFunction(CI);
746 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
747 return EraseInstFromFunction(CI);
752 return visitCallSite(II);
758 return visitCallSite(&II);
778 Type* DstTy = cast<PointerType>(CI->
getType())->getElementType();
793 if (
Value *With = Simplifier->optimizeCall(CI)) {
795 return CI->
use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
805 if (Underlying != TrampMem &&
808 if (!isa<AllocaInst>(Underlying))
835 if (InitTrampoline->
getOperand(0) != TrampMem)
838 return InitTrampoline;
884 bool Changed =
false;
889 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
892 if (
Function *CalleeF = dyn_cast<Function>(Callee))
899 !CalleeF->isDeclaration()) {
908 if (isa<CallInst>(OldCall))
909 return EraseInstFromFunction(*OldCall);
913 cast<InvokeInst>(OldCall)->setCalledFunction(
918 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
941 return transformCallThroughTrampoline(CS, II);
945 if (FTy->isVarArg()) {
972 if (I)
return EraseInstFromFunction(*I);
981 bool InstCombiner::transformConstExprCastCall(
CallSite CS) {
1001 if (OldRetTy != NewRetTy) {
1013 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1015 hasAttributes(AttributeFuncs::
1017 AttributeSet::ReturnIndex))
1026 if (
InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1029 if (
PHINode *PN = dyn_cast<PHINode>(*UI))
1030 if (PN->getParent() == II->getNormalDest() ||
1035 unsigned NumActualArgs = CS.
arg_size();
1036 unsigned NumCommonArgs = std::min(FT->
getNumParams(), NumActualArgs);
1039 for (
unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1041 Type *ActTy = (*AI)->getType();
1047 hasAttributes(AttributeFuncs::
1053 if (ParamTy != ActTy &&
1094 for (
unsigned i = CallerPAL.
getNumSlots(); i; --i) {
1096 if (Index <= FT->getNumParams())
1108 std::vector<Value*> Args;
1109 Args.reserve(NumActualArgs);
1111 attrVec.
reserve(NumCommonArgs);
1114 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1119 removeAttributes(AttributeFuncs::
1121 AttributeSet::ReturnIndex);
1124 if (RAttrs.hasAttributes())
1126 AttributeSet::ReturnIndex, RAttrs));
1129 for (
unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1132 if ((*AI)->getType() == ParamTy) {
1133 Args.push_back(*AI);
1135 Args.push_back(Builder->CreateBitCast(*AI, ParamTy));
1147 for (
unsigned i = NumCommonArgs; i != FT->
getNumParams(); ++i)
1155 for (
unsigned i = FT->
getNumParams(); i != NumActualArgs; ++i, ++AI) {
1157 if (PTy != (*AI)->getType()) {
1161 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
1163 Args.push_back(*AI);
1186 if (
InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1187 NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
1188 II->getUnwindDest(), Args);
1191 cast<InvokeInst>(
NC)->setAttributes(NewCallerPAL);
1193 CallInst *CI = cast<CallInst>(Caller);
1194 NC = Builder->CreateCall(Callee, Args);
1197 cast<CallInst>(NC)->setTailCall();
1199 cast<CallInst>(
NC)->setAttributes(NewCallerPAL);
1211 if (
InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1213 InsertNewInstBefore(NC, *I);
1216 InsertNewInstBefore(NC, *Caller);
1218 Worklist.AddUsersToWorkList(*Caller);
1225 ReplaceInstUsesWith(*Caller, NV);
1227 EraseInstFromFunction(*Caller);
1236 InstCombiner::transformCallThroughTrampoline(
CallSite CS,
1249 "transformCallThroughTrampoline called with incorrect CallSite.");
1253 FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1256 if (!NestAttrs.isEmpty()) {
1257 unsigned NestIdx = 1;
1263 E = NestFTy->param_end(); I != E; ++NestIdx, ++
I)
1273 std::vector<Value*> NewArgs;
1274 NewArgs.reserve(CS.
arg_size() + 1);
1277 NewAttrs.
reserve(Attrs.getNumSlots() + 1);
1283 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1285 Attrs.getRetAttributes()));
1291 if (Idx == NestIdx) {
1294 if (NestVal->
getType() != NestTy)
1295 NestVal = Builder->CreateBitCast(NestVal, NestTy,
"nest");
1296 NewArgs.push_back(NestVal);
1305 NewArgs.push_back(*I);
1310 Idx + (Idx >= NestIdx), B));
1318 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1319 NewAttrs.
push_back(AttributeSet::get(FTy->getContext(),
1320 Attrs.getFnAttributes()));
1326 std::vector<Type*> NewTypes;
1327 NewTypes.reserve(FTy->getNumParams()+1);
1334 E = FTy->param_end();
1339 NewTypes.push_back(NestTy);
1345 NewTypes.push_back(*I);
1360 AttributeSet::get(FTy->getContext(), NewAttrs);
1363 if (
InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1365 II->getNormalDest(), II->getUnwindDest(),
1367 cast<InvokeInst>(NewCaller)->setCallingConv(II->
getCallingConv());
1368 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1371 if (cast<CallInst>(Caller)->isTailCall())
1372 cast<CallInst>(NewCaller)->setTailCall();
1373 cast<CallInst>(NewCaller)->
1374 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1375 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1386 NestF->
getType() == PTy ? NestF :
unsigned getAlignment() const
void push_back(const T &Elt)
static ConstantInt * getFalse(LLVMContext &Context)
IntegerType * getType() const
class_match< Value > m_Value()
m_Value() - Match an arbitrary value and ignore it.
LLVMContext & getContext() const
const AttributeSet & getAttributes() const
AttributeSet getParamAttributes(unsigned Index) const
The attributes for the specified index are returned.
The main container class for the LLVM Intermediate Representation.
unsigned getNumParams() const
Instruction * visitCallInst(CallInst &CI)
Intrinsic::ID getIntrinsicID() const
unsigned arg_size() const
enable_if_c<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Nested function static chain.
static ConstantAggregateZero * get(Type *Ty)
Type::subtype_iterator param_iterator
void setCalledFunction(Value *V)
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Get a value with low bits set.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
m_Intrinsic_Ty< Opnd0 >::Ty m_BSwap(const Opnd0 &Op0)
const Function * getParent() const
Return the enclosing method, or null if none.
MDNode - a tuple of other values.
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
bool hasAttribute(unsigned Index, Attribute::AttrKind Kind) const
Return true if the attribute exists at the given index.
void setAlignment(Constant *A)
Type * getPointerElementType() const
const CallInst * isFreeCall(const Value *I, const TargetLibraryInfo *TLI)
isFreeCall - Returns non-null if the value is a call to the builtin free()
static Constant * getNullValue(Type *Ty)
bool isSingleValueType() const
bool match(Val *V, const Pattern &P)
Instruction * visitInvokeInst(InvokeInst &II)
static unsigned getBitWidth(Type *Ty, const DataLayout *TD)
bool doesNotThrow() const
Determine if the function cannot unwind.
static cl::opt< ITMode > IT(cl::desc("IT block support"), cl::Hidden, cl::init(DefaultIT), cl::ZeroOrMore, cl::values(clEnumValN(DefaultIT,"arm-default-it","Generate IT block based on arch"), clEnumValN(RestrictedIT,"arm-restrict-it","Disallow deprecated IT based on ARMv8"), clEnumValN(NoRestrictedIT,"arm-no-restrict-it","Allow IT blocks based on ARMv7"), clEnumValEnd))
Base class of casting instructions.
unsigned getNumArgOperands() const
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
m_Trunc
static Constant * get(ArrayRef< Constant * > V)
Type * getAlignmentType() const
void setName(const Twine &Name)
AttributeSet typeIncompatible(Type *Ty, uint64_t Index)
Which attributes cannot be applied to a type.
Hidden pointer to structure to return.
static IntrinsicInst * FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp, Value *TrampMem)
bool doesNotThrow() const
Determine if the call cannot unwind.
uint64_t getZExtValue() const
Return the zero extended value.
static IntrinsicInst * FindInitTrampoline(Value *Callee)
LLVMContext & getContext() const
getContext - Return the LLVMContext in which this type was uniqued.
CallingConv::ID getCallingConv() const
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
Get the constant's value with a saturation limit.
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
Function * getDeclaration(Module *M, ID id, ArrayRef< Type * > Tys=None)
ValTy * getCalledValue() const
APInt umul_ov(const APInt &RHS, bool &Overflow) const
unsigned getNumElements() const
Return the number of elements in the Vector type.
Type * getElementType() const
This class represents a truncation of integer types.
void ComputeMaskedBits(Value *V, APInt &KnownZero, APInt &KnownOne, const DataLayout *TD=0, unsigned Depth=0)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=0)
Construct any of the CastInst subclasses.
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Get a value with high bits set.
User::op_iterator arg_iterator
unsigned getNumSlots() const
Return the number of slots used in this attribute list. This is the number of arguments that have an ...
Type * getParamType(unsigned i) const
Parameter type accessors.
bool isLosslessCast() const
Determine if this is a lossless cast.
STATISTIC(NumSimplified,"Number of library calls simplified")
InstrTy * getInstruction() const
AttributeSet getSlotAttributes(unsigned Slot) const
Return the attributes at the given slot.
static Type * reduceToSingleValueType(Type *T)
LLVM Constant Representation.
static InvokeInst * Create(Value *Func, BasicBlock *IfNormal, BasicBlock *IfException, ArrayRef< Value * > Args, const Twine &NameStr="", Instruction *InsertBefore=0)
const DebugLoc & getDebugLoc() const
getDebugLoc - Return the debug location for this node as a DebugLoc.
APInt LLVM_ATTRIBUTE_UNUSED_RESULT sext(unsigned width) const
Sign extend to a new width.
static bool isBitCastable(Type *SrcTy, Type *DestTy)
Check whether a bitcast between these types is valid.
Value * getOperand(unsigned i) const
Integer representation type.
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Constant * getAggregateElement(unsigned Elt) const
void setAlignment(unsigned Align)
static CastInst * CreateZExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=0)
Create a ZExt or BitCast cast instruction.
static UndefValue * get(Type *T)
LLVMContext & getContext() const
All values hold a context through their type.
void setMetadata(unsigned KindID, MDNode *Node)
bool mayWriteToMemory() const
static CallInst * Create(Value *Func, ArrayRef< Value * > Args, const Twine &NameStr="", Instruction *InsertBefore=0)
static CastInst * CreateSExtOrBitCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=0)
Create a SExt or BitCast cast instruction.
unsigned countTrailingZeros() const
Count the number of trailing zero bits.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
Get or create an IntegerType instance.
static Constant * getBitCast(Constant *C, Type *Ty)
static PointerType * getInt1PtrTy(LLVMContext &C, unsigned AS=0)
unsigned getIntegerBitWidth() const
bool doesNotThrow() const
Determine if the call cannot unwind.
static PointerType * getUnqual(Type *ElementType)
Class for constant integers.
bool isByValArgument(unsigned ArgNo) const
Determine whether this argument is passed by value.
uint64_t getTypeAllocSize(Type *Ty) const
MDNode * getMetadata(unsigned KindID) const
static IntrinsicInst * FindInitTrampolineFromAlloca(Value *TrampMem)
Value * getLength() const
Value * stripPointerCasts()
Strips off any unneeded pointer casts, all-zero GEPs and aliases from the specified value...
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
Function * getCalledFunction() const
static bool isSafeToEliminateVarargsCast(const CallSite CS, const CastInst *const CI, const DataLayout *const TD, const int ix)
static Constant * get(Type *Ty, double V)
static ConstantInt * getTrue(LLVMContext &Context)
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
AttributeSet getAttributes() const
Return the attribute list for this Function.
Value * getArgOperand(unsigned i) const
Class for arbitrary precision integers.
static APInt getBitsSet(unsigned numBits, unsigned loBit, unsigned hiBit)
Get a value with a block of bits set.
static InsertValueInst * Create(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &NameStr="", Instruction *InsertBefore=0)
uint64_t MinAlign(uint64_t A, uint64_t B)
unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign, const DataLayout *TD=0)
PointerType * getType() const
getType - Global values are always pointers.
void setCalledFunction(Value *Fn)
setCalledFunction - Set the function called.
static IntegerType * getInt32Ty(LLVMContext &C)
bool isDeclaration() const
unsigned getSlotIndex(unsigned Slot) const
Return the index for the given slot.
bool hasAttributes(unsigned Index) const
Return true if attribute exists at the given index.
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Infer the opcode for cast operand and type.
TerminatorInst * getTerminator()
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
FunctionType * getFunctionType() const
void setArgOperand(unsigned i, Value *v)
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
unsigned getPrimitiveSizeInBits() const
Type * getReturnType() const
LLVM Value Representation.
void setAlignment(unsigned Align)
unsigned countLeadingZeros() const
The APInt version of the countLeadingZeros functions in MathExtras.h.
bool isPowerOf2_32(uint32_t Value)
APInt LLVM_ATTRIBUTE_UNUSED_RESULT zext(unsigned width) const
Zero extend to a new width.
CallingConv::ID getCallingConv() const
bool getObjectSize(const Value *Ptr, uint64_t &Size, const DataLayout *DL, const TargetLibraryInfo *TLI, bool RoundToAlign=false)
Compute the size of the object pointed by Ptr. Returns true and the object size in Size if successful...
bool isEmpty() const
Return true if there are no attributes.
static Type * getPromotedType(Type *Ty)
static RegisterPass< NVPTXAllocaHoisting > X("alloca-hoisting","Hoisting alloca instructions in non-entry ""blocks to the entry block")
const BasicBlock * getParent() const
INITIALIZE_PASS(GlobalMerge,"global-merge","Global Merge", false, false) bool GlobalMerge const DataLayout * TD
bool isVoidTy() const
isVoidTy - Return true if this is 'void'.
static unsigned getKnownAlignment(Value *V, const DataLayout *TD=0)
getKnownAlignment - Try to infer an alignment for the specified pointer.
AttributeSet getFnAttributes() const
The function attributes are returned.