1 //===- InstCombineCalls.cpp -----------------------------------------------===//
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 the visitCall and visitInvoke functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/IntrinsicInst.h"
16 #include "llvm/Support/CallSite.h"
17 #include "llvm/Target/TargetData.h"
18 #include "llvm/Analysis/MemoryBuiltins.h"
21 /// getPromotedType - Return the specified type promoted as it would be to pass
22 /// though a va_arg area.
23 static const Type *getPromotedType(const Type *Ty) {
24 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
25 if (ITy->getBitWidth() < 32)
26 return Type::getInt32Ty(Ty->getContext());
31 /// EnforceKnownAlignment - If the specified pointer points to an object that
32 /// we control, modify the object's alignment to PrefAlign. This isn't
33 /// often possible though. If alignment is important, a more reliable approach
34 /// is to simply align all global variables and allocation instructions to
35 /// their preferred alignment from the beginning.
37 static unsigned EnforceKnownAlignment(Value *V,
38 unsigned Align, unsigned PrefAlign) {
40 User *U = dyn_cast<User>(V);
43 switch (Operator::getOpcode(U)) {
45 case Instruction::BitCast:
46 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
47 case Instruction::GetElementPtr: {
48 // If all indexes are zero, it is just the alignment of the base pointer.
49 bool AllZeroOperands = true;
50 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
51 if (!isa<Constant>(*i) ||
52 !cast<Constant>(*i)->isNullValue()) {
53 AllZeroOperands = false;
57 if (AllZeroOperands) {
58 // Treat this like a bitcast.
59 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
65 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
66 // If there is a large requested alignment and we can, bump up the alignment
68 if (!GV->isDeclaration()) {
69 if (GV->getAlignment() >= PrefAlign)
70 Align = GV->getAlignment();
72 GV->setAlignment(PrefAlign);
76 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
77 // If there is a requested alignment and if this is an alloca, round up.
78 if (AI->getAlignment() >= PrefAlign)
79 Align = AI->getAlignment();
81 AI->setAlignment(PrefAlign);
89 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
90 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
91 /// and it is more than the alignment of the ultimate object, see if we can
92 /// increase the alignment of the ultimate object, making this check succeed.
93 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
95 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
96 sizeof(PrefAlign) * CHAR_BIT;
97 APInt Mask = APInt::getAllOnesValue(BitWidth);
98 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
99 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
100 unsigned TrailZ = KnownZero.countTrailingOnes();
101 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
103 if (PrefAlign > Align)
104 Align = EnforceKnownAlignment(V, Align, PrefAlign);
106 // We don't need to make any adjustment.
110 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
111 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
112 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
113 unsigned MinAlign = std::min(DstAlign, SrcAlign);
114 unsigned CopyAlign = MI->getAlignment();
116 if (CopyAlign < MinAlign) {
117 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
122 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
124 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
125 if (MemOpLength == 0) return 0;
127 // Source and destination pointer types are always "i8*" for intrinsic. See
128 // if the size is something we can handle with a single primitive load/store.
129 // A single load+store correctly handles overlapping memory in the memmove
131 unsigned Size = MemOpLength->getZExtValue();
132 if (Size == 0) return MI; // Delete this mem transfer.
134 if (Size > 8 || (Size&(Size-1)))
135 return 0; // If not 1/2/4/8 bytes, exit.
137 // Use an integer load+store unless we can find something better.
139 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
141 // Memcpy forces the use of i8* for the source and destination. That means
142 // that if you're using memcpy to move one double around, you'll get a cast
143 // from double* to i8*. We'd much rather use a double load+store rather than
144 // an i64 load+store, here because this improves the odds that the source or
145 // dest address will be promotable. See if we can find a better type than the
147 Value *StrippedDest = MI->getOperand(1)->stripPointerCasts();
148 if (StrippedDest != MI->getOperand(1)) {
149 const Type *SrcETy = cast<PointerType>(StrippedDest->getType())
151 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
152 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
153 // down through these levels if so.
154 while (!SrcETy->isSingleValueType()) {
155 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
156 if (STy->getNumElements() == 1)
157 SrcETy = STy->getElementType(0);
160 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
161 if (ATy->getNumElements() == 1)
162 SrcETy = ATy->getElementType();
169 if (SrcETy->isSingleValueType())
170 NewPtrTy = PointerType::getUnqual(SrcETy);
175 // If the memcpy/memmove provides better alignment info than we can
177 SrcAlign = std::max(SrcAlign, CopyAlign);
178 DstAlign = std::max(DstAlign, CopyAlign);
180 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
181 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
182 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
183 InsertNewInstBefore(L, *MI);
184 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
186 // Set the size of the copy to 0, it will be deleted on the next iteration.
187 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
191 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
192 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
193 if (MI->getAlignment() < Alignment) {
194 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
199 // Extract the length and alignment and fill if they are constant.
200 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
201 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
202 if (!LenC || !FillC || !FillC->getType()->isInteger(8))
204 uint64_t Len = LenC->getZExtValue();
205 Alignment = MI->getAlignment();
207 // If the length is zero, this is a no-op
208 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
210 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
211 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
212 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
214 Value *Dest = MI->getDest();
215 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
217 // Alignment 0 is identity for alignment 1 for memset, but not store.
218 if (Alignment == 0) Alignment = 1;
220 // Extract the fill value and store.
221 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
222 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
223 Dest, false, Alignment), *MI);
225 // Set the size of the copy to 0, it will be deleted on the next iteration.
226 MI->setLength(Constant::getNullValue(LenC->getType()));
233 /// visitCallInst - CallInst simplification. This mostly only handles folding
234 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
235 /// the heavy lifting.
237 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
239 return visitFree(CI);
241 // If the caller function is nounwind, mark the call as nounwind, even if the
243 if (CI.getParent()->getParent()->doesNotThrow() &&
244 !CI.doesNotThrow()) {
245 CI.setDoesNotThrow();
249 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
250 if (!II) return visitCallSite(&CI);
252 // Intrinsics cannot occur in an invoke, so handle them here instead of in
254 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
255 bool Changed = false;
257 // memmove/cpy/set of zero bytes is a noop.
258 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
259 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
261 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
262 if (CI->getZExtValue() == 1) {
263 // Replace the instruction with just byte operations. We would
264 // transform other cases to loads/stores, but we don't know if
265 // alignment is sufficient.
269 // If we have a memmove and the source operation is a constant global,
270 // then the source and dest pointers can't alias, so we can change this
271 // into a call to memcpy.
272 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
273 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
274 if (GVSrc->isConstant()) {
275 Module *M = CI.getParent()->getParent()->getParent();
276 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
278 Tys[0] = CI.getOperand(3)->getType();
280 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
285 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
286 // memmove(x,x,size) -> noop.
287 if (MTI->getSource() == MTI->getDest())
288 return EraseInstFromFunction(CI);
291 // If we can determine a pointer alignment that is bigger than currently
292 // set, update the alignment.
293 if (isa<MemTransferInst>(MI)) {
294 if (Instruction *I = SimplifyMemTransfer(MI))
296 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
297 if (Instruction *I = SimplifyMemSet(MSI))
301 if (Changed) return II;
304 switch (II->getIntrinsicID()) {
306 case Intrinsic::objectsize: {
307 const Type *ReturnTy = CI.getType();
308 Value *Op1 = II->getOperand(1);
309 bool Min = (cast<ConstantInt>(II->getOperand(2))->getZExtValue() == 1);
311 // We need target data for just about everything so depend on it.
314 // Get to the real allocated thing and offset as fast as possible.
315 Op1 = Op1->stripPointerCasts();
317 // If we've stripped down to a single global variable that we
318 // can know the size of then just return that.
319 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
320 if (GV->hasDefinitiveInitializer()) {
321 Constant *C = GV->getInitializer();
322 size_t globalSize = TD->getTypeAllocSize(C->getType());
323 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, globalSize));
325 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
326 return ReplaceInstUsesWith(CI, RetVal);
328 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op1)) {
330 // Only handle constant GEPs here.
331 if (CE->getOpcode() != Instruction::GetElementPtr) break;
332 GEPOperator *GEP = cast<GEPOperator>(CE);
334 // Get what we're pointing to and its size.
335 const PointerType *PT =
336 cast<PointerType>(GEP->getPointerOperand()->getType());
337 size_t Size = TD->getTypeAllocSize(PT->getElementType());
339 // Get the current byte offset into the thing.
340 SmallVector<Value*, 8> Ops(CE->op_begin()+1, CE->op_end());
341 size_t Offset = TD->getIndexedOffset(PT, &Ops[0], Ops.size());
343 assert(Size >= Offset);
345 Constant *RetVal = ConstantInt::get(ReturnTy, Size-Offset);
346 return ReplaceInstUsesWith(CI, RetVal);
350 case Intrinsic::bswap:
351 // bswap(bswap(x)) -> x
352 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
353 if (Operand->getIntrinsicID() == Intrinsic::bswap)
354 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
356 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
357 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
358 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
359 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
360 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
361 TI->getType()->getPrimitiveSizeInBits();
362 Value *CV = ConstantInt::get(Operand->getType(), C);
363 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
364 return new TruncInst(V, TI->getType());
369 case Intrinsic::powi:
370 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
373 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
376 return ReplaceInstUsesWith(CI, II->getOperand(1));
377 // powi(x, -1) -> 1/x
378 if (Power->isAllOnesValue())
379 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
383 case Intrinsic::cttz: {
384 // If all bits below the first known one are known zero,
385 // this value is constant.
386 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
387 uint32_t BitWidth = IT->getBitWidth();
388 APInt KnownZero(BitWidth, 0);
389 APInt KnownOne(BitWidth, 0);
390 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
391 KnownZero, KnownOne);
392 unsigned TrailingZeros = KnownOne.countTrailingZeros();
393 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
394 if ((Mask & KnownZero) == Mask)
395 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
396 APInt(BitWidth, TrailingZeros)));
400 case Intrinsic::ctlz: {
401 // If all bits above the first known one are known zero,
402 // this value is constant.
403 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
404 uint32_t BitWidth = IT->getBitWidth();
405 APInt KnownZero(BitWidth, 0);
406 APInt KnownOne(BitWidth, 0);
407 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
408 KnownZero, KnownOne);
409 unsigned LeadingZeros = KnownOne.countLeadingZeros();
410 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
411 if ((Mask & KnownZero) == Mask)
412 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
413 APInt(BitWidth, LeadingZeros)));
417 case Intrinsic::uadd_with_overflow: {
418 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
419 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
420 uint32_t BitWidth = IT->getBitWidth();
421 APInt Mask = APInt::getSignBit(BitWidth);
422 APInt LHSKnownZero(BitWidth, 0);
423 APInt LHSKnownOne(BitWidth, 0);
424 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
425 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
426 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
428 if (LHSKnownNegative || LHSKnownPositive) {
429 APInt RHSKnownZero(BitWidth, 0);
430 APInt RHSKnownOne(BitWidth, 0);
431 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
432 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
433 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
434 if (LHSKnownNegative && RHSKnownNegative) {
435 // The sign bit is set in both cases: this MUST overflow.
436 // Create a simple add instruction, and insert it into the struct.
437 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
440 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
442 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
443 return InsertValueInst::Create(Struct, Add, 0);
446 if (LHSKnownPositive && RHSKnownPositive) {
447 // The sign bit is clear in both cases: this CANNOT overflow.
448 // Create a simple add instruction, and insert it into the struct.
449 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
452 UndefValue::get(LHS->getType()),
453 ConstantInt::getFalse(II->getContext())
455 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
456 return InsertValueInst::Create(Struct, Add, 0);
460 // FALL THROUGH uadd into sadd
461 case Intrinsic::sadd_with_overflow:
462 // Canonicalize constants into the RHS.
463 if (isa<Constant>(II->getOperand(1)) &&
464 !isa<Constant>(II->getOperand(2))) {
465 Value *LHS = II->getOperand(1);
466 II->setOperand(1, II->getOperand(2));
467 II->setOperand(2, LHS);
471 // X + undef -> undef
472 if (isa<UndefValue>(II->getOperand(2)))
473 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
475 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
476 // X + 0 -> {X, false}
479 UndefValue::get(II->getOperand(0)->getType()),
480 ConstantInt::getFalse(II->getContext())
482 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
483 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
487 case Intrinsic::usub_with_overflow:
488 case Intrinsic::ssub_with_overflow:
489 // undef - X -> undef
490 // X - undef -> undef
491 if (isa<UndefValue>(II->getOperand(1)) ||
492 isa<UndefValue>(II->getOperand(2)))
493 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
495 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
496 // X - 0 -> {X, false}
499 UndefValue::get(II->getOperand(1)->getType()),
500 ConstantInt::getFalse(II->getContext())
502 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
503 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
507 case Intrinsic::umul_with_overflow:
508 case Intrinsic::smul_with_overflow:
509 // Canonicalize constants into the RHS.
510 if (isa<Constant>(II->getOperand(1)) &&
511 !isa<Constant>(II->getOperand(2))) {
512 Value *LHS = II->getOperand(1);
513 II->setOperand(1, II->getOperand(2));
514 II->setOperand(2, LHS);
518 // X * undef -> undef
519 if (isa<UndefValue>(II->getOperand(2)))
520 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
522 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
525 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
527 // X * 1 -> {X, false}
528 if (RHSI->equalsInt(1)) {
530 UndefValue::get(II->getOperand(1)->getType()),
531 ConstantInt::getFalse(II->getContext())
533 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
534 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
538 case Intrinsic::ppc_altivec_lvx:
539 case Intrinsic::ppc_altivec_lvxl:
540 case Intrinsic::x86_sse_loadu_ps:
541 case Intrinsic::x86_sse2_loadu_pd:
542 case Intrinsic::x86_sse2_loadu_dq:
543 // Turn PPC lvx -> load if the pointer is known aligned.
544 // Turn X86 loadups -> load if the pointer is known aligned.
545 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
546 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
547 PointerType::getUnqual(II->getType()));
548 return new LoadInst(Ptr);
551 case Intrinsic::ppc_altivec_stvx:
552 case Intrinsic::ppc_altivec_stvxl:
553 // Turn stvx -> store if the pointer is known aligned.
554 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
555 const Type *OpPtrTy =
556 PointerType::getUnqual(II->getOperand(1)->getType());
557 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
558 return new StoreInst(II->getOperand(1), Ptr);
561 case Intrinsic::x86_sse_storeu_ps:
562 case Intrinsic::x86_sse2_storeu_pd:
563 case Intrinsic::x86_sse2_storeu_dq:
564 // Turn X86 storeu -> store if the pointer is known aligned.
565 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
566 const Type *OpPtrTy =
567 PointerType::getUnqual(II->getOperand(2)->getType());
568 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
569 return new StoreInst(II->getOperand(2), Ptr);
573 case Intrinsic::x86_sse_cvttss2si: {
574 // These intrinsics only demands the 0th element of its input vector. If
575 // we can simplify the input based on that, do so now.
577 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
578 APInt DemandedElts(VWidth, 1);
579 APInt UndefElts(VWidth, 0);
580 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
582 II->setOperand(1, V);
588 case Intrinsic::ppc_altivec_vperm:
589 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
590 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
591 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
593 // Check that all of the elements are integer constants or undefs.
594 bool AllEltsOk = true;
595 for (unsigned i = 0; i != 16; ++i) {
596 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
597 !isa<UndefValue>(Mask->getOperand(i))) {
604 // Cast the input vectors to byte vectors.
605 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
606 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
607 Value *Result = UndefValue::get(Op0->getType());
609 // Only extract each element once.
610 Value *ExtractedElts[32];
611 memset(ExtractedElts, 0, sizeof(ExtractedElts));
613 for (unsigned i = 0; i != 16; ++i) {
614 if (isa<UndefValue>(Mask->getOperand(i)))
616 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
617 Idx &= 31; // Match the hardware behavior.
619 if (ExtractedElts[Idx] == 0) {
621 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
622 ConstantInt::get(Type::getInt32Ty(II->getContext()),
623 Idx&15, false), "tmp");
626 // Insert this value into the result vector.
627 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
628 ConstantInt::get(Type::getInt32Ty(II->getContext()),
631 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
636 case Intrinsic::stackrestore: {
637 // If the save is right next to the restore, remove the restore. This can
638 // happen when variable allocas are DCE'd.
639 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
640 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
641 BasicBlock::iterator BI = SS;
643 return EraseInstFromFunction(CI);
647 // Scan down this block to see if there is another stack restore in the
648 // same block without an intervening call/alloca.
649 BasicBlock::iterator BI = II;
650 TerminatorInst *TI = II->getParent()->getTerminator();
651 bool CannotRemove = false;
652 for (++BI; &*BI != TI; ++BI) {
653 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
657 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
658 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
659 // If there is a stackrestore below this one, remove this one.
660 if (II->getIntrinsicID() == Intrinsic::stackrestore)
661 return EraseInstFromFunction(CI);
662 // Otherwise, ignore the intrinsic.
664 // If we found a non-intrinsic call, we can't remove the stack
672 // If the stack restore is in a return/unwind block and if there are no
673 // allocas or calls between the restore and the return, nuke the restore.
674 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
675 return EraseInstFromFunction(CI);
680 return visitCallSite(II);
683 // InvokeInst simplification
685 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
686 return visitCallSite(&II);
689 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
690 /// passed through the varargs area, we can eliminate the use of the cast.
691 static bool isSafeToEliminateVarargsCast(const CallSite CS,
692 const CastInst * const CI,
693 const TargetData * const TD,
695 if (!CI->isLosslessCast())
698 // The size of ByVal arguments is derived from the type, so we
699 // can't change to a type with a different size. If the size were
700 // passed explicitly we could avoid this check.
701 if (!CS.paramHasAttr(ix, Attribute::ByVal))
705 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
706 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
707 if (!SrcTy->isSized() || !DstTy->isSized())
709 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
714 // visitCallSite - Improvements for call and invoke instructions.
716 Instruction *InstCombiner::visitCallSite(CallSite CS) {
717 bool Changed = false;
719 // If the callee is a constexpr cast of a function, attempt to move the cast
720 // to the arguments of the call/invoke.
721 if (transformConstExprCastCall(CS)) return 0;
723 Value *Callee = CS.getCalledValue();
725 if (Function *CalleeF = dyn_cast<Function>(Callee))
726 // If the call and callee calling conventions don't match, this call must
727 // be unreachable, as the call is undefined.
728 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
729 // Only do this for calls to a function with a body. A prototype may
730 // not actually end up matching the implementation's calling conv for a
731 // variety of reasons (e.g. it may be written in assembly).
732 !CalleeF->isDeclaration()) {
733 Instruction *OldCall = CS.getInstruction();
734 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
735 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
737 // If OldCall dues not return void then replaceAllUsesWith undef.
738 // This allows ValueHandlers and custom metadata to adjust itself.
739 if (!OldCall->getType()->isVoidTy())
740 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
741 if (isa<CallInst>(OldCall))
742 return EraseInstFromFunction(*OldCall);
744 // We cannot remove an invoke, because it would change the CFG, just
745 // change the callee to a null pointer.
746 cast<InvokeInst>(OldCall)->setOperand(0,
747 Constant::getNullValue(CalleeF->getType()));
751 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
752 // This instruction is not reachable, just remove it. We insert a store to
753 // undef so that we know that this code is not reachable, despite the fact
754 // that we can't modify the CFG here.
755 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
756 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
757 CS.getInstruction());
759 // If CS dues not return void then replaceAllUsesWith undef.
760 // This allows ValueHandlers and custom metadata to adjust itself.
761 if (!CS.getInstruction()->getType()->isVoidTy())
762 CS.getInstruction()->
763 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
765 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
766 // Don't break the CFG, insert a dummy cond branch.
767 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
768 ConstantInt::getTrue(Callee->getContext()), II);
770 return EraseInstFromFunction(*CS.getInstruction());
773 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
774 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
775 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
776 return transformCallThroughTrampoline(CS);
778 const PointerType *PTy = cast<PointerType>(Callee->getType());
779 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
780 if (FTy->isVarArg()) {
781 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
782 // See if we can optimize any arguments passed through the varargs area of
784 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
785 E = CS.arg_end(); I != E; ++I, ++ix) {
786 CastInst *CI = dyn_cast<CastInst>(*I);
787 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
788 *I = CI->getOperand(0);
794 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
795 // Inline asm calls cannot throw - mark them 'nounwind'.
796 CS.setDoesNotThrow();
800 return Changed ? CS.getInstruction() : 0;
803 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
804 // attempt to move the cast to the arguments of the call/invoke.
806 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
807 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
808 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
809 if (CE->getOpcode() != Instruction::BitCast ||
810 !isa<Function>(CE->getOperand(0)))
812 Function *Callee = cast<Function>(CE->getOperand(0));
813 Instruction *Caller = CS.getInstruction();
814 const AttrListPtr &CallerPAL = CS.getAttributes();
816 // Okay, this is a cast from a function to a different type. Unless doing so
817 // would cause a type conversion of one of our arguments, change this call to
818 // be a direct call with arguments casted to the appropriate types.
820 const FunctionType *FT = Callee->getFunctionType();
821 const Type *OldRetTy = Caller->getType();
822 const Type *NewRetTy = FT->getReturnType();
824 if (isa<StructType>(NewRetTy))
825 return false; // TODO: Handle multiple return values.
827 // Check to see if we are changing the return type...
828 if (OldRetTy != NewRetTy) {
829 if (Callee->isDeclaration() &&
830 // Conversion is ok if changing from one pointer type to another or from
831 // a pointer to an integer of the same size.
832 !((isa<PointerType>(OldRetTy) || !TD ||
833 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
834 (isa<PointerType>(NewRetTy) || !TD ||
835 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
836 return false; // Cannot transform this return value.
838 if (!Caller->use_empty() &&
839 // void -> non-void is handled specially
840 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
841 return false; // Cannot transform this return value.
843 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
844 Attributes RAttrs = CallerPAL.getRetAttributes();
845 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
846 return false; // Attribute not compatible with transformed value.
849 // If the callsite is an invoke instruction, and the return value is used by
850 // a PHI node in a successor, we cannot change the return type of the call
851 // because there is no place to put the cast instruction (without breaking
852 // the critical edge). Bail out in this case.
853 if (!Caller->use_empty())
854 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
855 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
857 if (PHINode *PN = dyn_cast<PHINode>(*UI))
858 if (PN->getParent() == II->getNormalDest() ||
859 PN->getParent() == II->getUnwindDest())
863 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
864 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
866 CallSite::arg_iterator AI = CS.arg_begin();
867 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
868 const Type *ParamTy = FT->getParamType(i);
869 const Type *ActTy = (*AI)->getType();
871 if (!CastInst::isCastable(ActTy, ParamTy))
872 return false; // Cannot transform this parameter value.
874 if (CallerPAL.getParamAttributes(i + 1)
875 & Attribute::typeIncompatible(ParamTy))
876 return false; // Attribute not compatible with transformed value.
878 // Converting from one pointer type to another or between a pointer and an
879 // integer of the same size is safe even if we do not have a body.
880 bool isConvertible = ActTy == ParamTy ||
881 (TD && ((isa<PointerType>(ParamTy) ||
882 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
883 (isa<PointerType>(ActTy) ||
884 ActTy == TD->getIntPtrType(Caller->getContext()))));
885 if (Callee->isDeclaration() && !isConvertible) return false;
888 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
889 Callee->isDeclaration())
890 return false; // Do not delete arguments unless we have a function body.
892 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
893 !CallerPAL.isEmpty())
894 // In this case we have more arguments than the new function type, but we
895 // won't be dropping them. Check that these extra arguments have attributes
896 // that are compatible with being a vararg call argument.
897 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
898 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
900 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
901 if (PAttrs & Attribute::VarArgsIncompatible)
905 // Okay, we decided that this is a safe thing to do: go ahead and start
906 // inserting cast instructions as necessary...
907 std::vector<Value*> Args;
908 Args.reserve(NumActualArgs);
909 SmallVector<AttributeWithIndex, 8> attrVec;
910 attrVec.reserve(NumCommonArgs);
912 // Get any return attributes.
913 Attributes RAttrs = CallerPAL.getRetAttributes();
915 // If the return value is not being used, the type may not be compatible
916 // with the existing attributes. Wipe out any problematic attributes.
917 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
919 // Add the new return attributes.
921 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
924 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
925 const Type *ParamTy = FT->getParamType(i);
926 if ((*AI)->getType() == ParamTy) {
929 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
930 false, ParamTy, false);
931 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
934 // Add any parameter attributes.
935 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
936 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
939 // If the function takes more arguments than the call was taking, add them
941 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
942 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
944 // If we are removing arguments to the function, emit an obnoxious warning.
945 if (FT->getNumParams() < NumActualArgs) {
946 if (!FT->isVarArg()) {
947 errs() << "WARNING: While resolving call to function '"
948 << Callee->getName() << "' arguments were dropped!\n";
950 // Add all of the arguments in their promoted form to the arg list.
951 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
952 const Type *PTy = getPromotedType((*AI)->getType());
953 if (PTy != (*AI)->getType()) {
954 // Must promote to pass through va_arg area!
955 Instruction::CastOps opcode =
956 CastInst::getCastOpcode(*AI, false, PTy, false);
957 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
962 // Add any parameter attributes.
963 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
964 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
969 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
970 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
972 if (NewRetTy->isVoidTy())
973 Caller->setName(""); // Void type should not have a name.
975 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
979 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
980 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
981 Args.begin(), Args.end(),
982 Caller->getName(), Caller);
983 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
984 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
986 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
987 Caller->getName(), Caller);
988 CallInst *CI = cast<CallInst>(Caller);
989 if (CI->isTailCall())
990 cast<CallInst>(NC)->setTailCall();
991 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
992 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
995 // Insert a cast of the return type as necessary.
997 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
998 if (!NV->getType()->isVoidTy()) {
999 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
1001 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
1003 // If this is an invoke instruction, we should insert it after the first
1004 // non-phi, instruction in the normal successor block.
1005 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1006 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
1007 InsertNewInstBefore(NC, *I);
1009 // Otherwise, it's a call, just insert cast right after the call instr
1010 InsertNewInstBefore(NC, *Caller);
1012 Worklist.AddUsersToWorkList(*Caller);
1014 NV = UndefValue::get(Caller->getType());
1019 if (!Caller->use_empty())
1020 Caller->replaceAllUsesWith(NV);
1022 EraseInstFromFunction(*Caller);
1026 // transformCallThroughTrampoline - Turn a call to a function created by the
1027 // init_trampoline intrinsic into a direct call to the underlying function.
1029 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
1030 Value *Callee = CS.getCalledValue();
1031 const PointerType *PTy = cast<PointerType>(Callee->getType());
1032 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1033 const AttrListPtr &Attrs = CS.getAttributes();
1035 // If the call already has the 'nest' attribute somewhere then give up -
1036 // otherwise 'nest' would occur twice after splicing in the chain.
1037 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1040 IntrinsicInst *Tramp =
1041 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
1043 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
1044 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1045 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1047 const AttrListPtr &NestAttrs = NestF->getAttributes();
1048 if (!NestAttrs.isEmpty()) {
1049 unsigned NestIdx = 1;
1050 const Type *NestTy = 0;
1051 Attributes NestAttr = Attribute::None;
1053 // Look for a parameter marked with the 'nest' attribute.
1054 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1055 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1056 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1057 // Record the parameter type and any other attributes.
1059 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1064 Instruction *Caller = CS.getInstruction();
1065 std::vector<Value*> NewArgs;
1066 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1068 SmallVector<AttributeWithIndex, 8> NewAttrs;
1069 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1071 // Insert the nest argument into the call argument list, which may
1072 // mean appending it. Likewise for attributes.
1074 // Add any result attributes.
1075 if (Attributes Attr = Attrs.getRetAttributes())
1076 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1080 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1082 if (Idx == NestIdx) {
1083 // Add the chain argument and attributes.
1084 Value *NestVal = Tramp->getOperand(3);
1085 if (NestVal->getType() != NestTy)
1086 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
1087 NewArgs.push_back(NestVal);
1088 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1094 // Add the original argument and attributes.
1095 NewArgs.push_back(*I);
1096 if (Attributes Attr = Attrs.getParamAttributes(Idx))
1098 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1104 // Add any function attributes.
1105 if (Attributes Attr = Attrs.getFnAttributes())
1106 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1108 // The trampoline may have been bitcast to a bogus type (FTy).
1109 // Handle this by synthesizing a new function type, equal to FTy
1110 // with the chain parameter inserted.
1112 std::vector<const Type*> NewTypes;
1113 NewTypes.reserve(FTy->getNumParams()+1);
1115 // Insert the chain's type into the list of parameter types, which may
1116 // mean appending it.
1119 FunctionType::param_iterator I = FTy->param_begin(),
1120 E = FTy->param_end();
1124 // Add the chain's type.
1125 NewTypes.push_back(NestTy);
1130 // Add the original type.
1131 NewTypes.push_back(*I);
1137 // Replace the trampoline call with a direct call. Let the generic
1138 // code sort out any function type mismatches.
1139 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
1141 Constant *NewCallee =
1142 NestF->getType() == PointerType::getUnqual(NewFTy) ?
1143 NestF : ConstantExpr::getBitCast(NestF,
1144 PointerType::getUnqual(NewFTy));
1145 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1148 Instruction *NewCaller;
1149 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1150 NewCaller = InvokeInst::Create(NewCallee,
1151 II->getNormalDest(), II->getUnwindDest(),
1152 NewArgs.begin(), NewArgs.end(),
1153 Caller->getName(), Caller);
1154 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1155 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1157 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
1158 Caller->getName(), Caller);
1159 if (cast<CallInst>(Caller)->isTailCall())
1160 cast<CallInst>(NewCaller)->setTailCall();
1161 cast<CallInst>(NewCaller)->
1162 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1163 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1165 if (!Caller->getType()->isVoidTy())
1166 Caller->replaceAllUsesWith(NewCaller);
1167 Caller->eraseFromParent();
1168 Worklist.Remove(Caller);
1173 // Replace the trampoline call with a direct call. Since there is no 'nest'
1174 // parameter, there is no need to adjust the argument list. Let the generic
1175 // code sort out any function type mismatches.
1176 Constant *NewCallee =
1177 NestF->getType() == PTy ? NestF :
1178 ConstantExpr::getBitCast(NestF, PTy);
1179 CS.setCalledFunction(NewCallee);
1180 return CS.getInstruction();