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 #define DEBUG_TYPE "instcombine"
15 #include "InstCombine.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/MemoryBuiltins.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/PatternMatch.h"
21 #include "llvm/Transforms/Utils/BuildLibCalls.h"
22 #include "llvm/Transforms/Utils/Local.h"
24 using namespace PatternMatch;
26 STATISTIC(NumSimplified, "Number of library calls simplified");
28 /// getPromotedType - Return the specified type promoted as it would be to pass
29 /// though a va_arg area.
30 static Type *getPromotedType(Type *Ty) {
31 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
32 if (ITy->getBitWidth() < 32)
33 return Type::getInt32Ty(Ty->getContext());
38 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a
39 /// single scalar element, like {{{type}}} or [1 x type], return type.
40 static Type *reduceToSingleValueType(Type *T) {
41 while (!T->isSingleValueType()) {
42 if (StructType *STy = dyn_cast<StructType>(T)) {
43 if (STy->getNumElements() == 1)
44 T = STy->getElementType(0);
47 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
48 if (ATy->getNumElements() == 1)
49 T = ATy->getElementType();
59 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
60 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL);
61 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL);
62 unsigned MinAlign = std::min(DstAlign, SrcAlign);
63 unsigned CopyAlign = MI->getAlignment();
65 if (CopyAlign < MinAlign) {
66 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
71 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
73 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
74 if (MemOpLength == 0) return 0;
76 // Source and destination pointer types are always "i8*" for intrinsic. See
77 // if the size is something we can handle with a single primitive load/store.
78 // A single load+store correctly handles overlapping memory in the memmove
80 uint64_t Size = MemOpLength->getLimitedValue();
81 assert(Size && "0-sized memory transferring should be removed already.");
83 if (Size > 8 || (Size&(Size-1)))
84 return 0; // If not 1/2/4/8 bytes, exit.
86 // Use an integer load+store unless we can find something better.
88 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
90 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
92 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
93 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
94 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
96 // Memcpy forces the use of i8* for the source and destination. That means
97 // that if you're using memcpy to move one double around, you'll get a cast
98 // from double* to i8*. We'd much rather use a double load+store rather than
99 // an i64 load+store, here because this improves the odds that the source or
100 // dest address will be promotable. See if we can find a better type than the
102 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
104 if (StrippedDest != MI->getArgOperand(0)) {
105 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
107 if (DL && SrcETy->isSized() && DL->getTypeStoreSize(SrcETy) == Size) {
108 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
109 // down through these levels if so.
110 SrcETy = reduceToSingleValueType(SrcETy);
112 if (SrcETy->isSingleValueType()) {
113 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
114 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
116 // If the memcpy has metadata describing the members, see if we can
117 // get the TBAA tag describing our copy.
118 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
119 if (M->getNumOperands() == 3 &&
121 isa<ConstantInt>(M->getOperand(0)) &&
122 cast<ConstantInt>(M->getOperand(0))->isNullValue() &&
124 isa<ConstantInt>(M->getOperand(1)) &&
125 cast<ConstantInt>(M->getOperand(1))->getValue() == Size &&
127 isa<MDNode>(M->getOperand(2)))
128 CopyMD = cast<MDNode>(M->getOperand(2));
134 // If the memcpy/memmove provides better alignment info than we can
136 SrcAlign = std::max(SrcAlign, CopyAlign);
137 DstAlign = std::max(DstAlign, CopyAlign);
139 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
140 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
141 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
142 L->setAlignment(SrcAlign);
144 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
145 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
146 S->setAlignment(DstAlign);
148 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
150 // Set the size of the copy to 0, it will be deleted on the next iteration.
151 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
155 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
156 unsigned Alignment = getKnownAlignment(MI->getDest(), DL);
157 if (MI->getAlignment() < Alignment) {
158 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
163 // Extract the length and alignment and fill if they are constant.
164 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
165 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
166 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
168 uint64_t Len = LenC->getLimitedValue();
169 Alignment = MI->getAlignment();
170 assert(Len && "0-sized memory setting should be removed already.");
172 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
173 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
174 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
176 Value *Dest = MI->getDest();
177 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
178 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
179 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
181 // Alignment 0 is identity for alignment 1 for memset, but not store.
182 if (Alignment == 0) Alignment = 1;
184 // Extract the fill value and store.
185 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
186 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
188 S->setAlignment(Alignment);
190 // Set the size of the copy to 0, it will be deleted on the next iteration.
191 MI->setLength(Constant::getNullValue(LenC->getType()));
198 /// visitCallInst - CallInst simplification. This mostly only handles folding
199 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
200 /// the heavy lifting.
202 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
203 if (isFreeCall(&CI, TLI))
204 return visitFree(CI);
206 // If the caller function is nounwind, mark the call as nounwind, even if the
208 if (CI.getParent()->getParent()->doesNotThrow() &&
209 !CI.doesNotThrow()) {
210 CI.setDoesNotThrow();
214 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
215 if (!II) return visitCallSite(&CI);
217 // Intrinsics cannot occur in an invoke, so handle them here instead of in
219 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
220 bool Changed = false;
222 // memmove/cpy/set of zero bytes is a noop.
223 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
224 if (NumBytes->isNullValue())
225 return EraseInstFromFunction(CI);
227 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
228 if (CI->getZExtValue() == 1) {
229 // Replace the instruction with just byte operations. We would
230 // transform other cases to loads/stores, but we don't know if
231 // alignment is sufficient.
235 // No other transformations apply to volatile transfers.
236 if (MI->isVolatile())
239 // If we have a memmove and the source operation is a constant global,
240 // then the source and dest pointers can't alias, so we can change this
241 // into a call to memcpy.
242 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
243 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
244 if (GVSrc->isConstant()) {
245 Module *M = CI.getParent()->getParent()->getParent();
246 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
247 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
248 CI.getArgOperand(1)->getType(),
249 CI.getArgOperand(2)->getType() };
250 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
255 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
256 // memmove(x,x,size) -> noop.
257 if (MTI->getSource() == MTI->getDest())
258 return EraseInstFromFunction(CI);
261 // If we can determine a pointer alignment that is bigger than currently
262 // set, update the alignment.
263 if (isa<MemTransferInst>(MI)) {
264 if (Instruction *I = SimplifyMemTransfer(MI))
266 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
267 if (Instruction *I = SimplifyMemSet(MSI))
271 if (Changed) return II;
274 switch (II->getIntrinsicID()) {
276 case Intrinsic::objectsize: {
278 if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
279 return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
282 case Intrinsic::bswap: {
283 Value *IIOperand = II->getArgOperand(0);
286 // bswap(bswap(x)) -> x
287 if (match(IIOperand, m_BSwap(m_Value(X))))
288 return ReplaceInstUsesWith(CI, X);
290 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
291 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
292 unsigned C = X->getType()->getPrimitiveSizeInBits() -
293 IIOperand->getType()->getPrimitiveSizeInBits();
294 Value *CV = ConstantInt::get(X->getType(), C);
295 Value *V = Builder->CreateLShr(X, CV);
296 return new TruncInst(V, IIOperand->getType());
301 case Intrinsic::powi:
302 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
305 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
308 return ReplaceInstUsesWith(CI, II->getArgOperand(0));
309 // powi(x, -1) -> 1/x
310 if (Power->isAllOnesValue())
311 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
312 II->getArgOperand(0));
315 case Intrinsic::cttz: {
316 // If all bits below the first known one are known zero,
317 // this value is constant.
318 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
319 // FIXME: Try to simplify vectors of integers.
321 uint32_t BitWidth = IT->getBitWidth();
322 APInt KnownZero(BitWidth, 0);
323 APInt KnownOne(BitWidth, 0);
324 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
325 unsigned TrailingZeros = KnownOne.countTrailingZeros();
326 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
327 if ((Mask & KnownZero) == Mask)
328 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
329 APInt(BitWidth, TrailingZeros)));
333 case Intrinsic::ctlz: {
334 // If all bits above the first known one are known zero,
335 // this value is constant.
336 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
337 // FIXME: Try to simplify vectors of integers.
339 uint32_t BitWidth = IT->getBitWidth();
340 APInt KnownZero(BitWidth, 0);
341 APInt KnownOne(BitWidth, 0);
342 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
343 unsigned LeadingZeros = KnownOne.countLeadingZeros();
344 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
345 if ((Mask & KnownZero) == Mask)
346 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
347 APInt(BitWidth, LeadingZeros)));
351 case Intrinsic::uadd_with_overflow: {
352 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
353 IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
354 uint32_t BitWidth = IT->getBitWidth();
355 APInt LHSKnownZero(BitWidth, 0);
356 APInt LHSKnownOne(BitWidth, 0);
357 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
358 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
359 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
361 if (LHSKnownNegative || LHSKnownPositive) {
362 APInt RHSKnownZero(BitWidth, 0);
363 APInt RHSKnownOne(BitWidth, 0);
364 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
365 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
366 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
367 if (LHSKnownNegative && RHSKnownNegative) {
368 // The sign bit is set in both cases: this MUST overflow.
369 // Create a simple add instruction, and insert it into the struct.
370 Value *Add = Builder->CreateAdd(LHS, RHS);
373 UndefValue::get(LHS->getType()),
374 ConstantInt::getTrue(II->getContext())
376 StructType *ST = cast<StructType>(II->getType());
377 Constant *Struct = ConstantStruct::get(ST, V);
378 return InsertValueInst::Create(Struct, Add, 0);
381 if (LHSKnownPositive && RHSKnownPositive) {
382 // The sign bit is clear in both cases: this CANNOT overflow.
383 // Create a simple add instruction, and insert it into the struct.
384 Value *Add = Builder->CreateNUWAdd(LHS, RHS);
387 UndefValue::get(LHS->getType()),
388 ConstantInt::getFalse(II->getContext())
390 StructType *ST = cast<StructType>(II->getType());
391 Constant *Struct = ConstantStruct::get(ST, V);
392 return InsertValueInst::Create(Struct, Add, 0);
396 // FALL THROUGH uadd into sadd
397 case Intrinsic::sadd_with_overflow:
398 // Canonicalize constants into the RHS.
399 if (isa<Constant>(II->getArgOperand(0)) &&
400 !isa<Constant>(II->getArgOperand(1))) {
401 Value *LHS = II->getArgOperand(0);
402 II->setArgOperand(0, II->getArgOperand(1));
403 II->setArgOperand(1, LHS);
407 // X + undef -> undef
408 if (isa<UndefValue>(II->getArgOperand(1)))
409 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
411 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
412 // X + 0 -> {X, false}
415 UndefValue::get(II->getArgOperand(0)->getType()),
416 ConstantInt::getFalse(II->getContext())
419 ConstantStruct::get(cast<StructType>(II->getType()), V);
420 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
424 case Intrinsic::usub_with_overflow:
425 case Intrinsic::ssub_with_overflow:
426 // undef - X -> undef
427 // X - undef -> undef
428 if (isa<UndefValue>(II->getArgOperand(0)) ||
429 isa<UndefValue>(II->getArgOperand(1)))
430 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
432 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
433 // X - 0 -> {X, false}
436 UndefValue::get(II->getArgOperand(0)->getType()),
437 ConstantInt::getFalse(II->getContext())
440 ConstantStruct::get(cast<StructType>(II->getType()), V);
441 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
445 case Intrinsic::umul_with_overflow: {
446 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
447 unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
449 APInt LHSKnownZero(BitWidth, 0);
450 APInt LHSKnownOne(BitWidth, 0);
451 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
452 APInt RHSKnownZero(BitWidth, 0);
453 APInt RHSKnownOne(BitWidth, 0);
454 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
456 // Get the largest possible values for each operand.
457 APInt LHSMax = ~LHSKnownZero;
458 APInt RHSMax = ~RHSKnownZero;
460 // If multiplying the maximum values does not overflow then we can turn
461 // this into a plain NUW mul.
463 LHSMax.umul_ov(RHSMax, Overflow);
465 Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
467 UndefValue::get(LHS->getType()),
470 Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
471 return InsertValueInst::Create(Struct, Mul, 0);
474 case Intrinsic::smul_with_overflow:
475 // Canonicalize constants into the RHS.
476 if (isa<Constant>(II->getArgOperand(0)) &&
477 !isa<Constant>(II->getArgOperand(1))) {
478 Value *LHS = II->getArgOperand(0);
479 II->setArgOperand(0, II->getArgOperand(1));
480 II->setArgOperand(1, LHS);
484 // X * undef -> undef
485 if (isa<UndefValue>(II->getArgOperand(1)))
486 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
488 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
491 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
493 // X * 1 -> {X, false}
494 if (RHSI->equalsInt(1)) {
496 UndefValue::get(II->getArgOperand(0)->getType()),
497 ConstantInt::getFalse(II->getContext())
500 ConstantStruct::get(cast<StructType>(II->getType()), V);
501 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
505 case Intrinsic::ppc_altivec_lvx:
506 case Intrinsic::ppc_altivec_lvxl:
507 // Turn PPC lvx -> load if the pointer is known aligned.
508 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
509 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
510 PointerType::getUnqual(II->getType()));
511 return new LoadInst(Ptr);
514 case Intrinsic::ppc_altivec_stvx:
515 case Intrinsic::ppc_altivec_stvxl:
516 // Turn stvx -> store if the pointer is known aligned.
517 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL) >= 16) {
519 PointerType::getUnqual(II->getArgOperand(0)->getType());
520 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
521 return new StoreInst(II->getArgOperand(0), Ptr);
524 case Intrinsic::x86_sse_storeu_ps:
525 case Intrinsic::x86_sse2_storeu_pd:
526 case Intrinsic::x86_sse2_storeu_dq:
527 // Turn X86 storeu -> store if the pointer is known aligned.
528 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
530 PointerType::getUnqual(II->getArgOperand(1)->getType());
531 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
532 return new StoreInst(II->getArgOperand(1), Ptr);
536 case Intrinsic::x86_sse_cvtss2si:
537 case Intrinsic::x86_sse_cvtss2si64:
538 case Intrinsic::x86_sse_cvttss2si:
539 case Intrinsic::x86_sse_cvttss2si64:
540 case Intrinsic::x86_sse2_cvtsd2si:
541 case Intrinsic::x86_sse2_cvtsd2si64:
542 case Intrinsic::x86_sse2_cvttsd2si:
543 case Intrinsic::x86_sse2_cvttsd2si64: {
544 // These intrinsics only demand the 0th element of their input vectors. If
545 // we can simplify the input based on that, do so now.
547 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
548 APInt DemandedElts(VWidth, 1);
549 APInt UndefElts(VWidth, 0);
550 if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
551 DemandedElts, UndefElts)) {
552 II->setArgOperand(0, V);
559 case Intrinsic::x86_sse41_pmovsxbw:
560 case Intrinsic::x86_sse41_pmovsxwd:
561 case Intrinsic::x86_sse41_pmovsxdq:
562 case Intrinsic::x86_sse41_pmovzxbw:
563 case Intrinsic::x86_sse41_pmovzxwd:
564 case Intrinsic::x86_sse41_pmovzxdq: {
565 // pmov{s|z}x ignores the upper half of their input vectors.
567 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
568 unsigned LowHalfElts = VWidth / 2;
569 APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
570 APInt UndefElts(VWidth, 0);
571 if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
574 II->setArgOperand(0, TmpV);
580 case Intrinsic::x86_avx_vpermilvar_ps:
581 case Intrinsic::x86_avx_vpermilvar_ps_256:
582 case Intrinsic::x86_avx_vpermilvar_pd:
583 case Intrinsic::x86_avx_vpermilvar_pd_256: {
584 // Convert vpermil* to shufflevector if the mask is constant.
585 Value *V = II->getArgOperand(1);
586 if (auto C = dyn_cast<ConstantDataVector>(V)) {
587 auto V1 = II->getArgOperand(0);
588 auto V2 = UndefValue::get(V1->getType());
589 auto Shuffle = Builder->CreateShuffleVector(V1, V2, C);
590 return ReplaceInstUsesWith(CI, Shuffle);
595 case Intrinsic::ppc_altivec_vperm:
596 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
597 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
598 assert(Mask->getType()->getVectorNumElements() == 16 &&
599 "Bad type for intrinsic!");
601 // Check that all of the elements are integer constants or undefs.
602 bool AllEltsOk = true;
603 for (unsigned i = 0; i != 16; ++i) {
604 Constant *Elt = Mask->getAggregateElement(i);
606 !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
613 // Cast the input vectors to byte vectors.
614 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
616 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
618 Value *Result = UndefValue::get(Op0->getType());
620 // Only extract each element once.
621 Value *ExtractedElts[32];
622 memset(ExtractedElts, 0, sizeof(ExtractedElts));
624 for (unsigned i = 0; i != 16; ++i) {
625 if (isa<UndefValue>(Mask->getAggregateElement(i)))
628 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
629 Idx &= 31; // Match the hardware behavior.
631 if (ExtractedElts[Idx] == 0) {
633 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
634 Builder->getInt32(Idx&15));
637 // Insert this value into the result vector.
638 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
639 Builder->getInt32(i));
641 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
646 case Intrinsic::arm_neon_vld1:
647 case Intrinsic::arm_neon_vld2:
648 case Intrinsic::arm_neon_vld3:
649 case Intrinsic::arm_neon_vld4:
650 case Intrinsic::arm_neon_vld2lane:
651 case Intrinsic::arm_neon_vld3lane:
652 case Intrinsic::arm_neon_vld4lane:
653 case Intrinsic::arm_neon_vst1:
654 case Intrinsic::arm_neon_vst2:
655 case Intrinsic::arm_neon_vst3:
656 case Intrinsic::arm_neon_vst4:
657 case Intrinsic::arm_neon_vst2lane:
658 case Intrinsic::arm_neon_vst3lane:
659 case Intrinsic::arm_neon_vst4lane: {
660 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL);
661 unsigned AlignArg = II->getNumArgOperands() - 1;
662 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
663 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
664 II->setArgOperand(AlignArg,
665 ConstantInt::get(Type::getInt32Ty(II->getContext()),
672 case Intrinsic::arm_neon_vmulls:
673 case Intrinsic::arm_neon_vmullu:
674 case Intrinsic::arm64_neon_smull:
675 case Intrinsic::arm64_neon_umull: {
676 Value *Arg0 = II->getArgOperand(0);
677 Value *Arg1 = II->getArgOperand(1);
679 // Handle mul by zero first:
680 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
681 return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
684 // Check for constant LHS & RHS - in this case we just simplify.
685 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
686 II->getIntrinsicID() == Intrinsic::arm64_neon_umull);
687 VectorType *NewVT = cast<VectorType>(II->getType());
688 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
689 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
690 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
691 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
693 return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
696 // Couldn't simplify - canonicalize constant to the RHS.
697 std::swap(Arg0, Arg1);
700 // Handle mul by one:
701 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
702 if (ConstantInt *Splat =
703 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
705 return CastInst::CreateIntegerCast(Arg0, II->getType(),
711 case Intrinsic::stackrestore: {
712 // If the save is right next to the restore, remove the restore. This can
713 // happen when variable allocas are DCE'd.
714 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
715 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
716 BasicBlock::iterator BI = SS;
718 return EraseInstFromFunction(CI);
722 // Scan down this block to see if there is another stack restore in the
723 // same block without an intervening call/alloca.
724 BasicBlock::iterator BI = II;
725 TerminatorInst *TI = II->getParent()->getTerminator();
726 bool CannotRemove = false;
727 for (++BI; &*BI != TI; ++BI) {
728 if (isa<AllocaInst>(BI)) {
732 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
733 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
734 // If there is a stackrestore below this one, remove this one.
735 if (II->getIntrinsicID() == Intrinsic::stackrestore)
736 return EraseInstFromFunction(CI);
737 // Otherwise, ignore the intrinsic.
739 // If we found a non-intrinsic call, we can't remove the stack
747 // If the stack restore is in a return, resume, or unwind block and if there
748 // are no allocas or calls between the restore and the return, nuke the
750 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
751 return EraseInstFromFunction(CI);
756 return visitCallSite(II);
759 // InvokeInst simplification
761 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
762 return visitCallSite(&II);
765 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
766 /// passed through the varargs area, we can eliminate the use of the cast.
767 static bool isSafeToEliminateVarargsCast(const CallSite CS,
768 const CastInst * const CI,
769 const DataLayout * const DL,
771 if (!CI->isLosslessCast())
774 // The size of ByVal or InAlloca arguments is derived from the type, so we
775 // can't change to a type with a different size. If the size were
776 // passed explicitly we could avoid this check.
777 if (!CS.isByValOrInAllocaArgument(ix))
781 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
782 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
783 if (!SrcTy->isSized() || !DstTy->isSized())
785 if (!DL || DL->getTypeAllocSize(SrcTy) != DL->getTypeAllocSize(DstTy))
790 // Try to fold some different type of calls here.
791 // Currently we're only working with the checking functions, memcpy_chk,
792 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
793 // strcat_chk and strncat_chk.
794 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *DL) {
795 if (CI->getCalledFunction() == 0) return 0;
797 if (Value *With = Simplifier->optimizeCall(CI)) {
799 return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
805 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
806 // Strip off at most one level of pointer casts, looking for an alloca. This
807 // is good enough in practice and simpler than handling any number of casts.
808 Value *Underlying = TrampMem->stripPointerCasts();
809 if (Underlying != TrampMem &&
810 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
812 if (!isa<AllocaInst>(Underlying))
815 IntrinsicInst *InitTrampoline = 0;
816 for (User *U : TrampMem->users()) {
817 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
820 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
822 // More than one init_trampoline writes to this value. Give up.
827 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
828 // Allow any number of calls to adjust.trampoline.
833 // No call to init.trampoline found.
837 // Check that the alloca is being used in the expected way.
838 if (InitTrampoline->getOperand(0) != TrampMem)
841 return InitTrampoline;
844 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
846 // Visit all the previous instructions in the basic block, and try to find a
847 // init.trampoline which has a direct path to the adjust.trampoline.
848 for (BasicBlock::iterator I = AdjustTramp,
849 E = AdjustTramp->getParent()->begin(); I != E; ) {
850 Instruction *Inst = --I;
851 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
852 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
853 II->getOperand(0) == TrampMem)
855 if (Inst->mayWriteToMemory())
861 // Given a call to llvm.adjust.trampoline, find and return the corresponding
862 // call to llvm.init.trampoline if the call to the trampoline can be optimized
863 // to a direct call to a function. Otherwise return NULL.
865 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
866 Callee = Callee->stripPointerCasts();
867 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
869 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
872 Value *TrampMem = AdjustTramp->getOperand(0);
874 if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
876 if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
881 // visitCallSite - Improvements for call and invoke instructions.
883 Instruction *InstCombiner::visitCallSite(CallSite CS) {
884 if (isAllocLikeFn(CS.getInstruction(), TLI))
885 return visitAllocSite(*CS.getInstruction());
887 bool Changed = false;
889 // If the callee is a pointer to a function, attempt to move any casts to the
890 // arguments of the call/invoke.
891 Value *Callee = CS.getCalledValue();
892 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
895 if (Function *CalleeF = dyn_cast<Function>(Callee))
896 // If the call and callee calling conventions don't match, this call must
897 // be unreachable, as the call is undefined.
898 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
899 // Only do this for calls to a function with a body. A prototype may
900 // not actually end up matching the implementation's calling conv for a
901 // variety of reasons (e.g. it may be written in assembly).
902 !CalleeF->isDeclaration()) {
903 Instruction *OldCall = CS.getInstruction();
904 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
905 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
907 // If OldCall does not return void then replaceAllUsesWith undef.
908 // This allows ValueHandlers and custom metadata to adjust itself.
909 if (!OldCall->getType()->isVoidTy())
910 ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
911 if (isa<CallInst>(OldCall))
912 return EraseInstFromFunction(*OldCall);
914 // We cannot remove an invoke, because it would change the CFG, just
915 // change the callee to a null pointer.
916 cast<InvokeInst>(OldCall)->setCalledFunction(
917 Constant::getNullValue(CalleeF->getType()));
921 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
922 // If CS does not return void then replaceAllUsesWith undef.
923 // This allows ValueHandlers and custom metadata to adjust itself.
924 if (!CS.getInstruction()->getType()->isVoidTy())
925 ReplaceInstUsesWith(*CS.getInstruction(),
926 UndefValue::get(CS.getInstruction()->getType()));
928 if (isa<InvokeInst>(CS.getInstruction())) {
929 // Can't remove an invoke because we cannot change the CFG.
933 // This instruction is not reachable, just remove it. We insert a store to
934 // undef so that we know that this code is not reachable, despite the fact
935 // that we can't modify the CFG here.
936 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
937 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
938 CS.getInstruction());
940 return EraseInstFromFunction(*CS.getInstruction());
943 if (IntrinsicInst *II = FindInitTrampoline(Callee))
944 return transformCallThroughTrampoline(CS, II);
946 PointerType *PTy = cast<PointerType>(Callee->getType());
947 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
948 if (FTy->isVarArg()) {
949 int ix = FTy->getNumParams();
950 // See if we can optimize any arguments passed through the varargs area of
952 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
953 E = CS.arg_end(); I != E; ++I, ++ix) {
954 CastInst *CI = dyn_cast<CastInst>(*I);
955 if (CI && isSafeToEliminateVarargsCast(CS, CI, DL, ix)) {
956 *I = CI->getOperand(0);
962 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
963 // Inline asm calls cannot throw - mark them 'nounwind'.
964 CS.setDoesNotThrow();
968 // Try to optimize the call if possible, we require DataLayout for most of
969 // this. None of these calls are seen as possibly dead so go ahead and
970 // delete the instruction now.
971 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
972 Instruction *I = tryOptimizeCall(CI, DL);
973 // If we changed something return the result, etc. Otherwise let
974 // the fallthrough check.
975 if (I) return EraseInstFromFunction(*I);
978 return Changed ? CS.getInstruction() : 0;
981 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
982 // attempt to move the cast to the arguments of the call/invoke.
984 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
986 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
989 Instruction *Caller = CS.getInstruction();
990 const AttributeSet &CallerPAL = CS.getAttributes();
992 // Okay, this is a cast from a function to a different type. Unless doing so
993 // would cause a type conversion of one of our arguments, change this call to
994 // be a direct call with arguments casted to the appropriate types.
996 FunctionType *FT = Callee->getFunctionType();
997 Type *OldRetTy = Caller->getType();
998 Type *NewRetTy = FT->getReturnType();
1000 // Check to see if we are changing the return type...
1001 if (OldRetTy != NewRetTy) {
1003 if (NewRetTy->isStructTy())
1004 return false; // TODO: Handle multiple return values.
1006 if (!CastInst::isBitCastable(NewRetTy, OldRetTy)) {
1007 if (Callee->isDeclaration())
1008 return false; // Cannot transform this return value.
1010 if (!Caller->use_empty() &&
1011 // void -> non-void is handled specially
1012 !NewRetTy->isVoidTy())
1013 return false; // Cannot transform this return value.
1016 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
1017 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1019 hasAttributes(AttributeFuncs::
1020 typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
1021 AttributeSet::ReturnIndex))
1022 return false; // Attribute not compatible with transformed value.
1025 // If the callsite is an invoke instruction, and the return value is used by
1026 // a PHI node in a successor, we cannot change the return type of the call
1027 // because there is no place to put the cast instruction (without breaking
1028 // the critical edge). Bail out in this case.
1029 if (!Caller->use_empty())
1030 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1031 for (User *U : II->users())
1032 if (PHINode *PN = dyn_cast<PHINode>(U))
1033 if (PN->getParent() == II->getNormalDest() ||
1034 PN->getParent() == II->getUnwindDest())
1038 unsigned NumActualArgs = CS.arg_size();
1039 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1041 CallSite::arg_iterator AI = CS.arg_begin();
1042 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1043 Type *ParamTy = FT->getParamType(i);
1044 Type *ActTy = (*AI)->getType();
1046 if (!CastInst::isBitCastable(ActTy, ParamTy))
1047 return false; // Cannot transform this parameter value.
1049 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
1050 hasAttributes(AttributeFuncs::
1051 typeIncompatible(ParamTy, i + 1), i + 1))
1052 return false; // Attribute not compatible with transformed value.
1054 if (CS.isInAllocaArgument(i))
1055 return false; // Cannot transform to and from inalloca.
1057 // If the parameter is passed as a byval argument, then we have to have a
1058 // sized type and the sized type has to have the same size as the old type.
1059 if (ParamTy != ActTy &&
1060 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
1061 Attribute::ByVal)) {
1062 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
1063 if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || DL == 0)
1066 Type *CurElTy = ActTy->getPointerElementType();
1067 if (DL->getTypeAllocSize(CurElTy) !=
1068 DL->getTypeAllocSize(ParamPTy->getElementType()))
1073 if (Callee->isDeclaration()) {
1074 // Do not delete arguments unless we have a function body.
1075 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
1078 // If the callee is just a declaration, don't change the varargsness of the
1079 // call. We don't want to introduce a varargs call where one doesn't
1081 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
1082 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
1085 // If both the callee and the cast type are varargs, we still have to make
1086 // sure the number of fixed parameters are the same or we have the same
1087 // ABI issues as if we introduce a varargs call.
1088 if (FT->isVarArg() &&
1089 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
1090 FT->getNumParams() !=
1091 cast<FunctionType>(APTy->getElementType())->getNumParams())
1095 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1096 !CallerPAL.isEmpty())
1097 // In this case we have more arguments than the new function type, but we
1098 // won't be dropping them. Check that these extra arguments have attributes
1099 // that are compatible with being a vararg call argument.
1100 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1101 unsigned Index = CallerPAL.getSlotIndex(i - 1);
1102 if (Index <= FT->getNumParams())
1105 // Check if it has an attribute that's incompatible with varargs.
1106 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
1107 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
1112 // Okay, we decided that this is a safe thing to do: go ahead and start
1113 // inserting cast instructions as necessary.
1114 std::vector<Value*> Args;
1115 Args.reserve(NumActualArgs);
1116 SmallVector<AttributeSet, 8> attrVec;
1117 attrVec.reserve(NumCommonArgs);
1119 // Get any return attributes.
1120 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1122 // If the return value is not being used, the type may not be compatible
1123 // with the existing attributes. Wipe out any problematic attributes.
1125 removeAttributes(AttributeFuncs::
1126 typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
1127 AttributeSet::ReturnIndex);
1129 // Add the new return attributes.
1130 if (RAttrs.hasAttributes())
1131 attrVec.push_back(AttributeSet::get(Caller->getContext(),
1132 AttributeSet::ReturnIndex, RAttrs));
1134 AI = CS.arg_begin();
1135 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1136 Type *ParamTy = FT->getParamType(i);
1138 if ((*AI)->getType() == ParamTy) {
1139 Args.push_back(*AI);
1141 Args.push_back(Builder->CreateBitCast(*AI, ParamTy));
1144 // Add any parameter attributes.
1145 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
1146 if (PAttrs.hasAttributes())
1147 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
1151 // If the function takes more arguments than the call was taking, add them
1153 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1154 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1156 // If we are removing arguments to the function, emit an obnoxious warning.
1157 if (FT->getNumParams() < NumActualArgs) {
1158 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
1159 if (FT->isVarArg()) {
1160 // Add all of the arguments in their promoted form to the arg list.
1161 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1162 Type *PTy = getPromotedType((*AI)->getType());
1163 if (PTy != (*AI)->getType()) {
1164 // Must promote to pass through va_arg area!
1165 Instruction::CastOps opcode =
1166 CastInst::getCastOpcode(*AI, false, PTy, false);
1167 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
1169 Args.push_back(*AI);
1172 // Add any parameter attributes.
1173 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
1174 if (PAttrs.hasAttributes())
1175 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
1181 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
1182 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
1183 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
1185 if (NewRetTy->isVoidTy())
1186 Caller->setName(""); // Void type should not have a name.
1188 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
1192 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1193 NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
1194 II->getUnwindDest(), Args);
1196 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1197 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1199 CallInst *CI = cast<CallInst>(Caller);
1200 NC = Builder->CreateCall(Callee, Args);
1202 if (CI->isTailCall())
1203 cast<CallInst>(NC)->setTailCall();
1204 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1205 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1208 // Insert a cast of the return type as necessary.
1210 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1211 if (!NV->getType()->isVoidTy()) {
1212 NV = NC = CastInst::Create(CastInst::BitCast, NC, OldRetTy);
1213 NC->setDebugLoc(Caller->getDebugLoc());
1215 // If this is an invoke instruction, we should insert it after the first
1216 // non-phi, instruction in the normal successor block.
1217 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1218 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
1219 InsertNewInstBefore(NC, *I);
1221 // Otherwise, it's a call, just insert cast right after the call.
1222 InsertNewInstBefore(NC, *Caller);
1224 Worklist.AddUsersToWorkList(*Caller);
1226 NV = UndefValue::get(Caller->getType());
1230 if (!Caller->use_empty())
1231 ReplaceInstUsesWith(*Caller, NV);
1232 else if (Caller->hasValueHandle())
1233 ValueHandleBase::ValueIsRAUWd(Caller, NV);
1235 EraseInstFromFunction(*Caller);
1239 // transformCallThroughTrampoline - Turn a call to a function created by
1240 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
1241 // underlying function.
1244 InstCombiner::transformCallThroughTrampoline(CallSite CS,
1245 IntrinsicInst *Tramp) {
1246 Value *Callee = CS.getCalledValue();
1247 PointerType *PTy = cast<PointerType>(Callee->getType());
1248 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1249 const AttributeSet &Attrs = CS.getAttributes();
1251 // If the call already has the 'nest' attribute somewhere then give up -
1252 // otherwise 'nest' would occur twice after splicing in the chain.
1253 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1257 "transformCallThroughTrampoline called with incorrect CallSite.");
1259 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
1260 PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1261 FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1263 const AttributeSet &NestAttrs = NestF->getAttributes();
1264 if (!NestAttrs.isEmpty()) {
1265 unsigned NestIdx = 1;
1267 AttributeSet NestAttr;
1269 // Look for a parameter marked with the 'nest' attribute.
1270 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1271 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1272 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
1273 // Record the parameter type and any other attributes.
1275 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1280 Instruction *Caller = CS.getInstruction();
1281 std::vector<Value*> NewArgs;
1282 NewArgs.reserve(CS.arg_size() + 1);
1284 SmallVector<AttributeSet, 8> NewAttrs;
1285 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1287 // Insert the nest argument into the call argument list, which may
1288 // mean appending it. Likewise for attributes.
1290 // Add any result attributes.
1291 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1292 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1293 Attrs.getRetAttributes()));
1297 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1299 if (Idx == NestIdx) {
1300 // Add the chain argument and attributes.
1301 Value *NestVal = Tramp->getArgOperand(2);
1302 if (NestVal->getType() != NestTy)
1303 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
1304 NewArgs.push_back(NestVal);
1305 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1312 // Add the original argument and attributes.
1313 NewArgs.push_back(*I);
1314 AttributeSet Attr = Attrs.getParamAttributes(Idx);
1315 if (Attr.hasAttributes(Idx)) {
1316 AttrBuilder B(Attr, Idx);
1317 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1318 Idx + (Idx >= NestIdx), B));
1325 // Add any function attributes.
1326 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1327 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
1328 Attrs.getFnAttributes()));
1330 // The trampoline may have been bitcast to a bogus type (FTy).
1331 // Handle this by synthesizing a new function type, equal to FTy
1332 // with the chain parameter inserted.
1334 std::vector<Type*> NewTypes;
1335 NewTypes.reserve(FTy->getNumParams()+1);
1337 // Insert the chain's type into the list of parameter types, which may
1338 // mean appending it.
1341 FunctionType::param_iterator I = FTy->param_begin(),
1342 E = FTy->param_end();
1346 // Add the chain's type.
1347 NewTypes.push_back(NestTy);
1352 // Add the original type.
1353 NewTypes.push_back(*I);
1359 // Replace the trampoline call with a direct call. Let the generic
1360 // code sort out any function type mismatches.
1361 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
1363 Constant *NewCallee =
1364 NestF->getType() == PointerType::getUnqual(NewFTy) ?
1365 NestF : ConstantExpr::getBitCast(NestF,
1366 PointerType::getUnqual(NewFTy));
1367 const AttributeSet &NewPAL =
1368 AttributeSet::get(FTy->getContext(), NewAttrs);
1370 Instruction *NewCaller;
1371 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1372 NewCaller = InvokeInst::Create(NewCallee,
1373 II->getNormalDest(), II->getUnwindDest(),
1375 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1376 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1378 NewCaller = CallInst::Create(NewCallee, NewArgs);
1379 if (cast<CallInst>(Caller)->isTailCall())
1380 cast<CallInst>(NewCaller)->setTailCall();
1381 cast<CallInst>(NewCaller)->
1382 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1383 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1390 // Replace the trampoline call with a direct call. Since there is no 'nest'
1391 // parameter, there is no need to adjust the argument list. Let the generic
1392 // code sort out any function type mismatches.
1393 Constant *NewCallee =
1394 NestF->getType() == PTy ? NestF :
1395 ConstantExpr::getBitCast(NestF, PTy);
1396 CS.setCalledFunction(NewCallee);
1397 return CS.getInstruction();