ScalarReplAggregates.cpp revision b2fd770136b92637c5f084b743eab29f910288d5
1//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===// 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 transformation implements the well known scalar replacement of 11// aggregates transformation. This xform breaks up alloca instructions of 12// aggregate type (structure or array) into individual alloca instructions for 13// each member (if possible). Then, if possible, it transforms the individual 14// alloca instructions into nice clean scalar SSA form. 15// 16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because 17// often interact, especially for C++ programs. As such, iterating between 18// SRoA, then Mem2Reg until we run out of things to promote works well. 19// 20//===----------------------------------------------------------------------===// 21 22#define DEBUG_TYPE "scalarrepl" 23#include "llvm/Transforms/Scalar.h" 24#include "llvm/Constants.h" 25#include "llvm/DerivedTypes.h" 26#include "llvm/Function.h" 27#include "llvm/GlobalVariable.h" 28#include "llvm/Instructions.h" 29#include "llvm/IntrinsicInst.h" 30#include "llvm/LLVMContext.h" 31#include "llvm/Module.h" 32#include "llvm/Pass.h" 33#include "llvm/Analysis/Dominators.h" 34#include "llvm/Analysis/Loads.h" 35#include "llvm/Analysis/ValueTracking.h" 36#include "llvm/Target/TargetData.h" 37#include "llvm/Transforms/Utils/PromoteMemToReg.h" 38#include "llvm/Transforms/Utils/Local.h" 39#include "llvm/Transforms/Utils/SSAUpdater.h" 40#include "llvm/Support/CallSite.h" 41#include "llvm/Support/Debug.h" 42#include "llvm/Support/ErrorHandling.h" 43#include "llvm/Support/GetElementPtrTypeIterator.h" 44#include "llvm/Support/IRBuilder.h" 45#include "llvm/Support/MathExtras.h" 46#include "llvm/Support/raw_ostream.h" 47#include "llvm/ADT/SetVector.h" 48#include "llvm/ADT/SmallVector.h" 49#include "llvm/ADT/Statistic.h" 50using namespace llvm; 51 52STATISTIC(NumReplaced, "Number of allocas broken up"); 53STATISTIC(NumPromoted, "Number of allocas promoted"); 54STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion"); 55STATISTIC(NumConverted, "Number of aggregates converted to scalar"); 56STATISTIC(NumGlobals, "Number of allocas copied from constant global"); 57 58namespace { 59 struct SROA : public FunctionPass { 60 SROA(int T, bool hasDT, char &ID) 61 : FunctionPass(ID), HasDomTree(hasDT) { 62 if (T == -1) 63 SRThreshold = 128; 64 else 65 SRThreshold = T; 66 } 67 68 bool runOnFunction(Function &F); 69 70 bool performScalarRepl(Function &F); 71 bool performPromotion(Function &F); 72 73 private: 74 bool HasDomTree; 75 TargetData *TD; 76 77 /// DeadInsts - Keep track of instructions we have made dead, so that 78 /// we can remove them after we are done working. 79 SmallVector<Value*, 32> DeadInsts; 80 81 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures 82 /// information about the uses. All these fields are initialized to false 83 /// and set to true when something is learned. 84 struct AllocaInfo { 85 /// The alloca to promote. 86 AllocaInst *AI; 87 88 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite 89 /// looping and avoid redundant work. 90 SmallPtrSet<PHINode*, 8> CheckedPHIs; 91 92 /// isUnsafe - This is set to true if the alloca cannot be SROA'd. 93 bool isUnsafe : 1; 94 95 /// isMemCpySrc - This is true if this aggregate is memcpy'd from. 96 bool isMemCpySrc : 1; 97 98 /// isMemCpyDst - This is true if this aggregate is memcpy'd into. 99 bool isMemCpyDst : 1; 100 101 /// hasSubelementAccess - This is true if a subelement of the alloca is 102 /// ever accessed, or false if the alloca is only accessed with mem 103 /// intrinsics or load/store that only access the entire alloca at once. 104 bool hasSubelementAccess : 1; 105 106 /// hasALoadOrStore - This is true if there are any loads or stores to it. 107 /// The alloca may just be accessed with memcpy, for example, which would 108 /// not set this. 109 bool hasALoadOrStore : 1; 110 111 explicit AllocaInfo(AllocaInst *ai) 112 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false), 113 hasSubelementAccess(false), hasALoadOrStore(false) {} 114 }; 115 116 unsigned SRThreshold; 117 118 void MarkUnsafe(AllocaInfo &I, Instruction *User) { 119 I.isUnsafe = true; 120 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n'); 121 } 122 123 bool isSafeAllocaToScalarRepl(AllocaInst *AI); 124 125 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info); 126 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset, 127 AllocaInfo &Info); 128 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info); 129 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize, 130 const Type *MemOpType, bool isStore, AllocaInfo &Info, 131 Instruction *TheAccess, bool AllowWholeAccess); 132 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size); 133 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset, 134 const Type *&IdxTy); 135 136 void DoScalarReplacement(AllocaInst *AI, 137 std::vector<AllocaInst*> &WorkList); 138 void DeleteDeadInstructions(); 139 140 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset, 141 SmallVector<AllocaInst*, 32> &NewElts); 142 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset, 143 SmallVector<AllocaInst*, 32> &NewElts); 144 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset, 145 SmallVector<AllocaInst*, 32> &NewElts); 146 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst, 147 AllocaInst *AI, 148 SmallVector<AllocaInst*, 32> &NewElts); 149 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI, 150 SmallVector<AllocaInst*, 32> &NewElts); 151 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI, 152 SmallVector<AllocaInst*, 32> &NewElts); 153 154 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI); 155 }; 156 157 // SROA_DT - SROA that uses DominatorTree. 158 struct SROA_DT : public SROA { 159 static char ID; 160 public: 161 SROA_DT(int T = -1) : SROA(T, true, ID) { 162 initializeSROA_DTPass(*PassRegistry::getPassRegistry()); 163 } 164 165 // getAnalysisUsage - This pass does not require any passes, but we know it 166 // will not alter the CFG, so say so. 167 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 168 AU.addRequired<DominatorTree>(); 169 AU.setPreservesCFG(); 170 } 171 }; 172 173 // SROA_SSAUp - SROA that uses SSAUpdater. 174 struct SROA_SSAUp : public SROA { 175 static char ID; 176 public: 177 SROA_SSAUp(int T = -1) : SROA(T, false, ID) { 178 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry()); 179 } 180 181 // getAnalysisUsage - This pass does not require any passes, but we know it 182 // will not alter the CFG, so say so. 183 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 184 AU.setPreservesCFG(); 185 } 186 }; 187 188} 189 190char SROA_DT::ID = 0; 191char SROA_SSAUp::ID = 0; 192 193INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl", 194 "Scalar Replacement of Aggregates (DT)", false, false) 195INITIALIZE_PASS_DEPENDENCY(DominatorTree) 196INITIALIZE_PASS_END(SROA_DT, "scalarrepl", 197 "Scalar Replacement of Aggregates (DT)", false, false) 198 199INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa", 200 "Scalar Replacement of Aggregates (SSAUp)", false, false) 201INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa", 202 "Scalar Replacement of Aggregates (SSAUp)", false, false) 203 204// Public interface to the ScalarReplAggregates pass 205FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold, 206 bool UseDomTree) { 207 if (UseDomTree) 208 return new SROA_DT(Threshold); 209 return new SROA_SSAUp(Threshold); 210} 211 212 213//===----------------------------------------------------------------------===// 214// Convert To Scalar Optimization. 215//===----------------------------------------------------------------------===// 216 217namespace { 218/// ConvertToScalarInfo - This class implements the "Convert To Scalar" 219/// optimization, which scans the uses of an alloca and determines if it can 220/// rewrite it in terms of a single new alloca that can be mem2reg'd. 221class ConvertToScalarInfo { 222 /// AllocaSize - The size of the alloca being considered. 223 unsigned AllocaSize; 224 const TargetData &TD; 225 226 /// IsNotTrivial - This is set to true if there is some access to the object 227 /// which means that mem2reg can't promote it. 228 bool IsNotTrivial; 229 230 /// VectorTy - This tracks the type that we should promote the vector to if 231 /// it is possible to turn it into a vector. This starts out null, and if it 232 /// isn't possible to turn into a vector type, it gets set to VoidTy. 233 const Type *VectorTy; 234 235 /// HadAVector - True if there is at least one vector access to the alloca. 236 /// We don't want to turn random arrays into vectors and use vector element 237 /// insert/extract, but if there are element accesses to something that is 238 /// also declared as a vector, we do want to promote to a vector. 239 bool HadAVector; 240 241public: 242 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td) 243 : AllocaSize(Size), TD(td) { 244 IsNotTrivial = false; 245 VectorTy = 0; 246 HadAVector = false; 247 } 248 249 AllocaInst *TryConvert(AllocaInst *AI); 250 251private: 252 bool CanConvertToScalar(Value *V, uint64_t Offset); 253 void MergeInType(const Type *In, uint64_t Offset); 254 bool MergeInVectorType(const VectorType *VInTy, uint64_t Offset); 255 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset); 256 257 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType, 258 uint64_t Offset, IRBuilder<> &Builder); 259 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal, 260 uint64_t Offset, IRBuilder<> &Builder); 261}; 262} // end anonymous namespace. 263 264 265/// TryConvert - Analyze the specified alloca, and if it is safe to do so, 266/// rewrite it to be a new alloca which is mem2reg'able. This returns the new 267/// alloca if possible or null if not. 268AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) { 269 // If we can't convert this scalar, or if mem2reg can trivially do it, bail 270 // out. 271 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial) 272 return 0; 273 274 // If we were able to find a vector type that can handle this with 275 // insert/extract elements, and if there was at least one use that had 276 // a vector type, promote this to a vector. We don't want to promote 277 // random stuff that doesn't use vectors (e.g. <9 x double>) because then 278 // we just get a lot of insert/extracts. If at least one vector is 279 // involved, then we probably really do have a union of vector/array. 280 const Type *NewTy; 281 if (VectorTy && VectorTy->isVectorTy() && HadAVector) { 282 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = " 283 << *VectorTy << '\n'); 284 NewTy = VectorTy; // Use the vector type. 285 } else { 286 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n"); 287 // Create and insert the integer alloca. 288 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8); 289 } 290 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin()); 291 ConvertUsesToScalar(AI, NewAI, 0); 292 return NewAI; 293} 294 295/// MergeInType - Add the 'In' type to the accumulated vector type (VectorTy) 296/// so far at the offset specified by Offset (which is specified in bytes). 297/// 298/// There are three cases we handle here: 299/// 1) A union of vector types of the same size and potentially its elements. 300/// Here we turn element accesses into insert/extract element operations. 301/// This promotes a <4 x float> with a store of float to the third element 302/// into a <4 x float> that uses insert element. 303/// 2) A union of vector types with power-of-2 size differences, e.g. a float, 304/// <2 x float> and <4 x float>. Here we turn element accesses into insert 305/// and extract element operations, and <2 x float> accesses into a cast to 306/// <2 x double>, an extract, and a cast back to <2 x float>. 307/// 3) A fully general blob of memory, which we turn into some (potentially 308/// large) integer type with extract and insert operations where the loads 309/// and stores would mutate the memory. We mark this by setting VectorTy 310/// to VoidTy. 311void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) { 312 // If we already decided to turn this into a blob of integer memory, there is 313 // nothing to be done. 314 if (VectorTy && VectorTy->isVoidTy()) 315 return; 316 317 // If this could be contributing to a vector, analyze it. 318 319 // If the In type is a vector that is the same size as the alloca, see if it 320 // matches the existing VecTy. 321 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) { 322 if (MergeInVectorType(VInTy, Offset)) 323 return; 324 } else if (In->isFloatTy() || In->isDoubleTy() || 325 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 && 326 isPowerOf2_32(In->getPrimitiveSizeInBits()))) { 327 // If we're accessing something that could be an element of a vector, see 328 // if the implied vector agrees with what we already have and if Offset is 329 // compatible with it. 330 unsigned EltSize = In->getPrimitiveSizeInBits()/8; 331 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 && 332 (VectorTy == 0 || 333 cast<VectorType>(VectorTy)->getElementType() 334 ->getPrimitiveSizeInBits()/8 == EltSize)) { 335 if (VectorTy == 0) 336 VectorTy = VectorType::get(In, AllocaSize/EltSize); 337 return; 338 } 339 } 340 341 // Otherwise, we have a case that we can't handle with an optimized vector 342 // form. We can still turn this into a large integer. 343 VectorTy = Type::getVoidTy(In->getContext()); 344} 345 346/// MergeInVectorType - Handles the vector case of MergeInType, returning true 347/// if the type was successfully merged and false otherwise. 348bool ConvertToScalarInfo::MergeInVectorType(const VectorType *VInTy, 349 uint64_t Offset) { 350 // Remember if we saw a vector type. 351 HadAVector = true; 352 353 // TODO: Support nonzero offsets? 354 if (Offset != 0) 355 return false; 356 357 // Only allow vectors that are a power-of-2 away from the size of the alloca. 358 if (!isPowerOf2_64(AllocaSize / (VInTy->getBitWidth() / 8))) 359 return false; 360 361 // If this the first vector we see, remember the type so that we know the 362 // element size. 363 if (!VectorTy) { 364 VectorTy = VInTy; 365 return true; 366 } 367 368 unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth(); 369 unsigned InBitWidth = VInTy->getBitWidth(); 370 371 // Vectors of the same size can be converted using a simple bitcast. 372 if (InBitWidth == BitWidth && AllocaSize == (InBitWidth / 8)) 373 return true; 374 375 const Type *ElementTy = cast<VectorType>(VectorTy)->getElementType(); 376 const Type *InElementTy = cast<VectorType>(VectorTy)->getElementType(); 377 378 // Do not allow mixed integer and floating-point accesses from vectors of 379 // different sizes. 380 if (ElementTy->isFloatingPointTy() != InElementTy->isFloatingPointTy()) 381 return false; 382 383 if (ElementTy->isFloatingPointTy()) { 384 // Only allow floating-point vectors of different sizes if they have the 385 // same element type. 386 // TODO: This could be loosened a bit, but would anything benefit? 387 if (ElementTy != InElementTy) 388 return false; 389 390 // There are no arbitrary-precision floating-point types, which limits the 391 // number of legal vector types with larger element types that we can form 392 // to bitcast and extract a subvector. 393 // TODO: We could support some more cases with mixed fp128 and double here. 394 if (!(BitWidth == 64 || BitWidth == 128) || 395 !(InBitWidth == 64 || InBitWidth == 128)) 396 return false; 397 } else { 398 assert(ElementTy->isIntegerTy() && "Vector elements must be either integer " 399 "or floating-point."); 400 unsigned BitWidth = ElementTy->getPrimitiveSizeInBits(); 401 unsigned InBitWidth = InElementTy->getPrimitiveSizeInBits(); 402 403 // Do not allow integer types smaller than a byte or types whose widths are 404 // not a multiple of a byte. 405 if (BitWidth < 8 || InBitWidth < 8 || 406 BitWidth % 8 != 0 || InBitWidth % 8 != 0) 407 return false; 408 } 409 410 // Pick the largest of the two vector types. 411 if (InBitWidth > BitWidth) 412 VectorTy = VInTy; 413 414 return true; 415} 416 417/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all 418/// its accesses to a single vector type, return true and set VecTy to 419/// the new type. If we could convert the alloca into a single promotable 420/// integer, return true but set VecTy to VoidTy. Further, if the use is not a 421/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset 422/// is the current offset from the base of the alloca being analyzed. 423/// 424/// If we see at least one access to the value that is as a vector type, set the 425/// SawVec flag. 426bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) { 427 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) { 428 Instruction *User = cast<Instruction>(*UI); 429 430 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 431 // Don't break volatile loads. 432 if (LI->isVolatile()) 433 return false; 434 // Don't touch MMX operations. 435 if (LI->getType()->isX86_MMXTy()) 436 return false; 437 MergeInType(LI->getType(), Offset); 438 continue; 439 } 440 441 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 442 // Storing the pointer, not into the value? 443 if (SI->getOperand(0) == V || SI->isVolatile()) return false; 444 // Don't touch MMX operations. 445 if (SI->getOperand(0)->getType()->isX86_MMXTy()) 446 return false; 447 MergeInType(SI->getOperand(0)->getType(), Offset); 448 continue; 449 } 450 451 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) { 452 IsNotTrivial = true; // Can't be mem2reg'd. 453 if (!CanConvertToScalar(BCI, Offset)) 454 return false; 455 continue; 456 } 457 458 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) { 459 // If this is a GEP with a variable indices, we can't handle it. 460 if (!GEP->hasAllConstantIndices()) 461 return false; 462 463 // Compute the offset that this GEP adds to the pointer. 464 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end()); 465 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(), 466 &Indices[0], Indices.size()); 467 // See if all uses can be converted. 468 if (!CanConvertToScalar(GEP, Offset+GEPOffset)) 469 return false; 470 IsNotTrivial = true; // Can't be mem2reg'd. 471 continue; 472 } 473 474 // If this is a constant sized memset of a constant value (e.g. 0) we can 475 // handle it. 476 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) { 477 // Store of constant value and constant size. 478 if (!isa<ConstantInt>(MSI->getValue()) || 479 !isa<ConstantInt>(MSI->getLength())) 480 return false; 481 IsNotTrivial = true; // Can't be mem2reg'd. 482 continue; 483 } 484 485 // If this is a memcpy or memmove into or out of the whole allocation, we 486 // can handle it like a load or store of the scalar type. 487 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) { 488 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()); 489 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0) 490 return false; 491 492 IsNotTrivial = true; // Can't be mem2reg'd. 493 continue; 494 } 495 496 // Otherwise, we cannot handle this! 497 return false; 498 } 499 500 return true; 501} 502 503/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca 504/// directly. This happens when we are converting an "integer union" to a 505/// single integer scalar, or when we are converting a "vector union" to a 506/// vector with insert/extractelement instructions. 507/// 508/// Offset is an offset from the original alloca, in bits that need to be 509/// shifted to the right. By the end of this, there should be no uses of Ptr. 510void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, 511 uint64_t Offset) { 512 while (!Ptr->use_empty()) { 513 Instruction *User = cast<Instruction>(Ptr->use_back()); 514 515 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) { 516 ConvertUsesToScalar(CI, NewAI, Offset); 517 CI->eraseFromParent(); 518 continue; 519 } 520 521 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) { 522 // Compute the offset that this GEP adds to the pointer. 523 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end()); 524 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(), 525 &Indices[0], Indices.size()); 526 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8); 527 GEP->eraseFromParent(); 528 continue; 529 } 530 531 IRBuilder<> Builder(User); 532 533 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 534 // The load is a bit extract from NewAI shifted right by Offset bits. 535 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp"); 536 Value *NewLoadVal 537 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder); 538 LI->replaceAllUsesWith(NewLoadVal); 539 LI->eraseFromParent(); 540 continue; 541 } 542 543 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 544 assert(SI->getOperand(0) != Ptr && "Consistency error!"); 545 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in"); 546 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset, 547 Builder); 548 Builder.CreateStore(New, NewAI); 549 SI->eraseFromParent(); 550 551 // If the load we just inserted is now dead, then the inserted store 552 // overwrote the entire thing. 553 if (Old->use_empty()) 554 Old->eraseFromParent(); 555 continue; 556 } 557 558 // If this is a constant sized memset of a constant value (e.g. 0) we can 559 // transform it into a store of the expanded constant value. 560 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) { 561 assert(MSI->getRawDest() == Ptr && "Consistency error!"); 562 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue(); 563 if (NumBytes != 0) { 564 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue(); 565 566 // Compute the value replicated the right number of times. 567 APInt APVal(NumBytes*8, Val); 568 569 // Splat the value if non-zero. 570 if (Val) 571 for (unsigned i = 1; i != NumBytes; ++i) 572 APVal |= APVal << 8; 573 574 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in"); 575 Value *New = ConvertScalar_InsertValue( 576 ConstantInt::get(User->getContext(), APVal), 577 Old, Offset, Builder); 578 Builder.CreateStore(New, NewAI); 579 580 // If the load we just inserted is now dead, then the memset overwrote 581 // the entire thing. 582 if (Old->use_empty()) 583 Old->eraseFromParent(); 584 } 585 MSI->eraseFromParent(); 586 continue; 587 } 588 589 // If this is a memcpy or memmove into or out of the whole allocation, we 590 // can handle it like a load or store of the scalar type. 591 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) { 592 assert(Offset == 0 && "must be store to start of alloca"); 593 594 // If the source and destination are both to the same alloca, then this is 595 // a noop copy-to-self, just delete it. Otherwise, emit a load and store 596 // as appropriate. 597 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0)); 598 599 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) { 600 // Dest must be OrigAI, change this to be a load from the original 601 // pointer (bitcasted), then a store to our new alloca. 602 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?"); 603 Value *SrcPtr = MTI->getSource(); 604 const PointerType* SPTy = cast<PointerType>(SrcPtr->getType()); 605 const PointerType* AIPTy = cast<PointerType>(NewAI->getType()); 606 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) { 607 AIPTy = PointerType::get(AIPTy->getElementType(), 608 SPTy->getAddressSpace()); 609 } 610 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy); 611 612 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval"); 613 SrcVal->setAlignment(MTI->getAlignment()); 614 Builder.CreateStore(SrcVal, NewAI); 615 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) { 616 // Src must be OrigAI, change this to be a load from NewAI then a store 617 // through the original dest pointer (bitcasted). 618 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?"); 619 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval"); 620 621 const PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType()); 622 const PointerType* AIPTy = cast<PointerType>(NewAI->getType()); 623 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) { 624 AIPTy = PointerType::get(AIPTy->getElementType(), 625 DPTy->getAddressSpace()); 626 } 627 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy); 628 629 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr); 630 NewStore->setAlignment(MTI->getAlignment()); 631 } else { 632 // Noop transfer. Src == Dst 633 } 634 635 MTI->eraseFromParent(); 636 continue; 637 } 638 639 llvm_unreachable("Unsupported operation!"); 640 } 641} 642 643/// getScaledElementType - Gets a scaled element type for a partial vector 644/// access of an alloca. The input type must be an integer or float, and 645/// the resulting type must be an integer, float or double. 646static const Type *getScaledElementType(const Type *OldTy, unsigned Scale) { 647 assert((OldTy->isIntegerTy() || OldTy->isFloatTy()) && "Partial vector " 648 "accesses must be scaled from integer or float elements."); 649 650 LLVMContext &Context = OldTy->getContext(); 651 unsigned Size = OldTy->getPrimitiveSizeInBits() * Scale; 652 653 if (OldTy->isIntegerTy()) 654 return Type::getIntNTy(Context, Size); 655 if (Size == 32) 656 return Type::getFloatTy(Context); 657 if (Size == 64) 658 return Type::getDoubleTy(Context); 659 660 llvm_unreachable("Invalid type for a partial vector access of an alloca!"); 661} 662 663/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer 664/// or vector value FromVal, extracting the bits from the offset specified by 665/// Offset. This returns the value, which is of type ToType. 666/// 667/// This happens when we are converting an "integer union" to a single 668/// integer scalar, or when we are converting a "vector union" to a vector with 669/// insert/extractelement instructions. 670/// 671/// Offset is an offset from the original alloca, in bits that need to be 672/// shifted to the right. 673Value *ConvertToScalarInfo:: 674ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType, 675 uint64_t Offset, IRBuilder<> &Builder) { 676 // If the load is of the whole new alloca, no conversion is needed. 677 if (FromVal->getType() == ToType && Offset == 0) 678 return FromVal; 679 680 // If the result alloca is a vector type, this is either an element 681 // access or a bitcast to another vector type of the same size. 682 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) { 683 if (ToType->isVectorTy()) { 684 if (isPowerOf2_64(AllocaSize / TD.getTypeAllocSize(ToType))) { 685 assert(Offset == 0 && "Can't extract a value of a smaller vector type " 686 "from a nonzero offset."); 687 688 const Type *ToElementTy = cast<VectorType>(ToType)->getElementType(); 689 unsigned Scale = AllocaSize / TD.getTypeAllocSize(ToType); 690 const Type *CastElementTy = getScaledElementType(ToElementTy, Scale); 691 unsigned NumCastVectorElements = VTy->getNumElements() / Scale; 692 693 LLVMContext &Context = FromVal->getContext(); 694 const Type *CastTy = VectorType::get(CastElementTy, 695 NumCastVectorElements); 696 Value *Cast = Builder.CreateBitCast(FromVal, CastTy, "tmp"); 697 Value *Extract = Builder.CreateExtractElement(Cast, ConstantInt::get( 698 Type::getInt32Ty(Context), 0), "tmp"); 699 return Builder.CreateBitCast(Extract, ToType, "tmp"); 700 } 701 702 return Builder.CreateBitCast(FromVal, ToType, "tmp"); 703 } 704 705 // Otherwise it must be an element access. 706 unsigned Elt = 0; 707 if (Offset) { 708 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType()); 709 Elt = Offset/EltSize; 710 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking"); 711 } 712 // Return the element extracted out of it. 713 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get( 714 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp"); 715 if (V->getType() != ToType) 716 V = Builder.CreateBitCast(V, ToType, "tmp"); 717 return V; 718 } 719 720 // If ToType is a first class aggregate, extract out each of the pieces and 721 // use insertvalue's to form the FCA. 722 if (const StructType *ST = dyn_cast<StructType>(ToType)) { 723 const StructLayout &Layout = *TD.getStructLayout(ST); 724 Value *Res = UndefValue::get(ST); 725 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) { 726 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i), 727 Offset+Layout.getElementOffsetInBits(i), 728 Builder); 729 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp"); 730 } 731 return Res; 732 } 733 734 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) { 735 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType()); 736 Value *Res = UndefValue::get(AT); 737 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { 738 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(), 739 Offset+i*EltSize, Builder); 740 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp"); 741 } 742 return Res; 743 } 744 745 // Otherwise, this must be a union that was converted to an integer value. 746 const IntegerType *NTy = cast<IntegerType>(FromVal->getType()); 747 748 // If this is a big-endian system and the load is narrower than the 749 // full alloca type, we need to do a shift to get the right bits. 750 int ShAmt = 0; 751 if (TD.isBigEndian()) { 752 // On big-endian machines, the lowest bit is stored at the bit offset 753 // from the pointer given by getTypeStoreSizeInBits. This matters for 754 // integers with a bitwidth that is not a multiple of 8. 755 ShAmt = TD.getTypeStoreSizeInBits(NTy) - 756 TD.getTypeStoreSizeInBits(ToType) - Offset; 757 } else { 758 ShAmt = Offset; 759 } 760 761 // Note: we support negative bitwidths (with shl) which are not defined. 762 // We do this to support (f.e.) loads off the end of a structure where 763 // only some bits are used. 764 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth()) 765 FromVal = Builder.CreateLShr(FromVal, 766 ConstantInt::get(FromVal->getType(), 767 ShAmt), "tmp"); 768 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth()) 769 FromVal = Builder.CreateShl(FromVal, 770 ConstantInt::get(FromVal->getType(), 771 -ShAmt), "tmp"); 772 773 // Finally, unconditionally truncate the integer to the right width. 774 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType); 775 if (LIBitWidth < NTy->getBitWidth()) 776 FromVal = 777 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(), 778 LIBitWidth), "tmp"); 779 else if (LIBitWidth > NTy->getBitWidth()) 780 FromVal = 781 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(), 782 LIBitWidth), "tmp"); 783 784 // If the result is an integer, this is a trunc or bitcast. 785 if (ToType->isIntegerTy()) { 786 // Should be done. 787 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) { 788 // Just do a bitcast, we know the sizes match up. 789 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp"); 790 } else { 791 // Otherwise must be a pointer. 792 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp"); 793 } 794 assert(FromVal->getType() == ToType && "Didn't convert right?"); 795 return FromVal; 796} 797 798/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer 799/// or vector value "Old" at the offset specified by Offset. 800/// 801/// This happens when we are converting an "integer union" to a 802/// single integer scalar, or when we are converting a "vector union" to a 803/// vector with insert/extractelement instructions. 804/// 805/// Offset is an offset from the original alloca, in bits that need to be 806/// shifted to the right. 807Value *ConvertToScalarInfo:: 808ConvertScalar_InsertValue(Value *SV, Value *Old, 809 uint64_t Offset, IRBuilder<> &Builder) { 810 // Convert the stored type to the actual type, shift it left to insert 811 // then 'or' into place. 812 const Type *AllocaType = Old->getType(); 813 LLVMContext &Context = Old->getContext(); 814 815 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) { 816 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy); 817 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType()); 818 819 // Changing the whole vector with memset or with an access of a different 820 // vector type? 821 if (ValSize == VecSize) 822 return Builder.CreateBitCast(SV, AllocaType, "tmp"); 823 824 if (SV->getType()->isVectorTy() && isPowerOf2_64(VecSize / ValSize)) { 825 assert(Offset == 0 && "Can't insert a value of a smaller vector type at " 826 "a nonzero offset."); 827 828 const Type *ToElementTy = 829 cast<VectorType>(SV->getType())->getElementType(); 830 unsigned Scale = VecSize / ValSize; 831 const Type *CastElementTy = getScaledElementType(ToElementTy, Scale); 832 unsigned NumCastVectorElements = VTy->getNumElements() / Scale; 833 834 LLVMContext &Context = SV->getContext(); 835 const Type *OldCastTy = VectorType::get(CastElementTy, 836 NumCastVectorElements); 837 Value *OldCast = Builder.CreateBitCast(Old, OldCastTy, "tmp"); 838 839 Value *SVCast = Builder.CreateBitCast(SV, CastElementTy, "tmp"); 840 Value *Insert = 841 Builder.CreateInsertElement(OldCast, SVCast, ConstantInt::get( 842 Type::getInt32Ty(Context), 0), "tmp"); 843 return Builder.CreateBitCast(Insert, AllocaType, "tmp"); 844 } 845 846 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType()); 847 848 // Must be an element insertion. 849 unsigned Elt = Offset/EltSize; 850 851 if (SV->getType() != VTy->getElementType()) 852 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp"); 853 854 SV = Builder.CreateInsertElement(Old, SV, 855 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt), 856 "tmp"); 857 return SV; 858 } 859 860 // If SV is a first-class aggregate value, insert each value recursively. 861 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) { 862 const StructLayout &Layout = *TD.getStructLayout(ST); 863 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) { 864 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp"); 865 Old = ConvertScalar_InsertValue(Elt, Old, 866 Offset+Layout.getElementOffsetInBits(i), 867 Builder); 868 } 869 return Old; 870 } 871 872 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) { 873 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType()); 874 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { 875 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp"); 876 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder); 877 } 878 return Old; 879 } 880 881 // If SV is a float, convert it to the appropriate integer type. 882 // If it is a pointer, do the same. 883 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType()); 884 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType); 885 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType()); 886 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType); 887 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy()) 888 SV = Builder.CreateBitCast(SV, 889 IntegerType::get(SV->getContext(),SrcWidth), "tmp"); 890 else if (SV->getType()->isPointerTy()) 891 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp"); 892 893 // Zero extend or truncate the value if needed. 894 if (SV->getType() != AllocaType) { 895 if (SV->getType()->getPrimitiveSizeInBits() < 896 AllocaType->getPrimitiveSizeInBits()) 897 SV = Builder.CreateZExt(SV, AllocaType, "tmp"); 898 else { 899 // Truncation may be needed if storing more than the alloca can hold 900 // (undefined behavior). 901 SV = Builder.CreateTrunc(SV, AllocaType, "tmp"); 902 SrcWidth = DestWidth; 903 SrcStoreWidth = DestStoreWidth; 904 } 905 } 906 907 // If this is a big-endian system and the store is narrower than the 908 // full alloca type, we need to do a shift to get the right bits. 909 int ShAmt = 0; 910 if (TD.isBigEndian()) { 911 // On big-endian machines, the lowest bit is stored at the bit offset 912 // from the pointer given by getTypeStoreSizeInBits. This matters for 913 // integers with a bitwidth that is not a multiple of 8. 914 ShAmt = DestStoreWidth - SrcStoreWidth - Offset; 915 } else { 916 ShAmt = Offset; 917 } 918 919 // Note: we support negative bitwidths (with shr) which are not defined. 920 // We do this to support (f.e.) stores off the end of a structure where 921 // only some bits in the structure are set. 922 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth)); 923 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) { 924 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), 925 ShAmt), "tmp"); 926 Mask <<= ShAmt; 927 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) { 928 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), 929 -ShAmt), "tmp"); 930 Mask = Mask.lshr(-ShAmt); 931 } 932 933 // Mask out the bits we are about to insert from the old value, and or 934 // in the new bits. 935 if (SrcWidth != DestWidth) { 936 assert(DestWidth > SrcWidth); 937 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask"); 938 SV = Builder.CreateOr(Old, SV, "ins"); 939 } 940 return SV; 941} 942 943 944//===----------------------------------------------------------------------===// 945// SRoA Driver 946//===----------------------------------------------------------------------===// 947 948 949bool SROA::runOnFunction(Function &F) { 950 TD = getAnalysisIfAvailable<TargetData>(); 951 952 bool Changed = performPromotion(F); 953 954 // FIXME: ScalarRepl currently depends on TargetData more than it 955 // theoretically needs to. It should be refactored in order to support 956 // target-independent IR. Until this is done, just skip the actual 957 // scalar-replacement portion of this pass. 958 if (!TD) return Changed; 959 960 while (1) { 961 bool LocalChange = performScalarRepl(F); 962 if (!LocalChange) break; // No need to repromote if no scalarrepl 963 Changed = true; 964 LocalChange = performPromotion(F); 965 if (!LocalChange) break; // No need to re-scalarrepl if no promotion 966 } 967 968 return Changed; 969} 970 971namespace { 972class AllocaPromoter : public LoadAndStorePromoter { 973 AllocaInst *AI; 974public: 975 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S) 976 : LoadAndStorePromoter(Insts, S), AI(0) {} 977 978 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) { 979 // Remember which alloca we're promoting (for isInstInList). 980 this->AI = AI; 981 LoadAndStorePromoter::run(Insts); 982 AI->eraseFromParent(); 983 } 984 985 virtual bool isInstInList(Instruction *I, 986 const SmallVectorImpl<Instruction*> &Insts) const { 987 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 988 return LI->getOperand(0) == AI; 989 return cast<StoreInst>(I)->getPointerOperand() == AI; 990 } 991}; 992} // end anon namespace 993 994/// isSafeSelectToSpeculate - Select instructions that use an alloca and are 995/// subsequently loaded can be rewritten to load both input pointers and then 996/// select between the result, allowing the load of the alloca to be promoted. 997/// From this: 998/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other 999/// %V = load i32* %P2 1000/// to: 1001/// %V1 = load i32* %Alloca -> will be mem2reg'd 1002/// %V2 = load i32* %Other 1003/// %V = select i1 %cond, i32 %V1, i32 %V2 1004/// 1005/// We can do this to a select if its only uses are loads and if the operand to 1006/// the select can be loaded unconditionally. 1007static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) { 1008 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer(); 1009 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer(); 1010 1011 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end(); 1012 UI != UE; ++UI) { 1013 LoadInst *LI = dyn_cast<LoadInst>(*UI); 1014 if (LI == 0 || LI->isVolatile()) return false; 1015 1016 // Both operands to the select need to be dereferencable, either absolutely 1017 // (e.g. allocas) or at this point because we can see other accesses to it. 1018 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI, 1019 LI->getAlignment(), TD)) 1020 return false; 1021 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI, 1022 LI->getAlignment(), TD)) 1023 return false; 1024 } 1025 1026 return true; 1027} 1028 1029/// isSafePHIToSpeculate - PHI instructions that use an alloca and are 1030/// subsequently loaded can be rewritten to load both input pointers in the pred 1031/// blocks and then PHI the results, allowing the load of the alloca to be 1032/// promoted. 1033/// From this: 1034/// %P2 = phi [i32* %Alloca, i32* %Other] 1035/// %V = load i32* %P2 1036/// to: 1037/// %V1 = load i32* %Alloca -> will be mem2reg'd 1038/// ... 1039/// %V2 = load i32* %Other 1040/// ... 1041/// %V = phi [i32 %V1, i32 %V2] 1042/// 1043/// We can do this to a select if its only uses are loads and if the operand to 1044/// the select can be loaded unconditionally. 1045static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) { 1046 // For now, we can only do this promotion if the load is in the same block as 1047 // the PHI, and if there are no stores between the phi and load. 1048 // TODO: Allow recursive phi users. 1049 // TODO: Allow stores. 1050 BasicBlock *BB = PN->getParent(); 1051 unsigned MaxAlign = 0; 1052 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end(); 1053 UI != UE; ++UI) { 1054 LoadInst *LI = dyn_cast<LoadInst>(*UI); 1055 if (LI == 0 || LI->isVolatile()) return false; 1056 1057 // For now we only allow loads in the same block as the PHI. This is a 1058 // common case that happens when instcombine merges two loads through a PHI. 1059 if (LI->getParent() != BB) return false; 1060 1061 // Ensure that there are no instructions between the PHI and the load that 1062 // could store. 1063 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI) 1064 if (BBI->mayWriteToMemory()) 1065 return false; 1066 1067 MaxAlign = std::max(MaxAlign, LI->getAlignment()); 1068 } 1069 1070 // Okay, we know that we have one or more loads in the same block as the PHI. 1071 // We can transform this if it is safe to push the loads into the predecessor 1072 // blocks. The only thing to watch out for is that we can't put a possibly 1073 // trapping load in the predecessor if it is a critical edge. 1074 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1075 BasicBlock *Pred = PN->getIncomingBlock(i); 1076 1077 // If the predecessor has a single successor, then the edge isn't critical. 1078 if (Pred->getTerminator()->getNumSuccessors() == 1) 1079 continue; 1080 1081 Value *InVal = PN->getIncomingValue(i); 1082 1083 // If the InVal is an invoke in the pred, we can't put a load on the edge. 1084 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal)) 1085 if (II->getParent() == Pred) 1086 return false; 1087 1088 // If this pointer is always safe to load, or if we can prove that there is 1089 // already a load in the block, then we can move the load to the pred block. 1090 if (InVal->isDereferenceablePointer() || 1091 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD)) 1092 continue; 1093 1094 return false; 1095 } 1096 1097 return true; 1098} 1099 1100 1101/// tryToMakeAllocaBePromotable - This returns true if the alloca only has 1102/// direct (non-volatile) loads and stores to it. If the alloca is close but 1103/// not quite there, this will transform the code to allow promotion. As such, 1104/// it is a non-pure predicate. 1105static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) { 1106 SetVector<Instruction*, SmallVector<Instruction*, 4>, 1107 SmallPtrSet<Instruction*, 4> > InstsToRewrite; 1108 1109 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end(); 1110 UI != UE; ++UI) { 1111 User *U = *UI; 1112 if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 1113 if (LI->isVolatile()) 1114 return false; 1115 continue; 1116 } 1117 1118 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 1119 if (SI->getOperand(0) == AI || SI->isVolatile()) 1120 return false; // Don't allow a store OF the AI, only INTO the AI. 1121 continue; 1122 } 1123 1124 if (SelectInst *SI = dyn_cast<SelectInst>(U)) { 1125 // If the condition being selected on is a constant, fold the select, yes 1126 // this does (rarely) happen early on. 1127 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) { 1128 Value *Result = SI->getOperand(1+CI->isZero()); 1129 SI->replaceAllUsesWith(Result); 1130 SI->eraseFromParent(); 1131 1132 // This is very rare and we just scrambled the use list of AI, start 1133 // over completely. 1134 return tryToMakeAllocaBePromotable(AI, TD); 1135 } 1136 1137 // If it is safe to turn "load (select c, AI, ptr)" into a select of two 1138 // loads, then we can transform this by rewriting the select. 1139 if (!isSafeSelectToSpeculate(SI, TD)) 1140 return false; 1141 1142 InstsToRewrite.insert(SI); 1143 continue; 1144 } 1145 1146 if (PHINode *PN = dyn_cast<PHINode>(U)) { 1147 if (PN->use_empty()) { // Dead PHIs can be stripped. 1148 InstsToRewrite.insert(PN); 1149 continue; 1150 } 1151 1152 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads 1153 // in the pred blocks, then we can transform this by rewriting the PHI. 1154 if (!isSafePHIToSpeculate(PN, TD)) 1155 return false; 1156 1157 InstsToRewrite.insert(PN); 1158 continue; 1159 } 1160 1161 return false; 1162 } 1163 1164 // If there are no instructions to rewrite, then all uses are load/stores and 1165 // we're done! 1166 if (InstsToRewrite.empty()) 1167 return true; 1168 1169 // If we have instructions that need to be rewritten for this to be promotable 1170 // take care of it now. 1171 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) { 1172 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) { 1173 // Selects in InstsToRewrite only have load uses. Rewrite each as two 1174 // loads with a new select. 1175 while (!SI->use_empty()) { 1176 LoadInst *LI = cast<LoadInst>(SI->use_back()); 1177 1178 IRBuilder<> Builder(LI); 1179 LoadInst *TrueLoad = 1180 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t"); 1181 LoadInst *FalseLoad = 1182 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".t"); 1183 1184 // Transfer alignment and TBAA info if present. 1185 TrueLoad->setAlignment(LI->getAlignment()); 1186 FalseLoad->setAlignment(LI->getAlignment()); 1187 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) { 1188 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag); 1189 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag); 1190 } 1191 1192 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad); 1193 V->takeName(LI); 1194 LI->replaceAllUsesWith(V); 1195 LI->eraseFromParent(); 1196 } 1197 1198 // Now that all the loads are gone, the select is gone too. 1199 SI->eraseFromParent(); 1200 continue; 1201 } 1202 1203 // Otherwise, we have a PHI node which allows us to push the loads into the 1204 // predecessors. 1205 PHINode *PN = cast<PHINode>(InstsToRewrite[i]); 1206 if (PN->use_empty()) { 1207 PN->eraseFromParent(); 1208 continue; 1209 } 1210 1211 const Type *LoadTy = cast<PointerType>(PN->getType())->getElementType(); 1212 PHINode *NewPN = PHINode::Create(LoadTy, PN->getName()+".ld", PN); 1213 1214 // Get the TBAA tag and alignment to use from one of the loads. It doesn't 1215 // matter which one we get and if any differ, it doesn't matter. 1216 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back()); 1217 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa); 1218 unsigned Align = SomeLoad->getAlignment(); 1219 1220 // Rewrite all loads of the PN to use the new PHI. 1221 while (!PN->use_empty()) { 1222 LoadInst *LI = cast<LoadInst>(PN->use_back()); 1223 LI->replaceAllUsesWith(NewPN); 1224 LI->eraseFromParent(); 1225 } 1226 1227 // Inject loads into all of the pred blocks. Keep track of which blocks we 1228 // insert them into in case we have multiple edges from the same block. 1229 DenseMap<BasicBlock*, LoadInst*> InsertedLoads; 1230 1231 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1232 BasicBlock *Pred = PN->getIncomingBlock(i); 1233 LoadInst *&Load = InsertedLoads[Pred]; 1234 if (Load == 0) { 1235 Load = new LoadInst(PN->getIncomingValue(i), 1236 PN->getName() + "." + Pred->getName(), 1237 Pred->getTerminator()); 1238 Load->setAlignment(Align); 1239 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag); 1240 } 1241 1242 NewPN->addIncoming(Load, Pred); 1243 } 1244 1245 PN->eraseFromParent(); 1246 } 1247 1248 ++NumAdjusted; 1249 return true; 1250} 1251 1252 1253bool SROA::performPromotion(Function &F) { 1254 std::vector<AllocaInst*> Allocas; 1255 DominatorTree *DT = 0; 1256 if (HasDomTree) 1257 DT = &getAnalysis<DominatorTree>(); 1258 1259 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function 1260 1261 bool Changed = false; 1262 SmallVector<Instruction*, 64> Insts; 1263 while (1) { 1264 Allocas.clear(); 1265 1266 // Find allocas that are safe to promote, by looking at all instructions in 1267 // the entry node 1268 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) 1269 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca? 1270 if (tryToMakeAllocaBePromotable(AI, TD)) 1271 Allocas.push_back(AI); 1272 1273 if (Allocas.empty()) break; 1274 1275 if (HasDomTree) 1276 PromoteMemToReg(Allocas, *DT); 1277 else { 1278 SSAUpdater SSA; 1279 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) { 1280 AllocaInst *AI = Allocas[i]; 1281 1282 // Build list of instructions to promote. 1283 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); 1284 UI != E; ++UI) 1285 Insts.push_back(cast<Instruction>(*UI)); 1286 1287 AllocaPromoter(Insts, SSA).run(AI, Insts); 1288 Insts.clear(); 1289 } 1290 } 1291 NumPromoted += Allocas.size(); 1292 Changed = true; 1293 } 1294 1295 return Changed; 1296} 1297 1298 1299/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for 1300/// SROA. It must be a struct or array type with a small number of elements. 1301static bool ShouldAttemptScalarRepl(AllocaInst *AI) { 1302 const Type *T = AI->getAllocatedType(); 1303 // Do not promote any struct into more than 32 separate vars. 1304 if (const StructType *ST = dyn_cast<StructType>(T)) 1305 return ST->getNumElements() <= 32; 1306 // Arrays are much less likely to be safe for SROA; only consider 1307 // them if they are very small. 1308 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 1309 return AT->getNumElements() <= 8; 1310 return false; 1311} 1312 1313 1314// performScalarRepl - This algorithm is a simple worklist driven algorithm, 1315// which runs on all of the malloc/alloca instructions in the function, removing 1316// them if they are only used by getelementptr instructions. 1317// 1318bool SROA::performScalarRepl(Function &F) { 1319 std::vector<AllocaInst*> WorkList; 1320 1321 // Scan the entry basic block, adding allocas to the worklist. 1322 BasicBlock &BB = F.getEntryBlock(); 1323 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) 1324 if (AllocaInst *A = dyn_cast<AllocaInst>(I)) 1325 WorkList.push_back(A); 1326 1327 // Process the worklist 1328 bool Changed = false; 1329 while (!WorkList.empty()) { 1330 AllocaInst *AI = WorkList.back(); 1331 WorkList.pop_back(); 1332 1333 // Handle dead allocas trivially. These can be formed by SROA'ing arrays 1334 // with unused elements. 1335 if (AI->use_empty()) { 1336 AI->eraseFromParent(); 1337 Changed = true; 1338 continue; 1339 } 1340 1341 // If this alloca is impossible for us to promote, reject it early. 1342 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized()) 1343 continue; 1344 1345 // Check to see if this allocation is only modified by a memcpy/memmove from 1346 // a constant global. If this is the case, we can change all users to use 1347 // the constant global instead. This is commonly produced by the CFE by 1348 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A' 1349 // is only subsequently read. 1350 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) { 1351 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n'); 1352 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n'); 1353 Constant *TheSrc = cast<Constant>(TheCopy->getSource()); 1354 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType())); 1355 TheCopy->eraseFromParent(); // Don't mutate the global. 1356 AI->eraseFromParent(); 1357 ++NumGlobals; 1358 Changed = true; 1359 continue; 1360 } 1361 1362 // Check to see if we can perform the core SROA transformation. We cannot 1363 // transform the allocation instruction if it is an array allocation 1364 // (allocations OF arrays are ok though), and an allocation of a scalar 1365 // value cannot be decomposed at all. 1366 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType()); 1367 1368 // Do not promote [0 x %struct]. 1369 if (AllocaSize == 0) continue; 1370 1371 // Do not promote any struct whose size is too big. 1372 if (AllocaSize > SRThreshold) continue; 1373 1374 // If the alloca looks like a good candidate for scalar replacement, and if 1375 // all its users can be transformed, then split up the aggregate into its 1376 // separate elements. 1377 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) { 1378 DoScalarReplacement(AI, WorkList); 1379 Changed = true; 1380 continue; 1381 } 1382 1383 // If we can turn this aggregate value (potentially with casts) into a 1384 // simple scalar value that can be mem2reg'd into a register value. 1385 // IsNotTrivial tracks whether this is something that mem2reg could have 1386 // promoted itself. If so, we don't want to transform it needlessly. Note 1387 // that we can't just check based on the type: the alloca may be of an i32 1388 // but that has pointer arithmetic to set byte 3 of it or something. 1389 if (AllocaInst *NewAI = 1390 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) { 1391 NewAI->takeName(AI); 1392 AI->eraseFromParent(); 1393 ++NumConverted; 1394 Changed = true; 1395 continue; 1396 } 1397 1398 // Otherwise, couldn't process this alloca. 1399 } 1400 1401 return Changed; 1402} 1403 1404/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl 1405/// predicate, do SROA now. 1406void SROA::DoScalarReplacement(AllocaInst *AI, 1407 std::vector<AllocaInst*> &WorkList) { 1408 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n'); 1409 SmallVector<AllocaInst*, 32> ElementAllocas; 1410 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { 1411 ElementAllocas.reserve(ST->getNumContainedTypes()); 1412 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { 1413 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 1414 AI->getAlignment(), 1415 AI->getName() + "." + Twine(i), AI); 1416 ElementAllocas.push_back(NA); 1417 WorkList.push_back(NA); // Add to worklist for recursive processing 1418 } 1419 } else { 1420 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); 1421 ElementAllocas.reserve(AT->getNumElements()); 1422 const Type *ElTy = AT->getElementType(); 1423 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { 1424 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(), 1425 AI->getName() + "." + Twine(i), AI); 1426 ElementAllocas.push_back(NA); 1427 WorkList.push_back(NA); // Add to worklist for recursive processing 1428 } 1429 } 1430 1431 // Now that we have created the new alloca instructions, rewrite all the 1432 // uses of the old alloca. 1433 RewriteForScalarRepl(AI, AI, 0, ElementAllocas); 1434 1435 // Now erase any instructions that were made dead while rewriting the alloca. 1436 DeleteDeadInstructions(); 1437 AI->eraseFromParent(); 1438 1439 ++NumReplaced; 1440} 1441 1442/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list, 1443/// recursively including all their operands that become trivially dead. 1444void SROA::DeleteDeadInstructions() { 1445 while (!DeadInsts.empty()) { 1446 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val()); 1447 1448 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) 1449 if (Instruction *U = dyn_cast<Instruction>(*OI)) { 1450 // Zero out the operand and see if it becomes trivially dead. 1451 // (But, don't add allocas to the dead instruction list -- they are 1452 // already on the worklist and will be deleted separately.) 1453 *OI = 0; 1454 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U)) 1455 DeadInsts.push_back(U); 1456 } 1457 1458 I->eraseFromParent(); 1459 } 1460} 1461 1462/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to 1463/// performing scalar replacement of alloca AI. The results are flagged in 1464/// the Info parameter. Offset indicates the position within AI that is 1465/// referenced by this instruction. 1466void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset, 1467 AllocaInfo &Info) { 1468 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) { 1469 Instruction *User = cast<Instruction>(*UI); 1470 1471 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) { 1472 isSafeForScalarRepl(BC, Offset, Info); 1473 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { 1474 uint64_t GEPOffset = Offset; 1475 isSafeGEP(GEPI, GEPOffset, Info); 1476 if (!Info.isUnsafe) 1477 isSafeForScalarRepl(GEPI, GEPOffset, Info); 1478 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) { 1479 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength()); 1480 if (Length == 0) 1481 return MarkUnsafe(Info, User); 1482 isSafeMemAccess(Offset, Length->getZExtValue(), 0, 1483 UI.getOperandNo() == 0, Info, MI, 1484 true /*AllowWholeAccess*/); 1485 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1486 if (LI->isVolatile()) 1487 return MarkUnsafe(Info, User); 1488 const Type *LIType = LI->getType(); 1489 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType), 1490 LIType, false, Info, LI, true /*AllowWholeAccess*/); 1491 Info.hasALoadOrStore = true; 1492 1493 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 1494 // Store is ok if storing INTO the pointer, not storing the pointer 1495 if (SI->isVolatile() || SI->getOperand(0) == I) 1496 return MarkUnsafe(Info, User); 1497 1498 const Type *SIType = SI->getOperand(0)->getType(); 1499 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType), 1500 SIType, true, Info, SI, true /*AllowWholeAccess*/); 1501 Info.hasALoadOrStore = true; 1502 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) { 1503 isSafePHISelectUseForScalarRepl(User, Offset, Info); 1504 } else { 1505 return MarkUnsafe(Info, User); 1506 } 1507 if (Info.isUnsafe) return; 1508 } 1509} 1510 1511 1512/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer 1513/// derived from the alloca, we can often still split the alloca into elements. 1514/// This is useful if we have a large alloca where one element is phi'd 1515/// together somewhere: we can SRoA and promote all the other elements even if 1516/// we end up not being able to promote this one. 1517/// 1518/// All we require is that the uses of the PHI do not index into other parts of 1519/// the alloca. The most important use case for this is single load and stores 1520/// that are PHI'd together, which can happen due to code sinking. 1521void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset, 1522 AllocaInfo &Info) { 1523 // If we've already checked this PHI, don't do it again. 1524 if (PHINode *PN = dyn_cast<PHINode>(I)) 1525 if (!Info.CheckedPHIs.insert(PN)) 1526 return; 1527 1528 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) { 1529 Instruction *User = cast<Instruction>(*UI); 1530 1531 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) { 1532 isSafePHISelectUseForScalarRepl(BC, Offset, Info); 1533 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { 1534 // Only allow "bitcast" GEPs for simplicity. We could generalize this, 1535 // but would have to prove that we're staying inside of an element being 1536 // promoted. 1537 if (!GEPI->hasAllZeroIndices()) 1538 return MarkUnsafe(Info, User); 1539 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info); 1540 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1541 if (LI->isVolatile()) 1542 return MarkUnsafe(Info, User); 1543 const Type *LIType = LI->getType(); 1544 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType), 1545 LIType, false, Info, LI, false /*AllowWholeAccess*/); 1546 Info.hasALoadOrStore = true; 1547 1548 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 1549 // Store is ok if storing INTO the pointer, not storing the pointer 1550 if (SI->isVolatile() || SI->getOperand(0) == I) 1551 return MarkUnsafe(Info, User); 1552 1553 const Type *SIType = SI->getOperand(0)->getType(); 1554 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType), 1555 SIType, true, Info, SI, false /*AllowWholeAccess*/); 1556 Info.hasALoadOrStore = true; 1557 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) { 1558 isSafePHISelectUseForScalarRepl(User, Offset, Info); 1559 } else { 1560 return MarkUnsafe(Info, User); 1561 } 1562 if (Info.isUnsafe) return; 1563 } 1564} 1565 1566/// isSafeGEP - Check if a GEP instruction can be handled for scalar 1567/// replacement. It is safe when all the indices are constant, in-bounds 1568/// references, and when the resulting offset corresponds to an element within 1569/// the alloca type. The results are flagged in the Info parameter. Upon 1570/// return, Offset is adjusted as specified by the GEP indices. 1571void SROA::isSafeGEP(GetElementPtrInst *GEPI, 1572 uint64_t &Offset, AllocaInfo &Info) { 1573 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI); 1574 if (GEPIt == E) 1575 return; 1576 1577 // Walk through the GEP type indices, checking the types that this indexes 1578 // into. 1579 for (; GEPIt != E; ++GEPIt) { 1580 // Ignore struct elements, no extra checking needed for these. 1581 if ((*GEPIt)->isStructTy()) 1582 continue; 1583 1584 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand()); 1585 if (!IdxVal) 1586 return MarkUnsafe(Info, GEPI); 1587 } 1588 1589 // Compute the offset due to this GEP and check if the alloca has a 1590 // component element at that offset. 1591 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end()); 1592 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), 1593 &Indices[0], Indices.size()); 1594 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 0)) 1595 MarkUnsafe(Info, GEPI); 1596} 1597 1598/// isHomogeneousAggregate - Check if type T is a struct or array containing 1599/// elements of the same type (which is always true for arrays). If so, 1600/// return true with NumElts and EltTy set to the number of elements and the 1601/// element type, respectively. 1602static bool isHomogeneousAggregate(const Type *T, unsigned &NumElts, 1603 const Type *&EltTy) { 1604 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) { 1605 NumElts = AT->getNumElements(); 1606 EltTy = (NumElts == 0 ? 0 : AT->getElementType()); 1607 return true; 1608 } 1609 if (const StructType *ST = dyn_cast<StructType>(T)) { 1610 NumElts = ST->getNumContainedTypes(); 1611 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0)); 1612 for (unsigned n = 1; n < NumElts; ++n) { 1613 if (ST->getContainedType(n) != EltTy) 1614 return false; 1615 } 1616 return true; 1617 } 1618 return false; 1619} 1620 1621/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are 1622/// "homogeneous" aggregates with the same element type and number of elements. 1623static bool isCompatibleAggregate(const Type *T1, const Type *T2) { 1624 if (T1 == T2) 1625 return true; 1626 1627 unsigned NumElts1, NumElts2; 1628 const Type *EltTy1, *EltTy2; 1629 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) && 1630 isHomogeneousAggregate(T2, NumElts2, EltTy2) && 1631 NumElts1 == NumElts2 && 1632 EltTy1 == EltTy2) 1633 return true; 1634 1635 return false; 1636} 1637 1638/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI 1639/// alloca or has an offset and size that corresponds to a component element 1640/// within it. The offset checked here may have been formed from a GEP with a 1641/// pointer bitcasted to a different type. 1642/// 1643/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a 1644/// unit. If false, it only allows accesses known to be in a single element. 1645void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize, 1646 const Type *MemOpType, bool isStore, 1647 AllocaInfo &Info, Instruction *TheAccess, 1648 bool AllowWholeAccess) { 1649 // Check if this is a load/store of the entire alloca. 1650 if (Offset == 0 && AllowWholeAccess && 1651 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) { 1652 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer 1653 // loads/stores (which are essentially the same as the MemIntrinsics with 1654 // regard to copying padding between elements). But, if an alloca is 1655 // flagged as both a source and destination of such operations, we'll need 1656 // to check later for padding between elements. 1657 if (!MemOpType || MemOpType->isIntegerTy()) { 1658 if (isStore) 1659 Info.isMemCpyDst = true; 1660 else 1661 Info.isMemCpySrc = true; 1662 return; 1663 } 1664 // This is also safe for references using a type that is compatible with 1665 // the type of the alloca, so that loads/stores can be rewritten using 1666 // insertvalue/extractvalue. 1667 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) { 1668 Info.hasSubelementAccess = true; 1669 return; 1670 } 1671 } 1672 // Check if the offset/size correspond to a component within the alloca type. 1673 const Type *T = Info.AI->getAllocatedType(); 1674 if (TypeHasComponent(T, Offset, MemSize)) { 1675 Info.hasSubelementAccess = true; 1676 return; 1677 } 1678 1679 return MarkUnsafe(Info, TheAccess); 1680} 1681 1682/// TypeHasComponent - Return true if T has a component type with the 1683/// specified offset and size. If Size is zero, do not check the size. 1684bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) { 1685 const Type *EltTy; 1686 uint64_t EltSize; 1687 if (const StructType *ST = dyn_cast<StructType>(T)) { 1688 const StructLayout *Layout = TD->getStructLayout(ST); 1689 unsigned EltIdx = Layout->getElementContainingOffset(Offset); 1690 EltTy = ST->getContainedType(EltIdx); 1691 EltSize = TD->getTypeAllocSize(EltTy); 1692 Offset -= Layout->getElementOffset(EltIdx); 1693 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) { 1694 EltTy = AT->getElementType(); 1695 EltSize = TD->getTypeAllocSize(EltTy); 1696 if (Offset >= AT->getNumElements() * EltSize) 1697 return false; 1698 Offset %= EltSize; 1699 } else { 1700 return false; 1701 } 1702 if (Offset == 0 && (Size == 0 || EltSize == Size)) 1703 return true; 1704 // Check if the component spans multiple elements. 1705 if (Offset + Size > EltSize) 1706 return false; 1707 return TypeHasComponent(EltTy, Offset, Size); 1708} 1709 1710/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite 1711/// the instruction I, which references it, to use the separate elements. 1712/// Offset indicates the position within AI that is referenced by this 1713/// instruction. 1714void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset, 1715 SmallVector<AllocaInst*, 32> &NewElts) { 1716 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) { 1717 Use &TheUse = UI.getUse(); 1718 Instruction *User = cast<Instruction>(*UI++); 1719 1720 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) { 1721 RewriteBitCast(BC, AI, Offset, NewElts); 1722 continue; 1723 } 1724 1725 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { 1726 RewriteGEP(GEPI, AI, Offset, NewElts); 1727 continue; 1728 } 1729 1730 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) { 1731 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength()); 1732 uint64_t MemSize = Length->getZExtValue(); 1733 if (Offset == 0 && 1734 MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) 1735 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts); 1736 // Otherwise the intrinsic can only touch a single element and the 1737 // address operand will be updated, so nothing else needs to be done. 1738 continue; 1739 } 1740 1741 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1742 const Type *LIType = LI->getType(); 1743 1744 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) { 1745 // Replace: 1746 // %res = load { i32, i32 }* %alloc 1747 // with: 1748 // %load.0 = load i32* %alloc.0 1749 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0 1750 // %load.1 = load i32* %alloc.1 1751 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1 1752 // (Also works for arrays instead of structs) 1753 Value *Insert = UndefValue::get(LIType); 1754 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 1755 Value *Load = new LoadInst(NewElts[i], "load", LI); 1756 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI); 1757 } 1758 LI->replaceAllUsesWith(Insert); 1759 DeadInsts.push_back(LI); 1760 } else if (LIType->isIntegerTy() && 1761 TD->getTypeAllocSize(LIType) == 1762 TD->getTypeAllocSize(AI->getAllocatedType())) { 1763 // If this is a load of the entire alloca to an integer, rewrite it. 1764 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts); 1765 } 1766 continue; 1767 } 1768 1769 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 1770 Value *Val = SI->getOperand(0); 1771 const Type *SIType = Val->getType(); 1772 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) { 1773 // Replace: 1774 // store { i32, i32 } %val, { i32, i32 }* %alloc 1775 // with: 1776 // %val.0 = extractvalue { i32, i32 } %val, 0 1777 // store i32 %val.0, i32* %alloc.0 1778 // %val.1 = extractvalue { i32, i32 } %val, 1 1779 // store i32 %val.1, i32* %alloc.1 1780 // (Also works for arrays instead of structs) 1781 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 1782 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI); 1783 new StoreInst(Extract, NewElts[i], SI); 1784 } 1785 DeadInsts.push_back(SI); 1786 } else if (SIType->isIntegerTy() && 1787 TD->getTypeAllocSize(SIType) == 1788 TD->getTypeAllocSize(AI->getAllocatedType())) { 1789 // If this is a store of the entire alloca from an integer, rewrite it. 1790 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts); 1791 } 1792 continue; 1793 } 1794 1795 if (isa<SelectInst>(User) || isa<PHINode>(User)) { 1796 // If we have a PHI user of the alloca itself (as opposed to a GEP or 1797 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to 1798 // the new pointer. 1799 if (!isa<AllocaInst>(I)) continue; 1800 1801 assert(Offset == 0 && NewElts[0] && 1802 "Direct alloca use should have a zero offset"); 1803 1804 // If we have a use of the alloca, we know the derived uses will be 1805 // utilizing just the first element of the scalarized result. Insert a 1806 // bitcast of the first alloca before the user as required. 1807 AllocaInst *NewAI = NewElts[0]; 1808 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI); 1809 NewAI->moveBefore(BCI); 1810 TheUse = BCI; 1811 continue; 1812 } 1813 } 1814} 1815 1816/// RewriteBitCast - Update a bitcast reference to the alloca being replaced 1817/// and recursively continue updating all of its uses. 1818void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset, 1819 SmallVector<AllocaInst*, 32> &NewElts) { 1820 RewriteForScalarRepl(BC, AI, Offset, NewElts); 1821 if (BC->getOperand(0) != AI) 1822 return; 1823 1824 // The bitcast references the original alloca. Replace its uses with 1825 // references to the first new element alloca. 1826 Instruction *Val = NewElts[0]; 1827 if (Val->getType() != BC->getDestTy()) { 1828 Val = new BitCastInst(Val, BC->getDestTy(), "", BC); 1829 Val->takeName(BC); 1830 } 1831 BC->replaceAllUsesWith(Val); 1832 DeadInsts.push_back(BC); 1833} 1834 1835/// FindElementAndOffset - Return the index of the element containing Offset 1836/// within the specified type, which must be either a struct or an array. 1837/// Sets T to the type of the element and Offset to the offset within that 1838/// element. IdxTy is set to the type of the index result to be used in a 1839/// GEP instruction. 1840uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset, 1841 const Type *&IdxTy) { 1842 uint64_t Idx = 0; 1843 if (const StructType *ST = dyn_cast<StructType>(T)) { 1844 const StructLayout *Layout = TD->getStructLayout(ST); 1845 Idx = Layout->getElementContainingOffset(Offset); 1846 T = ST->getContainedType(Idx); 1847 Offset -= Layout->getElementOffset(Idx); 1848 IdxTy = Type::getInt32Ty(T->getContext()); 1849 return Idx; 1850 } 1851 const ArrayType *AT = cast<ArrayType>(T); 1852 T = AT->getElementType(); 1853 uint64_t EltSize = TD->getTypeAllocSize(T); 1854 Idx = Offset / EltSize; 1855 Offset -= Idx * EltSize; 1856 IdxTy = Type::getInt64Ty(T->getContext()); 1857 return Idx; 1858} 1859 1860/// RewriteGEP - Check if this GEP instruction moves the pointer across 1861/// elements of the alloca that are being split apart, and if so, rewrite 1862/// the GEP to be relative to the new element. 1863void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset, 1864 SmallVector<AllocaInst*, 32> &NewElts) { 1865 uint64_t OldOffset = Offset; 1866 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end()); 1867 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), 1868 &Indices[0], Indices.size()); 1869 1870 RewriteForScalarRepl(GEPI, AI, Offset, NewElts); 1871 1872 const Type *T = AI->getAllocatedType(); 1873 const Type *IdxTy; 1874 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy); 1875 if (GEPI->getOperand(0) == AI) 1876 OldIdx = ~0ULL; // Force the GEP to be rewritten. 1877 1878 T = AI->getAllocatedType(); 1879 uint64_t EltOffset = Offset; 1880 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy); 1881 1882 // If this GEP does not move the pointer across elements of the alloca 1883 // being split, then it does not needs to be rewritten. 1884 if (Idx == OldIdx) 1885 return; 1886 1887 const Type *i32Ty = Type::getInt32Ty(AI->getContext()); 1888 SmallVector<Value*, 8> NewArgs; 1889 NewArgs.push_back(Constant::getNullValue(i32Ty)); 1890 while (EltOffset != 0) { 1891 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy); 1892 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx)); 1893 } 1894 Instruction *Val = NewElts[Idx]; 1895 if (NewArgs.size() > 1) { 1896 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(), 1897 NewArgs.end(), "", GEPI); 1898 Val->takeName(GEPI); 1899 } 1900 if (Val->getType() != GEPI->getType()) 1901 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI); 1902 GEPI->replaceAllUsesWith(Val); 1903 DeadInsts.push_back(GEPI); 1904} 1905 1906/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI. 1907/// Rewrite it to copy or set the elements of the scalarized memory. 1908void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst, 1909 AllocaInst *AI, 1910 SmallVector<AllocaInst*, 32> &NewElts) { 1911 // If this is a memcpy/memmove, construct the other pointer as the 1912 // appropriate type. The "Other" pointer is the pointer that goes to memory 1913 // that doesn't have anything to do with the alloca that we are promoting. For 1914 // memset, this Value* stays null. 1915 Value *OtherPtr = 0; 1916 unsigned MemAlignment = MI->getAlignment(); 1917 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy 1918 if (Inst == MTI->getRawDest()) 1919 OtherPtr = MTI->getRawSource(); 1920 else { 1921 assert(Inst == MTI->getRawSource()); 1922 OtherPtr = MTI->getRawDest(); 1923 } 1924 } 1925 1926 // If there is an other pointer, we want to convert it to the same pointer 1927 // type as AI has, so we can GEP through it safely. 1928 if (OtherPtr) { 1929 unsigned AddrSpace = 1930 cast<PointerType>(OtherPtr->getType())->getAddressSpace(); 1931 1932 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an 1933 // optimization, but it's also required to detect the corner case where 1934 // both pointer operands are referencing the same memory, and where 1935 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This 1936 // function is only called for mem intrinsics that access the whole 1937 // aggregate, so non-zero GEPs are not an issue here.) 1938 OtherPtr = OtherPtr->stripPointerCasts(); 1939 1940 // Copying the alloca to itself is a no-op: just delete it. 1941 if (OtherPtr == AI || OtherPtr == NewElts[0]) { 1942 // This code will run twice for a no-op memcpy -- once for each operand. 1943 // Put only one reference to MI on the DeadInsts list. 1944 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(), 1945 E = DeadInsts.end(); I != E; ++I) 1946 if (*I == MI) return; 1947 DeadInsts.push_back(MI); 1948 return; 1949 } 1950 1951 // If the pointer is not the right type, insert a bitcast to the right 1952 // type. 1953 const Type *NewTy = 1954 PointerType::get(AI->getType()->getElementType(), AddrSpace); 1955 1956 if (OtherPtr->getType() != NewTy) 1957 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI); 1958 } 1959 1960 // Process each element of the aggregate. 1961 bool SROADest = MI->getRawDest() == Inst; 1962 1963 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext())); 1964 1965 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 1966 // If this is a memcpy/memmove, emit a GEP of the other element address. 1967 Value *OtherElt = 0; 1968 unsigned OtherEltAlign = MemAlignment; 1969 1970 if (OtherPtr) { 1971 Value *Idx[2] = { Zero, 1972 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) }; 1973 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2, 1974 OtherPtr->getName()+"."+Twine(i), 1975 MI); 1976 uint64_t EltOffset; 1977 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType()); 1978 const Type *OtherTy = OtherPtrTy->getElementType(); 1979 if (const StructType *ST = dyn_cast<StructType>(OtherTy)) { 1980 EltOffset = TD->getStructLayout(ST)->getElementOffset(i); 1981 } else { 1982 const Type *EltTy = cast<SequentialType>(OtherTy)->getElementType(); 1983 EltOffset = TD->getTypeAllocSize(EltTy)*i; 1984 } 1985 1986 // The alignment of the other pointer is the guaranteed alignment of the 1987 // element, which is affected by both the known alignment of the whole 1988 // mem intrinsic and the alignment of the element. If the alignment of 1989 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the 1990 // known alignment is just 4 bytes. 1991 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset); 1992 } 1993 1994 Value *EltPtr = NewElts[i]; 1995 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType(); 1996 1997 // If we got down to a scalar, insert a load or store as appropriate. 1998 if (EltTy->isSingleValueType()) { 1999 if (isa<MemTransferInst>(MI)) { 2000 if (SROADest) { 2001 // From Other to Alloca. 2002 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI); 2003 new StoreInst(Elt, EltPtr, MI); 2004 } else { 2005 // From Alloca to Other. 2006 Value *Elt = new LoadInst(EltPtr, "tmp", MI); 2007 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI); 2008 } 2009 continue; 2010 } 2011 assert(isa<MemSetInst>(MI)); 2012 2013 // If the stored element is zero (common case), just store a null 2014 // constant. 2015 Constant *StoreVal; 2016 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) { 2017 if (CI->isZero()) { 2018 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0> 2019 } else { 2020 // If EltTy is a vector type, get the element type. 2021 const Type *ValTy = EltTy->getScalarType(); 2022 2023 // Construct an integer with the right value. 2024 unsigned EltSize = TD->getTypeSizeInBits(ValTy); 2025 APInt OneVal(EltSize, CI->getZExtValue()); 2026 APInt TotalVal(OneVal); 2027 // Set each byte. 2028 for (unsigned i = 0; 8*i < EltSize; ++i) { 2029 TotalVal = TotalVal.shl(8); 2030 TotalVal |= OneVal; 2031 } 2032 2033 // Convert the integer value to the appropriate type. 2034 StoreVal = ConstantInt::get(CI->getContext(), TotalVal); 2035 if (ValTy->isPointerTy()) 2036 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy); 2037 else if (ValTy->isFloatingPointTy()) 2038 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy); 2039 assert(StoreVal->getType() == ValTy && "Type mismatch!"); 2040 2041 // If the requested value was a vector constant, create it. 2042 if (EltTy != ValTy) { 2043 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements(); 2044 SmallVector<Constant*, 16> Elts(NumElts, StoreVal); 2045 StoreVal = ConstantVector::get(Elts); 2046 } 2047 } 2048 new StoreInst(StoreVal, EltPtr, MI); 2049 continue; 2050 } 2051 // Otherwise, if we're storing a byte variable, use a memset call for 2052 // this element. 2053 } 2054 2055 unsigned EltSize = TD->getTypeAllocSize(EltTy); 2056 2057 IRBuilder<> Builder(MI); 2058 2059 // Finally, insert the meminst for this element. 2060 if (isa<MemSetInst>(MI)) { 2061 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize, 2062 MI->isVolatile()); 2063 } else { 2064 assert(isa<MemTransferInst>(MI)); 2065 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr 2066 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr 2067 2068 if (isa<MemCpyInst>(MI)) 2069 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile()); 2070 else 2071 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile()); 2072 } 2073 } 2074 DeadInsts.push_back(MI); 2075} 2076 2077/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that 2078/// overwrites the entire allocation. Extract out the pieces of the stored 2079/// integer and store them individually. 2080void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI, 2081 SmallVector<AllocaInst*, 32> &NewElts){ 2082 // Extract each element out of the integer according to its structure offset 2083 // and store the element value to the individual alloca. 2084 Value *SrcVal = SI->getOperand(0); 2085 const Type *AllocaEltTy = AI->getAllocatedType(); 2086 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy); 2087 2088 IRBuilder<> Builder(SI); 2089 2090 // Handle tail padding by extending the operand 2091 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits) 2092 SrcVal = Builder.CreateZExt(SrcVal, 2093 IntegerType::get(SI->getContext(), AllocaSizeBits)); 2094 2095 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI 2096 << '\n'); 2097 2098 // There are two forms here: AI could be an array or struct. Both cases 2099 // have different ways to compute the element offset. 2100 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) { 2101 const StructLayout *Layout = TD->getStructLayout(EltSTy); 2102 2103 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 2104 // Get the number of bits to shift SrcVal to get the value. 2105 const Type *FieldTy = EltSTy->getElementType(i); 2106 uint64_t Shift = Layout->getElementOffsetInBits(i); 2107 2108 if (TD->isBigEndian()) 2109 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy); 2110 2111 Value *EltVal = SrcVal; 2112 if (Shift) { 2113 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift); 2114 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt"); 2115 } 2116 2117 // Truncate down to an integer of the right size. 2118 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy); 2119 2120 // Ignore zero sized fields like {}, they obviously contain no data. 2121 if (FieldSizeBits == 0) continue; 2122 2123 if (FieldSizeBits != AllocaSizeBits) 2124 EltVal = Builder.CreateTrunc(EltVal, 2125 IntegerType::get(SI->getContext(), FieldSizeBits)); 2126 Value *DestField = NewElts[i]; 2127 if (EltVal->getType() == FieldTy) { 2128 // Storing to an integer field of this size, just do it. 2129 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) { 2130 // Bitcast to the right element type (for fp/vector values). 2131 EltVal = Builder.CreateBitCast(EltVal, FieldTy); 2132 } else { 2133 // Otherwise, bitcast the dest pointer (for aggregates). 2134 DestField = Builder.CreateBitCast(DestField, 2135 PointerType::getUnqual(EltVal->getType())); 2136 } 2137 new StoreInst(EltVal, DestField, SI); 2138 } 2139 2140 } else { 2141 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy); 2142 const Type *ArrayEltTy = ATy->getElementType(); 2143 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy); 2144 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy); 2145 2146 uint64_t Shift; 2147 2148 if (TD->isBigEndian()) 2149 Shift = AllocaSizeBits-ElementOffset; 2150 else 2151 Shift = 0; 2152 2153 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 2154 // Ignore zero sized fields like {}, they obviously contain no data. 2155 if (ElementSizeBits == 0) continue; 2156 2157 Value *EltVal = SrcVal; 2158 if (Shift) { 2159 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift); 2160 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt"); 2161 } 2162 2163 // Truncate down to an integer of the right size. 2164 if (ElementSizeBits != AllocaSizeBits) 2165 EltVal = Builder.CreateTrunc(EltVal, 2166 IntegerType::get(SI->getContext(), 2167 ElementSizeBits)); 2168 Value *DestField = NewElts[i]; 2169 if (EltVal->getType() == ArrayEltTy) { 2170 // Storing to an integer field of this size, just do it. 2171 } else if (ArrayEltTy->isFloatingPointTy() || 2172 ArrayEltTy->isVectorTy()) { 2173 // Bitcast to the right element type (for fp/vector values). 2174 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy); 2175 } else { 2176 // Otherwise, bitcast the dest pointer (for aggregates). 2177 DestField = Builder.CreateBitCast(DestField, 2178 PointerType::getUnqual(EltVal->getType())); 2179 } 2180 new StoreInst(EltVal, DestField, SI); 2181 2182 if (TD->isBigEndian()) 2183 Shift -= ElementOffset; 2184 else 2185 Shift += ElementOffset; 2186 } 2187 } 2188 2189 DeadInsts.push_back(SI); 2190} 2191 2192/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to 2193/// an integer. Load the individual pieces to form the aggregate value. 2194void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI, 2195 SmallVector<AllocaInst*, 32> &NewElts) { 2196 // Extract each element out of the NewElts according to its structure offset 2197 // and form the result value. 2198 const Type *AllocaEltTy = AI->getAllocatedType(); 2199 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy); 2200 2201 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI 2202 << '\n'); 2203 2204 // There are two forms here: AI could be an array or struct. Both cases 2205 // have different ways to compute the element offset. 2206 const StructLayout *Layout = 0; 2207 uint64_t ArrayEltBitOffset = 0; 2208 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) { 2209 Layout = TD->getStructLayout(EltSTy); 2210 } else { 2211 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType(); 2212 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy); 2213 } 2214 2215 Value *ResultVal = 2216 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits)); 2217 2218 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 2219 // Load the value from the alloca. If the NewElt is an aggregate, cast 2220 // the pointer to an integer of the same size before doing the load. 2221 Value *SrcField = NewElts[i]; 2222 const Type *FieldTy = 2223 cast<PointerType>(SrcField->getType())->getElementType(); 2224 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy); 2225 2226 // Ignore zero sized fields like {}, they obviously contain no data. 2227 if (FieldSizeBits == 0) continue; 2228 2229 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(), 2230 FieldSizeBits); 2231 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() && 2232 !FieldTy->isVectorTy()) 2233 SrcField = new BitCastInst(SrcField, 2234 PointerType::getUnqual(FieldIntTy), 2235 "", LI); 2236 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI); 2237 2238 // If SrcField is a fp or vector of the right size but that isn't an 2239 // integer type, bitcast to an integer so we can shift it. 2240 if (SrcField->getType() != FieldIntTy) 2241 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI); 2242 2243 // Zero extend the field to be the same size as the final alloca so that 2244 // we can shift and insert it. 2245 if (SrcField->getType() != ResultVal->getType()) 2246 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI); 2247 2248 // Determine the number of bits to shift SrcField. 2249 uint64_t Shift; 2250 if (Layout) // Struct case. 2251 Shift = Layout->getElementOffsetInBits(i); 2252 else // Array case. 2253 Shift = i*ArrayEltBitOffset; 2254 2255 if (TD->isBigEndian()) 2256 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth(); 2257 2258 if (Shift) { 2259 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift); 2260 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI); 2261 } 2262 2263 // Don't create an 'or x, 0' on the first iteration. 2264 if (!isa<Constant>(ResultVal) || 2265 !cast<Constant>(ResultVal)->isNullValue()) 2266 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI); 2267 else 2268 ResultVal = SrcField; 2269 } 2270 2271 // Handle tail padding by truncating the result 2272 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits) 2273 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI); 2274 2275 LI->replaceAllUsesWith(ResultVal); 2276 DeadInsts.push_back(LI); 2277} 2278 2279/// HasPadding - Return true if the specified type has any structure or 2280/// alignment padding in between the elements that would be split apart 2281/// by SROA; return false otherwise. 2282static bool HasPadding(const Type *Ty, const TargetData &TD) { 2283 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 2284 Ty = ATy->getElementType(); 2285 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty); 2286 } 2287 2288 // SROA currently handles only Arrays and Structs. 2289 const StructType *STy = cast<StructType>(Ty); 2290 const StructLayout *SL = TD.getStructLayout(STy); 2291 unsigned PrevFieldBitOffset = 0; 2292 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 2293 unsigned FieldBitOffset = SL->getElementOffsetInBits(i); 2294 2295 // Check to see if there is any padding between this element and the 2296 // previous one. 2297 if (i) { 2298 unsigned PrevFieldEnd = 2299 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1)); 2300 if (PrevFieldEnd < FieldBitOffset) 2301 return true; 2302 } 2303 PrevFieldBitOffset = FieldBitOffset; 2304 } 2305 // Check for tail padding. 2306 if (unsigned EltCount = STy->getNumElements()) { 2307 unsigned PrevFieldEnd = PrevFieldBitOffset + 2308 TD.getTypeSizeInBits(STy->getElementType(EltCount-1)); 2309 if (PrevFieldEnd < SL->getSizeInBits()) 2310 return true; 2311 } 2312 return false; 2313} 2314 2315/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of 2316/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe, 2317/// or 1 if safe after canonicalization has been performed. 2318bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) { 2319 // Loop over the use list of the alloca. We can only transform it if all of 2320 // the users are safe to transform. 2321 AllocaInfo Info(AI); 2322 2323 isSafeForScalarRepl(AI, 0, Info); 2324 if (Info.isUnsafe) { 2325 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n'); 2326 return false; 2327 } 2328 2329 // Okay, we know all the users are promotable. If the aggregate is a memcpy 2330 // source and destination, we have to be careful. In particular, the memcpy 2331 // could be moving around elements that live in structure padding of the LLVM 2332 // types, but may actually be used. In these cases, we refuse to promote the 2333 // struct. 2334 if (Info.isMemCpySrc && Info.isMemCpyDst && 2335 HasPadding(AI->getAllocatedType(), *TD)) 2336 return false; 2337 2338 // If the alloca never has an access to just *part* of it, but is accessed 2339 // via loads and stores, then we should use ConvertToScalarInfo to promote 2340 // the alloca instead of promoting each piece at a time and inserting fission 2341 // and fusion code. 2342 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) { 2343 // If the struct/array just has one element, use basic SRoA. 2344 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { 2345 if (ST->getNumElements() > 1) return false; 2346 } else { 2347 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1) 2348 return false; 2349 } 2350 } 2351 2352 return true; 2353} 2354 2355 2356 2357/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to 2358/// some part of a constant global variable. This intentionally only accepts 2359/// constant expressions because we don't can't rewrite arbitrary instructions. 2360static bool PointsToConstantGlobal(Value *V) { 2361 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 2362 return GV->isConstant(); 2363 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 2364 if (CE->getOpcode() == Instruction::BitCast || 2365 CE->getOpcode() == Instruction::GetElementPtr) 2366 return PointsToConstantGlobal(CE->getOperand(0)); 2367 return false; 2368} 2369 2370/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived) 2371/// pointer to an alloca. Ignore any reads of the pointer, return false if we 2372/// see any stores or other unknown uses. If we see pointer arithmetic, keep 2373/// track of whether it moves the pointer (with isOffset) but otherwise traverse 2374/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to 2375/// the alloca, and if the source pointer is a pointer to a constant global, we 2376/// can optimize this. 2377static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy, 2378 bool isOffset) { 2379 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) { 2380 User *U = cast<Instruction>(*UI); 2381 2382 if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 2383 // Ignore non-volatile loads, they are always ok. 2384 if (LI->isVolatile()) return false; 2385 continue; 2386 } 2387 2388 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) { 2389 // If uses of the bitcast are ok, we are ok. 2390 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset)) 2391 return false; 2392 continue; 2393 } 2394 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 2395 // If the GEP has all zero indices, it doesn't offset the pointer. If it 2396 // doesn't, it does. 2397 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy, 2398 isOffset || !GEP->hasAllZeroIndices())) 2399 return false; 2400 continue; 2401 } 2402 2403 if (CallSite CS = U) { 2404 // If this is a readonly/readnone call site, then we know it is just a 2405 // load and we can ignore it. 2406 if (CS.onlyReadsMemory()) 2407 continue; 2408 2409 // If this is the function being called then we treat it like a load and 2410 // ignore it. 2411 if (CS.isCallee(UI)) 2412 continue; 2413 2414 // If this is being passed as a byval argument, the caller is making a 2415 // copy, so it is only a read of the alloca. 2416 unsigned ArgNo = CS.getArgumentNo(UI); 2417 if (CS.paramHasAttr(ArgNo+1, Attribute::ByVal)) 2418 continue; 2419 } 2420 2421 // If this is isn't our memcpy/memmove, reject it as something we can't 2422 // handle. 2423 MemTransferInst *MI = dyn_cast<MemTransferInst>(U); 2424 if (MI == 0) 2425 return false; 2426 2427 // If the transfer is using the alloca as a source of the transfer, then 2428 // ignore it since it is a load (unless the transfer is volatile). 2429 if (UI.getOperandNo() == 1) { 2430 if (MI->isVolatile()) return false; 2431 continue; 2432 } 2433 2434 // If we already have seen a copy, reject the second one. 2435 if (TheCopy) return false; 2436 2437 // If the pointer has been offset from the start of the alloca, we can't 2438 // safely handle this. 2439 if (isOffset) return false; 2440 2441 // If the memintrinsic isn't using the alloca as the dest, reject it. 2442 if (UI.getOperandNo() != 0) return false; 2443 2444 // If the source of the memcpy/move is not a constant global, reject it. 2445 if (!PointsToConstantGlobal(MI->getSource())) 2446 return false; 2447 2448 // Otherwise, the transform is safe. Remember the copy instruction. 2449 TheCopy = MI; 2450 } 2451 return true; 2452} 2453 2454/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only 2455/// modified by a copy from a constant global. If we can prove this, we can 2456/// replace any uses of the alloca with uses of the global directly. 2457MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) { 2458 MemTransferInst *TheCopy = 0; 2459 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false)) 2460 return TheCopy; 2461 return 0; 2462} 2463