blob: a241f169f28ac2c9a3703b2f0b803453a75cb1a6 [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"
15#include "llvm/IntrinsicInst.h"
16#include "llvm/Support/CallSite.h"
17#include "llvm/Target/TargetData.h"
18#include "llvm/Analysis/MemoryBuiltins.h"
19using namespace llvm;
20
21/// getPromotedType - Return the specified type promoted as it would be to pass
22/// though a va_arg area.
23static const Type *getPromotedType(const Type *Ty) {
24 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
25 if (ITy->getBitWidth() < 32)
26 return Type::getInt32Ty(Ty->getContext());
27 }
28 return Ty;
29}
30
31/// EnforceKnownAlignment - If the specified pointer points to an object that
32/// we control, modify the object's alignment to PrefAlign. This isn't
33/// often possible though. If alignment is important, a more reliable approach
34/// is to simply align all global variables and allocation instructions to
35/// their preferred alignment from the beginning.
36///
37static unsigned EnforceKnownAlignment(Value *V,
38 unsigned Align, unsigned PrefAlign) {
39
40 User *U = dyn_cast<User>(V);
41 if (!U) return Align;
42
43 switch (Operator::getOpcode(U)) {
44 default: break;
45 case Instruction::BitCast:
46 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
47 case Instruction::GetElementPtr: {
48 // If all indexes are zero, it is just the alignment of the base pointer.
49 bool AllZeroOperands = true;
50 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
51 if (!isa<Constant>(*i) ||
52 !cast<Constant>(*i)->isNullValue()) {
53 AllZeroOperands = false;
54 break;
55 }
56
57 if (AllZeroOperands) {
58 // Treat this like a bitcast.
59 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
60 }
61 break;
62 }
63 }
64
65 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
66 // If there is a large requested alignment and we can, bump up the alignment
67 // of the global.
68 if (!GV->isDeclaration()) {
69 if (GV->getAlignment() >= PrefAlign)
70 Align = GV->getAlignment();
71 else {
72 GV->setAlignment(PrefAlign);
73 Align = PrefAlign;
74 }
75 }
76 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
77 // If there is a requested alignment and if this is an alloca, round up.
78 if (AI->getAlignment() >= PrefAlign)
79 Align = AI->getAlignment();
80 else {
81 AI->setAlignment(PrefAlign);
82 Align = PrefAlign;
83 }
84 }
85
86 return Align;
87}
88
89/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
90/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
91/// and it is more than the alignment of the ultimate object, see if we can
92/// increase the alignment of the ultimate object, making this check succeed.
93unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
94 unsigned PrefAlign) {
95 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
96 sizeof(PrefAlign) * CHAR_BIT;
97 APInt Mask = APInt::getAllOnesValue(BitWidth);
98 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
99 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
100 unsigned TrailZ = KnownZero.countTrailingOnes();
101 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
102
103 if (PrefAlign > Align)
104 Align = EnforceKnownAlignment(V, Align, PrefAlign);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000105
Chris Lattner753a2b42010-01-05 07:32:13 +0000106 // We don't need to make any adjustment.
107 return Align;
108}
109
110Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
111 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
112 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
113 unsigned MinAlign = std::min(DstAlign, SrcAlign);
114 unsigned CopyAlign = MI->getAlignment();
115
116 if (CopyAlign < MinAlign) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000117 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Chris Lattner753a2b42010-01-05 07:32:13 +0000118 MinAlign, false));
119 return MI;
120 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000121
Chris Lattner753a2b42010-01-05 07:32:13 +0000122 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
123 // load/store.
124 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
125 if (MemOpLength == 0) return 0;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000126
Chris Lattner753a2b42010-01-05 07:32:13 +0000127 // Source and destination pointer types are always "i8*" for intrinsic. See
128 // if the size is something we can handle with a single primitive load/store.
129 // A single load+store correctly handles overlapping memory in the memmove
130 // case.
131 unsigned Size = MemOpLength->getZExtValue();
132 if (Size == 0) return MI; // Delete this mem transfer.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000133
Chris Lattner753a2b42010-01-05 07:32:13 +0000134 if (Size > 8 || (Size&(Size-1)))
135 return 0; // If not 1/2/4/8 bytes, exit.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000136
Chris Lattner753a2b42010-01-05 07:32:13 +0000137 // Use an integer load+store unless we can find something better.
138 Type *NewPtrTy =
139 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000140
Chris Lattner753a2b42010-01-05 07:32:13 +0000141 // Memcpy forces the use of i8* for the source and destination. That means
142 // that if you're using memcpy to move one double around, you'll get a cast
143 // from double* to i8*. We'd much rather use a double load+store rather than
144 // an i64 load+store, here because this improves the odds that the source or
145 // dest address will be promotable. See if we can find a better type than the
146 // integer datatype.
147 Value *StrippedDest = MI->getOperand(1)->stripPointerCasts();
148 if (StrippedDest != MI->getOperand(1)) {
149 const Type *SrcETy = cast<PointerType>(StrippedDest->getType())
150 ->getElementType();
151 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
152 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
153 // down through these levels if so.
154 while (!SrcETy->isSingleValueType()) {
155 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
156 if (STy->getNumElements() == 1)
157 SrcETy = STy->getElementType(0);
158 else
159 break;
160 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
161 if (ATy->getNumElements() == 1)
162 SrcETy = ATy->getElementType();
163 else
164 break;
165 } else
166 break;
167 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000168
Chris Lattner753a2b42010-01-05 07:32:13 +0000169 if (SrcETy->isSingleValueType())
170 NewPtrTy = PointerType::getUnqual(SrcETy);
171 }
172 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000173
174
Chris Lattner753a2b42010-01-05 07:32:13 +0000175 // If the memcpy/memmove provides better alignment info than we can
176 // infer, use it.
177 SrcAlign = std::max(SrcAlign, CopyAlign);
178 DstAlign = std::max(DstAlign, CopyAlign);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000179
Chris Lattner753a2b42010-01-05 07:32:13 +0000180 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
181 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
182 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
183 InsertNewInstBefore(L, *MI);
184 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
185
186 // Set the size of the copy to 0, it will be deleted on the next iteration.
187 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
188 return MI;
189}
190
191Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
192 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
193 if (MI->getAlignment() < Alignment) {
194 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
195 Alignment, false));
196 return MI;
197 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000198
Chris Lattner753a2b42010-01-05 07:32:13 +0000199 // Extract the length and alignment and fill if they are constant.
200 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
201 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000202 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Chris Lattner753a2b42010-01-05 07:32:13 +0000203 return 0;
204 uint64_t Len = LenC->getZExtValue();
205 Alignment = MI->getAlignment();
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000206
Chris Lattner753a2b42010-01-05 07:32:13 +0000207 // If the length is zero, this is a no-op
208 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000209
Chris Lattner753a2b42010-01-05 07:32:13 +0000210 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
211 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
212 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000213
Chris Lattner753a2b42010-01-05 07:32:13 +0000214 Value *Dest = MI->getDest();
215 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
216
217 // Alignment 0 is identity for alignment 1 for memset, but not store.
218 if (Alignment == 0) Alignment = 1;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000219
Chris Lattner753a2b42010-01-05 07:32:13 +0000220 // Extract the fill value and store.
221 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
222 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
223 Dest, false, Alignment), *MI);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000224
Chris Lattner753a2b42010-01-05 07:32:13 +0000225 // Set the size of the copy to 0, it will be deleted on the next iteration.
226 MI->setLength(Constant::getNullValue(LenC->getType()));
227 return MI;
228 }
229
230 return 0;
231}
232
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000233/// visitCallInst - CallInst simplification. This mostly only handles folding
Chris Lattner753a2b42010-01-05 07:32:13 +0000234/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
235/// the heavy lifting.
236///
237Instruction *InstCombiner::visitCallInst(CallInst &CI) {
238 if (isFreeCall(&CI))
239 return visitFree(CI);
240
241 // If the caller function is nounwind, mark the call as nounwind, even if the
242 // callee isn't.
243 if (CI.getParent()->getParent()->doesNotThrow() &&
244 !CI.doesNotThrow()) {
245 CI.setDoesNotThrow();
246 return &CI;
247 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000248
Chris Lattner753a2b42010-01-05 07:32:13 +0000249 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
250 if (!II) return visitCallSite(&CI);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000251
Chris Lattner753a2b42010-01-05 07:32:13 +0000252 // Intrinsics cannot occur in an invoke, so handle them here instead of in
253 // visitCallSite.
254 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
255 bool Changed = false;
256
257 // memmove/cpy/set of zero bytes is a noop.
258 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
259 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
260
261 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
262 if (CI->getZExtValue() == 1) {
263 // Replace the instruction with just byte operations. We would
264 // transform other cases to loads/stores, but we don't know if
265 // alignment is sufficient.
266 }
267 }
268
269 // If we have a memmove and the source operation is a constant global,
270 // then the source and dest pointers can't alias, so we can change this
271 // into a call to memcpy.
272 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
273 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
274 if (GVSrc->isConstant()) {
275 Module *M = CI.getParent()->getParent()->getParent();
276 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
277 const Type *Tys[1];
278 Tys[0] = CI.getOperand(3)->getType();
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000279 CI.setOperand(0,
Chris Lattner753a2b42010-01-05 07:32:13 +0000280 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
281 Changed = true;
282 }
283 }
284
285 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
286 // memmove(x,x,size) -> noop.
287 if (MTI->getSource() == MTI->getDest())
288 return EraseInstFromFunction(CI);
289 }
290
291 // If we can determine a pointer alignment that is bigger than currently
292 // set, update the alignment.
293 if (isa<MemTransferInst>(MI)) {
294 if (Instruction *I = SimplifyMemTransfer(MI))
295 return I;
296 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
297 if (Instruction *I = SimplifyMemSet(MSI))
298 return I;
299 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000300
Chris Lattner753a2b42010-01-05 07:32:13 +0000301 if (Changed) return II;
302 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000303
Chris Lattner753a2b42010-01-05 07:32:13 +0000304 switch (II->getIntrinsicID()) {
305 default: break;
Eric Christopher415326b2010-02-09 21:24:27 +0000306 case Intrinsic::objectsize: {
Eric Christopher26d0e892010-02-11 01:48:54 +0000307 // We need target data for just about everything so depend on it.
Eric Christopher415326b2010-02-09 21:24:27 +0000308 if (!TD) break;
Eric Christopher26d0e892010-02-11 01:48:54 +0000309
Evan Chenga8623262010-03-05 20:47:23 +0000310 const Type *ReturnTy = CI.getType();
311 bool Min = (cast<ConstantInt>(II->getOperand(2))->getZExtValue() == 1);
312
Eric Christopher26d0e892010-02-11 01:48:54 +0000313 // Get to the real allocated thing and offset as fast as possible.
Evan Chenga8623262010-03-05 20:47:23 +0000314 Value *Op1 = II->getOperand(1)->stripPointerCasts();
Eric Christopher415326b2010-02-09 21:24:27 +0000315
Eric Christopher26d0e892010-02-11 01:48:54 +0000316 // If we've stripped down to a single global variable that we
317 // can know the size of then just return that.
Eric Christopher415326b2010-02-09 21:24:27 +0000318 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
319 if (GV->hasDefinitiveInitializer()) {
320 Constant *C = GV->getInitializer();
Evan Chenga8623262010-03-05 20:47:23 +0000321 uint64_t GlobalSize = TD->getTypeAllocSize(C->getType());
322 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, GlobalSize));
Eric Christopher415326b2010-02-09 21:24:27 +0000323 } else {
Evan Chenga8623262010-03-05 20:47:23 +0000324 // Can't determine size of the GV.
Eric Christopher415326b2010-02-09 21:24:27 +0000325 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
326 return ReplaceInstUsesWith(CI, RetVal);
327 }
Evan Chenga8623262010-03-05 20:47:23 +0000328 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Op1)) {
329 // Get alloca size.
330 if (AI->getAllocatedType()->isSized()) {
331 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
332 if (AI->isArrayAllocation()) {
333 const ConstantInt *C = dyn_cast<ConstantInt>(AI->getArraySize());
334 if (!C) break;
335 AllocaSize *= C->getZExtValue();
336 }
337 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, AllocaSize));
338 }
339 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op1)) {
Eric Christopher26d0e892010-02-11 01:48:54 +0000340 // Only handle constant GEPs here.
341 if (CE->getOpcode() != Instruction::GetElementPtr) break;
342 GEPOperator *GEP = cast<GEPOperator>(CE);
343
Eric Christopherdfdddd82010-02-11 17:44:04 +0000344 // Make sure we're not a constant offset from an external
345 // global.
346 Value *Operand = GEP->getPointerOperand();
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000347 Operand = Operand->stripPointerCasts();
Eric Christopherdfdddd82010-02-11 17:44:04 +0000348 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand))
349 if (!GV->hasDefinitiveInitializer()) break;
350
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000351 // Get what we're pointing to and its size.
352 const PointerType *BaseType =
Eric Christopherdfdddd82010-02-11 17:44:04 +0000353 cast<PointerType>(Operand->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000354 uint64_t Size = TD->getTypeAllocSize(BaseType->getElementType());
Eric Christopher26d0e892010-02-11 01:48:54 +0000355
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000356 // Get the current byte offset into the thing. Use the original
357 // operand in case we're looking through a bitcast.
Eric Christopher26d0e892010-02-11 01:48:54 +0000358 SmallVector<Value*, 8> Ops(CE->op_begin()+1, CE->op_end());
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000359 const PointerType *OffsetType =
360 cast<PointerType>(GEP->getPointerOperand()->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000361 uint64_t Offset = TD->getIndexedOffset(OffsetType, &Ops[0], Ops.size());
Eric Christopher26d0e892010-02-11 01:48:54 +0000362
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000363 if (Size < Offset) {
364 // Out of bound reference? Negative index normalized to large
365 // index? Just return "I don't know".
366 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
367 return ReplaceInstUsesWith(CI, RetVal);
368 }
Eric Christopher26d0e892010-02-11 01:48:54 +0000369
370 Constant *RetVal = ConstantInt::get(ReturnTy, Size-Offset);
371 return ReplaceInstUsesWith(CI, RetVal);
372
Eric Christopherdfdddd82010-02-11 17:44:04 +0000373 }
Evan Chenga8623262010-03-05 20:47:23 +0000374
375 // Do not return "I don't know" here. Later optimization passes could
376 // make it possible to evaluate objectsize to a constant.
Evan Chengf79d6242010-03-05 01:22:47 +0000377 break;
Eric Christopher415326b2010-02-09 21:24:27 +0000378 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000379 case Intrinsic::bswap:
380 // bswap(bswap(x)) -> x
381 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
382 if (Operand->getIntrinsicID() == Intrinsic::bswap)
383 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000384
Chris Lattner753a2b42010-01-05 07:32:13 +0000385 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
386 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
387 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
388 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
389 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
390 TI->getType()->getPrimitiveSizeInBits();
391 Value *CV = ConstantInt::get(Operand->getType(), C);
392 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
393 return new TruncInst(V, TI->getType());
394 }
395 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000396
Chris Lattner753a2b42010-01-05 07:32:13 +0000397 break;
398 case Intrinsic::powi:
399 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
400 // powi(x, 0) -> 1.0
401 if (Power->isZero())
402 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
403 // powi(x, 1) -> x
404 if (Power->isOne())
405 return ReplaceInstUsesWith(CI, II->getOperand(1));
406 // powi(x, -1) -> 1/x
407 if (Power->isAllOnesValue())
408 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
409 II->getOperand(1));
410 }
411 break;
412 case Intrinsic::cttz: {
413 // If all bits below the first known one are known zero,
414 // this value is constant.
415 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
416 uint32_t BitWidth = IT->getBitWidth();
417 APInt KnownZero(BitWidth, 0);
418 APInt KnownOne(BitWidth, 0);
419 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
420 KnownZero, KnownOne);
421 unsigned TrailingZeros = KnownOne.countTrailingZeros();
422 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
423 if ((Mask & KnownZero) == Mask)
424 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
425 APInt(BitWidth, TrailingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000426
Chris Lattner753a2b42010-01-05 07:32:13 +0000427 }
428 break;
429 case Intrinsic::ctlz: {
430 // If all bits above the first known one are known zero,
431 // this value is constant.
432 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
433 uint32_t BitWidth = IT->getBitWidth();
434 APInt KnownZero(BitWidth, 0);
435 APInt KnownOne(BitWidth, 0);
436 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
437 KnownZero, KnownOne);
438 unsigned LeadingZeros = KnownOne.countLeadingZeros();
439 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
440 if ((Mask & KnownZero) == Mask)
441 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
442 APInt(BitWidth, LeadingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000443
Chris Lattner753a2b42010-01-05 07:32:13 +0000444 }
445 break;
446 case Intrinsic::uadd_with_overflow: {
447 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
448 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
449 uint32_t BitWidth = IT->getBitWidth();
450 APInt Mask = APInt::getSignBit(BitWidth);
451 APInt LHSKnownZero(BitWidth, 0);
452 APInt LHSKnownOne(BitWidth, 0);
453 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
454 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
455 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
456
457 if (LHSKnownNegative || LHSKnownPositive) {
458 APInt RHSKnownZero(BitWidth, 0);
459 APInt RHSKnownOne(BitWidth, 0);
460 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
461 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
462 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
463 if (LHSKnownNegative && RHSKnownNegative) {
464 // The sign bit is set in both cases: this MUST overflow.
465 // Create a simple add instruction, and insert it into the struct.
466 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
467 Worklist.Add(Add);
468 Constant *V[] = {
469 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
470 };
471 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
472 return InsertValueInst::Create(Struct, Add, 0);
473 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000474
Chris Lattner753a2b42010-01-05 07:32:13 +0000475 if (LHSKnownPositive && RHSKnownPositive) {
476 // The sign bit is clear in both cases: this CANNOT overflow.
477 // Create a simple add instruction, and insert it into the struct.
478 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
479 Worklist.Add(Add);
480 Constant *V[] = {
481 UndefValue::get(LHS->getType()),
482 ConstantInt::getFalse(II->getContext())
483 };
484 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
485 return InsertValueInst::Create(Struct, Add, 0);
486 }
487 }
488 }
489 // FALL THROUGH uadd into sadd
490 case Intrinsic::sadd_with_overflow:
491 // Canonicalize constants into the RHS.
492 if (isa<Constant>(II->getOperand(1)) &&
493 !isa<Constant>(II->getOperand(2))) {
494 Value *LHS = II->getOperand(1);
495 II->setOperand(1, II->getOperand(2));
496 II->setOperand(2, LHS);
497 return II;
498 }
499
500 // X + undef -> undef
501 if (isa<UndefValue>(II->getOperand(2)))
502 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000503
Chris Lattner753a2b42010-01-05 07:32:13 +0000504 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
505 // X + 0 -> {X, false}
506 if (RHS->isZero()) {
507 Constant *V[] = {
508 UndefValue::get(II->getOperand(0)->getType()),
509 ConstantInt::getFalse(II->getContext())
510 };
511 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
512 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
513 }
514 }
515 break;
516 case Intrinsic::usub_with_overflow:
517 case Intrinsic::ssub_with_overflow:
518 // undef - X -> undef
519 // X - undef -> undef
520 if (isa<UndefValue>(II->getOperand(1)) ||
521 isa<UndefValue>(II->getOperand(2)))
522 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000523
Chris Lattner753a2b42010-01-05 07:32:13 +0000524 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
525 // X - 0 -> {X, false}
526 if (RHS->isZero()) {
527 Constant *V[] = {
528 UndefValue::get(II->getOperand(1)->getType()),
529 ConstantInt::getFalse(II->getContext())
530 };
531 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
532 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
533 }
534 }
535 break;
536 case Intrinsic::umul_with_overflow:
537 case Intrinsic::smul_with_overflow:
538 // Canonicalize constants into the RHS.
539 if (isa<Constant>(II->getOperand(1)) &&
540 !isa<Constant>(II->getOperand(2))) {
541 Value *LHS = II->getOperand(1);
542 II->setOperand(1, II->getOperand(2));
543 II->setOperand(2, LHS);
544 return II;
545 }
546
547 // X * undef -> undef
548 if (isa<UndefValue>(II->getOperand(2)))
549 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000550
Chris Lattner753a2b42010-01-05 07:32:13 +0000551 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
552 // X*0 -> {0, false}
553 if (RHSI->isZero())
554 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000555
Chris Lattner753a2b42010-01-05 07:32:13 +0000556 // X * 1 -> {X, false}
557 if (RHSI->equalsInt(1)) {
558 Constant *V[] = {
559 UndefValue::get(II->getOperand(1)->getType()),
560 ConstantInt::getFalse(II->getContext())
561 };
562 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
563 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
564 }
565 }
566 break;
567 case Intrinsic::ppc_altivec_lvx:
568 case Intrinsic::ppc_altivec_lvxl:
569 case Intrinsic::x86_sse_loadu_ps:
570 case Intrinsic::x86_sse2_loadu_pd:
571 case Intrinsic::x86_sse2_loadu_dq:
572 // Turn PPC lvx -> load if the pointer is known aligned.
573 // Turn X86 loadups -> load if the pointer is known aligned.
574 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
575 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
576 PointerType::getUnqual(II->getType()));
577 return new LoadInst(Ptr);
578 }
579 break;
580 case Intrinsic::ppc_altivec_stvx:
581 case Intrinsic::ppc_altivec_stvxl:
582 // Turn stvx -> store if the pointer is known aligned.
583 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000584 const Type *OpPtrTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000585 PointerType::getUnqual(II->getOperand(1)->getType());
586 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
587 return new StoreInst(II->getOperand(1), Ptr);
588 }
589 break;
590 case Intrinsic::x86_sse_storeu_ps:
591 case Intrinsic::x86_sse2_storeu_pd:
592 case Intrinsic::x86_sse2_storeu_dq:
593 // Turn X86 storeu -> store if the pointer is known aligned.
594 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000595 const Type *OpPtrTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000596 PointerType::getUnqual(II->getOperand(2)->getType());
597 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
598 return new StoreInst(II->getOperand(2), Ptr);
599 }
600 break;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000601
Chris Lattner753a2b42010-01-05 07:32:13 +0000602 case Intrinsic::x86_sse_cvttss2si: {
603 // These intrinsics only demands the 0th element of its input vector. If
604 // we can simplify the input based on that, do so now.
605 unsigned VWidth =
606 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
607 APInt DemandedElts(VWidth, 1);
608 APInt UndefElts(VWidth, 0);
609 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
610 UndefElts)) {
611 II->setOperand(1, V);
612 return II;
613 }
614 break;
615 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000616
Chris Lattner753a2b42010-01-05 07:32:13 +0000617 case Intrinsic::ppc_altivec_vperm:
618 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
619 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
620 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000621
Chris Lattner753a2b42010-01-05 07:32:13 +0000622 // Check that all of the elements are integer constants or undefs.
623 bool AllEltsOk = true;
624 for (unsigned i = 0; i != 16; ++i) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000625 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
Chris Lattner753a2b42010-01-05 07:32:13 +0000626 !isa<UndefValue>(Mask->getOperand(i))) {
627 AllEltsOk = false;
628 break;
629 }
630 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000631
Chris Lattner753a2b42010-01-05 07:32:13 +0000632 if (AllEltsOk) {
633 // Cast the input vectors to byte vectors.
634 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
635 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
636 Value *Result = UndefValue::get(Op0->getType());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000637
Chris Lattner753a2b42010-01-05 07:32:13 +0000638 // Only extract each element once.
639 Value *ExtractedElts[32];
640 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000641
Chris Lattner753a2b42010-01-05 07:32:13 +0000642 for (unsigned i = 0; i != 16; ++i) {
643 if (isa<UndefValue>(Mask->getOperand(i)))
644 continue;
645 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
646 Idx &= 31; // Match the hardware behavior.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000647
Chris Lattner753a2b42010-01-05 07:32:13 +0000648 if (ExtractedElts[Idx] == 0) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000649 ExtractedElts[Idx] =
650 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner753a2b42010-01-05 07:32:13 +0000651 ConstantInt::get(Type::getInt32Ty(II->getContext()),
652 Idx&15, false), "tmp");
653 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000654
Chris Lattner753a2b42010-01-05 07:32:13 +0000655 // Insert this value into the result vector.
656 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
657 ConstantInt::get(Type::getInt32Ty(II->getContext()),
658 i, false), "tmp");
659 }
660 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
661 }
662 }
663 break;
664
665 case Intrinsic::stackrestore: {
666 // If the save is right next to the restore, remove the restore. This can
667 // happen when variable allocas are DCE'd.
668 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
669 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
670 BasicBlock::iterator BI = SS;
671 if (&*++BI == II)
672 return EraseInstFromFunction(CI);
673 }
674 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000675
Chris Lattner753a2b42010-01-05 07:32:13 +0000676 // Scan down this block to see if there is another stack restore in the
677 // same block without an intervening call/alloca.
678 BasicBlock::iterator BI = II;
679 TerminatorInst *TI = II->getParent()->getTerminator();
680 bool CannotRemove = false;
681 for (++BI; &*BI != TI; ++BI) {
682 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
683 CannotRemove = true;
684 break;
685 }
686 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
687 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
688 // If there is a stackrestore below this one, remove this one.
689 if (II->getIntrinsicID() == Intrinsic::stackrestore)
690 return EraseInstFromFunction(CI);
691 // Otherwise, ignore the intrinsic.
692 } else {
693 // If we found a non-intrinsic call, we can't remove the stack
694 // restore.
695 CannotRemove = true;
696 break;
697 }
698 }
699 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000700
Chris Lattner753a2b42010-01-05 07:32:13 +0000701 // If the stack restore is in a return/unwind block and if there are no
702 // allocas or calls between the restore and the return, nuke the restore.
703 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
704 return EraseInstFromFunction(CI);
705 break;
706 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000707 }
708
709 return visitCallSite(II);
710}
711
712// InvokeInst simplification
713//
714Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
715 return visitCallSite(&II);
716}
717
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000718/// isSafeToEliminateVarargsCast - If this cast does not affect the value
Chris Lattner753a2b42010-01-05 07:32:13 +0000719/// passed through the varargs area, we can eliminate the use of the cast.
720static bool isSafeToEliminateVarargsCast(const CallSite CS,
721 const CastInst * const CI,
722 const TargetData * const TD,
723 const int ix) {
724 if (!CI->isLosslessCast())
725 return false;
726
727 // The size of ByVal arguments is derived from the type, so we
728 // can't change to a type with a different size. If the size were
729 // passed explicitly we could avoid this check.
730 if (!CS.paramHasAttr(ix, Attribute::ByVal))
731 return true;
732
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000733 const Type* SrcTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000734 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
735 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
736 if (!SrcTy->isSized() || !DstTy->isSized())
737 return false;
738 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
739 return false;
740 return true;
741}
742
743// visitCallSite - Improvements for call and invoke instructions.
744//
745Instruction *InstCombiner::visitCallSite(CallSite CS) {
746 bool Changed = false;
747
748 // If the callee is a constexpr cast of a function, attempt to move the cast
749 // to the arguments of the call/invoke.
750 if (transformConstExprCastCall(CS)) return 0;
751
752 Value *Callee = CS.getCalledValue();
753
754 if (Function *CalleeF = dyn_cast<Function>(Callee))
Chris Lattnerd5695612010-02-01 18:11:34 +0000755 // If the call and callee calling conventions don't match, this call must
756 // be unreachable, as the call is undefined.
757 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
758 // Only do this for calls to a function with a body. A prototype may
759 // not actually end up matching the implementation's calling conv for a
760 // variety of reasons (e.g. it may be written in assembly).
761 !CalleeF->isDeclaration()) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000762 Instruction *OldCall = CS.getInstruction();
Chris Lattner753a2b42010-01-05 07:32:13 +0000763 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000764 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner753a2b42010-01-05 07:32:13 +0000765 OldCall);
766 // If OldCall dues not return void then replaceAllUsesWith undef.
767 // This allows ValueHandlers and custom metadata to adjust itself.
768 if (!OldCall->getType()->isVoidTy())
769 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner830f3f22010-02-01 18:04:58 +0000770 if (isa<CallInst>(OldCall))
Chris Lattner753a2b42010-01-05 07:32:13 +0000771 return EraseInstFromFunction(*OldCall);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000772
Chris Lattner830f3f22010-02-01 18:04:58 +0000773 // We cannot remove an invoke, because it would change the CFG, just
774 // change the callee to a null pointer.
775 cast<InvokeInst>(OldCall)->setOperand(0,
776 Constant::getNullValue(CalleeF->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000777 return 0;
778 }
779
780 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
781 // This instruction is not reachable, just remove it. We insert a store to
782 // undef so that we know that this code is not reachable, despite the fact
783 // that we can't modify the CFG here.
784 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
785 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
786 CS.getInstruction());
787
788 // If CS dues not return void then replaceAllUsesWith undef.
789 // This allows ValueHandlers and custom metadata to adjust itself.
790 if (!CS.getInstruction()->getType()->isVoidTy())
791 CS.getInstruction()->
792 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
793
794 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
795 // Don't break the CFG, insert a dummy cond branch.
796 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
797 ConstantInt::getTrue(Callee->getContext()), II);
798 }
799 return EraseInstFromFunction(*CS.getInstruction());
800 }
801
802 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
803 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
804 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
805 return transformCallThroughTrampoline(CS);
806
807 const PointerType *PTy = cast<PointerType>(Callee->getType());
808 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
809 if (FTy->isVarArg()) {
810 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
811 // See if we can optimize any arguments passed through the varargs area of
812 // the call.
813 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
814 E = CS.arg_end(); I != E; ++I, ++ix) {
815 CastInst *CI = dyn_cast<CastInst>(*I);
816 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
817 *I = CI->getOperand(0);
818 Changed = true;
819 }
820 }
821 }
822
823 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
824 // Inline asm calls cannot throw - mark them 'nounwind'.
825 CS.setDoesNotThrow();
826 Changed = true;
827 }
828
829 return Changed ? CS.getInstruction() : 0;
830}
831
832// transformConstExprCastCall - If the callee is a constexpr cast of a function,
833// attempt to move the cast to the arguments of the call/invoke.
834//
835bool InstCombiner::transformConstExprCastCall(CallSite CS) {
836 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
837 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000838 if (CE->getOpcode() != Instruction::BitCast ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000839 !isa<Function>(CE->getOperand(0)))
840 return false;
841 Function *Callee = cast<Function>(CE->getOperand(0));
842 Instruction *Caller = CS.getInstruction();
843 const AttrListPtr &CallerPAL = CS.getAttributes();
844
845 // Okay, this is a cast from a function to a different type. Unless doing so
846 // would cause a type conversion of one of our arguments, change this call to
847 // be a direct call with arguments casted to the appropriate types.
848 //
849 const FunctionType *FT = Callee->getFunctionType();
850 const Type *OldRetTy = Caller->getType();
851 const Type *NewRetTy = FT->getReturnType();
852
Duncan Sands1df98592010-02-16 11:11:14 +0000853 if (NewRetTy->isStructTy())
Chris Lattner753a2b42010-01-05 07:32:13 +0000854 return false; // TODO: Handle multiple return values.
855
856 // Check to see if we are changing the return type...
857 if (OldRetTy != NewRetTy) {
858 if (Callee->isDeclaration() &&
859 // Conversion is ok if changing from one pointer type to another or from
860 // a pointer to an integer of the same size.
Duncan Sands1df98592010-02-16 11:11:14 +0000861 !((OldRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000862 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +0000863 (NewRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000864 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
865 return false; // Cannot transform this return value.
866
867 if (!Caller->use_empty() &&
868 // void -> non-void is handled specially
869 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
870 return false; // Cannot transform this return value.
871
872 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
873 Attributes RAttrs = CallerPAL.getRetAttributes();
874 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
875 return false; // Attribute not compatible with transformed value.
876 }
877
878 // If the callsite is an invoke instruction, and the return value is used by
879 // a PHI node in a successor, we cannot change the return type of the call
880 // because there is no place to put the cast instruction (without breaking
881 // the critical edge). Bail out in this case.
882 if (!Caller->use_empty())
883 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
884 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
885 UI != E; ++UI)
886 if (PHINode *PN = dyn_cast<PHINode>(*UI))
887 if (PN->getParent() == II->getNormalDest() ||
888 PN->getParent() == II->getUnwindDest())
889 return false;
890 }
891
892 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
893 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
894
895 CallSite::arg_iterator AI = CS.arg_begin();
896 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
897 const Type *ParamTy = FT->getParamType(i);
898 const Type *ActTy = (*AI)->getType();
899
900 if (!CastInst::isCastable(ActTy, ParamTy))
901 return false; // Cannot transform this parameter value.
902
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000903 if (CallerPAL.getParamAttributes(i + 1)
Chris Lattner753a2b42010-01-05 07:32:13 +0000904 & Attribute::typeIncompatible(ParamTy))
905 return false; // Attribute not compatible with transformed value.
906
907 // Converting from one pointer type to another or between a pointer and an
908 // integer of the same size is safe even if we do not have a body.
909 bool isConvertible = ActTy == ParamTy ||
Duncan Sands1df98592010-02-16 11:11:14 +0000910 (TD && ((ParamTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000911 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +0000912 (ActTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000913 ActTy == TD->getIntPtrType(Caller->getContext()))));
914 if (Callee->isDeclaration() && !isConvertible) return false;
915 }
916
917 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
918 Callee->isDeclaration())
919 return false; // Do not delete arguments unless we have a function body.
920
921 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
922 !CallerPAL.isEmpty())
923 // In this case we have more arguments than the new function type, but we
924 // won't be dropping them. Check that these extra arguments have attributes
925 // that are compatible with being a vararg call argument.
926 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
927 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
928 break;
929 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
930 if (PAttrs & Attribute::VarArgsIncompatible)
931 return false;
932 }
933
934 // Okay, we decided that this is a safe thing to do: go ahead and start
935 // inserting cast instructions as necessary...
936 std::vector<Value*> Args;
937 Args.reserve(NumActualArgs);
938 SmallVector<AttributeWithIndex, 8> attrVec;
939 attrVec.reserve(NumCommonArgs);
940
941 // Get any return attributes.
942 Attributes RAttrs = CallerPAL.getRetAttributes();
943
944 // If the return value is not being used, the type may not be compatible
945 // with the existing attributes. Wipe out any problematic attributes.
946 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
947
948 // Add the new return attributes.
949 if (RAttrs)
950 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
951
952 AI = CS.arg_begin();
953 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
954 const Type *ParamTy = FT->getParamType(i);
955 if ((*AI)->getType() == ParamTy) {
956 Args.push_back(*AI);
957 } else {
958 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
959 false, ParamTy, false);
960 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
961 }
962
963 // Add any parameter attributes.
964 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
965 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
966 }
967
968 // If the function takes more arguments than the call was taking, add them
969 // now.
970 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
971 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
972
973 // If we are removing arguments to the function, emit an obnoxious warning.
974 if (FT->getNumParams() < NumActualArgs) {
975 if (!FT->isVarArg()) {
976 errs() << "WARNING: While resolving call to function '"
977 << Callee->getName() << "' arguments were dropped!\n";
978 } else {
979 // Add all of the arguments in their promoted form to the arg list.
980 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
981 const Type *PTy = getPromotedType((*AI)->getType());
982 if (PTy != (*AI)->getType()) {
983 // Must promote to pass through va_arg area!
984 Instruction::CastOps opcode =
985 CastInst::getCastOpcode(*AI, false, PTy, false);
986 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
987 } else {
988 Args.push_back(*AI);
989 }
990
991 // Add any parameter attributes.
992 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
993 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
994 }
995 }
996 }
997
998 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
999 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
1000
1001 if (NewRetTy->isVoidTy())
1002 Caller->setName(""); // Void type should not have a name.
1003
1004 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
1005 attrVec.end());
1006
1007 Instruction *NC;
1008 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1009 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
1010 Args.begin(), Args.end(),
1011 Caller->getName(), Caller);
1012 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1013 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1014 } else {
1015 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
1016 Caller->getName(), Caller);
1017 CallInst *CI = cast<CallInst>(Caller);
1018 if (CI->isTailCall())
1019 cast<CallInst>(NC)->setTailCall();
1020 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1021 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1022 }
1023
1024 // Insert a cast of the return type as necessary.
1025 Value *NV = NC;
1026 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1027 if (!NV->getType()->isVoidTy()) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001028 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Chris Lattner753a2b42010-01-05 07:32:13 +00001029 OldRetTy, false);
1030 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
1031
1032 // If this is an invoke instruction, we should insert it after the first
1033 // non-phi, instruction in the normal successor block.
1034 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1035 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
1036 InsertNewInstBefore(NC, *I);
1037 } else {
1038 // Otherwise, it's a call, just insert cast right after the call instr
1039 InsertNewInstBefore(NC, *Caller);
1040 }
1041 Worklist.AddUsersToWorkList(*Caller);
1042 } else {
1043 NV = UndefValue::get(Caller->getType());
1044 }
1045 }
1046
1047
1048 if (!Caller->use_empty())
1049 Caller->replaceAllUsesWith(NV);
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001050
Chris Lattner753a2b42010-01-05 07:32:13 +00001051 EraseInstFromFunction(*Caller);
1052 return true;
1053}
1054
1055// transformCallThroughTrampoline - Turn a call to a function created by the
1056// init_trampoline intrinsic into a direct call to the underlying function.
1057//
1058Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
1059 Value *Callee = CS.getCalledValue();
1060 const PointerType *PTy = cast<PointerType>(Callee->getType());
1061 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1062 const AttrListPtr &Attrs = CS.getAttributes();
1063
1064 // If the call already has the 'nest' attribute somewhere then give up -
1065 // otherwise 'nest' would occur twice after splicing in the chain.
1066 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1067 return 0;
1068
1069 IntrinsicInst *Tramp =
1070 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
1071
1072 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
1073 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1074 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1075
1076 const AttrListPtr &NestAttrs = NestF->getAttributes();
1077 if (!NestAttrs.isEmpty()) {
1078 unsigned NestIdx = 1;
1079 const Type *NestTy = 0;
1080 Attributes NestAttr = Attribute::None;
1081
1082 // Look for a parameter marked with the 'nest' attribute.
1083 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1084 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1085 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1086 // Record the parameter type and any other attributes.
1087 NestTy = *I;
1088 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1089 break;
1090 }
1091
1092 if (NestTy) {
1093 Instruction *Caller = CS.getInstruction();
1094 std::vector<Value*> NewArgs;
1095 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1096
1097 SmallVector<AttributeWithIndex, 8> NewAttrs;
1098 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1099
1100 // Insert the nest argument into the call argument list, which may
1101 // mean appending it. Likewise for attributes.
1102
1103 // Add any result attributes.
1104 if (Attributes Attr = Attrs.getRetAttributes())
1105 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1106
1107 {
1108 unsigned Idx = 1;
1109 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1110 do {
1111 if (Idx == NestIdx) {
1112 // Add the chain argument and attributes.
1113 Value *NestVal = Tramp->getOperand(3);
1114 if (NestVal->getType() != NestTy)
1115 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
1116 NewArgs.push_back(NestVal);
1117 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1118 }
1119
1120 if (I == E)
1121 break;
1122
1123 // Add the original argument and attributes.
1124 NewArgs.push_back(*I);
1125 if (Attributes Attr = Attrs.getParamAttributes(Idx))
1126 NewAttrs.push_back
1127 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1128
1129 ++Idx, ++I;
1130 } while (1);
1131 }
1132
1133 // Add any function attributes.
1134 if (Attributes Attr = Attrs.getFnAttributes())
1135 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1136
1137 // The trampoline may have been bitcast to a bogus type (FTy).
1138 // Handle this by synthesizing a new function type, equal to FTy
1139 // with the chain parameter inserted.
1140
1141 std::vector<const Type*> NewTypes;
1142 NewTypes.reserve(FTy->getNumParams()+1);
1143
1144 // Insert the chain's type into the list of parameter types, which may
1145 // mean appending it.
1146 {
1147 unsigned Idx = 1;
1148 FunctionType::param_iterator I = FTy->param_begin(),
1149 E = FTy->param_end();
1150
1151 do {
1152 if (Idx == NestIdx)
1153 // Add the chain's type.
1154 NewTypes.push_back(NestTy);
1155
1156 if (I == E)
1157 break;
1158
1159 // Add the original type.
1160 NewTypes.push_back(*I);
1161
1162 ++Idx, ++I;
1163 } while (1);
1164 }
1165
1166 // Replace the trampoline call with a direct call. Let the generic
1167 // code sort out any function type mismatches.
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001168 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner753a2b42010-01-05 07:32:13 +00001169 FTy->isVarArg());
1170 Constant *NewCallee =
1171 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001172 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner753a2b42010-01-05 07:32:13 +00001173 PointerType::getUnqual(NewFTy));
1174 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1175 NewAttrs.end());
1176
1177 Instruction *NewCaller;
1178 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1179 NewCaller = InvokeInst::Create(NewCallee,
1180 II->getNormalDest(), II->getUnwindDest(),
1181 NewArgs.begin(), NewArgs.end(),
1182 Caller->getName(), Caller);
1183 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1184 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1185 } else {
1186 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
1187 Caller->getName(), Caller);
1188 if (cast<CallInst>(Caller)->isTailCall())
1189 cast<CallInst>(NewCaller)->setTailCall();
1190 cast<CallInst>(NewCaller)->
1191 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1192 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1193 }
1194 if (!Caller->getType()->isVoidTy())
1195 Caller->replaceAllUsesWith(NewCaller);
1196 Caller->eraseFromParent();
1197 Worklist.Remove(Caller);
1198 return 0;
1199 }
1200 }
1201
1202 // Replace the trampoline call with a direct call. Since there is no 'nest'
1203 // parameter, there is no need to adjust the argument list. Let the generic
1204 // code sort out any function type mismatches.
1205 Constant *NewCallee =
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001206 NestF->getType() == PTy ? NestF :
Chris Lattner753a2b42010-01-05 07:32:13 +00001207 ConstantExpr::getBitCast(NestF, PTy);
1208 CS.setCalledFunction(NewCallee);
1209 return CS.getInstruction();
1210}
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001211