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