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