blob: f3602675ed010d76acc2555e5333fedb7dc26ed7 [file] [log] [blame]
Chris Lattner7a9e47a2010-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"
Meador Ingee3f2b262012-11-30 04:05:06 +000015#include "llvm/ADT/Statistic.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000016#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000017#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
Eric Christophera7fb58f2010-03-06 10:50:38 +000020#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000021#include "llvm/Transforms/Utils/Local.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000022using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000023using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000024
Meador Ingee3f2b262012-11-30 04:05:06 +000025STATISTIC(NumSimplified, "Number of library calls simplified");
26
Chris Lattner7a9e47a2010-01-05 07:32:13 +000027/// getPromotedType - Return the specified type promoted as it would be to pass
28/// though a va_arg area.
Chris Lattner229907c2011-07-18 04:54:35 +000029static Type *getPromotedType(Type *Ty) {
30 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000031 if (ITy->getBitWidth() < 32)
32 return Type::getInt32Ty(Ty->getContext());
33 }
34 return Ty;
35}
36
Dan Gohmand0080c42012-09-13 18:19:06 +000037/// reduceToSingleValueType - Given an aggregate type which ultimately holds a
38/// single scalar element, like {{{type}}} or [1 x type], return type.
39static Type *reduceToSingleValueType(Type *T) {
40 while (!T->isSingleValueType()) {
41 if (StructType *STy = dyn_cast<StructType>(T)) {
42 if (STy->getNumElements() == 1)
43 T = STy->getElementType(0);
44 else
45 break;
46 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
47 if (ATy->getNumElements() == 1)
48 T = ATy->getElementType();
49 else
50 break;
51 } else
52 break;
53 }
54
55 return T;
56}
Chris Lattner7a9e47a2010-01-05 07:32:13 +000057
58Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +000059 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL);
60 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL);
Chris Lattner7a9e47a2010-01-05 07:32:13 +000061 unsigned MinAlign = std::min(DstAlign, SrcAlign);
62 unsigned CopyAlign = MI->getAlignment();
63
64 if (CopyAlign < MinAlign) {
Jim Grosbach7815f562012-02-03 00:07:04 +000065 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +000066 MinAlign, false));
67 return MI;
68 }
Jim Grosbach7815f562012-02-03 00:07:04 +000069
Chris Lattner7a9e47a2010-01-05 07:32:13 +000070 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
71 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +000072 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +000073 if (MemOpLength == 0) return 0;
Jim Grosbach7815f562012-02-03 00:07:04 +000074
Chris Lattner7a9e47a2010-01-05 07:32:13 +000075 // Source and destination pointer types are always "i8*" for intrinsic. See
76 // if the size is something we can handle with a single primitive load/store.
77 // A single load+store correctly handles overlapping memory in the memmove
78 // case.
Michael Liao69e172a2012-08-15 03:49:59 +000079 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +000080 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +000081
Chris Lattner7a9e47a2010-01-05 07:32:13 +000082 if (Size > 8 || (Size&(Size-1)))
83 return 0; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +000084
Chris Lattner7a9e47a2010-01-05 07:32:13 +000085 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +000086 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +000087 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +000088 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +000089 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +000090
Chris Lattner229907c2011-07-18 04:54:35 +000091 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +000092 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
93 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +000094
Chris Lattner7a9e47a2010-01-05 07:32:13 +000095 // Memcpy forces the use of i8* for the source and destination. That means
96 // that if you're using memcpy to move one double around, you'll get a cast
97 // from double* to i8*. We'd much rather use a double load+store rather than
98 // an i64 load+store, here because this improves the odds that the source or
99 // dest address will be promotable. See if we can find a better type than the
100 // integer datatype.
Gabor Greif589a0b92010-06-24 12:58:35 +0000101 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
Dan Gohman3f553c22012-09-13 21:51:01 +0000102 MDNode *CopyMD = 0;
Gabor Greif589a0b92010-06-24 12:58:35 +0000103 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000104 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000105 ->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000106 if (DL && SrcETy->isSized() && DL->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000107 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
108 // down through these levels if so.
Dan Gohmand0080c42012-09-13 18:19:06 +0000109 SrcETy = reduceToSingleValueType(SrcETy);
Jim Grosbach7815f562012-02-03 00:07:04 +0000110
Mon P Wangc576ee92010-04-04 03:10:48 +0000111 if (SrcETy->isSingleValueType()) {
112 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
113 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
Dan Gohman3f553c22012-09-13 21:51:01 +0000114
115 // If the memcpy has metadata describing the members, see if we can
116 // get the TBAA tag describing our copy.
117 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
118 if (M->getNumOperands() == 3 &&
Nick Lewycky49ac81a2012-10-11 02:05:23 +0000119 M->getOperand(0) &&
Dan Gohman3f553c22012-09-13 21:51:01 +0000120 isa<ConstantInt>(M->getOperand(0)) &&
121 cast<ConstantInt>(M->getOperand(0))->isNullValue() &&
Nick Lewycky49ac81a2012-10-11 02:05:23 +0000122 M->getOperand(1) &&
Dan Gohman3f553c22012-09-13 21:51:01 +0000123 isa<ConstantInt>(M->getOperand(1)) &&
124 cast<ConstantInt>(M->getOperand(1))->getValue() == Size &&
Nick Lewycky49ac81a2012-10-11 02:05:23 +0000125 M->getOperand(2) &&
Dan Gohman3f553c22012-09-13 21:51:01 +0000126 isa<MDNode>(M->getOperand(2)))
127 CopyMD = cast<MDNode>(M->getOperand(2));
128 }
Mon P Wangc576ee92010-04-04 03:10:48 +0000129 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000130 }
131 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000132
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000133 // If the memcpy/memmove provides better alignment info than we can
134 // infer, use it.
135 SrcAlign = std::max(SrcAlign, CopyAlign);
136 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000137
Gabor Greif5f3e6562010-06-25 07:57:14 +0000138 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
139 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman49346012011-05-18 19:57:14 +0000140 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
141 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000142 if (CopyMD)
143 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Eli Friedman49346012011-05-18 19:57:14 +0000144 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
145 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000146 if (CopyMD)
147 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000148
149 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000150 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000151 return MI;
152}
153
154Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000155 unsigned Alignment = getKnownAlignment(MI->getDest(), DL);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000156 if (MI->getAlignment() < Alignment) {
157 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
158 Alignment, false));
159 return MI;
160 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000161
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000162 // Extract the length and alignment and fill if they are constant.
163 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
164 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000165 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000166 return 0;
Michael Liao69e172a2012-08-15 03:49:59 +0000167 uint64_t Len = LenC->getLimitedValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000168 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000169 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000170
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000171 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
172 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000173 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000174
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000175 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000176 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
177 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
178 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000179
180 // Alignment 0 is identity for alignment 1 for memset, but not store.
181 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000182
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000183 // Extract the fill value and store.
184 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000185 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
186 MI->isVolatile());
187 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000188
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000189 // Set the size of the copy to 0, it will be deleted on the next iteration.
190 MI->setLength(Constant::getNullValue(LenC->getType()));
191 return MI;
192 }
193
194 return 0;
195}
196
Jim Grosbach7815f562012-02-03 00:07:04 +0000197/// visitCallInst - CallInst simplification. This mostly only handles folding
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000198/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
199/// the heavy lifting.
200///
201Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000202 if (isFreeCall(&CI, TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000203 return visitFree(CI);
204
205 // If the caller function is nounwind, mark the call as nounwind, even if the
206 // callee isn't.
207 if (CI.getParent()->getParent()->doesNotThrow() &&
208 !CI.doesNotThrow()) {
209 CI.setDoesNotThrow();
210 return &CI;
211 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000212
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000213 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
214 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +0000215
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000216 // Intrinsics cannot occur in an invoke, so handle them here instead of in
217 // visitCallSite.
218 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
219 bool Changed = false;
220
221 // memmove/cpy/set of zero bytes is a noop.
222 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +0000223 if (NumBytes->isNullValue())
224 return EraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000225
226 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
227 if (CI->getZExtValue() == 1) {
228 // Replace the instruction with just byte operations. We would
229 // transform other cases to loads/stores, but we don't know if
230 // alignment is sufficient.
231 }
232 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000233
Chris Lattnerc663a672010-10-01 05:51:02 +0000234 // No other transformations apply to volatile transfers.
235 if (MI->isVolatile())
236 return 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000237
238 // If we have a memmove and the source operation is a constant global,
239 // then the source and dest pointers can't alias, so we can change this
240 // into a call to memcpy.
241 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
242 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
243 if (GVSrc->isConstant()) {
Eric Christopher7258dcd2010-04-16 23:37:20 +0000244 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000245 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +0000246 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
247 CI.getArgOperand(1)->getType(),
248 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +0000249 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000250 Changed = true;
251 }
252 }
253
254 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
255 // memmove(x,x,size) -> noop.
256 if (MTI->getSource() == MTI->getDest())
257 return EraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +0000258 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000259
Eric Christopher7258dcd2010-04-16 23:37:20 +0000260 // If we can determine a pointer alignment that is bigger than currently
261 // set, update the alignment.
262 if (isa<MemTransferInst>(MI)) {
263 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000264 return I;
265 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
266 if (Instruction *I = SimplifyMemSet(MSI))
267 return I;
268 }
Gabor Greif590d95e2010-06-24 13:42:49 +0000269
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000270 if (Changed) return II;
271 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000272
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000273 switch (II->getIntrinsicID()) {
274 default: break;
Eric Christopher7b7028f2010-02-09 21:24:27 +0000275 case Intrinsic::objectsize: {
Nuno Lopes55fff832012-06-21 15:45:28 +0000276 uint64_t Size;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000277 if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
Nuno Lopes55fff832012-06-21 15:45:28 +0000278 return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
279 return 0;
Eric Christopher7b7028f2010-02-09 21:24:27 +0000280 }
Michael Ilseman536cc322012-12-13 03:13:36 +0000281 case Intrinsic::bswap: {
282 Value *IIOperand = II->getArgOperand(0);
283 Value *X = 0;
284
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000285 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +0000286 if (match(IIOperand, m_BSwap(m_Value(X))))
287 return ReplaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +0000288
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000289 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +0000290 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
291 unsigned C = X->getType()->getPrimitiveSizeInBits() -
292 IIOperand->getType()->getPrimitiveSizeInBits();
293 Value *CV = ConstantInt::get(X->getType(), C);
294 Value *V = Builder->CreateLShr(X, CV);
295 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000296 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000297 break;
Michael Ilseman536cc322012-12-13 03:13:36 +0000298 }
299
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000300 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +0000301 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000302 // powi(x, 0) -> 1.0
303 if (Power->isZero())
304 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
305 // powi(x, 1) -> x
306 if (Power->isOne())
Gabor Greif589a0b92010-06-24 12:58:35 +0000307 return ReplaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000308 // powi(x, -1) -> 1/x
309 if (Power->isAllOnesValue())
310 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +0000311 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000312 }
313 break;
314 case Intrinsic::cttz: {
315 // If all bits below the first known one are known zero,
316 // this value is constant.
Chris Lattner229907c2011-07-18 04:54:35 +0000317 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Anderson2f37bdc2011-07-01 21:52:38 +0000318 // FIXME: Try to simplify vectors of integers.
319 if (!IT) break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000320 uint32_t BitWidth = IT->getBitWidth();
321 APInt KnownZero(BitWidth, 0);
322 APInt KnownOne(BitWidth, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000323 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000324 unsigned TrailingZeros = KnownOne.countTrailingZeros();
325 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
326 if ((Mask & KnownZero) == Mask)
327 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
328 APInt(BitWidth, TrailingZeros)));
Jim Grosbach7815f562012-02-03 00:07:04 +0000329
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000330 }
331 break;
332 case Intrinsic::ctlz: {
333 // If all bits above the first known one are known zero,
334 // this value is constant.
Chris Lattner229907c2011-07-18 04:54:35 +0000335 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Anderson2f37bdc2011-07-01 21:52:38 +0000336 // FIXME: Try to simplify vectors of integers.
337 if (!IT) break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000338 uint32_t BitWidth = IT->getBitWidth();
339 APInt KnownZero(BitWidth, 0);
340 APInt KnownOne(BitWidth, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000341 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000342 unsigned LeadingZeros = KnownOne.countLeadingZeros();
343 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
344 if ((Mask & KnownZero) == Mask)
345 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
346 APInt(BitWidth, LeadingZeros)));
Jim Grosbach7815f562012-02-03 00:07:04 +0000347
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000348 }
349 break;
350 case Intrinsic::uadd_with_overflow: {
Gabor Greif589a0b92010-06-24 12:58:35 +0000351 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattner229907c2011-07-18 04:54:35 +0000352 IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000353 uint32_t BitWidth = IT->getBitWidth();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000354 APInt LHSKnownZero(BitWidth, 0);
355 APInt LHSKnownOne(BitWidth, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000356 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000357 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
358 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
359
360 if (LHSKnownNegative || LHSKnownPositive) {
361 APInt RHSKnownZero(BitWidth, 0);
362 APInt RHSKnownOne(BitWidth, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000363 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000364 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
365 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
366 if (LHSKnownNegative && RHSKnownNegative) {
367 // The sign bit is set in both cases: this MUST overflow.
368 // Create a simple add instruction, and insert it into the struct.
Eli Friedman49346012011-05-18 19:57:14 +0000369 Value *Add = Builder->CreateAdd(LHS, RHS);
370 Add->takeName(&CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000371 Constant *V[] = {
Eli Friedman49346012011-05-18 19:57:14 +0000372 UndefValue::get(LHS->getType()),
373 ConstantInt::getTrue(II->getContext())
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000374 };
Chris Lattner229907c2011-07-18 04:54:35 +0000375 StructType *ST = cast<StructType>(II->getType());
Chris Lattnercc19efa2011-06-20 04:01:31 +0000376 Constant *Struct = ConstantStruct::get(ST, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000377 return InsertValueInst::Create(Struct, Add, 0);
378 }
Eli Friedman49346012011-05-18 19:57:14 +0000379
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000380 if (LHSKnownPositive && RHSKnownPositive) {
381 // The sign bit is clear in both cases: this CANNOT overflow.
382 // Create a simple add instruction, and insert it into the struct.
Eli Friedman49346012011-05-18 19:57:14 +0000383 Value *Add = Builder->CreateNUWAdd(LHS, RHS);
384 Add->takeName(&CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000385 Constant *V[] = {
386 UndefValue::get(LHS->getType()),
387 ConstantInt::getFalse(II->getContext())
388 };
Chris Lattner229907c2011-07-18 04:54:35 +0000389 StructType *ST = cast<StructType>(II->getType());
Chris Lattnercc19efa2011-06-20 04:01:31 +0000390 Constant *Struct = ConstantStruct::get(ST, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000391 return InsertValueInst::Create(Struct, Add, 0);
392 }
393 }
394 }
395 // FALL THROUGH uadd into sadd
396 case Intrinsic::sadd_with_overflow:
397 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000398 if (isa<Constant>(II->getArgOperand(0)) &&
399 !isa<Constant>(II->getArgOperand(1))) {
400 Value *LHS = II->getArgOperand(0);
401 II->setArgOperand(0, II->getArgOperand(1));
402 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000403 return II;
404 }
405
406 // X + undef -> undef
Gabor Greif5f3e6562010-06-25 07:57:14 +0000407 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000408 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Jim Grosbach7815f562012-02-03 00:07:04 +0000409
Gabor Greif5f3e6562010-06-25 07:57:14 +0000410 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000411 // X + 0 -> {X, false}
412 if (RHS->isZero()) {
413 Constant *V[] = {
Eli Friedmanf99e7e62010-08-09 20:49:43 +0000414 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000415 ConstantInt::getFalse(II->getContext())
416 };
Chris Lattnercc19efa2011-06-20 04:01:31 +0000417 Constant *Struct =
418 ConstantStruct::get(cast<StructType>(II->getType()), V);
Gabor Greif589a0b92010-06-24 12:58:35 +0000419 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000420 }
421 }
422 break;
423 case Intrinsic::usub_with_overflow:
424 case Intrinsic::ssub_with_overflow:
425 // undef - X -> undef
426 // X - undef -> undef
Gabor Greif5f3e6562010-06-25 07:57:14 +0000427 if (isa<UndefValue>(II->getArgOperand(0)) ||
428 isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000429 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Jim Grosbach7815f562012-02-03 00:07:04 +0000430
Gabor Greif5f3e6562010-06-25 07:57:14 +0000431 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000432 // X - 0 -> {X, false}
433 if (RHS->isZero()) {
434 Constant *V[] = {
Gabor Greif5f3e6562010-06-25 07:57:14 +0000435 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000436 ConstantInt::getFalse(II->getContext())
437 };
Jim Grosbach7815f562012-02-03 00:07:04 +0000438 Constant *Struct =
Chris Lattnercc19efa2011-06-20 04:01:31 +0000439 ConstantStruct::get(cast<StructType>(II->getType()), V);
Gabor Greif5f3e6562010-06-25 07:57:14 +0000440 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000441 }
442 }
443 break;
Benjamin Kramerb49b9642011-03-10 18:40:14 +0000444 case Intrinsic::umul_with_overflow: {
445 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
446 unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
Benjamin Kramerb49b9642011-03-10 18:40:14 +0000447
448 APInt LHSKnownZero(BitWidth, 0);
449 APInt LHSKnownOne(BitWidth, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000450 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
Benjamin Kramerb49b9642011-03-10 18:40:14 +0000451 APInt RHSKnownZero(BitWidth, 0);
452 APInt RHSKnownOne(BitWidth, 0);
Rafael Espindolaba0a6ca2012-04-04 12:51:34 +0000453 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
Benjamin Kramerb49b9642011-03-10 18:40:14 +0000454
Benjamin Kramer1f90da12011-03-27 15:04:38 +0000455 // Get the largest possible values for each operand.
456 APInt LHSMax = ~LHSKnownZero;
457 APInt RHSMax = ~RHSKnownZero;
Benjamin Kramerb49b9642011-03-10 18:40:14 +0000458
459 // If multiplying the maximum values does not overflow then we can turn
460 // this into a plain NUW mul.
Benjamin Kramer1f90da12011-03-27 15:04:38 +0000461 bool Overflow;
462 LHSMax.umul_ov(RHSMax, Overflow);
463 if (!Overflow) {
Benjamin Kramerb49b9642011-03-10 18:40:14 +0000464 Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
465 Constant *V[] = {
466 UndefValue::get(LHS->getType()),
467 Builder->getFalse()
468 };
Chris Lattnercc19efa2011-06-20 04:01:31 +0000469 Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
Benjamin Kramerb49b9642011-03-10 18:40:14 +0000470 return InsertValueInst::Create(Struct, Mul, 0);
471 }
472 } // FALL THROUGH
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000473 case Intrinsic::smul_with_overflow:
474 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000475 if (isa<Constant>(II->getArgOperand(0)) &&
476 !isa<Constant>(II->getArgOperand(1))) {
477 Value *LHS = II->getArgOperand(0);
478 II->setArgOperand(0, II->getArgOperand(1));
479 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000480 return II;
481 }
482
483 // X * undef -> undef
Gabor Greif5f3e6562010-06-25 07:57:14 +0000484 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000485 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Jim Grosbach7815f562012-02-03 00:07:04 +0000486
Gabor Greif5f3e6562010-06-25 07:57:14 +0000487 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000488 // X*0 -> {0, false}
489 if (RHSI->isZero())
490 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
Jim Grosbach7815f562012-02-03 00:07:04 +0000491
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000492 // X * 1 -> {X, false}
493 if (RHSI->equalsInt(1)) {
494 Constant *V[] = {
Gabor Greif589a0b92010-06-24 12:58:35 +0000495 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000496 ConstantInt::getFalse(II->getContext())
497 };
Jim Grosbach7815f562012-02-03 00:07:04 +0000498 Constant *Struct =
Chris Lattnercc19efa2011-06-20 04:01:31 +0000499 ConstantStruct::get(cast<StructType>(II->getType()), V);
Gabor Greif589a0b92010-06-24 12:58:35 +0000500 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000501 }
502 }
503 break;
504 case Intrinsic::ppc_altivec_lvx:
505 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +0000506 // Turn PPC lvx -> load if the pointer is known aligned.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000507 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +0000508 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000509 PointerType::getUnqual(II->getType()));
510 return new LoadInst(Ptr);
511 }
512 break;
513 case Intrinsic::ppc_altivec_stvx:
514 case Intrinsic::ppc_altivec_stvxl:
515 // Turn stvx -> store if the pointer is known aligned.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000516 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +0000517 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +0000518 PointerType::getUnqual(II->getArgOperand(0)->getType());
519 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
520 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000521 }
522 break;
523 case Intrinsic::x86_sse_storeu_ps:
524 case Intrinsic::x86_sse2_storeu_pd:
525 case Intrinsic::x86_sse2_storeu_dq:
526 // Turn X86 storeu -> store if the pointer is known aligned.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000527 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +0000528 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +0000529 PointerType::getUnqual(II->getArgOperand(1)->getType());
530 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
531 return new StoreInst(II->getArgOperand(1), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000532 }
533 break;
Chandler Carruthcf414cf2011-01-10 07:19:37 +0000534
535 case Intrinsic::x86_sse_cvtss2si:
536 case Intrinsic::x86_sse_cvtss2si64:
537 case Intrinsic::x86_sse_cvttss2si:
538 case Intrinsic::x86_sse_cvttss2si64:
539 case Intrinsic::x86_sse2_cvtsd2si:
540 case Intrinsic::x86_sse2_cvtsd2si64:
541 case Intrinsic::x86_sse2_cvttsd2si:
542 case Intrinsic::x86_sse2_cvttsd2si64: {
543 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000544 // we can simplify the input based on that, do so now.
545 unsigned VWidth =
Gabor Greif5f3e6562010-06-25 07:57:14 +0000546 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000547 APInt DemandedElts(VWidth, 1);
548 APInt UndefElts(VWidth, 0);
Gabor Greif3e44ea12010-07-22 10:37:47 +0000549 if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
550 DemandedElts, UndefElts)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +0000551 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000552 return II;
553 }
554 break;
555 }
Chandler Carruthcf414cf2011-01-10 07:19:37 +0000556
Stuart Hastings5bd18b62011-05-17 22:13:31 +0000557
558 case Intrinsic::x86_sse41_pmovsxbw:
559 case Intrinsic::x86_sse41_pmovsxwd:
560 case Intrinsic::x86_sse41_pmovsxdq:
561 case Intrinsic::x86_sse41_pmovzxbw:
562 case Intrinsic::x86_sse41_pmovzxwd:
563 case Intrinsic::x86_sse41_pmovzxdq: {
Evan Chengdc867ae2011-05-19 18:18:39 +0000564 // pmov{s|z}x ignores the upper half of their input vectors.
Stuart Hastings5bd18b62011-05-17 22:13:31 +0000565 unsigned VWidth =
566 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
567 unsigned LowHalfElts = VWidth / 2;
Stuart Hastings728f6262011-05-18 15:54:26 +0000568 APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
Stuart Hastings5bd18b62011-05-17 22:13:31 +0000569 APInt UndefElts(VWidth, 0);
570 if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
571 InputDemandedElts,
572 UndefElts)) {
573 II->setArgOperand(0, TmpV);
574 return II;
575 }
576 break;
577 }
578
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000579 case Intrinsic::ppc_altivec_vperm:
580 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Chris Lattner0256be92012-01-27 03:08:05 +0000581 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
582 assert(Mask->getType()->getVectorNumElements() == 16 &&
583 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +0000584
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000585 // Check that all of the elements are integer constants or undefs.
586 bool AllEltsOk = true;
587 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +0000588 Constant *Elt = Mask->getAggregateElement(i);
589 if (Elt == 0 ||
590 !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000591 AllEltsOk = false;
592 break;
593 }
594 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000595
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000596 if (AllEltsOk) {
597 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +0000598 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
599 Mask->getType());
600 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
601 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000602 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +0000603
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000604 // Only extract each element once.
605 Value *ExtractedElts[32];
606 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +0000607
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000608 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +0000609 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000610 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +0000611 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +0000612 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000613 Idx &= 31; // Match the hardware behavior.
Jim Grosbach7815f562012-02-03 00:07:04 +0000614
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000615 if (ExtractedElts[Idx] == 0) {
Jim Grosbach7815f562012-02-03 00:07:04 +0000616 ExtractedElts[Idx] =
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000617 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
618 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000619 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000620
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000621 // Insert this value into the result vector.
622 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000623 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000624 }
625 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
626 }
627 }
628 break;
629
Bob Wilsona4e231c2010-10-22 21:41:48 +0000630 case Intrinsic::arm_neon_vld1:
631 case Intrinsic::arm_neon_vld2:
632 case Intrinsic::arm_neon_vld3:
633 case Intrinsic::arm_neon_vld4:
634 case Intrinsic::arm_neon_vld2lane:
635 case Intrinsic::arm_neon_vld3lane:
636 case Intrinsic::arm_neon_vld4lane:
637 case Intrinsic::arm_neon_vst1:
638 case Intrinsic::arm_neon_vst2:
639 case Intrinsic::arm_neon_vst3:
640 case Intrinsic::arm_neon_vst4:
641 case Intrinsic::arm_neon_vst2lane:
642 case Intrinsic::arm_neon_vst3lane:
643 case Intrinsic::arm_neon_vst4lane: {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000644 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL);
Bob Wilsona4e231c2010-10-22 21:41:48 +0000645 unsigned AlignArg = II->getNumArgOperands() - 1;
646 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
647 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
648 II->setArgOperand(AlignArg,
649 ConstantInt::get(Type::getInt32Ty(II->getContext()),
650 MemAlign, false));
651 return II;
652 }
653 break;
654 }
655
Lang Hames3a90fab2012-05-01 00:20:38 +0000656 case Intrinsic::arm_neon_vmulls:
657 case Intrinsic::arm_neon_vmullu: {
658 Value *Arg0 = II->getArgOperand(0);
659 Value *Arg1 = II->getArgOperand(1);
660
661 // Handle mul by zero first:
662 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
663 return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
664 }
665
666 // Check for constant LHS & RHS - in this case we just simplify.
667 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu);
668 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +0000669 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
670 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
671 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
672 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
673
674 return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +0000675 }
676
Alp Tokercb402912014-01-24 17:20:08 +0000677 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +0000678 std::swap(Arg0, Arg1);
679 }
680
681 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +0000682 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +0000683 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +0000684 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
685 if (Splat->isOne())
686 return CastInst::CreateIntegerCast(Arg0, II->getType(),
687 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +0000688
689 break;
690 }
691
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000692 case Intrinsic::stackrestore: {
693 // If the save is right next to the restore, remove the restore. This can
694 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +0000695 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000696 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
697 BasicBlock::iterator BI = SS;
698 if (&*++BI == II)
699 return EraseInstFromFunction(CI);
700 }
701 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000702
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000703 // Scan down this block to see if there is another stack restore in the
704 // same block without an intervening call/alloca.
705 BasicBlock::iterator BI = II;
706 TerminatorInst *TI = II->getParent()->getTerminator();
707 bool CannotRemove = false;
708 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +0000709 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000710 CannotRemove = true;
711 break;
712 }
713 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
714 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
715 // If there is a stackrestore below this one, remove this one.
716 if (II->getIntrinsicID() == Intrinsic::stackrestore)
717 return EraseInstFromFunction(CI);
718 // Otherwise, ignore the intrinsic.
719 } else {
720 // If we found a non-intrinsic call, we can't remove the stack
721 // restore.
722 CannotRemove = true;
723 break;
724 }
725 }
726 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000727
Bill Wendlingf891bf82011-07-31 06:30:59 +0000728 // If the stack restore is in a return, resume, or unwind block and if there
729 // are no allocas or calls between the restore and the return, nuke the
730 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +0000731 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000732 return EraseInstFromFunction(CI);
733 break;
734 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000735 }
736
737 return visitCallSite(II);
738}
739
740// InvokeInst simplification
741//
742Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
743 return visitCallSite(&II);
744}
745
Jim Grosbach7815f562012-02-03 00:07:04 +0000746/// isSafeToEliminateVarargsCast - If this cast does not affect the value
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000747/// passed through the varargs area, we can eliminate the use of the cast.
748static bool isSafeToEliminateVarargsCast(const CallSite CS,
749 const CastInst * const CI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000750 const DataLayout * const DL,
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000751 const int ix) {
752 if (!CI->isLosslessCast())
753 return false;
754
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000755 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000756 // can't change to a type with a different size. If the size were
757 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +0000758 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000759 return true;
760
Jim Grosbach7815f562012-02-03 00:07:04 +0000761 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000762 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000763 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000764 if (!SrcTy->isSized() || !DstTy->isSized())
765 return false;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000766 if (!DL || DL->getTypeAllocSize(SrcTy) != DL->getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000767 return false;
768 return true;
769}
770
Eric Christophera7fb58f2010-03-06 10:50:38 +0000771// Try to fold some different type of calls here.
Jim Grosbach7815f562012-02-03 00:07:04 +0000772// Currently we're only working with the checking functions, memcpy_chk,
Eric Christophera7fb58f2010-03-06 10:50:38 +0000773// mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
774// strcat_chk and strncat_chk.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000775Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *DL) {
Eric Christophera7fb58f2010-03-06 10:50:38 +0000776 if (CI->getCalledFunction() == 0) return 0;
Eric Christophera7fb58f2010-03-06 10:50:38 +0000777
Meador Ingee3f2b262012-11-30 04:05:06 +0000778 if (Value *With = Simplifier->optimizeCall(CI)) {
779 ++NumSimplified;
Meador Ingef1bc9e72012-11-27 18:52:49 +0000780 return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +0000781 }
Meador Ingedf796f82012-10-13 16:45:24 +0000782
783 return 0;
Eric Christophera7fb58f2010-03-06 10:50:38 +0000784}
785
Duncan Sandsa0984362011-09-06 13:37:06 +0000786static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
787 // Strip off at most one level of pointer casts, looking for an alloca. This
788 // is good enough in practice and simpler than handling any number of casts.
789 Value *Underlying = TrampMem->stripPointerCasts();
790 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +0000791 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +0000792 return 0;
793 if (!isa<AllocaInst>(Underlying))
794 return 0;
795
796 IntrinsicInst *InitTrampoline = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000797 for (User *U : TrampMem->users()) {
798 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +0000799 if (!II)
800 return 0;
801 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
802 if (InitTrampoline)
803 // More than one init_trampoline writes to this value. Give up.
804 return 0;
805 InitTrampoline = II;
806 continue;
807 }
808 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
809 // Allow any number of calls to adjust.trampoline.
810 continue;
811 return 0;
812 }
813
814 // No call to init.trampoline found.
815 if (!InitTrampoline)
816 return 0;
817
818 // Check that the alloca is being used in the expected way.
819 if (InitTrampoline->getOperand(0) != TrampMem)
820 return 0;
821
822 return InitTrampoline;
823}
824
825static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
826 Value *TrampMem) {
827 // Visit all the previous instructions in the basic block, and try to find a
828 // init.trampoline which has a direct path to the adjust.trampoline.
829 for (BasicBlock::iterator I = AdjustTramp,
830 E = AdjustTramp->getParent()->begin(); I != E; ) {
831 Instruction *Inst = --I;
832 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
833 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
834 II->getOperand(0) == TrampMem)
835 return II;
836 if (Inst->mayWriteToMemory())
837 return 0;
838 }
839 return 0;
840}
841
842// Given a call to llvm.adjust.trampoline, find and return the corresponding
843// call to llvm.init.trampoline if the call to the trampoline can be optimized
844// to a direct call to a function. Otherwise return NULL.
845//
846static IntrinsicInst *FindInitTrampoline(Value *Callee) {
847 Callee = Callee->stripPointerCasts();
848 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
849 if (!AdjustTramp ||
850 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
851 return 0;
852
853 Value *TrampMem = AdjustTramp->getOperand(0);
854
855 if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
856 return IT;
857 if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
858 return IT;
859 return 0;
860}
861
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000862// visitCallSite - Improvements for call and invoke instructions.
863//
864Instruction *InstCombiner::visitCallSite(CallSite CS) {
Benjamin Kramer8bcc9712012-08-29 15:32:21 +0000865 if (isAllocLikeFn(CS.getInstruction(), TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000866 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +0000867
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000868 bool Changed = false;
869
Chris Lattner73989652010-12-20 08:25:06 +0000870 // If the callee is a pointer to a function, attempt to move any casts to the
871 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000872 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +0000873 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
874 return 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000875
876 if (Function *CalleeF = dyn_cast<Function>(Callee))
Chris Lattner846a52e2010-02-01 18:11:34 +0000877 // If the call and callee calling conventions don't match, this call must
878 // be unreachable, as the call is undefined.
879 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
880 // Only do this for calls to a function with a body. A prototype may
881 // not actually end up matching the implementation's calling conv for a
882 // variety of reasons (e.g. it may be written in assembly).
883 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000884 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000885 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +0000886 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000887 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +0000888 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000889 // This allows ValueHandlers and custom metadata to adjust itself.
890 if (!OldCall->getType()->isVoidTy())
Eli Friedmanb9ed18f2011-05-18 00:32:01 +0000891 ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +0000892 if (isa<CallInst>(OldCall))
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000893 return EraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +0000894
Chris Lattner2cecedf2010-02-01 18:04:58 +0000895 // We cannot remove an invoke, because it would change the CFG, just
896 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +0000897 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +0000898 Constant::getNullValue(CalleeF->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000899 return 0;
900 }
901
902 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +0000903 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000904 // This allows ValueHandlers and custom metadata to adjust itself.
905 if (!CS.getInstruction()->getType()->isVoidTy())
Eli Friedmanb9ed18f2011-05-18 00:32:01 +0000906 ReplaceInstUsesWith(*CS.getInstruction(),
907 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000908
Nuno Lopes771e7bd2012-06-21 23:52:14 +0000909 if (isa<InvokeInst>(CS.getInstruction())) {
910 // Can't remove an invoke because we cannot change the CFG.
911 return 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000912 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +0000913
914 // This instruction is not reachable, just remove it. We insert a store to
915 // undef so that we know that this code is not reachable, despite the fact
916 // that we can't modify the CFG here.
917 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
918 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
919 CS.getInstruction());
920
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000921 return EraseInstFromFunction(*CS.getInstruction());
922 }
923
Duncan Sandsa0984362011-09-06 13:37:06 +0000924 if (IntrinsicInst *II = FindInitTrampoline(Callee))
925 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000926
Chris Lattner229907c2011-07-18 04:54:35 +0000927 PointerType *PTy = cast<PointerType>(Callee->getType());
928 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000929 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +0000930 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000931 // See if we can optimize any arguments passed through the varargs area of
932 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +0000933 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000934 E = CS.arg_end(); I != E; ++I, ++ix) {
935 CastInst *CI = dyn_cast<CastInst>(*I);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000936 if (CI && isSafeToEliminateVarargsCast(CS, CI, DL, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000937 *I = CI->getOperand(0);
938 Changed = true;
939 }
940 }
941 }
942
943 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
944 // Inline asm calls cannot throw - mark them 'nounwind'.
945 CS.setDoesNotThrow();
946 Changed = true;
947 }
948
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000949 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +0000950 // this. None of these calls are seen as possibly dead so go ahead and
951 // delete the instruction now.
952 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000953 Instruction *I = tryOptimizeCall(CI, DL);
Eric Christopher1810d772010-03-06 10:59:25 +0000954 // If we changed something return the result, etc. Otherwise let
955 // the fallthrough check.
956 if (I) return EraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +0000957 }
958
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000959 return Changed ? CS.getInstruction() : 0;
960}
961
962// transformConstExprCastCall - If the callee is a constexpr cast of a function,
963// attempt to move the cast to the arguments of the call/invoke.
964//
965bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Chris Lattner73989652010-12-20 08:25:06 +0000966 Function *Callee =
967 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
968 if (Callee == 0)
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000969 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000970 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +0000971 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000972
973 // Okay, this is a cast from a function to a different type. Unless doing so
974 // would cause a type conversion of one of our arguments, change this call to
975 // be a direct call with arguments casted to the appropriate types.
976 //
Chris Lattner229907c2011-07-18 04:54:35 +0000977 FunctionType *FT = Callee->getFunctionType();
978 Type *OldRetTy = Caller->getType();
979 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000980
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000981 // Check to see if we are changing the return type...
982 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +0000983
984 if (NewRetTy->isStructTy())
985 return false; // TODO: Handle multiple return values.
986
Matt Arsenaulte6952f22013-09-17 21:10:14 +0000987 if (!CastInst::isBitCastable(NewRetTy, OldRetTy)) {
988 if (Callee->isDeclaration())
989 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000990
Matt Arsenaulte6952f22013-09-17 21:10:14 +0000991 if (!Caller->use_empty() &&
992 // void -> non-void is handled specially
993 !NewRetTy->isVoidTy())
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000994 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +0000995 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000996
997 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +0000998 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Bill Wendlingd2196752013-01-30 23:07:40 +0000999 if (RAttrs.
1000 hasAttributes(AttributeFuncs::
1001 typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
1002 AttributeSet::ReturnIndex))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001003 return false; // Attribute not compatible with transformed value.
1004 }
1005
1006 // If the callsite is an invoke instruction, and the return value is used by
1007 // a PHI node in a successor, we cannot change the return type of the call
1008 // because there is no place to put the cast instruction (without breaking
1009 // the critical edge). Bail out in this case.
1010 if (!Caller->use_empty())
1011 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00001012 for (User *U : II->users())
1013 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001014 if (PN->getParent() == II->getNormalDest() ||
1015 PN->getParent() == II->getUnwindDest())
1016 return false;
1017 }
1018
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00001019 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001020 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1021
1022 CallSite::arg_iterator AI = CS.arg_begin();
1023 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00001024 Type *ParamTy = FT->getParamType(i);
1025 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001026
Matt Arsenaulte6952f22013-09-17 21:10:14 +00001027 if (!CastInst::isBitCastable(ActTy, ParamTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001028 return false; // Cannot transform this parameter value.
1029
Bill Wendling49bc76c2013-01-23 06:14:59 +00001030 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Bill Wendlingd2196752013-01-30 23:07:40 +00001031 hasAttributes(AttributeFuncs::
1032 typeIncompatible(ParamTy, i + 1), i + 1))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001033 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00001034
Reid Kleckner26af2ca2014-01-28 02:38:36 +00001035 if (CS.isInAllocaArgument(i))
1036 return false; // Cannot transform to and from inalloca.
1037
Chris Lattner27ca8eb2010-12-20 08:36:38 +00001038 // If the parameter is passed as a byval argument, then we have to have a
1039 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00001040 if (ParamTy != ActTy &&
1041 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
1042 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001043 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001044 if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || DL == 0)
Chris Lattner27ca8eb2010-12-20 08:36:38 +00001045 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00001046
Matt Arsenaultfa252722013-09-27 22:18:51 +00001047 Type *CurElTy = ActTy->getPointerElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001048 if (DL->getTypeAllocSize(CurElTy) !=
1049 DL->getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00001050 return false;
1051 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001052 }
1053
Chris Lattneradf38b32011-02-24 05:10:56 +00001054 if (Callee->isDeclaration()) {
1055 // Do not delete arguments unless we have a function body.
1056 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
1057 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001058
Chris Lattneradf38b32011-02-24 05:10:56 +00001059 // If the callee is just a declaration, don't change the varargsness of the
1060 // call. We don't want to introduce a varargs call where one doesn't
1061 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00001062 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00001063 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
1064 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00001065
1066 // If both the callee and the cast type are varargs, we still have to make
1067 // sure the number of fixed parameters are the same or we have the same
1068 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00001069 if (FT->isVarArg() &&
1070 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
1071 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00001072 cast<FunctionType>(APTy->getElementType())->getNumParams())
1073 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00001074 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001075
Jim Grosbach0ab54182012-02-03 00:00:50 +00001076 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1077 !CallerPAL.isEmpty())
1078 // In this case we have more arguments than the new function type, but we
1079 // won't be dropping them. Check that these extra arguments have attributes
1080 // that are compatible with being a vararg call argument.
1081 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00001082 unsigned Index = CallerPAL.getSlotIndex(i - 1);
1083 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00001084 break;
Bill Wendling57625a42013-01-25 23:09:36 +00001085
Bill Wendlingd97b75d2012-12-19 08:57:40 +00001086 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00001087 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
1088 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00001089 return false;
1090 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001091
Jim Grosbach7815f562012-02-03 00:07:04 +00001092
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001093 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00001094 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001095 std::vector<Value*> Args;
1096 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00001097 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001098 attrVec.reserve(NumCommonArgs);
1099
1100 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00001101 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001102
1103 // If the return value is not being used, the type may not be compatible
1104 // with the existing attributes. Wipe out any problematic attributes.
Bill Wendlingd2196752013-01-30 23:07:40 +00001105 RAttrs.
1106 removeAttributes(AttributeFuncs::
1107 typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
1108 AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001109
1110 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00001111 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00001112 attrVec.push_back(AttributeSet::get(Caller->getContext(),
1113 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001114
1115 AI = CS.arg_begin();
1116 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00001117 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00001118
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001119 if ((*AI)->getType() == ParamTy) {
1120 Args.push_back(*AI);
1121 } else {
Matt Arsenaultcacbb232013-07-30 20:45:05 +00001122 Args.push_back(Builder->CreateBitCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001123 }
1124
1125 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00001126 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00001127 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00001128 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
1129 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001130 }
1131
1132 // If the function takes more arguments than the call was taking, add them
1133 // now.
1134 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1135 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1136
1137 // If we are removing arguments to the function, emit an obnoxious warning.
1138 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00001139 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
1140 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001141 // Add all of the arguments in their promoted form to the arg list.
1142 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00001143 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001144 if (PTy != (*AI)->getType()) {
1145 // Must promote to pass through va_arg area!
1146 Instruction::CastOps opcode =
1147 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001148 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001149 } else {
1150 Args.push_back(*AI);
1151 }
1152
1153 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00001154 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00001155 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00001156 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
1157 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001158 }
1159 }
1160 }
1161
Bill Wendlingbd4ea162013-01-21 21:57:28 +00001162 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00001163 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00001164 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001165
1166 if (NewRetTy->isVoidTy())
1167 Caller->setName(""); // Void type should not have a name.
1168
Bill Wendlinge94d8432012-12-07 23:16:57 +00001169 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00001170 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001171
1172 Instruction *NC;
1173 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Eli Friedman96254a02011-05-18 01:28:27 +00001174 NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
Jay Foad5bd375a2011-07-15 08:37:34 +00001175 II->getUnwindDest(), Args);
Eli Friedman96254a02011-05-18 01:28:27 +00001176 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001177 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1178 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1179 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001180 CallInst *CI = cast<CallInst>(Caller);
Jay Foad5bd375a2011-07-15 08:37:34 +00001181 NC = Builder->CreateCall(Callee, Args);
Eli Friedman96254a02011-05-18 01:28:27 +00001182 NC->takeName(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001183 if (CI->isTailCall())
1184 cast<CallInst>(NC)->setTailCall();
1185 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1186 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1187 }
1188
1189 // Insert a cast of the return type as necessary.
1190 Value *NV = NC;
1191 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1192 if (!NV->getType()->isVoidTy()) {
Matt Arsenaultcacbb232013-07-30 20:45:05 +00001193 NV = NC = CastInst::Create(CastInst::BitCast, NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00001194 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001195
1196 // If this is an invoke instruction, we should insert it after the first
1197 // non-phi, instruction in the normal successor block.
1198 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00001199 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001200 InsertNewInstBefore(NC, *I);
1201 } else {
Chris Lattner73989652010-12-20 08:25:06 +00001202 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001203 InsertNewInstBefore(NC, *Caller);
1204 }
1205 Worklist.AddUsersToWorkList(*Caller);
1206 } else {
1207 NV = UndefValue::get(Caller->getType());
1208 }
1209 }
1210
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001211 if (!Caller->use_empty())
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00001212 ReplaceInstUsesWith(*Caller, NV);
Nick Lewycky75080ff2014-02-20 23:00:15 +00001213 else if (Caller->hasValueHandle())
1214 ValueHandleBase::ValueIsRAUWd(Caller, NV);
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00001215
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001216 EraseInstFromFunction(*Caller);
1217 return true;
1218}
1219
Duncan Sandsa0984362011-09-06 13:37:06 +00001220// transformCallThroughTrampoline - Turn a call to a function created by
1221// init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
1222// underlying function.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001223//
Duncan Sandsa0984362011-09-06 13:37:06 +00001224Instruction *
1225InstCombiner::transformCallThroughTrampoline(CallSite CS,
1226 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001227 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00001228 PointerType *PTy = cast<PointerType>(Callee->getType());
1229 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00001230 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001231
1232 // If the call already has the 'nest' attribute somewhere then give up -
1233 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00001234 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1235 return 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001236
Duncan Sandsa0984362011-09-06 13:37:06 +00001237 assert(Tramp &&
1238 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001239
Gabor Greif3e44ea12010-07-22 10:37:47 +00001240 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Chris Lattner229907c2011-07-18 04:54:35 +00001241 PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1242 FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001243
Bill Wendlinge94d8432012-12-07 23:16:57 +00001244 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001245 if (!NestAttrs.isEmpty()) {
1246 unsigned NestIdx = 1;
Jay Foadb804a2b2011-07-12 14:06:48 +00001247 Type *NestTy = 0;
Bill Wendling49bc76c2013-01-23 06:14:59 +00001248 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001249
1250 // Look for a parameter marked with the 'nest' attribute.
1251 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1252 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00001253 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001254 // Record the parameter type and any other attributes.
1255 NestTy = *I;
1256 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1257 break;
1258 }
1259
1260 if (NestTy) {
1261 Instruction *Caller = CS.getInstruction();
1262 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00001263 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001264
Bill Wendling3575c8c2013-01-27 02:08:22 +00001265 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001266 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1267
1268 // Insert the nest argument into the call argument list, which may
1269 // mean appending it. Likewise for attributes.
1270
1271 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00001272 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00001273 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1274 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001275
1276 {
1277 unsigned Idx = 1;
1278 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1279 do {
1280 if (Idx == NestIdx) {
1281 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00001282 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001283 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00001284 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001285 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00001286 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1287 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001288 }
1289
1290 if (I == E)
1291 break;
1292
1293 // Add the original argument and attributes.
1294 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00001295 AttributeSet Attr = Attrs.getParamAttributes(Idx);
1296 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00001297 AttrBuilder B(Attr, Idx);
1298 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1299 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00001300 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001301
1302 ++Idx, ++I;
1303 } while (1);
1304 }
1305
1306 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00001307 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00001308 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
1309 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001310
1311 // The trampoline may have been bitcast to a bogus type (FTy).
1312 // Handle this by synthesizing a new function type, equal to FTy
1313 // with the chain parameter inserted.
1314
Jay Foadb804a2b2011-07-12 14:06:48 +00001315 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001316 NewTypes.reserve(FTy->getNumParams()+1);
1317
1318 // Insert the chain's type into the list of parameter types, which may
1319 // mean appending it.
1320 {
1321 unsigned Idx = 1;
1322 FunctionType::param_iterator I = FTy->param_begin(),
1323 E = FTy->param_end();
1324
1325 do {
1326 if (Idx == NestIdx)
1327 // Add the chain's type.
1328 NewTypes.push_back(NestTy);
1329
1330 if (I == E)
1331 break;
1332
1333 // Add the original type.
1334 NewTypes.push_back(*I);
1335
1336 ++Idx, ++I;
1337 } while (1);
1338 }
1339
1340 // Replace the trampoline call with a direct call. Let the generic
1341 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00001342 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001343 FTy->isVarArg());
1344 Constant *NewCallee =
1345 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00001346 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001347 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001348 const AttributeSet &NewPAL =
1349 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001350
1351 Instruction *NewCaller;
1352 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1353 NewCaller = InvokeInst::Create(NewCallee,
1354 II->getNormalDest(), II->getUnwindDest(),
Jay Foad5bd375a2011-07-15 08:37:34 +00001355 NewArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001356 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1357 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1358 } else {
Jay Foad5bd375a2011-07-15 08:37:34 +00001359 NewCaller = CallInst::Create(NewCallee, NewArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001360 if (cast<CallInst>(Caller)->isTailCall())
1361 cast<CallInst>(NewCaller)->setTailCall();
1362 cast<CallInst>(NewCaller)->
1363 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1364 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1365 }
Eli Friedman49346012011-05-18 19:57:14 +00001366
1367 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001368 }
1369 }
1370
1371 // Replace the trampoline call with a direct call. Since there is no 'nest'
1372 // parameter, there is no need to adjust the argument list. Let the generic
1373 // code sort out any function type mismatches.
1374 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00001375 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001376 ConstantExpr::getBitCast(NestF, PTy);
1377 CS.setCalledFunction(NewCallee);
1378 return CS.getInstruction();
1379}