LLVM API Documentation
00001 //===- InstCombineCalls.cpp -----------------------------------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the visitCall and visitInvoke functions. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "InstCombine.h" 00015 #include "llvm/ADT/Statistic.h" 00016 #include "llvm/Analysis/MemoryBuiltins.h" 00017 #include "llvm/IR/DataLayout.h" 00018 #include "llvm/Support/CallSite.h" 00019 #include "llvm/Support/PatternMatch.h" 00020 #include "llvm/Transforms/Utils/BuildLibCalls.h" 00021 #include "llvm/Transforms/Utils/Local.h" 00022 using namespace llvm; 00023 using namespace PatternMatch; 00024 00025 STATISTIC(NumSimplified, "Number of library calls simplified"); 00026 00027 /// getPromotedType - Return the specified type promoted as it would be to pass 00028 /// though a va_arg area. 00029 static Type *getPromotedType(Type *Ty) { 00030 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) { 00031 if (ITy->getBitWidth() < 32) 00032 return Type::getInt32Ty(Ty->getContext()); 00033 } 00034 return Ty; 00035 } 00036 00037 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a 00038 /// single scalar element, like {{{type}}} or [1 x type], return type. 00039 static Type *reduceToSingleValueType(Type *T) { 00040 while (!T->isSingleValueType()) { 00041 if (StructType *STy = dyn_cast<StructType>(T)) { 00042 if (STy->getNumElements() == 1) 00043 T = STy->getElementType(0); 00044 else 00045 break; 00046 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) { 00047 if (ATy->getNumElements() == 1) 00048 T = ATy->getElementType(); 00049 else 00050 break; 00051 } else 00052 break; 00053 } 00054 00055 return T; 00056 } 00057 00058 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) { 00059 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), TD); 00060 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), TD); 00061 unsigned MinAlign = std::min(DstAlign, SrcAlign); 00062 unsigned CopyAlign = MI->getAlignment(); 00063 00064 if (CopyAlign < MinAlign) { 00065 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 00066 MinAlign, false)); 00067 return MI; 00068 } 00069 00070 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with 00071 // load/store. 00072 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2)); 00073 if (MemOpLength == 0) return 0; 00074 00075 // Source and destination pointer types are always "i8*" for intrinsic. See 00076 // if the size is something we can handle with a single primitive load/store. 00077 // A single load+store correctly handles overlapping memory in the memmove 00078 // case. 00079 uint64_t Size = MemOpLength->getLimitedValue(); 00080 assert(Size && "0-sized memory transfering should be removed already."); 00081 00082 if (Size > 8 || (Size&(Size-1))) 00083 return 0; // If not 1/2/4/8 bytes, exit. 00084 00085 // Use an integer load+store unless we can find something better. 00086 unsigned SrcAddrSp = 00087 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace(); 00088 unsigned DstAddrSp = 00089 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace(); 00090 00091 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3); 00092 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp); 00093 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp); 00094 00095 // Memcpy forces the use of i8* for the source and destination. That means 00096 // that if you're using memcpy to move one double around, you'll get a cast 00097 // from double* to i8*. We'd much rather use a double load+store rather than 00098 // an i64 load+store, here because this improves the odds that the source or 00099 // dest address will be promotable. See if we can find a better type than the 00100 // integer datatype. 00101 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts(); 00102 MDNode *CopyMD = 0; 00103 if (StrippedDest != MI->getArgOperand(0)) { 00104 Type *SrcETy = cast<PointerType>(StrippedDest->getType()) 00105 ->getElementType(); 00106 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) { 00107 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip 00108 // down through these levels if so. 00109 SrcETy = reduceToSingleValueType(SrcETy); 00110 00111 if (SrcETy->isSingleValueType()) { 00112 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp); 00113 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp); 00114 00115 // If the memcpy has metadata describing the members, see if we can 00116 // get the TBAA tag describing our copy. 00117 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) { 00118 if (M->getNumOperands() == 3 && 00119 M->getOperand(0) && 00120 isa<ConstantInt>(M->getOperand(0)) && 00121 cast<ConstantInt>(M->getOperand(0))->isNullValue() && 00122 M->getOperand(1) && 00123 isa<ConstantInt>(M->getOperand(1)) && 00124 cast<ConstantInt>(M->getOperand(1))->getValue() == Size && 00125 M->getOperand(2) && 00126 isa<MDNode>(M->getOperand(2))) 00127 CopyMD = cast<MDNode>(M->getOperand(2)); 00128 } 00129 } 00130 } 00131 } 00132 00133 // If the memcpy/memmove provides better alignment info than we can 00134 // infer, use it. 00135 SrcAlign = std::max(SrcAlign, CopyAlign); 00136 DstAlign = std::max(DstAlign, CopyAlign); 00137 00138 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy); 00139 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy); 00140 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile()); 00141 L->setAlignment(SrcAlign); 00142 if (CopyMD) 00143 L->setMetadata(LLVMContext::MD_tbaa, CopyMD); 00144 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile()); 00145 S->setAlignment(DstAlign); 00146 if (CopyMD) 00147 S->setMetadata(LLVMContext::MD_tbaa, CopyMD); 00148 00149 // Set the size of the copy to 0, it will be deleted on the next iteration. 00150 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType())); 00151 return MI; 00152 } 00153 00154 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) { 00155 unsigned Alignment = getKnownAlignment(MI->getDest(), TD); 00156 if (MI->getAlignment() < Alignment) { 00157 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), 00158 Alignment, false)); 00159 return MI; 00160 } 00161 00162 // Extract the length and alignment and fill if they are constant. 00163 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength()); 00164 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue()); 00165 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8)) 00166 return 0; 00167 uint64_t Len = LenC->getLimitedValue(); 00168 Alignment = MI->getAlignment(); 00169 assert(Len && "0-sized memory setting should be removed already."); 00170 00171 // memset(s,c,n) -> store s, c (for n=1,2,4,8) 00172 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) { 00173 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8. 00174 00175 Value *Dest = MI->getDest(); 00176 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace(); 00177 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp); 00178 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy); 00179 00180 // Alignment 0 is identity for alignment 1 for memset, but not store. 00181 if (Alignment == 0) Alignment = 1; 00182 00183 // Extract the fill value and store. 00184 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL; 00185 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest, 00186 MI->isVolatile()); 00187 S->setAlignment(Alignment); 00188 00189 // Set the size of the copy to 0, it will be deleted on the next iteration. 00190 MI->setLength(Constant::getNullValue(LenC->getType())); 00191 return MI; 00192 } 00193 00194 return 0; 00195 } 00196 00197 /// visitCallInst - CallInst simplification. This mostly only handles folding 00198 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do 00199 /// the heavy lifting. 00200 /// 00201 Instruction *InstCombiner::visitCallInst(CallInst &CI) { 00202 if (isFreeCall(&CI, TLI)) 00203 return visitFree(CI); 00204 00205 // If the caller function is nounwind, mark the call as nounwind, even if the 00206 // callee isn't. 00207 if (CI.getParent()->getParent()->doesNotThrow() && 00208 !CI.doesNotThrow()) { 00209 CI.setDoesNotThrow(); 00210 return &CI; 00211 } 00212 00213 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI); 00214 if (!II) return visitCallSite(&CI); 00215 00216 // Intrinsics cannot occur in an invoke, so handle them here instead of in 00217 // visitCallSite. 00218 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) { 00219 bool Changed = false; 00220 00221 // memmove/cpy/set of zero bytes is a noop. 00222 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) { 00223 if (NumBytes->isNullValue()) 00224 return EraseInstFromFunction(CI); 00225 00226 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes)) 00227 if (CI->getZExtValue() == 1) { 00228 // Replace the instruction with just byte operations. We would 00229 // transform other cases to loads/stores, but we don't know if 00230 // alignment is sufficient. 00231 } 00232 } 00233 00234 // No other transformations apply to volatile transfers. 00235 if (MI->isVolatile()) 00236 return 0; 00237 00238 // If we have a memmove and the source operation is a constant global, 00239 // then the source and dest pointers can't alias, so we can change this 00240 // into a call to memcpy. 00241 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) { 00242 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource())) 00243 if (GVSrc->isConstant()) { 00244 Module *M = CI.getParent()->getParent()->getParent(); 00245 Intrinsic::ID MemCpyID = Intrinsic::memcpy; 00246 Type *Tys[3] = { CI.getArgOperand(0)->getType(), 00247 CI.getArgOperand(1)->getType(), 00248 CI.getArgOperand(2)->getType() }; 00249 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys)); 00250 Changed = true; 00251 } 00252 } 00253 00254 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { 00255 // memmove(x,x,size) -> noop. 00256 if (MTI->getSource() == MTI->getDest()) 00257 return EraseInstFromFunction(CI); 00258 } 00259 00260 // If we can determine a pointer alignment that is bigger than currently 00261 // set, update the alignment. 00262 if (isa<MemTransferInst>(MI)) { 00263 if (Instruction *I = SimplifyMemTransfer(MI)) 00264 return I; 00265 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) { 00266 if (Instruction *I = SimplifyMemSet(MSI)) 00267 return I; 00268 } 00269 00270 if (Changed) return II; 00271 } 00272 00273 switch (II->getIntrinsicID()) { 00274 default: break; 00275 case Intrinsic::objectsize: { 00276 uint64_t Size; 00277 if (getObjectSize(II->getArgOperand(0), Size, TD, TLI)) 00278 return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size)); 00279 return 0; 00280 } 00281 case Intrinsic::bswap: { 00282 Value *IIOperand = II->getArgOperand(0); 00283 Value *X = 0; 00284 00285 // bswap(bswap(x)) -> x 00286 if (match(IIOperand, m_BSwap(m_Value(X)))) 00287 return ReplaceInstUsesWith(CI, X); 00288 00289 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c)) 00290 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) { 00291 unsigned C = X->getType()->getPrimitiveSizeInBits() - 00292 IIOperand->getType()->getPrimitiveSizeInBits(); 00293 Value *CV = ConstantInt::get(X->getType(), C); 00294 Value *V = Builder->CreateLShr(X, CV); 00295 return new TruncInst(V, IIOperand->getType()); 00296 } 00297 break; 00298 } 00299 00300 case Intrinsic::powi: 00301 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 00302 // powi(x, 0) -> 1.0 00303 if (Power->isZero()) 00304 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0)); 00305 // powi(x, 1) -> x 00306 if (Power->isOne()) 00307 return ReplaceInstUsesWith(CI, II->getArgOperand(0)); 00308 // powi(x, -1) -> 1/x 00309 if (Power->isAllOnesValue()) 00310 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0), 00311 II->getArgOperand(0)); 00312 } 00313 break; 00314 case Intrinsic::cttz: { 00315 // If all bits below the first known one are known zero, 00316 // this value is constant. 00317 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType()); 00318 // FIXME: Try to simplify vectors of integers. 00319 if (!IT) break; 00320 uint32_t BitWidth = IT->getBitWidth(); 00321 APInt KnownZero(BitWidth, 0); 00322 APInt KnownOne(BitWidth, 0); 00323 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne); 00324 unsigned TrailingZeros = KnownOne.countTrailingZeros(); 00325 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros)); 00326 if ((Mask & KnownZero) == Mask) 00327 return ReplaceInstUsesWith(CI, ConstantInt::get(IT, 00328 APInt(BitWidth, TrailingZeros))); 00329 00330 } 00331 break; 00332 case Intrinsic::ctlz: { 00333 // If all bits above the first known one are known zero, 00334 // this value is constant. 00335 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType()); 00336 // FIXME: Try to simplify vectors of integers. 00337 if (!IT) break; 00338 uint32_t BitWidth = IT->getBitWidth(); 00339 APInt KnownZero(BitWidth, 0); 00340 APInt KnownOne(BitWidth, 0); 00341 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne); 00342 unsigned LeadingZeros = KnownOne.countLeadingZeros(); 00343 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros)); 00344 if ((Mask & KnownZero) == Mask) 00345 return ReplaceInstUsesWith(CI, ConstantInt::get(IT, 00346 APInt(BitWidth, LeadingZeros))); 00347 00348 } 00349 break; 00350 case Intrinsic::uadd_with_overflow: { 00351 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 00352 IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType()); 00353 uint32_t BitWidth = IT->getBitWidth(); 00354 APInt LHSKnownZero(BitWidth, 0); 00355 APInt LHSKnownOne(BitWidth, 0); 00356 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne); 00357 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1]; 00358 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1]; 00359 00360 if (LHSKnownNegative || LHSKnownPositive) { 00361 APInt RHSKnownZero(BitWidth, 0); 00362 APInt RHSKnownOne(BitWidth, 0); 00363 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne); 00364 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1]; 00365 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1]; 00366 if (LHSKnownNegative && RHSKnownNegative) { 00367 // The sign bit is set in both cases: this MUST overflow. 00368 // Create a simple add instruction, and insert it into the struct. 00369 Value *Add = Builder->CreateAdd(LHS, RHS); 00370 Add->takeName(&CI); 00371 Constant *V[] = { 00372 UndefValue::get(LHS->getType()), 00373 ConstantInt::getTrue(II->getContext()) 00374 }; 00375 StructType *ST = cast<StructType>(II->getType()); 00376 Constant *Struct = ConstantStruct::get(ST, V); 00377 return InsertValueInst::Create(Struct, Add, 0); 00378 } 00379 00380 if (LHSKnownPositive && RHSKnownPositive) { 00381 // The sign bit is clear in both cases: this CANNOT overflow. 00382 // Create a simple add instruction, and insert it into the struct. 00383 Value *Add = Builder->CreateNUWAdd(LHS, RHS); 00384 Add->takeName(&CI); 00385 Constant *V[] = { 00386 UndefValue::get(LHS->getType()), 00387 ConstantInt::getFalse(II->getContext()) 00388 }; 00389 StructType *ST = cast<StructType>(II->getType()); 00390 Constant *Struct = ConstantStruct::get(ST, V); 00391 return InsertValueInst::Create(Struct, Add, 0); 00392 } 00393 } 00394 } 00395 // FALL THROUGH uadd into sadd 00396 case Intrinsic::sadd_with_overflow: 00397 // Canonicalize constants into the RHS. 00398 if (isa<Constant>(II->getArgOperand(0)) && 00399 !isa<Constant>(II->getArgOperand(1))) { 00400 Value *LHS = II->getArgOperand(0); 00401 II->setArgOperand(0, II->getArgOperand(1)); 00402 II->setArgOperand(1, LHS); 00403 return II; 00404 } 00405 00406 // X + undef -> undef 00407 if (isa<UndefValue>(II->getArgOperand(1))) 00408 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType())); 00409 00410 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 00411 // X + 0 -> {X, false} 00412 if (RHS->isZero()) { 00413 Constant *V[] = { 00414 UndefValue::get(II->getArgOperand(0)->getType()), 00415 ConstantInt::getFalse(II->getContext()) 00416 }; 00417 Constant *Struct = 00418 ConstantStruct::get(cast<StructType>(II->getType()), V); 00419 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0); 00420 } 00421 } 00422 break; 00423 case Intrinsic::usub_with_overflow: 00424 case Intrinsic::ssub_with_overflow: 00425 // undef - X -> undef 00426 // X - undef -> undef 00427 if (isa<UndefValue>(II->getArgOperand(0)) || 00428 isa<UndefValue>(II->getArgOperand(1))) 00429 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType())); 00430 00431 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 00432 // X - 0 -> {X, false} 00433 if (RHS->isZero()) { 00434 Constant *V[] = { 00435 UndefValue::get(II->getArgOperand(0)->getType()), 00436 ConstantInt::getFalse(II->getContext()) 00437 }; 00438 Constant *Struct = 00439 ConstantStruct::get(cast<StructType>(II->getType()), V); 00440 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0); 00441 } 00442 } 00443 break; 00444 case Intrinsic::umul_with_overflow: { 00445 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1); 00446 unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth(); 00447 00448 APInt LHSKnownZero(BitWidth, 0); 00449 APInt LHSKnownOne(BitWidth, 0); 00450 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne); 00451 APInt RHSKnownZero(BitWidth, 0); 00452 APInt RHSKnownOne(BitWidth, 0); 00453 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne); 00454 00455 // Get the largest possible values for each operand. 00456 APInt LHSMax = ~LHSKnownZero; 00457 APInt RHSMax = ~RHSKnownZero; 00458 00459 // If multiplying the maximum values does not overflow then we can turn 00460 // this into a plain NUW mul. 00461 bool Overflow; 00462 LHSMax.umul_ov(RHSMax, Overflow); 00463 if (!Overflow) { 00464 Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow"); 00465 Constant *V[] = { 00466 UndefValue::get(LHS->getType()), 00467 Builder->getFalse() 00468 }; 00469 Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V); 00470 return InsertValueInst::Create(Struct, Mul, 0); 00471 } 00472 } // FALL THROUGH 00473 case Intrinsic::smul_with_overflow: 00474 // Canonicalize constants into the RHS. 00475 if (isa<Constant>(II->getArgOperand(0)) && 00476 !isa<Constant>(II->getArgOperand(1))) { 00477 Value *LHS = II->getArgOperand(0); 00478 II->setArgOperand(0, II->getArgOperand(1)); 00479 II->setArgOperand(1, LHS); 00480 return II; 00481 } 00482 00483 // X * undef -> undef 00484 if (isa<UndefValue>(II->getArgOperand(1))) 00485 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType())); 00486 00487 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) { 00488 // X*0 -> {0, false} 00489 if (RHSI->isZero()) 00490 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType())); 00491 00492 // X * 1 -> {X, false} 00493 if (RHSI->equalsInt(1)) { 00494 Constant *V[] = { 00495 UndefValue::get(II->getArgOperand(0)->getType()), 00496 ConstantInt::getFalse(II->getContext()) 00497 }; 00498 Constant *Struct = 00499 ConstantStruct::get(cast<StructType>(II->getType()), V); 00500 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0); 00501 } 00502 } 00503 break; 00504 case Intrinsic::ppc_altivec_lvx: 00505 case Intrinsic::ppc_altivec_lvxl: 00506 // Turn PPC lvx -> load if the pointer is known aligned. 00507 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) { 00508 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), 00509 PointerType::getUnqual(II->getType())); 00510 return new LoadInst(Ptr); 00511 } 00512 break; 00513 case Intrinsic::ppc_altivec_stvx: 00514 case Intrinsic::ppc_altivec_stvxl: 00515 // Turn stvx -> store if the pointer is known aligned. 00516 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, TD) >= 16) { 00517 Type *OpPtrTy = 00518 PointerType::getUnqual(II->getArgOperand(0)->getType()); 00519 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy); 00520 return new StoreInst(II->getArgOperand(0), Ptr); 00521 } 00522 break; 00523 case Intrinsic::x86_sse_storeu_ps: 00524 case Intrinsic::x86_sse2_storeu_pd: 00525 case Intrinsic::x86_sse2_storeu_dq: 00526 // Turn X86 storeu -> store if the pointer is known aligned. 00527 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) { 00528 Type *OpPtrTy = 00529 PointerType::getUnqual(II->getArgOperand(1)->getType()); 00530 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy); 00531 return new StoreInst(II->getArgOperand(1), Ptr); 00532 } 00533 break; 00534 00535 case Intrinsic::x86_sse_cvtss2si: 00536 case Intrinsic::x86_sse_cvtss2si64: 00537 case Intrinsic::x86_sse_cvttss2si: 00538 case Intrinsic::x86_sse_cvttss2si64: 00539 case Intrinsic::x86_sse2_cvtsd2si: 00540 case Intrinsic::x86_sse2_cvtsd2si64: 00541 case Intrinsic::x86_sse2_cvttsd2si: 00542 case Intrinsic::x86_sse2_cvttsd2si64: { 00543 // These intrinsics only demand the 0th element of their input vectors. If 00544 // we can simplify the input based on that, do so now. 00545 unsigned VWidth = 00546 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements(); 00547 APInt DemandedElts(VWidth, 1); 00548 APInt UndefElts(VWidth, 0); 00549 if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0), 00550 DemandedElts, UndefElts)) { 00551 II->setArgOperand(0, V); 00552 return II; 00553 } 00554 break; 00555 } 00556 00557 00558 case Intrinsic::x86_sse41_pmovsxbw: 00559 case Intrinsic::x86_sse41_pmovsxwd: 00560 case Intrinsic::x86_sse41_pmovsxdq: 00561 case Intrinsic::x86_sse41_pmovzxbw: 00562 case Intrinsic::x86_sse41_pmovzxwd: 00563 case Intrinsic::x86_sse41_pmovzxdq: { 00564 // pmov{s|z}x ignores the upper half of their input vectors. 00565 unsigned VWidth = 00566 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements(); 00567 unsigned LowHalfElts = VWidth / 2; 00568 APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts)); 00569 APInt UndefElts(VWidth, 0); 00570 if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0), 00571 InputDemandedElts, 00572 UndefElts)) { 00573 II->setArgOperand(0, TmpV); 00574 return II; 00575 } 00576 break; 00577 } 00578 00579 case Intrinsic::ppc_altivec_vperm: 00580 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant. 00581 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) { 00582 assert(Mask->getType()->getVectorNumElements() == 16 && 00583 "Bad type for intrinsic!"); 00584 00585 // Check that all of the elements are integer constants or undefs. 00586 bool AllEltsOk = true; 00587 for (unsigned i = 0; i != 16; ++i) { 00588 Constant *Elt = Mask->getAggregateElement(i); 00589 if (Elt == 0 || 00590 !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) { 00591 AllEltsOk = false; 00592 break; 00593 } 00594 } 00595 00596 if (AllEltsOk) { 00597 // Cast the input vectors to byte vectors. 00598 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0), 00599 Mask->getType()); 00600 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1), 00601 Mask->getType()); 00602 Value *Result = UndefValue::get(Op0->getType()); 00603 00604 // Only extract each element once. 00605 Value *ExtractedElts[32]; 00606 memset(ExtractedElts, 0, sizeof(ExtractedElts)); 00607 00608 for (unsigned i = 0; i != 16; ++i) { 00609 if (isa<UndefValue>(Mask->getAggregateElement(i))) 00610 continue; 00611 unsigned Idx = 00612 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue(); 00613 Idx &= 31; // Match the hardware behavior. 00614 00615 if (ExtractedElts[Idx] == 0) { 00616 ExtractedElts[Idx] = 00617 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1, 00618 Builder->getInt32(Idx&15)); 00619 } 00620 00621 // Insert this value into the result vector. 00622 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx], 00623 Builder->getInt32(i)); 00624 } 00625 return CastInst::Create(Instruction::BitCast, Result, CI.getType()); 00626 } 00627 } 00628 break; 00629 00630 case Intrinsic::arm_neon_vld1: 00631 case Intrinsic::arm_neon_vld2: 00632 case Intrinsic::arm_neon_vld3: 00633 case Intrinsic::arm_neon_vld4: 00634 case Intrinsic::arm_neon_vld2lane: 00635 case Intrinsic::arm_neon_vld3lane: 00636 case Intrinsic::arm_neon_vld4lane: 00637 case Intrinsic::arm_neon_vst1: 00638 case Intrinsic::arm_neon_vst2: 00639 case Intrinsic::arm_neon_vst3: 00640 case Intrinsic::arm_neon_vst4: 00641 case Intrinsic::arm_neon_vst2lane: 00642 case Intrinsic::arm_neon_vst3lane: 00643 case Intrinsic::arm_neon_vst4lane: { 00644 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), TD); 00645 unsigned AlignArg = II->getNumArgOperands() - 1; 00646 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg)); 00647 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) { 00648 II->setArgOperand(AlignArg, 00649 ConstantInt::get(Type::getInt32Ty(II->getContext()), 00650 MemAlign, false)); 00651 return II; 00652 } 00653 break; 00654 } 00655 00656 case Intrinsic::arm_neon_vmulls: 00657 case Intrinsic::arm_neon_vmullu: { 00658 Value *Arg0 = II->getArgOperand(0); 00659 Value *Arg1 = II->getArgOperand(1); 00660 00661 // Handle mul by zero first: 00662 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) { 00663 return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType())); 00664 } 00665 00666 // Check for constant LHS & RHS - in this case we just simplify. 00667 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu); 00668 VectorType *NewVT = cast<VectorType>(II->getType()); 00669 unsigned NewWidth = NewVT->getElementType()->getIntegerBitWidth(); 00670 if (ConstantDataVector *CV0 = dyn_cast<ConstantDataVector>(Arg0)) { 00671 if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) { 00672 VectorType* VT = cast<VectorType>(CV0->getType()); 00673 SmallVector<Constant*, 4> NewElems; 00674 for (unsigned i = 0; i < VT->getNumElements(); ++i) { 00675 APInt CV0E = 00676 (cast<ConstantInt>(CV0->getAggregateElement(i)))->getValue(); 00677 CV0E = Zext ? CV0E.zext(NewWidth) : CV0E.sext(NewWidth); 00678 APInt CV1E = 00679 (cast<ConstantInt>(CV1->getAggregateElement(i)))->getValue(); 00680 CV1E = Zext ? CV1E.zext(NewWidth) : CV1E.sext(NewWidth); 00681 NewElems.push_back( 00682 ConstantInt::get(NewVT->getElementType(), CV0E * CV1E)); 00683 } 00684 return ReplaceInstUsesWith(CI, ConstantVector::get(NewElems)); 00685 } 00686 00687 // Couldn't simplify - cannonicalize constant to the RHS. 00688 std::swap(Arg0, Arg1); 00689 } 00690 00691 // Handle mul by one: 00692 if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) { 00693 if (ConstantInt *Splat = 00694 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) { 00695 if (Splat->isOne()) { 00696 if (Zext) 00697 return CastInst::CreateZExtOrBitCast(Arg0, II->getType()); 00698 // else 00699 return CastInst::CreateSExtOrBitCast(Arg0, II->getType()); 00700 } 00701 } 00702 } 00703 00704 break; 00705 } 00706 00707 case Intrinsic::stackrestore: { 00708 // If the save is right next to the restore, remove the restore. This can 00709 // happen when variable allocas are DCE'd. 00710 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) { 00711 if (SS->getIntrinsicID() == Intrinsic::stacksave) { 00712 BasicBlock::iterator BI = SS; 00713 if (&*++BI == II) 00714 return EraseInstFromFunction(CI); 00715 } 00716 } 00717 00718 // Scan down this block to see if there is another stack restore in the 00719 // same block without an intervening call/alloca. 00720 BasicBlock::iterator BI = II; 00721 TerminatorInst *TI = II->getParent()->getTerminator(); 00722 bool CannotRemove = false; 00723 for (++BI; &*BI != TI; ++BI) { 00724 if (isa<AllocaInst>(BI)) { 00725 CannotRemove = true; 00726 break; 00727 } 00728 if (CallInst *BCI = dyn_cast<CallInst>(BI)) { 00729 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) { 00730 // If there is a stackrestore below this one, remove this one. 00731 if (II->getIntrinsicID() == Intrinsic::stackrestore) 00732 return EraseInstFromFunction(CI); 00733 // Otherwise, ignore the intrinsic. 00734 } else { 00735 // If we found a non-intrinsic call, we can't remove the stack 00736 // restore. 00737 CannotRemove = true; 00738 break; 00739 } 00740 } 00741 } 00742 00743 // If the stack restore is in a return, resume, or unwind block and if there 00744 // are no allocas or calls between the restore and the return, nuke the 00745 // restore. 00746 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI))) 00747 return EraseInstFromFunction(CI); 00748 break; 00749 } 00750 } 00751 00752 return visitCallSite(II); 00753 } 00754 00755 // InvokeInst simplification 00756 // 00757 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) { 00758 return visitCallSite(&II); 00759 } 00760 00761 /// isSafeToEliminateVarargsCast - If this cast does not affect the value 00762 /// passed through the varargs area, we can eliminate the use of the cast. 00763 static bool isSafeToEliminateVarargsCast(const CallSite CS, 00764 const CastInst * const CI, 00765 const DataLayout * const TD, 00766 const int ix) { 00767 if (!CI->isLosslessCast()) 00768 return false; 00769 00770 // The size of ByVal arguments is derived from the type, so we 00771 // can't change to a type with a different size. If the size were 00772 // passed explicitly we could avoid this check. 00773 if (!CS.isByValArgument(ix)) 00774 return true; 00775 00776 Type* SrcTy = 00777 cast<PointerType>(CI->getOperand(0)->getType())->getElementType(); 00778 Type* DstTy = cast<PointerType>(CI->getType())->getElementType(); 00779 if (!SrcTy->isSized() || !DstTy->isSized()) 00780 return false; 00781 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy)) 00782 return false; 00783 return true; 00784 } 00785 00786 // Try to fold some different type of calls here. 00787 // Currently we're only working with the checking functions, memcpy_chk, 00788 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk, 00789 // strcat_chk and strncat_chk. 00790 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *TD) { 00791 if (CI->getCalledFunction() == 0) return 0; 00792 00793 if (Value *With = Simplifier->optimizeCall(CI)) { 00794 ++NumSimplified; 00795 return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With); 00796 } 00797 00798 return 0; 00799 } 00800 00801 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) { 00802 // Strip off at most one level of pointer casts, looking for an alloca. This 00803 // is good enough in practice and simpler than handling any number of casts. 00804 Value *Underlying = TrampMem->stripPointerCasts(); 00805 if (Underlying != TrampMem && 00806 (!Underlying->hasOneUse() || *Underlying->use_begin() != TrampMem)) 00807 return 0; 00808 if (!isa<AllocaInst>(Underlying)) 00809 return 0; 00810 00811 IntrinsicInst *InitTrampoline = 0; 00812 for (Value::use_iterator I = TrampMem->use_begin(), E = TrampMem->use_end(); 00813 I != E; I++) { 00814 IntrinsicInst *II = dyn_cast<IntrinsicInst>(*I); 00815 if (!II) 00816 return 0; 00817 if (II->getIntrinsicID() == Intrinsic::init_trampoline) { 00818 if (InitTrampoline) 00819 // More than one init_trampoline writes to this value. Give up. 00820 return 0; 00821 InitTrampoline = II; 00822 continue; 00823 } 00824 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline) 00825 // Allow any number of calls to adjust.trampoline. 00826 continue; 00827 return 0; 00828 } 00829 00830 // No call to init.trampoline found. 00831 if (!InitTrampoline) 00832 return 0; 00833 00834 // Check that the alloca is being used in the expected way. 00835 if (InitTrampoline->getOperand(0) != TrampMem) 00836 return 0; 00837 00838 return InitTrampoline; 00839 } 00840 00841 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp, 00842 Value *TrampMem) { 00843 // Visit all the previous instructions in the basic block, and try to find a 00844 // init.trampoline which has a direct path to the adjust.trampoline. 00845 for (BasicBlock::iterator I = AdjustTramp, 00846 E = AdjustTramp->getParent()->begin(); I != E; ) { 00847 Instruction *Inst = --I; 00848 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) 00849 if (II->getIntrinsicID() == Intrinsic::init_trampoline && 00850 II->getOperand(0) == TrampMem) 00851 return II; 00852 if (Inst->mayWriteToMemory()) 00853 return 0; 00854 } 00855 return 0; 00856 } 00857 00858 // Given a call to llvm.adjust.trampoline, find and return the corresponding 00859 // call to llvm.init.trampoline if the call to the trampoline can be optimized 00860 // to a direct call to a function. Otherwise return NULL. 00861 // 00862 static IntrinsicInst *FindInitTrampoline(Value *Callee) { 00863 Callee = Callee->stripPointerCasts(); 00864 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee); 00865 if (!AdjustTramp || 00866 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline) 00867 return 0; 00868 00869 Value *TrampMem = AdjustTramp->getOperand(0); 00870 00871 if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem)) 00872 return IT; 00873 if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem)) 00874 return IT; 00875 return 0; 00876 } 00877 00878 // visitCallSite - Improvements for call and invoke instructions. 00879 // 00880 Instruction *InstCombiner::visitCallSite(CallSite CS) { 00881 if (isAllocLikeFn(CS.getInstruction(), TLI)) 00882 return visitAllocSite(*CS.getInstruction()); 00883 00884 bool Changed = false; 00885 00886 // If the callee is a pointer to a function, attempt to move any casts to the 00887 // arguments of the call/invoke. 00888 Value *Callee = CS.getCalledValue(); 00889 if (!isa<Function>(Callee) && transformConstExprCastCall(CS)) 00890 return 0; 00891 00892 if (Function *CalleeF = dyn_cast<Function>(Callee)) 00893 // If the call and callee calling conventions don't match, this call must 00894 // be unreachable, as the call is undefined. 00895 if (CalleeF->getCallingConv() != CS.getCallingConv() && 00896 // Only do this for calls to a function with a body. A prototype may 00897 // not actually end up matching the implementation's calling conv for a 00898 // variety of reasons (e.g. it may be written in assembly). 00899 !CalleeF->isDeclaration()) { 00900 Instruction *OldCall = CS.getInstruction(); 00901 new StoreInst(ConstantInt::getTrue(Callee->getContext()), 00902 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())), 00903 OldCall); 00904 // If OldCall does not return void then replaceAllUsesWith undef. 00905 // This allows ValueHandlers and custom metadata to adjust itself. 00906 if (!OldCall->getType()->isVoidTy()) 00907 ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType())); 00908 if (isa<CallInst>(OldCall)) 00909 return EraseInstFromFunction(*OldCall); 00910 00911 // We cannot remove an invoke, because it would change the CFG, just 00912 // change the callee to a null pointer. 00913 cast<InvokeInst>(OldCall)->setCalledFunction( 00914 Constant::getNullValue(CalleeF->getType())); 00915 return 0; 00916 } 00917 00918 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) { 00919 // If CS does not return void then replaceAllUsesWith undef. 00920 // This allows ValueHandlers and custom metadata to adjust itself. 00921 if (!CS.getInstruction()->getType()->isVoidTy()) 00922 ReplaceInstUsesWith(*CS.getInstruction(), 00923 UndefValue::get(CS.getInstruction()->getType())); 00924 00925 if (isa<InvokeInst>(CS.getInstruction())) { 00926 // Can't remove an invoke because we cannot change the CFG. 00927 return 0; 00928 } 00929 00930 // This instruction is not reachable, just remove it. We insert a store to 00931 // undef so that we know that this code is not reachable, despite the fact 00932 // that we can't modify the CFG here. 00933 new StoreInst(ConstantInt::getTrue(Callee->getContext()), 00934 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())), 00935 CS.getInstruction()); 00936 00937 return EraseInstFromFunction(*CS.getInstruction()); 00938 } 00939 00940 if (IntrinsicInst *II = FindInitTrampoline(Callee)) 00941 return transformCallThroughTrampoline(CS, II); 00942 00943 PointerType *PTy = cast<PointerType>(Callee->getType()); 00944 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 00945 if (FTy->isVarArg()) { 00946 int ix = FTy->getNumParams(); 00947 // See if we can optimize any arguments passed through the varargs area of 00948 // the call. 00949 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(), 00950 E = CS.arg_end(); I != E; ++I, ++ix) { 00951 CastInst *CI = dyn_cast<CastInst>(*I); 00952 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) { 00953 *I = CI->getOperand(0); 00954 Changed = true; 00955 } 00956 } 00957 } 00958 00959 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) { 00960 // Inline asm calls cannot throw - mark them 'nounwind'. 00961 CS.setDoesNotThrow(); 00962 Changed = true; 00963 } 00964 00965 // Try to optimize the call if possible, we require DataLayout for most of 00966 // this. None of these calls are seen as possibly dead so go ahead and 00967 // delete the instruction now. 00968 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) { 00969 Instruction *I = tryOptimizeCall(CI, TD); 00970 // If we changed something return the result, etc. Otherwise let 00971 // the fallthrough check. 00972 if (I) return EraseInstFromFunction(*I); 00973 } 00974 00975 return Changed ? CS.getInstruction() : 0; 00976 } 00977 00978 // transformConstExprCastCall - If the callee is a constexpr cast of a function, 00979 // attempt to move the cast to the arguments of the call/invoke. 00980 // 00981 bool InstCombiner::transformConstExprCastCall(CallSite CS) { 00982 Function *Callee = 00983 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts()); 00984 if (Callee == 0) 00985 return false; 00986 Instruction *Caller = CS.getInstruction(); 00987 const AttributeSet &CallerPAL = CS.getAttributes(); 00988 00989 // Okay, this is a cast from a function to a different type. Unless doing so 00990 // would cause a type conversion of one of our arguments, change this call to 00991 // be a direct call with arguments casted to the appropriate types. 00992 // 00993 FunctionType *FT = Callee->getFunctionType(); 00994 Type *OldRetTy = Caller->getType(); 00995 Type *NewRetTy = FT->getReturnType(); 00996 00997 if (NewRetTy->isStructTy()) 00998 return false; // TODO: Handle multiple return values. 00999 01000 // Check to see if we are changing the return type... 01001 if (OldRetTy != NewRetTy) { 01002 if (Callee->isDeclaration() && 01003 // Conversion is ok if changing from one pointer type to another or from 01004 // a pointer to an integer of the same size. 01005 !((OldRetTy->isPointerTy() || !TD || 01006 OldRetTy == TD->getIntPtrType(Caller->getContext())) && 01007 (NewRetTy->isPointerTy() || !TD || 01008 NewRetTy == TD->getIntPtrType(Caller->getContext())))) 01009 return false; // Cannot transform this return value. 01010 01011 if (!Caller->use_empty() && 01012 // void -> non-void is handled specially 01013 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy)) 01014 return false; // Cannot transform this return value. 01015 01016 if (!CallerPAL.isEmpty() && !Caller->use_empty()) { 01017 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex); 01018 if (RAttrs. 01019 hasAttributes(AttributeFuncs:: 01020 typeIncompatible(NewRetTy, AttributeSet::ReturnIndex), 01021 AttributeSet::ReturnIndex)) 01022 return false; // Attribute not compatible with transformed value. 01023 } 01024 01025 // If the callsite is an invoke instruction, and the return value is used by 01026 // a PHI node in a successor, we cannot change the return type of the call 01027 // because there is no place to put the cast instruction (without breaking 01028 // the critical edge). Bail out in this case. 01029 if (!Caller->use_empty()) 01030 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) 01031 for (Value::use_iterator UI = II->use_begin(), E = II->use_end(); 01032 UI != E; ++UI) 01033 if (PHINode *PN = dyn_cast<PHINode>(*UI)) 01034 if (PN->getParent() == II->getNormalDest() || 01035 PN->getParent() == II->getUnwindDest()) 01036 return false; 01037 } 01038 01039 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin()); 01040 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs); 01041 01042 CallSite::arg_iterator AI = CS.arg_begin(); 01043 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) { 01044 Type *ParamTy = FT->getParamType(i); 01045 Type *ActTy = (*AI)->getType(); 01046 01047 if (!CastInst::isCastable(ActTy, ParamTy)) 01048 return false; // Cannot transform this parameter value. 01049 01050 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1). 01051 hasAttributes(AttributeFuncs:: 01052 typeIncompatible(ParamTy, i + 1), i + 1)) 01053 return false; // Attribute not compatible with transformed value. 01054 01055 // If the parameter is passed as a byval argument, then we have to have a 01056 // sized type and the sized type has to have the same size as the old type. 01057 if (ParamTy != ActTy && 01058 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1, 01059 Attribute::ByVal)) { 01060 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy); 01061 if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || TD == 0) 01062 return false; 01063 01064 Type *CurElTy = cast<PointerType>(ActTy)->getElementType(); 01065 if (TD->getTypeAllocSize(CurElTy) != 01066 TD->getTypeAllocSize(ParamPTy->getElementType())) 01067 return false; 01068 } 01069 01070 // Converting from one pointer type to another or between a pointer and an 01071 // integer of the same size is safe even if we do not have a body. 01072 bool isConvertible = ActTy == ParamTy || 01073 (TD && ((ParamTy->isPointerTy() || 01074 ParamTy == TD->getIntPtrType(Caller->getContext())) && 01075 (ActTy->isPointerTy() || 01076 ActTy == TD->getIntPtrType(Caller->getContext())))); 01077 if (Callee->isDeclaration() && !isConvertible) return false; 01078 } 01079 01080 if (Callee->isDeclaration()) { 01081 // Do not delete arguments unless we have a function body. 01082 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg()) 01083 return false; 01084 01085 // If the callee is just a declaration, don't change the varargsness of the 01086 // call. We don't want to introduce a varargs call where one doesn't 01087 // already exist. 01088 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType()); 01089 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg()) 01090 return false; 01091 01092 // If both the callee and the cast type are varargs, we still have to make 01093 // sure the number of fixed parameters are the same or we have the same 01094 // ABI issues as if we introduce a varargs call. 01095 if (FT->isVarArg() && 01096 cast<FunctionType>(APTy->getElementType())->isVarArg() && 01097 FT->getNumParams() != 01098 cast<FunctionType>(APTy->getElementType())->getNumParams()) 01099 return false; 01100 } 01101 01102 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && 01103 !CallerPAL.isEmpty()) 01104 // In this case we have more arguments than the new function type, but we 01105 // won't be dropping them. Check that these extra arguments have attributes 01106 // that are compatible with being a vararg call argument. 01107 for (unsigned i = CallerPAL.getNumSlots(); i; --i) { 01108 unsigned Index = CallerPAL.getSlotIndex(i - 1); 01109 if (Index <= FT->getNumParams()) 01110 break; 01111 01112 // Check if it has an attribute that's incompatible with varargs. 01113 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1); 01114 if (PAttrs.hasAttribute(Index, Attribute::StructRet)) 01115 return false; 01116 } 01117 01118 01119 // Okay, we decided that this is a safe thing to do: go ahead and start 01120 // inserting cast instructions as necessary. 01121 std::vector<Value*> Args; 01122 Args.reserve(NumActualArgs); 01123 SmallVector<AttributeSet, 8> attrVec; 01124 attrVec.reserve(NumCommonArgs); 01125 01126 // Get any return attributes. 01127 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex); 01128 01129 // If the return value is not being used, the type may not be compatible 01130 // with the existing attributes. Wipe out any problematic attributes. 01131 RAttrs. 01132 removeAttributes(AttributeFuncs:: 01133 typeIncompatible(NewRetTy, AttributeSet::ReturnIndex), 01134 AttributeSet::ReturnIndex); 01135 01136 // Add the new return attributes. 01137 if (RAttrs.hasAttributes()) 01138 attrVec.push_back(AttributeSet::get(Caller->getContext(), 01139 AttributeSet::ReturnIndex, RAttrs)); 01140 01141 AI = CS.arg_begin(); 01142 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) { 01143 Type *ParamTy = FT->getParamType(i); 01144 if ((*AI)->getType() == ParamTy) { 01145 Args.push_back(*AI); 01146 } else { 01147 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, 01148 false, ParamTy, false); 01149 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy)); 01150 } 01151 01152 // Add any parameter attributes. 01153 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1); 01154 if (PAttrs.hasAttributes()) 01155 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1, 01156 PAttrs)); 01157 } 01158 01159 // If the function takes more arguments than the call was taking, add them 01160 // now. 01161 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) 01162 Args.push_back(Constant::getNullValue(FT->getParamType(i))); 01163 01164 // If we are removing arguments to the function, emit an obnoxious warning. 01165 if (FT->getNumParams() < NumActualArgs) { 01166 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722 01167 if (FT->isVarArg()) { 01168 // Add all of the arguments in their promoted form to the arg list. 01169 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) { 01170 Type *PTy = getPromotedType((*AI)->getType()); 01171 if (PTy != (*AI)->getType()) { 01172 // Must promote to pass through va_arg area! 01173 Instruction::CastOps opcode = 01174 CastInst::getCastOpcode(*AI, false, PTy, false); 01175 Args.push_back(Builder->CreateCast(opcode, *AI, PTy)); 01176 } else { 01177 Args.push_back(*AI); 01178 } 01179 01180 // Add any parameter attributes. 01181 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1); 01182 if (PAttrs.hasAttributes()) 01183 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1, 01184 PAttrs)); 01185 } 01186 } 01187 } 01188 01189 AttributeSet FnAttrs = CallerPAL.getFnAttributes(); 01190 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex)) 01191 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs)); 01192 01193 if (NewRetTy->isVoidTy()) 01194 Caller->setName(""); // Void type should not have a name. 01195 01196 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(), 01197 attrVec); 01198 01199 Instruction *NC; 01200 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 01201 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), 01202 II->getUnwindDest(), Args); 01203 NC->takeName(II); 01204 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv()); 01205 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL); 01206 } else { 01207 CallInst *CI = cast<CallInst>(Caller); 01208 NC = Builder->CreateCall(Callee, Args); 01209 NC->takeName(CI); 01210 if (CI->isTailCall()) 01211 cast<CallInst>(NC)->setTailCall(); 01212 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv()); 01213 cast<CallInst>(NC)->setAttributes(NewCallerPAL); 01214 } 01215 01216 // Insert a cast of the return type as necessary. 01217 Value *NV = NC; 01218 if (OldRetTy != NV->getType() && !Caller->use_empty()) { 01219 if (!NV->getType()->isVoidTy()) { 01220 Instruction::CastOps opcode = 01221 CastInst::getCastOpcode(NC, false, OldRetTy, false); 01222 NV = NC = CastInst::Create(opcode, NC, OldRetTy); 01223 NC->setDebugLoc(Caller->getDebugLoc()); 01224 01225 // If this is an invoke instruction, we should insert it after the first 01226 // non-phi, instruction in the normal successor block. 01227 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 01228 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt(); 01229 InsertNewInstBefore(NC, *I); 01230 } else { 01231 // Otherwise, it's a call, just insert cast right after the call. 01232 InsertNewInstBefore(NC, *Caller); 01233 } 01234 Worklist.AddUsersToWorkList(*Caller); 01235 } else { 01236 NV = UndefValue::get(Caller->getType()); 01237 } 01238 } 01239 01240 if (!Caller->use_empty()) 01241 ReplaceInstUsesWith(*Caller, NV); 01242 01243 EraseInstFromFunction(*Caller); 01244 return true; 01245 } 01246 01247 // transformCallThroughTrampoline - Turn a call to a function created by 01248 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the 01249 // underlying function. 01250 // 01251 Instruction * 01252 InstCombiner::transformCallThroughTrampoline(CallSite CS, 01253 IntrinsicInst *Tramp) { 01254 Value *Callee = CS.getCalledValue(); 01255 PointerType *PTy = cast<PointerType>(Callee->getType()); 01256 FunctionType *FTy = cast<FunctionType>(PTy->getElementType()); 01257 const AttributeSet &Attrs = CS.getAttributes(); 01258 01259 // If the call already has the 'nest' attribute somewhere then give up - 01260 // otherwise 'nest' would occur twice after splicing in the chain. 01261 if (Attrs.hasAttrSomewhere(Attribute::Nest)) 01262 return 0; 01263 01264 assert(Tramp && 01265 "transformCallThroughTrampoline called with incorrect CallSite."); 01266 01267 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts()); 01268 PointerType *NestFPTy = cast<PointerType>(NestF->getType()); 01269 FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType()); 01270 01271 const AttributeSet &NestAttrs = NestF->getAttributes(); 01272 if (!NestAttrs.isEmpty()) { 01273 unsigned NestIdx = 1; 01274 Type *NestTy = 0; 01275 AttributeSet NestAttr; 01276 01277 // Look for a parameter marked with the 'nest' attribute. 01278 for (FunctionType::param_iterator I = NestFTy->param_begin(), 01279 E = NestFTy->param_end(); I != E; ++NestIdx, ++I) 01280 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) { 01281 // Record the parameter type and any other attributes. 01282 NestTy = *I; 01283 NestAttr = NestAttrs.getParamAttributes(NestIdx); 01284 break; 01285 } 01286 01287 if (NestTy) { 01288 Instruction *Caller = CS.getInstruction(); 01289 std::vector<Value*> NewArgs; 01290 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1); 01291 01292 SmallVector<AttributeSet, 8> NewAttrs; 01293 NewAttrs.reserve(Attrs.getNumSlots() + 1); 01294 01295 // Insert the nest argument into the call argument list, which may 01296 // mean appending it. Likewise for attributes. 01297 01298 // Add any result attributes. 01299 if (Attrs.hasAttributes(AttributeSet::ReturnIndex)) 01300 NewAttrs.push_back(AttributeSet::get(Caller->getContext(), 01301 Attrs.getRetAttributes())); 01302 01303 { 01304 unsigned Idx = 1; 01305 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end(); 01306 do { 01307 if (Idx == NestIdx) { 01308 // Add the chain argument and attributes. 01309 Value *NestVal = Tramp->getArgOperand(2); 01310 if (NestVal->getType() != NestTy) 01311 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest"); 01312 NewArgs.push_back(NestVal); 01313 NewAttrs.push_back(AttributeSet::get(Caller->getContext(), 01314 NestAttr)); 01315 } 01316 01317 if (I == E) 01318 break; 01319 01320 // Add the original argument and attributes. 01321 NewArgs.push_back(*I); 01322 AttributeSet Attr = Attrs.getParamAttributes(Idx); 01323 if (Attr.hasAttributes(Idx)) { 01324 AttrBuilder B(Attr, Idx); 01325 NewAttrs.push_back(AttributeSet::get(Caller->getContext(), 01326 Idx + (Idx >= NestIdx), B)); 01327 } 01328 01329 ++Idx, ++I; 01330 } while (1); 01331 } 01332 01333 // Add any function attributes. 01334 if (Attrs.hasAttributes(AttributeSet::FunctionIndex)) 01335 NewAttrs.push_back(AttributeSet::get(FTy->getContext(), 01336 Attrs.getFnAttributes())); 01337 01338 // The trampoline may have been bitcast to a bogus type (FTy). 01339 // Handle this by synthesizing a new function type, equal to FTy 01340 // with the chain parameter inserted. 01341 01342 std::vector<Type*> NewTypes; 01343 NewTypes.reserve(FTy->getNumParams()+1); 01344 01345 // Insert the chain's type into the list of parameter types, which may 01346 // mean appending it. 01347 { 01348 unsigned Idx = 1; 01349 FunctionType::param_iterator I = FTy->param_begin(), 01350 E = FTy->param_end(); 01351 01352 do { 01353 if (Idx == NestIdx) 01354 // Add the chain's type. 01355 NewTypes.push_back(NestTy); 01356 01357 if (I == E) 01358 break; 01359 01360 // Add the original type. 01361 NewTypes.push_back(*I); 01362 01363 ++Idx, ++I; 01364 } while (1); 01365 } 01366 01367 // Replace the trampoline call with a direct call. Let the generic 01368 // code sort out any function type mismatches. 01369 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes, 01370 FTy->isVarArg()); 01371 Constant *NewCallee = 01372 NestF->getType() == PointerType::getUnqual(NewFTy) ? 01373 NestF : ConstantExpr::getBitCast(NestF, 01374 PointerType::getUnqual(NewFTy)); 01375 const AttributeSet &NewPAL = 01376 AttributeSet::get(FTy->getContext(), NewAttrs); 01377 01378 Instruction *NewCaller; 01379 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) { 01380 NewCaller = InvokeInst::Create(NewCallee, 01381 II->getNormalDest(), II->getUnwindDest(), 01382 NewArgs); 01383 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv()); 01384 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL); 01385 } else { 01386 NewCaller = CallInst::Create(NewCallee, NewArgs); 01387 if (cast<CallInst>(Caller)->isTailCall()) 01388 cast<CallInst>(NewCaller)->setTailCall(); 01389 cast<CallInst>(NewCaller)-> 01390 setCallingConv(cast<CallInst>(Caller)->getCallingConv()); 01391 cast<CallInst>(NewCaller)->setAttributes(NewPAL); 01392 } 01393 01394 return NewCaller; 01395 } 01396 } 01397 01398 // Replace the trampoline call with a direct call. Since there is no 'nest' 01399 // parameter, there is no need to adjust the argument list. Let the generic 01400 // code sort out any function type mismatches. 01401 Constant *NewCallee = 01402 NestF->getType() == PTy ? NestF : 01403 ConstantExpr::getBitCast(NestF, PTy); 01404 CS.setCalledFunction(NewCallee); 01405 return CS.getInstruction(); 01406 }