blob: 43419eb9fc09d0545f22f44b0b3e28b0dfc8149b [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());
Benjamin Kramer8c65f6e2010-01-05 21:05:54 +0000202 if (!LenC || !FillC || !FillC->getType()->isInteger(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: {
307 const Type *ReturnTy = CI.getType();
308 Value *Op1 = II->getOperand(1);
309 bool Min = (cast<ConstantInt>(II->getOperand(2))->getZExtValue() == 1);
310
Eric Christopher26d0e892010-02-11 01:48:54 +0000311 // We need target data for just about everything so depend on it.
Eric Christopher415326b2010-02-09 21:24:27 +0000312 if (!TD) break;
Eric Christopher26d0e892010-02-11 01:48:54 +0000313
314 // Get to the real allocated thing and offset as fast as possible.
Eric Christopher415326b2010-02-09 21:24:27 +0000315 Op1 = Op1->stripPointerCasts();
316
Eric Christopher26d0e892010-02-11 01:48:54 +0000317 // If we've stripped down to a single global variable that we
318 // can know the size of then just return that.
Eric Christopher415326b2010-02-09 21:24:27 +0000319 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
320 if (GV->hasDefinitiveInitializer()) {
321 Constant *C = GV->getInitializer();
322 size_t globalSize = TD->getTypeAllocSize(C->getType());
323 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, globalSize));
324 } else {
325 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
326 return ReplaceInstUsesWith(CI, RetVal);
327 }
Eric Christopher26d0e892010-02-11 01:48:54 +0000328 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op1)) {
329
330 // Only handle constant GEPs here.
331 if (CE->getOpcode() != Instruction::GetElementPtr) break;
332 GEPOperator *GEP = cast<GEPOperator>(CE);
333
Eric Christopherdfdddd82010-02-11 17:44:04 +0000334 // Make sure we're not a constant offset from an external
335 // global.
336 Value *Operand = GEP->getPointerOperand();
337 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand))
338 if (!GV->hasDefinitiveInitializer()) break;
339
Eric Christopher26d0e892010-02-11 01:48:54 +0000340 // Get what we're pointing to and its size.
341 const PointerType *PT =
Eric Christopherdfdddd82010-02-11 17:44:04 +0000342 cast<PointerType>(Operand->getType());
Eric Christopher26d0e892010-02-11 01:48:54 +0000343 size_t Size = TD->getTypeAllocSize(PT->getElementType());
344
345 // Get the current byte offset into the thing.
346 SmallVector<Value*, 8> Ops(CE->op_begin()+1, CE->op_end());
347 size_t Offset = TD->getIndexedOffset(PT, &Ops[0], Ops.size());
348
349 assert(Size >= Offset);
350
351 Constant *RetVal = ConstantInt::get(ReturnTy, Size-Offset);
352 return ReplaceInstUsesWith(CI, RetVal);
353
Eric Christopherdfdddd82010-02-11 17:44:04 +0000354 }
Eric Christopher415326b2010-02-09 21:24:27 +0000355 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000356 case Intrinsic::bswap:
357 // bswap(bswap(x)) -> x
358 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
359 if (Operand->getIntrinsicID() == Intrinsic::bswap)
360 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000361
Chris Lattner753a2b42010-01-05 07:32:13 +0000362 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
363 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
364 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
365 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
366 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
367 TI->getType()->getPrimitiveSizeInBits();
368 Value *CV = ConstantInt::get(Operand->getType(), C);
369 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
370 return new TruncInst(V, TI->getType());
371 }
372 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000373
Chris Lattner753a2b42010-01-05 07:32:13 +0000374 break;
375 case Intrinsic::powi:
376 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
377 // powi(x, 0) -> 1.0
378 if (Power->isZero())
379 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
380 // powi(x, 1) -> x
381 if (Power->isOne())
382 return ReplaceInstUsesWith(CI, II->getOperand(1));
383 // powi(x, -1) -> 1/x
384 if (Power->isAllOnesValue())
385 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
386 II->getOperand(1));
387 }
388 break;
389 case Intrinsic::cttz: {
390 // If all bits below the first known one are known zero,
391 // this value is constant.
392 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
393 uint32_t BitWidth = IT->getBitWidth();
394 APInt KnownZero(BitWidth, 0);
395 APInt KnownOne(BitWidth, 0);
396 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
397 KnownZero, KnownOne);
398 unsigned TrailingZeros = KnownOne.countTrailingZeros();
399 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
400 if ((Mask & KnownZero) == Mask)
401 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
402 APInt(BitWidth, TrailingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000403
Chris Lattner753a2b42010-01-05 07:32:13 +0000404 }
405 break;
406 case Intrinsic::ctlz: {
407 // If all bits above the first known one are known zero,
408 // this value is constant.
409 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
410 uint32_t BitWidth = IT->getBitWidth();
411 APInt KnownZero(BitWidth, 0);
412 APInt KnownOne(BitWidth, 0);
413 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
414 KnownZero, KnownOne);
415 unsigned LeadingZeros = KnownOne.countLeadingZeros();
416 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
417 if ((Mask & KnownZero) == Mask)
418 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
419 APInt(BitWidth, LeadingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000420
Chris Lattner753a2b42010-01-05 07:32:13 +0000421 }
422 break;
423 case Intrinsic::uadd_with_overflow: {
424 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
425 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
426 uint32_t BitWidth = IT->getBitWidth();
427 APInt Mask = APInt::getSignBit(BitWidth);
428 APInt LHSKnownZero(BitWidth, 0);
429 APInt LHSKnownOne(BitWidth, 0);
430 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
431 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
432 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
433
434 if (LHSKnownNegative || LHSKnownPositive) {
435 APInt RHSKnownZero(BitWidth, 0);
436 APInt RHSKnownOne(BitWidth, 0);
437 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
438 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
439 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
440 if (LHSKnownNegative && RHSKnownNegative) {
441 // The sign bit is set in both cases: this MUST overflow.
442 // Create a simple add instruction, and insert it into the struct.
443 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
444 Worklist.Add(Add);
445 Constant *V[] = {
446 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
447 };
448 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
449 return InsertValueInst::Create(Struct, Add, 0);
450 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000451
Chris Lattner753a2b42010-01-05 07:32:13 +0000452 if (LHSKnownPositive && RHSKnownPositive) {
453 // The sign bit is clear in both cases: this CANNOT overflow.
454 // Create a simple add instruction, and insert it into the struct.
455 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
456 Worklist.Add(Add);
457 Constant *V[] = {
458 UndefValue::get(LHS->getType()),
459 ConstantInt::getFalse(II->getContext())
460 };
461 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
462 return InsertValueInst::Create(Struct, Add, 0);
463 }
464 }
465 }
466 // FALL THROUGH uadd into sadd
467 case Intrinsic::sadd_with_overflow:
468 // Canonicalize constants into the RHS.
469 if (isa<Constant>(II->getOperand(1)) &&
470 !isa<Constant>(II->getOperand(2))) {
471 Value *LHS = II->getOperand(1);
472 II->setOperand(1, II->getOperand(2));
473 II->setOperand(2, LHS);
474 return II;
475 }
476
477 // X + undef -> undef
478 if (isa<UndefValue>(II->getOperand(2)))
479 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000480
Chris Lattner753a2b42010-01-05 07:32:13 +0000481 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
482 // X + 0 -> {X, false}
483 if (RHS->isZero()) {
484 Constant *V[] = {
485 UndefValue::get(II->getOperand(0)->getType()),
486 ConstantInt::getFalse(II->getContext())
487 };
488 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
489 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
490 }
491 }
492 break;
493 case Intrinsic::usub_with_overflow:
494 case Intrinsic::ssub_with_overflow:
495 // undef - X -> undef
496 // X - undef -> undef
497 if (isa<UndefValue>(II->getOperand(1)) ||
498 isa<UndefValue>(II->getOperand(2)))
499 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000500
Chris Lattner753a2b42010-01-05 07:32:13 +0000501 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
502 // X - 0 -> {X, false}
503 if (RHS->isZero()) {
504 Constant *V[] = {
505 UndefValue::get(II->getOperand(1)->getType()),
506 ConstantInt::getFalse(II->getContext())
507 };
508 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
509 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
510 }
511 }
512 break;
513 case Intrinsic::umul_with_overflow:
514 case Intrinsic::smul_with_overflow:
515 // Canonicalize constants into the RHS.
516 if (isa<Constant>(II->getOperand(1)) &&
517 !isa<Constant>(II->getOperand(2))) {
518 Value *LHS = II->getOperand(1);
519 II->setOperand(1, II->getOperand(2));
520 II->setOperand(2, LHS);
521 return II;
522 }
523
524 // X * undef -> undef
525 if (isa<UndefValue>(II->getOperand(2)))
526 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000527
Chris Lattner753a2b42010-01-05 07:32:13 +0000528 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
529 // X*0 -> {0, false}
530 if (RHSI->isZero())
531 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000532
Chris Lattner753a2b42010-01-05 07:32:13 +0000533 // X * 1 -> {X, false}
534 if (RHSI->equalsInt(1)) {
535 Constant *V[] = {
536 UndefValue::get(II->getOperand(1)->getType()),
537 ConstantInt::getFalse(II->getContext())
538 };
539 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
540 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
541 }
542 }
543 break;
544 case Intrinsic::ppc_altivec_lvx:
545 case Intrinsic::ppc_altivec_lvxl:
546 case Intrinsic::x86_sse_loadu_ps:
547 case Intrinsic::x86_sse2_loadu_pd:
548 case Intrinsic::x86_sse2_loadu_dq:
549 // Turn PPC lvx -> load if the pointer is known aligned.
550 // Turn X86 loadups -> load if the pointer is known aligned.
551 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
552 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
553 PointerType::getUnqual(II->getType()));
554 return new LoadInst(Ptr);
555 }
556 break;
557 case Intrinsic::ppc_altivec_stvx:
558 case Intrinsic::ppc_altivec_stvxl:
559 // Turn stvx -> store if the pointer is known aligned.
560 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000561 const Type *OpPtrTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000562 PointerType::getUnqual(II->getOperand(1)->getType());
563 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
564 return new StoreInst(II->getOperand(1), Ptr);
565 }
566 break;
567 case Intrinsic::x86_sse_storeu_ps:
568 case Intrinsic::x86_sse2_storeu_pd:
569 case Intrinsic::x86_sse2_storeu_dq:
570 // Turn X86 storeu -> store if the pointer is known aligned.
571 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000572 const Type *OpPtrTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000573 PointerType::getUnqual(II->getOperand(2)->getType());
574 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
575 return new StoreInst(II->getOperand(2), Ptr);
576 }
577 break;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000578
Chris Lattner753a2b42010-01-05 07:32:13 +0000579 case Intrinsic::x86_sse_cvttss2si: {
580 // These intrinsics only demands the 0th element of its input vector. If
581 // we can simplify the input based on that, do so now.
582 unsigned VWidth =
583 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
584 APInt DemandedElts(VWidth, 1);
585 APInt UndefElts(VWidth, 0);
586 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
587 UndefElts)) {
588 II->setOperand(1, V);
589 return II;
590 }
591 break;
592 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000593
Chris Lattner753a2b42010-01-05 07:32:13 +0000594 case Intrinsic::ppc_altivec_vperm:
595 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
596 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
597 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000598
Chris Lattner753a2b42010-01-05 07:32:13 +0000599 // Check that all of the elements are integer constants or undefs.
600 bool AllEltsOk = true;
601 for (unsigned i = 0; i != 16; ++i) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000602 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
Chris Lattner753a2b42010-01-05 07:32:13 +0000603 !isa<UndefValue>(Mask->getOperand(i))) {
604 AllEltsOk = false;
605 break;
606 }
607 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000608
Chris Lattner753a2b42010-01-05 07:32:13 +0000609 if (AllEltsOk) {
610 // Cast the input vectors to byte vectors.
611 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
612 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
613 Value *Result = UndefValue::get(Op0->getType());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000614
Chris Lattner753a2b42010-01-05 07:32:13 +0000615 // Only extract each element once.
616 Value *ExtractedElts[32];
617 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000618
Chris Lattner753a2b42010-01-05 07:32:13 +0000619 for (unsigned i = 0; i != 16; ++i) {
620 if (isa<UndefValue>(Mask->getOperand(i)))
621 continue;
622 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
623 Idx &= 31; // Match the hardware behavior.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000624
Chris Lattner753a2b42010-01-05 07:32:13 +0000625 if (ExtractedElts[Idx] == 0) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000626 ExtractedElts[Idx] =
627 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner753a2b42010-01-05 07:32:13 +0000628 ConstantInt::get(Type::getInt32Ty(II->getContext()),
629 Idx&15, false), "tmp");
630 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000631
Chris Lattner753a2b42010-01-05 07:32:13 +0000632 // Insert this value into the result vector.
633 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
634 ConstantInt::get(Type::getInt32Ty(II->getContext()),
635 i, false), "tmp");
636 }
637 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
638 }
639 }
640 break;
641
642 case Intrinsic::stackrestore: {
643 // If the save is right next to the restore, remove the restore. This can
644 // happen when variable allocas are DCE'd.
645 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
646 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
647 BasicBlock::iterator BI = SS;
648 if (&*++BI == II)
649 return EraseInstFromFunction(CI);
650 }
651 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000652
Chris Lattner753a2b42010-01-05 07:32:13 +0000653 // Scan down this block to see if there is another stack restore in the
654 // same block without an intervening call/alloca.
655 BasicBlock::iterator BI = II;
656 TerminatorInst *TI = II->getParent()->getTerminator();
657 bool CannotRemove = false;
658 for (++BI; &*BI != TI; ++BI) {
659 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
660 CannotRemove = true;
661 break;
662 }
663 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
664 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
665 // If there is a stackrestore below this one, remove this one.
666 if (II->getIntrinsicID() == Intrinsic::stackrestore)
667 return EraseInstFromFunction(CI);
668 // Otherwise, ignore the intrinsic.
669 } else {
670 // If we found a non-intrinsic call, we can't remove the stack
671 // restore.
672 CannotRemove = true;
673 break;
674 }
675 }
676 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000677
Chris Lattner753a2b42010-01-05 07:32:13 +0000678 // If the stack restore is in a return/unwind block and if there are no
679 // allocas or calls between the restore and the return, nuke the restore.
680 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
681 return EraseInstFromFunction(CI);
682 break;
683 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000684 }
685
686 return visitCallSite(II);
687}
688
689// InvokeInst simplification
690//
691Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
692 return visitCallSite(&II);
693}
694
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000695/// isSafeToEliminateVarargsCast - If this cast does not affect the value
Chris Lattner753a2b42010-01-05 07:32:13 +0000696/// passed through the varargs area, we can eliminate the use of the cast.
697static bool isSafeToEliminateVarargsCast(const CallSite CS,
698 const CastInst * const CI,
699 const TargetData * const TD,
700 const int ix) {
701 if (!CI->isLosslessCast())
702 return false;
703
704 // The size of ByVal arguments is derived from the type, so we
705 // can't change to a type with a different size. If the size were
706 // passed explicitly we could avoid this check.
707 if (!CS.paramHasAttr(ix, Attribute::ByVal))
708 return true;
709
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000710 const Type* SrcTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000711 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
712 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
713 if (!SrcTy->isSized() || !DstTy->isSized())
714 return false;
715 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
716 return false;
717 return true;
718}
719
720// visitCallSite - Improvements for call and invoke instructions.
721//
722Instruction *InstCombiner::visitCallSite(CallSite CS) {
723 bool Changed = false;
724
725 // If the callee is a constexpr cast of a function, attempt to move the cast
726 // to the arguments of the call/invoke.
727 if (transformConstExprCastCall(CS)) return 0;
728
729 Value *Callee = CS.getCalledValue();
730
731 if (Function *CalleeF = dyn_cast<Function>(Callee))
Chris Lattnerd5695612010-02-01 18:11:34 +0000732 // If the call and callee calling conventions don't match, this call must
733 // be unreachable, as the call is undefined.
734 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
735 // Only do this for calls to a function with a body. A prototype may
736 // not actually end up matching the implementation's calling conv for a
737 // variety of reasons (e.g. it may be written in assembly).
738 !CalleeF->isDeclaration()) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000739 Instruction *OldCall = CS.getInstruction();
Chris Lattner753a2b42010-01-05 07:32:13 +0000740 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000741 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner753a2b42010-01-05 07:32:13 +0000742 OldCall);
743 // If OldCall dues not return void then replaceAllUsesWith undef.
744 // This allows ValueHandlers and custom metadata to adjust itself.
745 if (!OldCall->getType()->isVoidTy())
746 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner830f3f22010-02-01 18:04:58 +0000747 if (isa<CallInst>(OldCall))
Chris Lattner753a2b42010-01-05 07:32:13 +0000748 return EraseInstFromFunction(*OldCall);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000749
Chris Lattner830f3f22010-02-01 18:04:58 +0000750 // We cannot remove an invoke, because it would change the CFG, just
751 // change the callee to a null pointer.
752 cast<InvokeInst>(OldCall)->setOperand(0,
753 Constant::getNullValue(CalleeF->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000754 return 0;
755 }
756
757 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
758 // This instruction is not reachable, just remove it. We insert a store to
759 // undef so that we know that this code is not reachable, despite the fact
760 // that we can't modify the CFG here.
761 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
762 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
763 CS.getInstruction());
764
765 // If CS dues not return void then replaceAllUsesWith undef.
766 // This allows ValueHandlers and custom metadata to adjust itself.
767 if (!CS.getInstruction()->getType()->isVoidTy())
768 CS.getInstruction()->
769 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
770
771 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
772 // Don't break the CFG, insert a dummy cond branch.
773 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
774 ConstantInt::getTrue(Callee->getContext()), II);
775 }
776 return EraseInstFromFunction(*CS.getInstruction());
777 }
778
779 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
780 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
781 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
782 return transformCallThroughTrampoline(CS);
783
784 const PointerType *PTy = cast<PointerType>(Callee->getType());
785 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
786 if (FTy->isVarArg()) {
787 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
788 // See if we can optimize any arguments passed through the varargs area of
789 // the call.
790 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
791 E = CS.arg_end(); I != E; ++I, ++ix) {
792 CastInst *CI = dyn_cast<CastInst>(*I);
793 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
794 *I = CI->getOperand(0);
795 Changed = true;
796 }
797 }
798 }
799
800 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
801 // Inline asm calls cannot throw - mark them 'nounwind'.
802 CS.setDoesNotThrow();
803 Changed = true;
804 }
805
806 return Changed ? CS.getInstruction() : 0;
807}
808
809// transformConstExprCastCall - If the callee is a constexpr cast of a function,
810// attempt to move the cast to the arguments of the call/invoke.
811//
812bool InstCombiner::transformConstExprCastCall(CallSite CS) {
813 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
814 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000815 if (CE->getOpcode() != Instruction::BitCast ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000816 !isa<Function>(CE->getOperand(0)))
817 return false;
818 Function *Callee = cast<Function>(CE->getOperand(0));
819 Instruction *Caller = CS.getInstruction();
820 const AttrListPtr &CallerPAL = CS.getAttributes();
821
822 // Okay, this is a cast from a function to a different type. Unless doing so
823 // would cause a type conversion of one of our arguments, change this call to
824 // be a direct call with arguments casted to the appropriate types.
825 //
826 const FunctionType *FT = Callee->getFunctionType();
827 const Type *OldRetTy = Caller->getType();
828 const Type *NewRetTy = FT->getReturnType();
829
830 if (isa<StructType>(NewRetTy))
831 return false; // TODO: Handle multiple return values.
832
833 // Check to see if we are changing the return type...
834 if (OldRetTy != NewRetTy) {
835 if (Callee->isDeclaration() &&
836 // Conversion is ok if changing from one pointer type to another or from
837 // a pointer to an integer of the same size.
838 !((isa<PointerType>(OldRetTy) || !TD ||
839 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
840 (isa<PointerType>(NewRetTy) || !TD ||
841 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
842 return false; // Cannot transform this return value.
843
844 if (!Caller->use_empty() &&
845 // void -> non-void is handled specially
846 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
847 return false; // Cannot transform this return value.
848
849 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
850 Attributes RAttrs = CallerPAL.getRetAttributes();
851 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
852 return false; // Attribute not compatible with transformed value.
853 }
854
855 // If the callsite is an invoke instruction, and the return value is used by
856 // a PHI node in a successor, we cannot change the return type of the call
857 // because there is no place to put the cast instruction (without breaking
858 // the critical edge). Bail out in this case.
859 if (!Caller->use_empty())
860 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
861 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
862 UI != E; ++UI)
863 if (PHINode *PN = dyn_cast<PHINode>(*UI))
864 if (PN->getParent() == II->getNormalDest() ||
865 PN->getParent() == II->getUnwindDest())
866 return false;
867 }
868
869 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
870 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
871
872 CallSite::arg_iterator AI = CS.arg_begin();
873 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
874 const Type *ParamTy = FT->getParamType(i);
875 const Type *ActTy = (*AI)->getType();
876
877 if (!CastInst::isCastable(ActTy, ParamTy))
878 return false; // Cannot transform this parameter value.
879
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000880 if (CallerPAL.getParamAttributes(i + 1)
Chris Lattner753a2b42010-01-05 07:32:13 +0000881 & Attribute::typeIncompatible(ParamTy))
882 return false; // Attribute not compatible with transformed value.
883
884 // Converting from one pointer type to another or between a pointer and an
885 // integer of the same size is safe even if we do not have a body.
886 bool isConvertible = ActTy == ParamTy ||
887 (TD && ((isa<PointerType>(ParamTy) ||
888 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
889 (isa<PointerType>(ActTy) ||
890 ActTy == TD->getIntPtrType(Caller->getContext()))));
891 if (Callee->isDeclaration() && !isConvertible) return false;
892 }
893
894 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
895 Callee->isDeclaration())
896 return false; // Do not delete arguments unless we have a function body.
897
898 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
899 !CallerPAL.isEmpty())
900 // In this case we have more arguments than the new function type, but we
901 // won't be dropping them. Check that these extra arguments have attributes
902 // that are compatible with being a vararg call argument.
903 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
904 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
905 break;
906 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
907 if (PAttrs & Attribute::VarArgsIncompatible)
908 return false;
909 }
910
911 // Okay, we decided that this is a safe thing to do: go ahead and start
912 // inserting cast instructions as necessary...
913 std::vector<Value*> Args;
914 Args.reserve(NumActualArgs);
915 SmallVector<AttributeWithIndex, 8> attrVec;
916 attrVec.reserve(NumCommonArgs);
917
918 // Get any return attributes.
919 Attributes RAttrs = CallerPAL.getRetAttributes();
920
921 // If the return value is not being used, the type may not be compatible
922 // with the existing attributes. Wipe out any problematic attributes.
923 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
924
925 // Add the new return attributes.
926 if (RAttrs)
927 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
928
929 AI = CS.arg_begin();
930 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
931 const Type *ParamTy = FT->getParamType(i);
932 if ((*AI)->getType() == ParamTy) {
933 Args.push_back(*AI);
934 } else {
935 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
936 false, ParamTy, false);
937 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
938 }
939
940 // Add any parameter attributes.
941 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
942 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
943 }
944
945 // If the function takes more arguments than the call was taking, add them
946 // now.
947 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
948 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
949
950 // If we are removing arguments to the function, emit an obnoxious warning.
951 if (FT->getNumParams() < NumActualArgs) {
952 if (!FT->isVarArg()) {
953 errs() << "WARNING: While resolving call to function '"
954 << Callee->getName() << "' arguments were dropped!\n";
955 } else {
956 // Add all of the arguments in their promoted form to the arg list.
957 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
958 const Type *PTy = getPromotedType((*AI)->getType());
959 if (PTy != (*AI)->getType()) {
960 // Must promote to pass through va_arg area!
961 Instruction::CastOps opcode =
962 CastInst::getCastOpcode(*AI, false, PTy, false);
963 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
964 } else {
965 Args.push_back(*AI);
966 }
967
968 // Add any parameter attributes.
969 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
970 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
971 }
972 }
973 }
974
975 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
976 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
977
978 if (NewRetTy->isVoidTy())
979 Caller->setName(""); // Void type should not have a name.
980
981 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
982 attrVec.end());
983
984 Instruction *NC;
985 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
986 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
987 Args.begin(), Args.end(),
988 Caller->getName(), Caller);
989 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
990 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
991 } else {
992 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
993 Caller->getName(), Caller);
994 CallInst *CI = cast<CallInst>(Caller);
995 if (CI->isTailCall())
996 cast<CallInst>(NC)->setTailCall();
997 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
998 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
999 }
1000
1001 // Insert a cast of the return type as necessary.
1002 Value *NV = NC;
1003 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1004 if (!NV->getType()->isVoidTy()) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001005 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Chris Lattner753a2b42010-01-05 07:32:13 +00001006 OldRetTy, false);
1007 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
1008
1009 // If this is an invoke instruction, we should insert it after the first
1010 // non-phi, instruction in the normal successor block.
1011 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1012 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
1013 InsertNewInstBefore(NC, *I);
1014 } else {
1015 // Otherwise, it's a call, just insert cast right after the call instr
1016 InsertNewInstBefore(NC, *Caller);
1017 }
1018 Worklist.AddUsersToWorkList(*Caller);
1019 } else {
1020 NV = UndefValue::get(Caller->getType());
1021 }
1022 }
1023
1024
1025 if (!Caller->use_empty())
1026 Caller->replaceAllUsesWith(NV);
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001027
Chris Lattner753a2b42010-01-05 07:32:13 +00001028 EraseInstFromFunction(*Caller);
1029 return true;
1030}
1031
1032// transformCallThroughTrampoline - Turn a call to a function created by the
1033// init_trampoline intrinsic into a direct call to the underlying function.
1034//
1035Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
1036 Value *Callee = CS.getCalledValue();
1037 const PointerType *PTy = cast<PointerType>(Callee->getType());
1038 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1039 const AttrListPtr &Attrs = CS.getAttributes();
1040
1041 // If the call already has the 'nest' attribute somewhere then give up -
1042 // otherwise 'nest' would occur twice after splicing in the chain.
1043 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1044 return 0;
1045
1046 IntrinsicInst *Tramp =
1047 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
1048
1049 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
1050 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1051 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1052
1053 const AttrListPtr &NestAttrs = NestF->getAttributes();
1054 if (!NestAttrs.isEmpty()) {
1055 unsigned NestIdx = 1;
1056 const Type *NestTy = 0;
1057 Attributes NestAttr = Attribute::None;
1058
1059 // Look for a parameter marked with the 'nest' attribute.
1060 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1061 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1062 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1063 // Record the parameter type and any other attributes.
1064 NestTy = *I;
1065 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1066 break;
1067 }
1068
1069 if (NestTy) {
1070 Instruction *Caller = CS.getInstruction();
1071 std::vector<Value*> NewArgs;
1072 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1073
1074 SmallVector<AttributeWithIndex, 8> NewAttrs;
1075 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1076
1077 // Insert the nest argument into the call argument list, which may
1078 // mean appending it. Likewise for attributes.
1079
1080 // Add any result attributes.
1081 if (Attributes Attr = Attrs.getRetAttributes())
1082 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1083
1084 {
1085 unsigned Idx = 1;
1086 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1087 do {
1088 if (Idx == NestIdx) {
1089 // Add the chain argument and attributes.
1090 Value *NestVal = Tramp->getOperand(3);
1091 if (NestVal->getType() != NestTy)
1092 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
1093 NewArgs.push_back(NestVal);
1094 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1095 }
1096
1097 if (I == E)
1098 break;
1099
1100 // Add the original argument and attributes.
1101 NewArgs.push_back(*I);
1102 if (Attributes Attr = Attrs.getParamAttributes(Idx))
1103 NewAttrs.push_back
1104 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1105
1106 ++Idx, ++I;
1107 } while (1);
1108 }
1109
1110 // Add any function attributes.
1111 if (Attributes Attr = Attrs.getFnAttributes())
1112 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1113
1114 // The trampoline may have been bitcast to a bogus type (FTy).
1115 // Handle this by synthesizing a new function type, equal to FTy
1116 // with the chain parameter inserted.
1117
1118 std::vector<const Type*> NewTypes;
1119 NewTypes.reserve(FTy->getNumParams()+1);
1120
1121 // Insert the chain's type into the list of parameter types, which may
1122 // mean appending it.
1123 {
1124 unsigned Idx = 1;
1125 FunctionType::param_iterator I = FTy->param_begin(),
1126 E = FTy->param_end();
1127
1128 do {
1129 if (Idx == NestIdx)
1130 // Add the chain's type.
1131 NewTypes.push_back(NestTy);
1132
1133 if (I == E)
1134 break;
1135
1136 // Add the original type.
1137 NewTypes.push_back(*I);
1138
1139 ++Idx, ++I;
1140 } while (1);
1141 }
1142
1143 // Replace the trampoline call with a direct call. Let the generic
1144 // code sort out any function type mismatches.
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001145 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner753a2b42010-01-05 07:32:13 +00001146 FTy->isVarArg());
1147 Constant *NewCallee =
1148 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001149 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner753a2b42010-01-05 07:32:13 +00001150 PointerType::getUnqual(NewFTy));
1151 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1152 NewAttrs.end());
1153
1154 Instruction *NewCaller;
1155 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1156 NewCaller = InvokeInst::Create(NewCallee,
1157 II->getNormalDest(), II->getUnwindDest(),
1158 NewArgs.begin(), NewArgs.end(),
1159 Caller->getName(), Caller);
1160 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1161 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1162 } else {
1163 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
1164 Caller->getName(), Caller);
1165 if (cast<CallInst>(Caller)->isTailCall())
1166 cast<CallInst>(NewCaller)->setTailCall();
1167 cast<CallInst>(NewCaller)->
1168 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1169 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1170 }
1171 if (!Caller->getType()->isVoidTy())
1172 Caller->replaceAllUsesWith(NewCaller);
1173 Caller->eraseFromParent();
1174 Worklist.Remove(Caller);
1175 return 0;
1176 }
1177 }
1178
1179 // Replace the trampoline call with a direct call. Since there is no 'nest'
1180 // parameter, there is no need to adjust the argument list. Let the generic
1181 // code sort out any function type mismatches.
1182 Constant *NewCallee =
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001183 NestF->getType() == PTy ? NestF :
Chris Lattner753a2b42010-01-05 07:32:13 +00001184 ConstantExpr::getBitCast(NestF, PTy);
1185 CS.setCalledFunction(NewCallee);
1186 return CS.getInstruction();
1187}
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001188