blob: 04b7b2146f6e379679783774f409e7fa1fa8adfb [file] [log] [blame]
Chris Lattner753a2b42010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitCall and visitInvoke functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
Chris Lattner753a2b42010-01-05 07:32:13 +000015#include "llvm/Support/CallSite.h"
Micah Villmow3574eca2012-10-08 16:38:25 +000016#include "llvm/DataLayout.h"
Chris Lattner753a2b42010-01-05 07:32:13 +000017#include "llvm/Analysis/MemoryBuiltins.h"
Eric Christopher27ceaa12010-03-06 10:50:38 +000018#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattner687140c2010-12-25 20:37:57 +000019#include "llvm/Transforms/Utils/Local.h"
Chris Lattner753a2b42010-01-05 07:32:13 +000020using namespace llvm;
21
22/// getPromotedType - Return the specified type promoted as it would be to pass
23/// though a va_arg area.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000024static Type *getPromotedType(Type *Ty) {
25 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner753a2b42010-01-05 07:32:13 +000026 if (ITy->getBitWidth() < 32)
27 return Type::getInt32Ty(Ty->getContext());
28 }
29 return Ty;
30}
31
Dan Gohmance52bc52012-09-13 18:19:06 +000032/// reduceToSingleValueType - Given an aggregate type which ultimately holds a
33/// single scalar element, like {{{type}}} or [1 x type], return type.
34static Type *reduceToSingleValueType(Type *T) {
35 while (!T->isSingleValueType()) {
36 if (StructType *STy = dyn_cast<StructType>(T)) {
37 if (STy->getNumElements() == 1)
38 T = STy->getElementType(0);
39 else
40 break;
41 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
42 if (ATy->getNumElements() == 1)
43 T = ATy->getElementType();
44 else
45 break;
46 } else
47 break;
48 }
49
50 return T;
51}
Chris Lattner753a2b42010-01-05 07:32:13 +000052
53Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Chris Lattner687140c2010-12-25 20:37:57 +000054 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), TD);
55 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), TD);
Chris Lattner753a2b42010-01-05 07:32:13 +000056 unsigned MinAlign = std::min(DstAlign, SrcAlign);
57 unsigned CopyAlign = MI->getAlignment();
58
59 if (CopyAlign < MinAlign) {
Jim Grosbach00e403a2012-02-03 00:07:04 +000060 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Chris Lattner753a2b42010-01-05 07:32:13 +000061 MinAlign, false));
62 return MI;
63 }
Jim Grosbach00e403a2012-02-03 00:07:04 +000064
Chris Lattner753a2b42010-01-05 07:32:13 +000065 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
66 // load/store.
Gabor Greifbcda85c2010-06-24 13:54:33 +000067 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Chris Lattner753a2b42010-01-05 07:32:13 +000068 if (MemOpLength == 0) return 0;
Jim Grosbach00e403a2012-02-03 00:07:04 +000069
Chris Lattner753a2b42010-01-05 07:32:13 +000070 // Source and destination pointer types are always "i8*" for intrinsic. See
71 // if the size is something we can handle with a single primitive load/store.
72 // A single load+store correctly handles overlapping memory in the memmove
73 // case.
Michael Liao9441ad02012-08-15 03:49:59 +000074 uint64_t Size = MemOpLength->getLimitedValue();
75 assert(Size && "0-sized memory transfering should be removed already.");
Jim Grosbach00e403a2012-02-03 00:07:04 +000076
Chris Lattner753a2b42010-01-05 07:32:13 +000077 if (Size > 8 || (Size&(Size-1)))
78 return 0; // If not 1/2/4/8 bytes, exit.
Jim Grosbach00e403a2012-02-03 00:07:04 +000079
Chris Lattner753a2b42010-01-05 07:32:13 +000080 // Use an integer load+store unless we can find something better.
Mon P Wang20adc9d2010-04-04 03:10:48 +000081 unsigned SrcAddrSp =
Gabor Greifbcda85c2010-06-24 13:54:33 +000082 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greif4ec22582010-04-16 15:33:14 +000083 unsigned DstAddrSp =
Gabor Greifbcda85c2010-06-24 13:54:33 +000084 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wang20adc9d2010-04-04 03:10:48 +000085
Chris Lattnerdb125cf2011-07-18 04:54:35 +000086 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wang20adc9d2010-04-04 03:10:48 +000087 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
88 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach00e403a2012-02-03 00:07:04 +000089
Chris Lattner753a2b42010-01-05 07:32:13 +000090 // Memcpy forces the use of i8* for the source and destination. That means
91 // that if you're using memcpy to move one double around, you'll get a cast
92 // from double* to i8*. We'd much rather use a double load+store rather than
93 // an i64 load+store, here because this improves the odds that the source or
94 // dest address will be promotable. See if we can find a better type than the
95 // integer datatype.
Gabor Greifcea7ac72010-06-24 12:58:35 +000096 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
Dan Gohmanb9989132012-09-13 21:51:01 +000097 MDNode *CopyMD = 0;
Gabor Greifcea7ac72010-06-24 12:58:35 +000098 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +000099 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
Chris Lattner753a2b42010-01-05 07:32:13 +0000100 ->getElementType();
101 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
102 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
103 // down through these levels if so.
Dan Gohmance52bc52012-09-13 18:19:06 +0000104 SrcETy = reduceToSingleValueType(SrcETy);
Jim Grosbach00e403a2012-02-03 00:07:04 +0000105
Mon P Wang20adc9d2010-04-04 03:10:48 +0000106 if (SrcETy->isSingleValueType()) {
107 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
108 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
Dan Gohmanb9989132012-09-13 21:51:01 +0000109
110 // If the memcpy has metadata describing the members, see if we can
111 // get the TBAA tag describing our copy.
112 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
113 if (M->getNumOperands() == 3 &&
Nick Lewycky5e01f802012-10-11 02:05:23 +0000114 M->getOperand(0) &&
Dan Gohmanb9989132012-09-13 21:51:01 +0000115 isa<ConstantInt>(M->getOperand(0)) &&
116 cast<ConstantInt>(M->getOperand(0))->isNullValue() &&
Nick Lewycky5e01f802012-10-11 02:05:23 +0000117 M->getOperand(1) &&
Dan Gohmanb9989132012-09-13 21:51:01 +0000118 isa<ConstantInt>(M->getOperand(1)) &&
119 cast<ConstantInt>(M->getOperand(1))->getValue() == Size &&
Nick Lewycky5e01f802012-10-11 02:05:23 +0000120 M->getOperand(2) &&
Dan Gohmanb9989132012-09-13 21:51:01 +0000121 isa<MDNode>(M->getOperand(2)))
122 CopyMD = cast<MDNode>(M->getOperand(2));
123 }
Mon P Wang20adc9d2010-04-04 03:10:48 +0000124 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000125 }
126 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000127
Chris Lattner753a2b42010-01-05 07:32:13 +0000128 // If the memcpy/memmove provides better alignment info than we can
129 // infer, use it.
130 SrcAlign = std::max(SrcAlign, CopyAlign);
131 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach00e403a2012-02-03 00:07:04 +0000132
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000133 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
134 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman59f15912011-05-18 19:57:14 +0000135 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
136 L->setAlignment(SrcAlign);
Dan Gohmanb9989132012-09-13 21:51:01 +0000137 if (CopyMD)
138 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Eli Friedman59f15912011-05-18 19:57:14 +0000139 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
140 S->setAlignment(DstAlign);
Dan Gohmanb9989132012-09-13 21:51:01 +0000141 if (CopyMD)
142 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Chris Lattner753a2b42010-01-05 07:32:13 +0000143
144 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000145 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000146 return MI;
147}
148
149Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Chris Lattnerae47be12010-12-25 20:52:04 +0000150 unsigned Alignment = getKnownAlignment(MI->getDest(), TD);
Chris Lattner753a2b42010-01-05 07:32:13 +0000151 if (MI->getAlignment() < Alignment) {
152 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
153 Alignment, false));
154 return MI;
155 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000156
Chris Lattner753a2b42010-01-05 07:32:13 +0000157 // Extract the length and alignment and fill if they are constant.
158 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
159 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000160 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Chris Lattner753a2b42010-01-05 07:32:13 +0000161 return 0;
Michael Liao9441ad02012-08-15 03:49:59 +0000162 uint64_t Len = LenC->getLimitedValue();
Chris Lattner753a2b42010-01-05 07:32:13 +0000163 Alignment = MI->getAlignment();
Michael Liao9441ad02012-08-15 03:49:59 +0000164 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach00e403a2012-02-03 00:07:04 +0000165
Chris Lattner753a2b42010-01-05 07:32:13 +0000166 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
167 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000168 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach00e403a2012-02-03 00:07:04 +0000169
Chris Lattner753a2b42010-01-05 07:32:13 +0000170 Value *Dest = MI->getDest();
Mon P Wang55fb9b02010-12-20 01:05:30 +0000171 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
172 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
173 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner753a2b42010-01-05 07:32:13 +0000174
175 // Alignment 0 is identity for alignment 1 for memset, but not store.
176 if (Alignment == 0) Alignment = 1;
Jim Grosbach00e403a2012-02-03 00:07:04 +0000177
Chris Lattner753a2b42010-01-05 07:32:13 +0000178 // Extract the fill value and store.
179 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman59f15912011-05-18 19:57:14 +0000180 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
181 MI->isVolatile());
182 S->setAlignment(Alignment);
Jim Grosbach00e403a2012-02-03 00:07:04 +0000183
Chris Lattner753a2b42010-01-05 07:32:13 +0000184 // Set the size of the copy to 0, it will be deleted on the next iteration.
185 MI->setLength(Constant::getNullValue(LenC->getType()));
186 return MI;
187 }
188
189 return 0;
190}
191
Jim Grosbach00e403a2012-02-03 00:07:04 +0000192/// visitCallInst - CallInst simplification. This mostly only handles folding
Chris Lattner753a2b42010-01-05 07:32:13 +0000193/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
194/// the heavy lifting.
195///
196Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000197 if (isFreeCall(&CI, TLI))
Chris Lattner753a2b42010-01-05 07:32:13 +0000198 return visitFree(CI);
199
200 // If the caller function is nounwind, mark the call as nounwind, even if the
201 // callee isn't.
202 if (CI.getParent()->getParent()->doesNotThrow() &&
203 !CI.doesNotThrow()) {
204 CI.setDoesNotThrow();
205 return &CI;
206 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000207
Chris Lattner753a2b42010-01-05 07:32:13 +0000208 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
209 if (!II) return visitCallSite(&CI);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000210
Chris Lattner753a2b42010-01-05 07:32:13 +0000211 // Intrinsics cannot occur in an invoke, so handle them here instead of in
212 // visitCallSite.
213 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
214 bool Changed = false;
215
216 // memmove/cpy/set of zero bytes is a noop.
217 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattner6eff7512010-10-01 05:51:02 +0000218 if (NumBytes->isNullValue())
219 return EraseInstFromFunction(CI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000220
221 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
222 if (CI->getZExtValue() == 1) {
223 // Replace the instruction with just byte operations. We would
224 // transform other cases to loads/stores, but we don't know if
225 // alignment is sufficient.
226 }
227 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000228
Chris Lattner6eff7512010-10-01 05:51:02 +0000229 // No other transformations apply to volatile transfers.
230 if (MI->isVolatile())
231 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +0000232
233 // If we have a memmove and the source operation is a constant global,
234 // then the source and dest pointers can't alias, so we can change this
235 // into a call to memcpy.
236 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
237 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
238 if (GVSrc->isConstant()) {
Eric Christopher551754c2010-04-16 23:37:20 +0000239 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner753a2b42010-01-05 07:32:13 +0000240 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foad5fdd6c82011-07-12 14:06:48 +0000241 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
242 CI.getArgOperand(1)->getType(),
243 CI.getArgOperand(2)->getType() };
Benjamin Kramereb9a85f2011-07-14 17:45:39 +0000244 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner753a2b42010-01-05 07:32:13 +0000245 Changed = true;
246 }
247 }
248
249 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
250 // memmove(x,x,size) -> noop.
251 if (MTI->getSource() == MTI->getDest())
252 return EraseInstFromFunction(CI);
Eric Christopher551754c2010-04-16 23:37:20 +0000253 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000254
Eric Christopher551754c2010-04-16 23:37:20 +0000255 // If we can determine a pointer alignment that is bigger than currently
256 // set, update the alignment.
257 if (isa<MemTransferInst>(MI)) {
258 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner753a2b42010-01-05 07:32:13 +0000259 return I;
260 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
261 if (Instruction *I = SimplifyMemSet(MSI))
262 return I;
263 }
Gabor Greifc310fcc2010-06-24 13:42:49 +0000264
Chris Lattner753a2b42010-01-05 07:32:13 +0000265 if (Changed) return II;
266 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000267
Chris Lattner753a2b42010-01-05 07:32:13 +0000268 switch (II->getIntrinsicID()) {
269 default: break;
Eric Christopher415326b2010-02-09 21:24:27 +0000270 case Intrinsic::objectsize: {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000271 uint64_t Size;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000272 if (getObjectSize(II->getArgOperand(0), Size, TD, TLI))
Nuno Lopes9e72a792012-06-21 15:45:28 +0000273 return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
274 return 0;
Eric Christopher415326b2010-02-09 21:24:27 +0000275 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000276 case Intrinsic::bswap:
277 // bswap(bswap(x)) -> x
Gabor Greifcea7ac72010-06-24 12:58:35 +0000278 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getArgOperand(0)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000279 if (Operand->getIntrinsicID() == Intrinsic::bswap)
Gabor Greifcea7ac72010-06-24 12:58:35 +0000280 return ReplaceInstUsesWith(CI, Operand->getArgOperand(0));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000281
Chris Lattner753a2b42010-01-05 07:32:13 +0000282 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Gabor Greifcea7ac72010-06-24 12:58:35 +0000283 if (TruncInst *TI = dyn_cast<TruncInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000284 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
285 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
286 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
287 TI->getType()->getPrimitiveSizeInBits();
288 Value *CV = ConstantInt::get(Operand->getType(), C);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000289 Value *V = Builder->CreateLShr(Operand->getArgOperand(0), CV);
Chris Lattner753a2b42010-01-05 07:32:13 +0000290 return new TruncInst(V, TI->getType());
291 }
292 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000293
Chris Lattner753a2b42010-01-05 07:32:13 +0000294 break;
295 case Intrinsic::powi:
Gabor Greifcea7ac72010-06-24 12:58:35 +0000296 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000297 // powi(x, 0) -> 1.0
298 if (Power->isZero())
299 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
300 // powi(x, 1) -> x
301 if (Power->isOne())
Gabor Greifcea7ac72010-06-24 12:58:35 +0000302 return ReplaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000303 // powi(x, -1) -> 1/x
304 if (Power->isAllOnesValue())
305 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greifcea7ac72010-06-24 12:58:35 +0000306 II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000307 }
308 break;
309 case Intrinsic::cttz: {
310 // If all bits below the first known one are known zero,
311 // this value is constant.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000312 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Andersonf1ac4652011-07-01 21:52:38 +0000313 // FIXME: Try to simplify vectors of integers.
314 if (!IT) break;
Chris Lattner753a2b42010-01-05 07:32:13 +0000315 uint32_t BitWidth = IT->getBitWidth();
316 APInt KnownZero(BitWidth, 0);
317 APInt KnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000318 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
Chris Lattner753a2b42010-01-05 07:32:13 +0000319 unsigned TrailingZeros = KnownOne.countTrailingZeros();
320 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
321 if ((Mask & KnownZero) == Mask)
322 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
323 APInt(BitWidth, TrailingZeros)));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000324
Chris Lattner753a2b42010-01-05 07:32:13 +0000325 }
326 break;
327 case Intrinsic::ctlz: {
328 // If all bits above the first known one are known zero,
329 // this value is constant.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000330 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Andersonf1ac4652011-07-01 21:52:38 +0000331 // FIXME: Try to simplify vectors of integers.
332 if (!IT) break;
Chris Lattner753a2b42010-01-05 07:32:13 +0000333 uint32_t BitWidth = IT->getBitWidth();
334 APInt KnownZero(BitWidth, 0);
335 APInt KnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000336 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
Chris Lattner753a2b42010-01-05 07:32:13 +0000337 unsigned LeadingZeros = KnownOne.countLeadingZeros();
338 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
339 if ((Mask & KnownZero) == Mask)
340 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
341 APInt(BitWidth, LeadingZeros)));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000342
Chris Lattner753a2b42010-01-05 07:32:13 +0000343 }
344 break;
345 case Intrinsic::uadd_with_overflow: {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000346 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000347 IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000348 uint32_t BitWidth = IT->getBitWidth();
Chris Lattner753a2b42010-01-05 07:32:13 +0000349 APInt LHSKnownZero(BitWidth, 0);
350 APInt LHSKnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000351 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
Chris Lattner753a2b42010-01-05 07:32:13 +0000352 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
353 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
354
355 if (LHSKnownNegative || LHSKnownPositive) {
356 APInt RHSKnownZero(BitWidth, 0);
357 APInt RHSKnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000358 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
Chris Lattner753a2b42010-01-05 07:32:13 +0000359 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
360 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
361 if (LHSKnownNegative && RHSKnownNegative) {
362 // The sign bit is set in both cases: this MUST overflow.
363 // Create a simple add instruction, and insert it into the struct.
Eli Friedman59f15912011-05-18 19:57:14 +0000364 Value *Add = Builder->CreateAdd(LHS, RHS);
365 Add->takeName(&CI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000366 Constant *V[] = {
Eli Friedman59f15912011-05-18 19:57:14 +0000367 UndefValue::get(LHS->getType()),
368 ConstantInt::getTrue(II->getContext())
Chris Lattner753a2b42010-01-05 07:32:13 +0000369 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000370 StructType *ST = cast<StructType>(II->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +0000371 Constant *Struct = ConstantStruct::get(ST, V);
Chris Lattner753a2b42010-01-05 07:32:13 +0000372 return InsertValueInst::Create(Struct, Add, 0);
373 }
Eli Friedman59f15912011-05-18 19:57:14 +0000374
Chris Lattner753a2b42010-01-05 07:32:13 +0000375 if (LHSKnownPositive && RHSKnownPositive) {
376 // The sign bit is clear in both cases: this CANNOT overflow.
377 // Create a simple add instruction, and insert it into the struct.
Eli Friedman59f15912011-05-18 19:57:14 +0000378 Value *Add = Builder->CreateNUWAdd(LHS, RHS);
379 Add->takeName(&CI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000380 Constant *V[] = {
381 UndefValue::get(LHS->getType()),
382 ConstantInt::getFalse(II->getContext())
383 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000384 StructType *ST = cast<StructType>(II->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +0000385 Constant *Struct = ConstantStruct::get(ST, V);
Chris Lattner753a2b42010-01-05 07:32:13 +0000386 return InsertValueInst::Create(Struct, Add, 0);
387 }
388 }
389 }
390 // FALL THROUGH uadd into sadd
391 case Intrinsic::sadd_with_overflow:
392 // Canonicalize constants into the RHS.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000393 if (isa<Constant>(II->getArgOperand(0)) &&
394 !isa<Constant>(II->getArgOperand(1))) {
395 Value *LHS = II->getArgOperand(0);
396 II->setArgOperand(0, II->getArgOperand(1));
397 II->setArgOperand(1, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000398 return II;
399 }
400
401 // X + undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000402 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000403 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000404
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000405 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000406 // X + 0 -> {X, false}
407 if (RHS->isZero()) {
408 Constant *V[] = {
Eli Friedman4fffb342010-08-09 20:49:43 +0000409 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000410 ConstantInt::getFalse(II->getContext())
411 };
Chris Lattnerb065b062011-06-20 04:01:31 +0000412 Constant *Struct =
413 ConstantStruct::get(cast<StructType>(II->getType()), V);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000414 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000415 }
416 }
417 break;
418 case Intrinsic::usub_with_overflow:
419 case Intrinsic::ssub_with_overflow:
420 // undef - X -> undef
421 // X - undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000422 if (isa<UndefValue>(II->getArgOperand(0)) ||
423 isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000424 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000425
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000426 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000427 // X - 0 -> {X, false}
428 if (RHS->isZero()) {
429 Constant *V[] = {
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000430 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000431 ConstantInt::getFalse(II->getContext())
432 };
Jim Grosbach00e403a2012-02-03 00:07:04 +0000433 Constant *Struct =
Chris Lattnerb065b062011-06-20 04:01:31 +0000434 ConstantStruct::get(cast<StructType>(II->getType()), V);
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000435 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000436 }
437 }
438 break;
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000439 case Intrinsic::umul_with_overflow: {
440 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
441 unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000442
443 APInt LHSKnownZero(BitWidth, 0);
444 APInt LHSKnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000445 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000446 APInt RHSKnownZero(BitWidth, 0);
447 APInt RHSKnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000448 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000449
Benjamin Kramerd655e6e2011-03-27 15:04:38 +0000450 // Get the largest possible values for each operand.
451 APInt LHSMax = ~LHSKnownZero;
452 APInt RHSMax = ~RHSKnownZero;
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000453
454 // If multiplying the maximum values does not overflow then we can turn
455 // this into a plain NUW mul.
Benjamin Kramerd655e6e2011-03-27 15:04:38 +0000456 bool Overflow;
457 LHSMax.umul_ov(RHSMax, Overflow);
458 if (!Overflow) {
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000459 Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
460 Constant *V[] = {
461 UndefValue::get(LHS->getType()),
462 Builder->getFalse()
463 };
Chris Lattnerb065b062011-06-20 04:01:31 +0000464 Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000465 return InsertValueInst::Create(Struct, Mul, 0);
466 }
467 } // FALL THROUGH
Chris Lattner753a2b42010-01-05 07:32:13 +0000468 case Intrinsic::smul_with_overflow:
469 // Canonicalize constants into the RHS.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000470 if (isa<Constant>(II->getArgOperand(0)) &&
471 !isa<Constant>(II->getArgOperand(1))) {
472 Value *LHS = II->getArgOperand(0);
473 II->setArgOperand(0, II->getArgOperand(1));
474 II->setArgOperand(1, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000475 return II;
476 }
477
478 // X * undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000479 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000480 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000481
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000482 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000483 // X*0 -> {0, false}
484 if (RHSI->isZero())
485 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000486
Chris Lattner753a2b42010-01-05 07:32:13 +0000487 // X * 1 -> {X, false}
488 if (RHSI->equalsInt(1)) {
489 Constant *V[] = {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000490 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000491 ConstantInt::getFalse(II->getContext())
492 };
Jim Grosbach00e403a2012-02-03 00:07:04 +0000493 Constant *Struct =
Chris Lattnerb065b062011-06-20 04:01:31 +0000494 ConstantStruct::get(cast<StructType>(II->getType()), V);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000495 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000496 }
497 }
498 break;
499 case Intrinsic::ppc_altivec_lvx:
500 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingf93f7b22011-04-13 00:36:11 +0000501 // Turn PPC lvx -> load if the pointer is known aligned.
Chris Lattner687140c2010-12-25 20:37:57 +0000502 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000503 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner753a2b42010-01-05 07:32:13 +0000504 PointerType::getUnqual(II->getType()));
505 return new LoadInst(Ptr);
506 }
507 break;
508 case Intrinsic::ppc_altivec_stvx:
509 case Intrinsic::ppc_altivec_stvxl:
510 // Turn stvx -> store if the pointer is known aligned.
Chris Lattner687140c2010-12-25 20:37:57 +0000511 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, TD) >= 16) {
Jim Grosbach00e403a2012-02-03 00:07:04 +0000512 Type *OpPtrTy =
Gabor Greif2f1ab742010-06-24 15:51:11 +0000513 PointerType::getUnqual(II->getArgOperand(0)->getType());
514 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
515 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000516 }
517 break;
518 case Intrinsic::x86_sse_storeu_ps:
519 case Intrinsic::x86_sse2_storeu_pd:
520 case Intrinsic::x86_sse2_storeu_dq:
521 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattner687140c2010-12-25 20:37:57 +0000522 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) {
Jim Grosbach00e403a2012-02-03 00:07:04 +0000523 Type *OpPtrTy =
Gabor Greif2f1ab742010-06-24 15:51:11 +0000524 PointerType::getUnqual(II->getArgOperand(1)->getType());
525 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
526 return new StoreInst(II->getArgOperand(1), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000527 }
528 break;
Chandler Carruth9cc9f502011-01-10 07:19:37 +0000529
530 case Intrinsic::x86_sse_cvtss2si:
531 case Intrinsic::x86_sse_cvtss2si64:
532 case Intrinsic::x86_sse_cvttss2si:
533 case Intrinsic::x86_sse_cvttss2si64:
534 case Intrinsic::x86_sse2_cvtsd2si:
535 case Intrinsic::x86_sse2_cvtsd2si64:
536 case Intrinsic::x86_sse2_cvttsd2si:
537 case Intrinsic::x86_sse2_cvttsd2si64: {
538 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner753a2b42010-01-05 07:32:13 +0000539 // we can simplify the input based on that, do so now.
540 unsigned VWidth =
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000541 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
Chris Lattner753a2b42010-01-05 07:32:13 +0000542 APInt DemandedElts(VWidth, 1);
543 APInt UndefElts(VWidth, 0);
Gabor Greifa3997812010-07-22 10:37:47 +0000544 if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
545 DemandedElts, UndefElts)) {
Gabor Greifa90c5c72010-06-28 16:50:57 +0000546 II->setArgOperand(0, V);
Chris Lattner753a2b42010-01-05 07:32:13 +0000547 return II;
548 }
549 break;
550 }
Chandler Carruth9cc9f502011-01-10 07:19:37 +0000551
Stuart Hastingsca1ef482011-05-17 22:13:31 +0000552
553 case Intrinsic::x86_sse41_pmovsxbw:
554 case Intrinsic::x86_sse41_pmovsxwd:
555 case Intrinsic::x86_sse41_pmovsxdq:
556 case Intrinsic::x86_sse41_pmovzxbw:
557 case Intrinsic::x86_sse41_pmovzxwd:
558 case Intrinsic::x86_sse41_pmovzxdq: {
Evan Chengaaa7f492011-05-19 18:18:39 +0000559 // pmov{s|z}x ignores the upper half of their input vectors.
Stuart Hastingsca1ef482011-05-17 22:13:31 +0000560 unsigned VWidth =
561 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
562 unsigned LowHalfElts = VWidth / 2;
Stuart Hastingsd1166112011-05-18 15:54:26 +0000563 APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
Stuart Hastingsca1ef482011-05-17 22:13:31 +0000564 APInt UndefElts(VWidth, 0);
565 if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
566 InputDemandedElts,
567 UndefElts)) {
568 II->setArgOperand(0, TmpV);
569 return II;
570 }
571 break;
572 }
573
Chris Lattner753a2b42010-01-05 07:32:13 +0000574 case Intrinsic::ppc_altivec_vperm:
575 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000576 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
577 assert(Mask->getType()->getVectorNumElements() == 16 &&
578 "Bad type for intrinsic!");
Jim Grosbach00e403a2012-02-03 00:07:04 +0000579
Chris Lattner753a2b42010-01-05 07:32:13 +0000580 // Check that all of the elements are integer constants or undefs.
581 bool AllEltsOk = true;
582 for (unsigned i = 0; i != 16; ++i) {
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000583 Constant *Elt = Mask->getAggregateElement(i);
584 if (Elt == 0 ||
585 !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000586 AllEltsOk = false;
587 break;
588 }
589 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000590
Chris Lattner753a2b42010-01-05 07:32:13 +0000591 if (AllEltsOk) {
592 // Cast the input vectors to byte vectors.
Gabor Greifa3997812010-07-22 10:37:47 +0000593 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
594 Mask->getType());
595 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
596 Mask->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000597 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach00e403a2012-02-03 00:07:04 +0000598
Chris Lattner753a2b42010-01-05 07:32:13 +0000599 // Only extract each element once.
600 Value *ExtractedElts[32];
601 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000602
Chris Lattner753a2b42010-01-05 07:32:13 +0000603 for (unsigned i = 0; i != 16; ++i) {
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000604 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000605 continue;
Jim Grosbach00e403a2012-02-03 00:07:04 +0000606 unsigned Idx =
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000607 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner753a2b42010-01-05 07:32:13 +0000608 Idx &= 31; // Match the hardware behavior.
Jim Grosbach00e403a2012-02-03 00:07:04 +0000609
Chris Lattner753a2b42010-01-05 07:32:13 +0000610 if (ExtractedElts[Idx] == 0) {
Jim Grosbach00e403a2012-02-03 00:07:04 +0000611 ExtractedElts[Idx] =
Benjamin Kramera9390a42011-09-27 20:39:19 +0000612 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
613 Builder->getInt32(Idx&15));
Chris Lattner753a2b42010-01-05 07:32:13 +0000614 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000615
Chris Lattner753a2b42010-01-05 07:32:13 +0000616 // Insert this value into the result vector.
617 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramera9390a42011-09-27 20:39:19 +0000618 Builder->getInt32(i));
Chris Lattner753a2b42010-01-05 07:32:13 +0000619 }
620 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
621 }
622 }
623 break;
624
Bob Wilson364f17c2010-10-22 21:41:48 +0000625 case Intrinsic::arm_neon_vld1:
626 case Intrinsic::arm_neon_vld2:
627 case Intrinsic::arm_neon_vld3:
628 case Intrinsic::arm_neon_vld4:
629 case Intrinsic::arm_neon_vld2lane:
630 case Intrinsic::arm_neon_vld3lane:
631 case Intrinsic::arm_neon_vld4lane:
632 case Intrinsic::arm_neon_vst1:
633 case Intrinsic::arm_neon_vst2:
634 case Intrinsic::arm_neon_vst3:
635 case Intrinsic::arm_neon_vst4:
636 case Intrinsic::arm_neon_vst2lane:
637 case Intrinsic::arm_neon_vst3lane:
638 case Intrinsic::arm_neon_vst4lane: {
Chris Lattnerae47be12010-12-25 20:52:04 +0000639 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), TD);
Bob Wilson364f17c2010-10-22 21:41:48 +0000640 unsigned AlignArg = II->getNumArgOperands() - 1;
641 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
642 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
643 II->setArgOperand(AlignArg,
644 ConstantInt::get(Type::getInt32Ty(II->getContext()),
645 MemAlign, false));
646 return II;
647 }
648 break;
649 }
650
Lang Hames973f72a2012-05-01 00:20:38 +0000651 case Intrinsic::arm_neon_vmulls:
652 case Intrinsic::arm_neon_vmullu: {
653 Value *Arg0 = II->getArgOperand(0);
654 Value *Arg1 = II->getArgOperand(1);
655
656 // Handle mul by zero first:
657 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
658 return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
659 }
660
661 // Check for constant LHS & RHS - in this case we just simplify.
662 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu);
663 VectorType *NewVT = cast<VectorType>(II->getType());
664 unsigned NewWidth = NewVT->getElementType()->getIntegerBitWidth();
665 if (ConstantDataVector *CV0 = dyn_cast<ConstantDataVector>(Arg0)) {
666 if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) {
667 VectorType* VT = cast<VectorType>(CV0->getType());
668 SmallVector<Constant*, 4> NewElems;
669 for (unsigned i = 0; i < VT->getNumElements(); ++i) {
670 APInt CV0E =
671 (cast<ConstantInt>(CV0->getAggregateElement(i)))->getValue();
672 CV0E = Zext ? CV0E.zext(NewWidth) : CV0E.sext(NewWidth);
673 APInt CV1E =
674 (cast<ConstantInt>(CV1->getAggregateElement(i)))->getValue();
675 CV1E = Zext ? CV1E.zext(NewWidth) : CV1E.sext(NewWidth);
676 NewElems.push_back(
677 ConstantInt::get(NewVT->getElementType(), CV0E * CV1E));
678 }
679 return ReplaceInstUsesWith(CI, ConstantVector::get(NewElems));
680 }
681
682 // Couldn't simplify - cannonicalize constant to the RHS.
683 std::swap(Arg0, Arg1);
684 }
685
686 // Handle mul by one:
687 if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) {
688 if (ConstantInt *Splat =
689 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) {
690 if (Splat->isOne()) {
691 if (Zext)
692 return CastInst::CreateZExtOrBitCast(Arg0, II->getType());
693 // else
694 return CastInst::CreateSExtOrBitCast(Arg0, II->getType());
695 }
696 }
697 }
698
699 break;
700 }
701
Chris Lattner753a2b42010-01-05 07:32:13 +0000702 case Intrinsic::stackrestore: {
703 // If the save is right next to the restore, remove the restore. This can
704 // happen when variable allocas are DCE'd.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000705 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000706 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
707 BasicBlock::iterator BI = SS;
708 if (&*++BI == II)
709 return EraseInstFromFunction(CI);
710 }
711 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000712
Chris Lattner753a2b42010-01-05 07:32:13 +0000713 // Scan down this block to see if there is another stack restore in the
714 // same block without an intervening call/alloca.
715 BasicBlock::iterator BI = II;
716 TerminatorInst *TI = II->getParent()->getTerminator();
717 bool CannotRemove = false;
718 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000719 if (isa<AllocaInst>(BI)) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000720 CannotRemove = true;
721 break;
722 }
723 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
724 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
725 // If there is a stackrestore below this one, remove this one.
726 if (II->getIntrinsicID() == Intrinsic::stackrestore)
727 return EraseInstFromFunction(CI);
728 // Otherwise, ignore the intrinsic.
729 } else {
730 // If we found a non-intrinsic call, we can't remove the stack
731 // restore.
732 CannotRemove = true;
733 break;
734 }
735 }
736 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000737
Bill Wendlingdccc03b2011-07-31 06:30:59 +0000738 // If the stack restore is in a return, resume, or unwind block and if there
739 // are no allocas or calls between the restore and the return, nuke the
740 // restore.
Bill Wendlingaa5abe82012-02-06 21:16:41 +0000741 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000742 return EraseInstFromFunction(CI);
743 break;
744 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000745 }
746
747 return visitCallSite(II);
748}
749
750// InvokeInst simplification
751//
752Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
753 return visitCallSite(&II);
754}
755
Jim Grosbach00e403a2012-02-03 00:07:04 +0000756/// isSafeToEliminateVarargsCast - If this cast does not affect the value
Chris Lattner753a2b42010-01-05 07:32:13 +0000757/// passed through the varargs area, we can eliminate the use of the cast.
758static bool isSafeToEliminateVarargsCast(const CallSite CS,
759 const CastInst * const CI,
Micah Villmow3574eca2012-10-08 16:38:25 +0000760 const DataLayout * const TD,
Chris Lattner753a2b42010-01-05 07:32:13 +0000761 const int ix) {
762 if (!CI->isLosslessCast())
763 return false;
764
765 // The size of ByVal arguments is derived from the type, so we
766 // can't change to a type with a different size. If the size were
767 // passed explicitly we could avoid this check.
Nick Lewycky173862e2011-11-20 19:09:04 +0000768 if (!CS.isByValArgument(ix))
Chris Lattner753a2b42010-01-05 07:32:13 +0000769 return true;
770
Jim Grosbach00e403a2012-02-03 00:07:04 +0000771 Type* SrcTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000772 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000773 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner753a2b42010-01-05 07:32:13 +0000774 if (!SrcTy->isSized() || !DstTy->isSized())
775 return false;
776 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
777 return false;
778 return true;
779}
780
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000781namespace {
782class InstCombineFortifiedLibCalls : public SimplifyFortifiedLibCalls {
783 InstCombiner *IC;
784protected:
785 void replaceCall(Value *With) {
786 NewInstruction = IC->ReplaceInstUsesWith(*CI, With);
787 }
788 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
Benjamin Kramer8143a842011-01-06 14:22:52 +0000789 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
790 return true;
Gabor Greifa3997812010-07-22 10:37:47 +0000791 if (ConstantInt *SizeCI =
792 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000793 if (SizeCI->isAllOnesValue())
794 return true;
Eric Christopherb9b80c32011-03-15 00:25:41 +0000795 if (isString) {
796 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
797 // If the length is 0 we don't know how long it is and so we can't
798 // remove the check.
799 if (Len == 0) return false;
800 return SizeCI->getZExtValue() >= Len;
801 }
Gabor Greifa3997812010-07-22 10:37:47 +0000802 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
803 CI->getArgOperand(SizeArgOp)))
Evan Cheng9d8f0022010-03-23 06:06:09 +0000804 return SizeCI->getZExtValue() >= Arg->getZExtValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000805 }
806 return false;
807 }
808public:
809 InstCombineFortifiedLibCalls(InstCombiner *IC) : IC(IC), NewInstruction(0) { }
810 Instruction *NewInstruction;
811};
812} // end anonymous namespace
813
Eric Christopher27ceaa12010-03-06 10:50:38 +0000814// Try to fold some different type of calls here.
Jim Grosbach00e403a2012-02-03 00:07:04 +0000815// Currently we're only working with the checking functions, memcpy_chk,
Eric Christopher27ceaa12010-03-06 10:50:38 +0000816// mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
817// strcat_chk and strncat_chk.
Micah Villmow3574eca2012-10-08 16:38:25 +0000818Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *TD) {
Eric Christopher27ceaa12010-03-06 10:50:38 +0000819 if (CI->getCalledFunction() == 0) return 0;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000820
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000821 InstCombineFortifiedLibCalls Simplifier(this);
Nuno Lopes51004df2012-07-25 16:46:31 +0000822 Simplifier.fold(CI, TD, TLI);
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000823 return Simplifier.NewInstruction;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000824}
825
Duncan Sands4a544a72011-09-06 13:37:06 +0000826static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
827 // Strip off at most one level of pointer casts, looking for an alloca. This
828 // is good enough in practice and simpler than handling any number of casts.
829 Value *Underlying = TrampMem->stripPointerCasts();
830 if (Underlying != TrampMem &&
831 (!Underlying->hasOneUse() || *Underlying->use_begin() != TrampMem))
832 return 0;
833 if (!isa<AllocaInst>(Underlying))
834 return 0;
835
836 IntrinsicInst *InitTrampoline = 0;
837 for (Value::use_iterator I = TrampMem->use_begin(), E = TrampMem->use_end();
838 I != E; I++) {
839 IntrinsicInst *II = dyn_cast<IntrinsicInst>(*I);
840 if (!II)
841 return 0;
842 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
843 if (InitTrampoline)
844 // More than one init_trampoline writes to this value. Give up.
845 return 0;
846 InitTrampoline = II;
847 continue;
848 }
849 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
850 // Allow any number of calls to adjust.trampoline.
851 continue;
852 return 0;
853 }
854
855 // No call to init.trampoline found.
856 if (!InitTrampoline)
857 return 0;
858
859 // Check that the alloca is being used in the expected way.
860 if (InitTrampoline->getOperand(0) != TrampMem)
861 return 0;
862
863 return InitTrampoline;
864}
865
866static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
867 Value *TrampMem) {
868 // Visit all the previous instructions in the basic block, and try to find a
869 // init.trampoline which has a direct path to the adjust.trampoline.
870 for (BasicBlock::iterator I = AdjustTramp,
871 E = AdjustTramp->getParent()->begin(); I != E; ) {
872 Instruction *Inst = --I;
873 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
874 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
875 II->getOperand(0) == TrampMem)
876 return II;
877 if (Inst->mayWriteToMemory())
878 return 0;
879 }
880 return 0;
881}
882
883// Given a call to llvm.adjust.trampoline, find and return the corresponding
884// call to llvm.init.trampoline if the call to the trampoline can be optimized
885// to a direct call to a function. Otherwise return NULL.
886//
887static IntrinsicInst *FindInitTrampoline(Value *Callee) {
888 Callee = Callee->stripPointerCasts();
889 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
890 if (!AdjustTramp ||
891 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
892 return 0;
893
894 Value *TrampMem = AdjustTramp->getOperand(0);
895
896 if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
897 return IT;
898 if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
899 return IT;
900 return 0;
901}
902
Chris Lattner753a2b42010-01-05 07:32:13 +0000903// visitCallSite - Improvements for call and invoke instructions.
904//
905Instruction *InstCombiner::visitCallSite(CallSite CS) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000906 if (isAllocLikeFn(CS.getInstruction(), TLI))
Nuno Lopes78f8ef42012-07-09 18:38:20 +0000907 return visitAllocSite(*CS.getInstruction());
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000908
Chris Lattner753a2b42010-01-05 07:32:13 +0000909 bool Changed = false;
910
Chris Lattnerab215bc2010-12-20 08:25:06 +0000911 // If the callee is a pointer to a function, attempt to move any casts to the
912 // arguments of the call/invoke.
Chris Lattner753a2b42010-01-05 07:32:13 +0000913 Value *Callee = CS.getCalledValue();
Chris Lattnerab215bc2010-12-20 08:25:06 +0000914 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
915 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +0000916
917 if (Function *CalleeF = dyn_cast<Function>(Callee))
Chris Lattnerd5695612010-02-01 18:11:34 +0000918 // If the call and callee calling conventions don't match, this call must
919 // be unreachable, as the call is undefined.
920 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
921 // Only do this for calls to a function with a body. A prototype may
922 // not actually end up matching the implementation's calling conv for a
923 // variety of reasons (e.g. it may be written in assembly).
924 !CalleeF->isDeclaration()) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000925 Instruction *OldCall = CS.getInstruction();
Chris Lattner753a2b42010-01-05 07:32:13 +0000926 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach00e403a2012-02-03 00:07:04 +0000927 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner753a2b42010-01-05 07:32:13 +0000928 OldCall);
929 // If OldCall dues not return void then replaceAllUsesWith undef.
930 // This allows ValueHandlers and custom metadata to adjust itself.
931 if (!OldCall->getType()->isVoidTy())
Eli Friedman3e22cb92011-05-18 00:32:01 +0000932 ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner830f3f22010-02-01 18:04:58 +0000933 if (isa<CallInst>(OldCall))
Chris Lattner753a2b42010-01-05 07:32:13 +0000934 return EraseInstFromFunction(*OldCall);
Jim Grosbach00e403a2012-02-03 00:07:04 +0000935
Chris Lattner830f3f22010-02-01 18:04:58 +0000936 // We cannot remove an invoke, because it would change the CFG, just
937 // change the callee to a null pointer.
Gabor Greif654c06f2010-03-20 21:00:25 +0000938 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner830f3f22010-02-01 18:04:58 +0000939 Constant::getNullValue(CalleeF->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000940 return 0;
941 }
942
943 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000944 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner753a2b42010-01-05 07:32:13 +0000945 // This allows ValueHandlers and custom metadata to adjust itself.
946 if (!CS.getInstruction()->getType()->isVoidTy())
Eli Friedman3e22cb92011-05-18 00:32:01 +0000947 ReplaceInstUsesWith(*CS.getInstruction(),
948 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000949
Nuno Lopesf1fb6c82012-06-21 23:52:14 +0000950 if (isa<InvokeInst>(CS.getInstruction())) {
951 // Can't remove an invoke because we cannot change the CFG.
952 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +0000953 }
Nuno Lopesf1fb6c82012-06-21 23:52:14 +0000954
955 // This instruction is not reachable, just remove it. We insert a store to
956 // undef so that we know that this code is not reachable, despite the fact
957 // that we can't modify the CFG here.
958 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
959 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
960 CS.getInstruction());
961
Chris Lattner753a2b42010-01-05 07:32:13 +0000962 return EraseInstFromFunction(*CS.getInstruction());
963 }
964
Duncan Sands4a544a72011-09-06 13:37:06 +0000965 if (IntrinsicInst *II = FindInitTrampoline(Callee))
966 return transformCallThroughTrampoline(CS, II);
Chris Lattner753a2b42010-01-05 07:32:13 +0000967
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000968 PointerType *PTy = cast<PointerType>(Callee->getType());
969 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000970 if (FTy->isVarArg()) {
Eli Friedmanba78c882011-11-29 01:18:23 +0000971 int ix = FTy->getNumParams();
Chris Lattner753a2b42010-01-05 07:32:13 +0000972 // See if we can optimize any arguments passed through the varargs area of
973 // the call.
974 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
975 E = CS.arg_end(); I != E; ++I, ++ix) {
976 CastInst *CI = dyn_cast<CastInst>(*I);
977 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
978 *I = CI->getOperand(0);
979 Changed = true;
980 }
981 }
982 }
983
984 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
985 // Inline asm calls cannot throw - mark them 'nounwind'.
986 CS.setDoesNotThrow();
987 Changed = true;
988 }
989
Micah Villmow3574eca2012-10-08 16:38:25 +0000990 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christopher27ceaa12010-03-06 10:50:38 +0000991 // this. None of these calls are seen as possibly dead so go ahead and
992 // delete the instruction now.
993 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
994 Instruction *I = tryOptimizeCall(CI, TD);
Eric Christopher7b323a32010-03-06 10:59:25 +0000995 // If we changed something return the result, etc. Otherwise let
996 // the fallthrough check.
997 if (I) return EraseInstFromFunction(*I);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000998 }
999
Chris Lattner753a2b42010-01-05 07:32:13 +00001000 return Changed ? CS.getInstruction() : 0;
1001}
1002
1003// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1004// attempt to move the cast to the arguments of the call/invoke.
1005//
1006bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Chris Lattnerab215bc2010-12-20 08:25:06 +00001007 Function *Callee =
1008 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
1009 if (Callee == 0)
Chris Lattner753a2b42010-01-05 07:32:13 +00001010 return false;
Chris Lattner753a2b42010-01-05 07:32:13 +00001011 Instruction *Caller = CS.getInstruction();
1012 const AttrListPtr &CallerPAL = CS.getAttributes();
1013
1014 // Okay, this is a cast from a function to a different type. Unless doing so
1015 // would cause a type conversion of one of our arguments, change this call to
1016 // be a direct call with arguments casted to the appropriate types.
1017 //
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001018 FunctionType *FT = Callee->getFunctionType();
1019 Type *OldRetTy = Caller->getType();
1020 Type *NewRetTy = FT->getReturnType();
Chris Lattner753a2b42010-01-05 07:32:13 +00001021
Duncan Sands1df98592010-02-16 11:11:14 +00001022 if (NewRetTy->isStructTy())
Chris Lattner753a2b42010-01-05 07:32:13 +00001023 return false; // TODO: Handle multiple return values.
1024
1025 // Check to see if we are changing the return type...
1026 if (OldRetTy != NewRetTy) {
1027 if (Callee->isDeclaration() &&
1028 // Conversion is ok if changing from one pointer type to another or from
1029 // a pointer to an integer of the same size.
Duncan Sands1df98592010-02-16 11:11:14 +00001030 !((OldRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001031 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001032 (NewRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001033 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
1034 return false; // Cannot transform this return value.
1035
1036 if (!Caller->use_empty() &&
1037 // void -> non-void is handled specially
1038 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
1039 return false; // Cannot transform this return value.
1040
1041 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling8831c062012-10-09 00:01:21 +00001042 Attributes::Builder RAttrs = CallerPAL.getRetAttributes();
1043 if (RAttrs.hasAttributes(Attributes::typeIncompatible(NewRetTy)))
Chris Lattner753a2b42010-01-05 07:32:13 +00001044 return false; // Attribute not compatible with transformed value.
1045 }
1046
1047 // If the callsite is an invoke instruction, and the return value is used by
1048 // a PHI node in a successor, we cannot change the return type of the call
1049 // because there is no place to put the cast instruction (without breaking
1050 // the critical edge). Bail out in this case.
1051 if (!Caller->use_empty())
1052 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1053 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
1054 UI != E; ++UI)
1055 if (PHINode *PN = dyn_cast<PHINode>(*UI))
1056 if (PN->getParent() == II->getNormalDest() ||
1057 PN->getParent() == II->getUnwindDest())
1058 return false;
1059 }
1060
1061 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1062 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1063
1064 CallSite::arg_iterator AI = CS.arg_begin();
1065 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001066 Type *ParamTy = FT->getParamType(i);
1067 Type *ActTy = (*AI)->getType();
Chris Lattner753a2b42010-01-05 07:32:13 +00001068
1069 if (!CastInst::isCastable(ActTy, ParamTy))
1070 return false; // Cannot transform this parameter value.
1071
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001072 Attributes Attrs = CallerPAL.getParamAttributes(i + 1);
Bill Wendling853a8c52012-09-25 20:38:59 +00001073 if (Attrs & Attributes::typeIncompatible(ParamTy))
Chris Lattner753a2b42010-01-05 07:32:13 +00001074 return false; // Attribute not compatible with transformed value.
Jim Grosbach00e403a2012-02-03 00:07:04 +00001075
Chris Lattner2b9375e2010-12-20 08:36:38 +00001076 // If the parameter is passed as a byval argument, then we have to have a
1077 // sized type and the sized type has to have the same size as the old type.
Bill Wendling67658342012-10-09 07:45:08 +00001078 if (ParamTy != ActTy && Attrs.hasAttribute(Attributes::ByVal)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001079 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Chris Lattner2b9375e2010-12-20 08:36:38 +00001080 if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || TD == 0)
1081 return false;
Jim Grosbach00e403a2012-02-03 00:07:04 +00001082
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001083 Type *CurElTy = cast<PointerType>(ActTy)->getElementType();
Chris Lattner2b9375e2010-12-20 08:36:38 +00001084 if (TD->getTypeAllocSize(CurElTy) !=
1085 TD->getTypeAllocSize(ParamPTy->getElementType()))
1086 return false;
1087 }
Chris Lattner753a2b42010-01-05 07:32:13 +00001088
1089 // Converting from one pointer type to another or between a pointer and an
1090 // integer of the same size is safe even if we do not have a body.
1091 bool isConvertible = ActTy == ParamTy ||
Duncan Sands1df98592010-02-16 11:11:14 +00001092 (TD && ((ParamTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001093 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001094 (ActTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001095 ActTy == TD->getIntPtrType(Caller->getContext()))));
1096 if (Callee->isDeclaration() && !isConvertible) return false;
1097 }
1098
Chris Lattner091b1e32011-02-24 05:10:56 +00001099 if (Callee->isDeclaration()) {
1100 // Do not delete arguments unless we have a function body.
1101 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
1102 return false;
Chris Lattner753a2b42010-01-05 07:32:13 +00001103
Chris Lattner091b1e32011-02-24 05:10:56 +00001104 // If the callee is just a declaration, don't change the varargsness of the
1105 // call. We don't want to introduce a varargs call where one doesn't
1106 // already exist.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001107 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattner091b1e32011-02-24 05:10:56 +00001108 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
1109 return false;
Jim Grosbachf3744862012-02-03 00:00:55 +00001110
1111 // If both the callee and the cast type are varargs, we still have to make
1112 // sure the number of fixed parameters are the same or we have the same
1113 // ABI issues as if we introduce a varargs call.
Jim Grosbach871a2052012-02-03 00:26:07 +00001114 if (FT->isVarArg() &&
1115 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
1116 FT->getNumParams() !=
Jim Grosbachf3744862012-02-03 00:00:55 +00001117 cast<FunctionType>(APTy->getElementType())->getNumParams())
1118 return false;
Chris Lattner091b1e32011-02-24 05:10:56 +00001119 }
Jim Grosbach00e403a2012-02-03 00:07:04 +00001120
Jim Grosbachd5917f02012-02-03 00:00:50 +00001121 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1122 !CallerPAL.isEmpty())
1123 // In this case we have more arguments than the new function type, but we
1124 // won't be dropping them. Check that these extra arguments have attributes
1125 // that are compatible with being a vararg call argument.
1126 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1127 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
1128 break;
1129 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Bill Wendling8831c062012-10-09 00:01:21 +00001130 if (PAttrs.hasIncompatibleWithVarArgsAttrs())
Jim Grosbachd5917f02012-02-03 00:00:50 +00001131 return false;
1132 }
Chris Lattner753a2b42010-01-05 07:32:13 +00001133
Jim Grosbach00e403a2012-02-03 00:07:04 +00001134
Chris Lattner753a2b42010-01-05 07:32:13 +00001135 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattner091b1e32011-02-24 05:10:56 +00001136 // inserting cast instructions as necessary.
Chris Lattner753a2b42010-01-05 07:32:13 +00001137 std::vector<Value*> Args;
1138 Args.reserve(NumActualArgs);
1139 SmallVector<AttributeWithIndex, 8> attrVec;
1140 attrVec.reserve(NumCommonArgs);
1141
1142 // Get any return attributes.
Bill Wendling8831c062012-10-09 00:01:21 +00001143 Attributes::Builder RAttrs = CallerPAL.getRetAttributes();
Chris Lattner753a2b42010-01-05 07:32:13 +00001144
1145 // If the return value is not being used, the type may not be compatible
1146 // with the existing attributes. Wipe out any problematic attributes.
Bill Wendling8831c062012-10-09 00:01:21 +00001147 RAttrs.removeAttributes(Attributes::typeIncompatible(NewRetTy));
Chris Lattner753a2b42010-01-05 07:32:13 +00001148
1149 // Add the new return attributes.
Bill Wendling8831c062012-10-09 00:01:21 +00001150 if (RAttrs.hasAttributes())
1151 attrVec.push_back(AttributeWithIndex::get(0, Attributes::get(RAttrs)));
Chris Lattner753a2b42010-01-05 07:32:13 +00001152
1153 AI = CS.arg_begin();
1154 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001155 Type *ParamTy = FT->getParamType(i);
Chris Lattner753a2b42010-01-05 07:32:13 +00001156 if ((*AI)->getType() == ParamTy) {
1157 Args.push_back(*AI);
1158 } else {
1159 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1160 false, ParamTy, false);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001161 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy));
Chris Lattner753a2b42010-01-05 07:32:13 +00001162 }
1163
1164 // Add any parameter attributes.
1165 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1166 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1167 }
1168
1169 // If the function takes more arguments than the call was taking, add them
1170 // now.
1171 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1172 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1173
1174 // If we are removing arguments to the function, emit an obnoxious warning.
1175 if (FT->getNumParams() < NumActualArgs) {
1176 if (!FT->isVarArg()) {
1177 errs() << "WARNING: While resolving call to function '"
1178 << Callee->getName() << "' arguments were dropped!\n";
1179 } else {
1180 // Add all of the arguments in their promoted form to the arg list.
1181 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001182 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +00001183 if (PTy != (*AI)->getType()) {
1184 // Must promote to pass through va_arg area!
1185 Instruction::CastOps opcode =
1186 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001187 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner753a2b42010-01-05 07:32:13 +00001188 } else {
1189 Args.push_back(*AI);
1190 }
1191
1192 // Add any parameter attributes.
1193 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1194 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1195 }
1196 }
1197 }
1198
1199 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
1200 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
1201
1202 if (NewRetTy->isVoidTy())
1203 Caller->setName(""); // Void type should not have a name.
1204
Chris Lattnerd509d0b2012-05-28 01:47:44 +00001205 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec);
Chris Lattner753a2b42010-01-05 07:32:13 +00001206
1207 Instruction *NC;
1208 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Eli Friedmanef819d02011-05-18 01:28:27 +00001209 NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
Jay Foada3efbb12011-07-15 08:37:34 +00001210 II->getUnwindDest(), Args);
Eli Friedmanef819d02011-05-18 01:28:27 +00001211 NC->takeName(II);
Chris Lattner753a2b42010-01-05 07:32:13 +00001212 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1213 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1214 } else {
Chris Lattner753a2b42010-01-05 07:32:13 +00001215 CallInst *CI = cast<CallInst>(Caller);
Jay Foada3efbb12011-07-15 08:37:34 +00001216 NC = Builder->CreateCall(Callee, Args);
Eli Friedmanef819d02011-05-18 01:28:27 +00001217 NC->takeName(CI);
Chris Lattner753a2b42010-01-05 07:32:13 +00001218 if (CI->isTailCall())
1219 cast<CallInst>(NC)->setTailCall();
1220 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1221 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1222 }
1223
1224 // Insert a cast of the return type as necessary.
1225 Value *NV = NC;
1226 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1227 if (!NV->getType()->isVoidTy()) {
Chris Lattnerab215bc2010-12-20 08:25:06 +00001228 Instruction::CastOps opcode =
1229 CastInst::getCastOpcode(NC, false, OldRetTy, false);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001230 NV = NC = CastInst::Create(opcode, NC, OldRetTy);
Eli Friedmana311c342011-05-27 00:19:40 +00001231 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner753a2b42010-01-05 07:32:13 +00001232
1233 // If this is an invoke instruction, we should insert it after the first
1234 // non-phi, instruction in the normal successor block.
1235 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling89d44112011-08-25 01:08:34 +00001236 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner753a2b42010-01-05 07:32:13 +00001237 InsertNewInstBefore(NC, *I);
1238 } else {
Chris Lattnerab215bc2010-12-20 08:25:06 +00001239 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner753a2b42010-01-05 07:32:13 +00001240 InsertNewInstBefore(NC, *Caller);
1241 }
1242 Worklist.AddUsersToWorkList(*Caller);
1243 } else {
1244 NV = UndefValue::get(Caller->getType());
1245 }
1246 }
1247
Chris Lattner753a2b42010-01-05 07:32:13 +00001248 if (!Caller->use_empty())
Eli Friedman3e22cb92011-05-18 00:32:01 +00001249 ReplaceInstUsesWith(*Caller, NV);
1250
Chris Lattner753a2b42010-01-05 07:32:13 +00001251 EraseInstFromFunction(*Caller);
1252 return true;
1253}
1254
Duncan Sands4a544a72011-09-06 13:37:06 +00001255// transformCallThroughTrampoline - Turn a call to a function created by
1256// init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
1257// underlying function.
Chris Lattner753a2b42010-01-05 07:32:13 +00001258//
Duncan Sands4a544a72011-09-06 13:37:06 +00001259Instruction *
1260InstCombiner::transformCallThroughTrampoline(CallSite CS,
1261 IntrinsicInst *Tramp) {
Chris Lattner753a2b42010-01-05 07:32:13 +00001262 Value *Callee = CS.getCalledValue();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001263 PointerType *PTy = cast<PointerType>(Callee->getType());
1264 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner753a2b42010-01-05 07:32:13 +00001265 const AttrListPtr &Attrs = CS.getAttributes();
1266
1267 // If the call already has the 'nest' attribute somewhere then give up -
1268 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling8831c062012-10-09 00:01:21 +00001269 for (unsigned I = 0, E = Attrs.getNumAttrs(); I != E; ++I)
Bill Wendling67658342012-10-09 07:45:08 +00001270 if (Attrs.getAttributesAtIndex(I).hasAttribute(Attributes::Nest))
Bill Wendling8831c062012-10-09 00:01:21 +00001271 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +00001272
Duncan Sands4a544a72011-09-06 13:37:06 +00001273 assert(Tramp &&
1274 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner753a2b42010-01-05 07:32:13 +00001275
Gabor Greifa3997812010-07-22 10:37:47 +00001276 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001277 PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1278 FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
Chris Lattner753a2b42010-01-05 07:32:13 +00001279
1280 const AttrListPtr &NestAttrs = NestF->getAttributes();
1281 if (!NestAttrs.isEmpty()) {
1282 unsigned NestIdx = 1;
Jay Foad5fdd6c82011-07-12 14:06:48 +00001283 Type *NestTy = 0;
Bill Wendling8831c062012-10-09 00:01:21 +00001284 Attributes NestAttr;
Chris Lattner753a2b42010-01-05 07:32:13 +00001285
1286 // Look for a parameter marked with the 'nest' attribute.
1287 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1288 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling67658342012-10-09 07:45:08 +00001289 if (NestAttrs.getParamAttributes(NestIdx).hasAttribute(Attributes::Nest)){
Chris Lattner753a2b42010-01-05 07:32:13 +00001290 // Record the parameter type and any other attributes.
1291 NestTy = *I;
1292 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1293 break;
1294 }
1295
1296 if (NestTy) {
1297 Instruction *Caller = CS.getInstruction();
1298 std::vector<Value*> NewArgs;
1299 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1300
1301 SmallVector<AttributeWithIndex, 8> NewAttrs;
1302 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1303
1304 // Insert the nest argument into the call argument list, which may
1305 // mean appending it. Likewise for attributes.
1306
1307 // Add any result attributes.
1308 if (Attributes Attr = Attrs.getRetAttributes())
1309 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1310
1311 {
1312 unsigned Idx = 1;
1313 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1314 do {
1315 if (Idx == NestIdx) {
1316 // Add the chain argument and attributes.
Gabor Greifcea7ac72010-06-24 12:58:35 +00001317 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner753a2b42010-01-05 07:32:13 +00001318 if (NestVal->getType() != NestTy)
Eli Friedmane6f364b2011-05-18 23:58:37 +00001319 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner753a2b42010-01-05 07:32:13 +00001320 NewArgs.push_back(NestVal);
1321 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1322 }
1323
1324 if (I == E)
1325 break;
1326
1327 // Add the original argument and attributes.
1328 NewArgs.push_back(*I);
1329 if (Attributes Attr = Attrs.getParamAttributes(Idx))
1330 NewAttrs.push_back
1331 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1332
1333 ++Idx, ++I;
1334 } while (1);
1335 }
1336
1337 // Add any function attributes.
1338 if (Attributes Attr = Attrs.getFnAttributes())
1339 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1340
1341 // The trampoline may have been bitcast to a bogus type (FTy).
1342 // Handle this by synthesizing a new function type, equal to FTy
1343 // with the chain parameter inserted.
1344
Jay Foad5fdd6c82011-07-12 14:06:48 +00001345 std::vector<Type*> NewTypes;
Chris Lattner753a2b42010-01-05 07:32:13 +00001346 NewTypes.reserve(FTy->getNumParams()+1);
1347
1348 // Insert the chain's type into the list of parameter types, which may
1349 // mean appending it.
1350 {
1351 unsigned Idx = 1;
1352 FunctionType::param_iterator I = FTy->param_begin(),
1353 E = FTy->param_end();
1354
1355 do {
1356 if (Idx == NestIdx)
1357 // Add the chain's type.
1358 NewTypes.push_back(NestTy);
1359
1360 if (I == E)
1361 break;
1362
1363 // Add the original type.
1364 NewTypes.push_back(*I);
1365
1366 ++Idx, ++I;
1367 } while (1);
1368 }
1369
1370 // Replace the trampoline call with a direct call. Let the generic
1371 // code sort out any function type mismatches.
Jim Grosbach00e403a2012-02-03 00:07:04 +00001372 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner753a2b42010-01-05 07:32:13 +00001373 FTy->isVarArg());
1374 Constant *NewCallee =
1375 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach00e403a2012-02-03 00:07:04 +00001376 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner753a2b42010-01-05 07:32:13 +00001377 PointerType::getUnqual(NewFTy));
Chris Lattnerd509d0b2012-05-28 01:47:44 +00001378 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs);
Chris Lattner753a2b42010-01-05 07:32:13 +00001379
1380 Instruction *NewCaller;
1381 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1382 NewCaller = InvokeInst::Create(NewCallee,
1383 II->getNormalDest(), II->getUnwindDest(),
Jay Foada3efbb12011-07-15 08:37:34 +00001384 NewArgs);
Chris Lattner753a2b42010-01-05 07:32:13 +00001385 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1386 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1387 } else {
Jay Foada3efbb12011-07-15 08:37:34 +00001388 NewCaller = CallInst::Create(NewCallee, NewArgs);
Chris Lattner753a2b42010-01-05 07:32:13 +00001389 if (cast<CallInst>(Caller)->isTailCall())
1390 cast<CallInst>(NewCaller)->setTailCall();
1391 cast<CallInst>(NewCaller)->
1392 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1393 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1394 }
Eli Friedman59f15912011-05-18 19:57:14 +00001395
1396 return NewCaller;
Chris Lattner753a2b42010-01-05 07:32:13 +00001397 }
1398 }
1399
1400 // Replace the trampoline call with a direct call. Since there is no 'nest'
1401 // parameter, there is no need to adjust the argument list. Let the generic
1402 // code sort out any function type mismatches.
1403 Constant *NewCallee =
Jim Grosbach00e403a2012-02-03 00:07:04 +00001404 NestF->getType() == PTy ? NestF :
Chris Lattner753a2b42010-01-05 07:32:13 +00001405 ConstantExpr::getBitCast(NestF, PTy);
1406 CS.setCalledFunction(NewCallee);
1407 return CS.getInstruction();
1408}