ScalarReplAggregates.cpp revision 6934a04a8c15e9971cd1ea4d5c8df2d7afdd5be5
1//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file was developed by the LLVM research group and is distributed under 6// the University of Illinois Open Source 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/Pass.h" 28#include "llvm/Instructions.h" 29#include "llvm/Analysis/Dominators.h" 30#include "llvm/Target/TargetData.h" 31#include "llvm/Transforms/Utils/PromoteMemToReg.h" 32#include "llvm/Support/Debug.h" 33#include "llvm/Support/GetElementPtrTypeIterator.h" 34#include "llvm/Support/MathExtras.h" 35#include "llvm/Support/Compiler.h" 36#include "llvm/ADT/Statistic.h" 37#include "llvm/ADT/StringExtras.h" 38using namespace llvm; 39 40STATISTIC(NumReplaced, "Number of allocas broken up"); 41STATISTIC(NumPromoted, "Number of allocas promoted"); 42STATISTIC(NumConverted, "Number of aggregates converted to scalar"); 43 44namespace { 45 struct VISIBILITY_HIDDEN SROA : public FunctionPass { 46 bool runOnFunction(Function &F); 47 48 bool performScalarRepl(Function &F); 49 bool performPromotion(Function &F); 50 51 // getAnalysisUsage - This pass does not require any passes, but we know it 52 // will not alter the CFG, so say so. 53 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 54 AU.addRequired<DominatorTree>(); 55 AU.addRequired<DominanceFrontier>(); 56 AU.addRequired<TargetData>(); 57 AU.setPreservesCFG(); 58 } 59 60 private: 61 int isSafeElementUse(Value *Ptr); 62 int isSafeUseOfAllocation(Instruction *User); 63 int isSafeAllocaToScalarRepl(AllocationInst *AI); 64 void CanonicalizeAllocaUsers(AllocationInst *AI); 65 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base); 66 67 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial); 68 void ConvertToScalar(AllocationInst *AI, const Type *Ty); 69 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset); 70 }; 71 72 RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates"); 73} 74 75// Public interface to the ScalarReplAggregates pass 76FunctionPass *llvm::createScalarReplAggregatesPass() { return new SROA(); } 77 78 79bool SROA::runOnFunction(Function &F) { 80 bool Changed = performPromotion(F); 81 while (1) { 82 bool LocalChange = performScalarRepl(F); 83 if (!LocalChange) break; // No need to repromote if no scalarrepl 84 Changed = true; 85 LocalChange = performPromotion(F); 86 if (!LocalChange) break; // No need to re-scalarrepl if no promotion 87 } 88 89 return Changed; 90} 91 92 93bool SROA::performPromotion(Function &F) { 94 std::vector<AllocaInst*> Allocas; 95 const TargetData &TD = getAnalysis<TargetData>(); 96 DominatorTree &DT = getAnalysis<DominatorTree>(); 97 DominanceFrontier &DF = getAnalysis<DominanceFrontier>(); 98 99 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function 100 101 bool Changed = false; 102 103 while (1) { 104 Allocas.clear(); 105 106 // Find allocas that are safe to promote, by looking at all instructions in 107 // the entry node 108 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) 109 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca? 110 if (isAllocaPromotable(AI, TD)) 111 Allocas.push_back(AI); 112 113 if (Allocas.empty()) break; 114 115 PromoteMemToReg(Allocas, DT, DF, TD); 116 NumPromoted += Allocas.size(); 117 Changed = true; 118 } 119 120 return Changed; 121} 122 123// performScalarRepl - This algorithm is a simple worklist driven algorithm, 124// which runs on all of the malloc/alloca instructions in the function, removing 125// them if they are only used by getelementptr instructions. 126// 127bool SROA::performScalarRepl(Function &F) { 128 std::vector<AllocationInst*> WorkList; 129 130 // Scan the entry basic block, adding any alloca's and mallocs to the worklist 131 BasicBlock &BB = F.getEntryBlock(); 132 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) 133 if (AllocationInst *A = dyn_cast<AllocationInst>(I)) 134 WorkList.push_back(A); 135 136 // Process the worklist 137 bool Changed = false; 138 while (!WorkList.empty()) { 139 AllocationInst *AI = WorkList.back(); 140 WorkList.pop_back(); 141 142 // Handle dead allocas trivially. These can be formed by SROA'ing arrays 143 // with unused elements. 144 if (AI->use_empty()) { 145 AI->eraseFromParent(); 146 continue; 147 } 148 149 // If we can turn this aggregate value (potentially with casts) into a 150 // simple scalar value that can be mem2reg'd into a register value. 151 bool IsNotTrivial = false; 152 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial)) 153 if (IsNotTrivial && ActualType != Type::VoidTy) { 154 ConvertToScalar(AI, ActualType); 155 Changed = true; 156 continue; 157 } 158 159 // We cannot transform the allocation instruction if it is an array 160 // allocation (allocations OF arrays are ok though), and an allocation of a 161 // scalar value cannot be decomposed at all. 162 // 163 if (AI->isArrayAllocation() || 164 (!isa<StructType>(AI->getAllocatedType()) && 165 !isa<ArrayType>(AI->getAllocatedType()))) continue; 166 167 // Check that all of the users of the allocation are capable of being 168 // transformed. 169 switch (isSafeAllocaToScalarRepl(AI)) { 170 default: assert(0 && "Unexpected value!"); 171 case 0: // Not safe to scalar replace. 172 continue; 173 case 1: // Safe, but requires cleanup/canonicalizations first 174 CanonicalizeAllocaUsers(AI); 175 case 3: // Safe to scalar replace. 176 break; 177 } 178 179 DOUT << "Found inst to xform: " << *AI; 180 Changed = true; 181 182 std::vector<AllocaInst*> ElementAllocas; 183 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { 184 ElementAllocas.reserve(ST->getNumContainedTypes()); 185 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { 186 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 187 AI->getAlignment(), 188 AI->getName() + "." + utostr(i), AI); 189 ElementAllocas.push_back(NA); 190 WorkList.push_back(NA); // Add to worklist for recursive processing 191 } 192 } else { 193 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); 194 ElementAllocas.reserve(AT->getNumElements()); 195 const Type *ElTy = AT->getElementType(); 196 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { 197 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(), 198 AI->getName() + "." + utostr(i), AI); 199 ElementAllocas.push_back(NA); 200 WorkList.push_back(NA); // Add to worklist for recursive processing 201 } 202 } 203 204 // Now that we have created the alloca instructions that we want to use, 205 // expand the getelementptr instructions to use them. 206 // 207 while (!AI->use_empty()) { 208 Instruction *User = cast<Instruction>(AI->use_back()); 209 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User); 210 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst> 211 unsigned Idx = 212 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue(); 213 214 assert(Idx < ElementAllocas.size() && "Index out of range?"); 215 AllocaInst *AllocaToUse = ElementAllocas[Idx]; 216 217 Value *RepValue; 218 if (GEPI->getNumOperands() == 3) { 219 // Do not insert a new getelementptr instruction with zero indices, only 220 // to have it optimized out later. 221 RepValue = AllocaToUse; 222 } else { 223 // We are indexing deeply into the structure, so we still need a 224 // getelement ptr instruction to finish the indexing. This may be 225 // expanded itself once the worklist is rerun. 226 // 227 std::vector<Value*> NewArgs; 228 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty)); 229 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end()); 230 RepValue = new GetElementPtrInst(AllocaToUse, NewArgs, "", GEPI); 231 RepValue->takeName(GEPI); 232 } 233 234 // Move all of the users over to the new GEP. 235 GEPI->replaceAllUsesWith(RepValue); 236 // Delete the old GEP 237 GEPI->eraseFromParent(); 238 } 239 240 // Finally, delete the Alloca instruction 241 AI->eraseFromParent(); 242 NumReplaced++; 243 } 244 245 return Changed; 246} 247 248 249/// isSafeElementUse - Check to see if this use is an allowed use for a 250/// getelementptr instruction of an array aggregate allocation. 251/// 252int SROA::isSafeElementUse(Value *Ptr) { 253 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end(); 254 I != E; ++I) { 255 Instruction *User = cast<Instruction>(*I); 256 switch (User->getOpcode()) { 257 case Instruction::Load: break; 258 case Instruction::Store: 259 // Store is ok if storing INTO the pointer, not storing the pointer 260 if (User->getOperand(0) == Ptr) return 0; 261 break; 262 case Instruction::GetElementPtr: { 263 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User); 264 if (GEP->getNumOperands() > 1) { 265 if (!isa<Constant>(GEP->getOperand(1)) || 266 !cast<Constant>(GEP->getOperand(1))->isNullValue()) 267 return 0; // Using pointer arithmetic to navigate the array... 268 } 269 if (!isSafeElementUse(GEP)) return 0; 270 break; 271 } 272 default: 273 DOUT << " Transformation preventing inst: " << *User; 274 return 0; 275 } 276 } 277 return 3; // All users look ok :) 278} 279 280/// AllUsersAreLoads - Return true if all users of this value are loads. 281static bool AllUsersAreLoads(Value *Ptr) { 282 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end(); 283 I != E; ++I) 284 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load) 285 return false; 286 return true; 287} 288 289/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an 290/// aggregate allocation. 291/// 292int SROA::isSafeUseOfAllocation(Instruction *User) { 293 if (!isa<GetElementPtrInst>(User)) return 0; 294 295 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User); 296 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI); 297 298 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>". 299 if (I == E || 300 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) 301 return 0; 302 303 ++I; 304 if (I == E) return 0; // ran out of GEP indices?? 305 306 // If this is a use of an array allocation, do a bit more checking for sanity. 307 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) { 308 uint64_t NumElements = AT->getNumElements(); 309 310 if (isa<ConstantInt>(I.getOperand())) { 311 // Check to make sure that index falls within the array. If not, 312 // something funny is going on, so we won't do the optimization. 313 // 314 if (cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue() >= NumElements) 315 return 0; 316 317 // We cannot scalar repl this level of the array unless any array 318 // sub-indices are in-range constants. In particular, consider: 319 // A[0][i]. We cannot know that the user isn't doing invalid things like 320 // allowing i to index an out-of-range subscript that accesses A[1]. 321 // 322 // Scalar replacing *just* the outer index of the array is probably not 323 // going to be a win anyway, so just give up. 324 for (++I; I != E && (isa<ArrayType>(*I) || isa<PackedType>(*I)); ++I) { 325 uint64_t NumElements; 326 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*I)) 327 NumElements = SubArrayTy->getNumElements(); 328 else 329 NumElements = cast<PackedType>(*I)->getNumElements(); 330 331 if (!isa<ConstantInt>(I.getOperand())) return 0; 332 if (cast<ConstantInt>(I.getOperand())->getZExtValue() >= NumElements) 333 return 0; 334 } 335 336 } else { 337 // If this is an array index and the index is not constant, we cannot 338 // promote... that is unless the array has exactly one or two elements in 339 // it, in which case we CAN promote it, but we have to canonicalize this 340 // out if this is the only problem. 341 if ((NumElements == 1 || NumElements == 2) && 342 AllUsersAreLoads(GEPI)) 343 return 1; // Canonicalization required! 344 return 0; 345 } 346 } 347 348 // If there are any non-simple uses of this getelementptr, make sure to reject 349 // them. 350 return isSafeElementUse(GEPI); 351} 352 353/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of 354/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe, 355/// or 1 if safe after canonicalization has been performed. 356/// 357int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) { 358 // Loop over the use list of the alloca. We can only transform it if all of 359 // the users are safe to transform. 360 // 361 int isSafe = 3; 362 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); 363 I != E; ++I) { 364 isSafe &= isSafeUseOfAllocation(cast<Instruction>(*I)); 365 if (isSafe == 0) { 366 DOUT << "Cannot transform: " << *AI << " due to user: " << **I; 367 return 0; 368 } 369 } 370 // If we require cleanup, isSafe is now 1, otherwise it is 3. 371 return isSafe; 372} 373 374/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified 375/// allocation, but only if cleaned up, perform the cleanups required. 376void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) { 377 // At this point, we know that the end result will be SROA'd and promoted, so 378 // we can insert ugly code if required so long as sroa+mem2reg will clean it 379 // up. 380 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); 381 UI != E; ) { 382 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(*UI++); 383 gep_type_iterator I = gep_type_begin(GEPI); 384 ++I; 385 386 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) { 387 uint64_t NumElements = AT->getNumElements(); 388 389 if (!isa<ConstantInt>(I.getOperand())) { 390 if (NumElements == 1) { 391 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty)); 392 } else { 393 assert(NumElements == 2 && "Unhandled case!"); 394 // All users of the GEP must be loads. At each use of the GEP, insert 395 // two loads of the appropriate indexed GEP and select between them. 396 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(), 397 Constant::getNullValue(I.getOperand()->getType()), 398 "isone", GEPI); 399 // Insert the new GEP instructions, which are properly indexed. 400 std::vector<Value*> Indices(GEPI->op_begin()+1, GEPI->op_end()); 401 Indices[1] = Constant::getNullValue(Type::Int32Ty); 402 Value *ZeroIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices, 403 GEPI->getName()+".0", GEPI); 404 Indices[1] = ConstantInt::get(Type::Int32Ty, 1); 405 Value *OneIdx = new GetElementPtrInst(GEPI->getOperand(0), Indices, 406 GEPI->getName()+".1", GEPI); 407 // Replace all loads of the variable index GEP with loads from both 408 // indexes and a select. 409 while (!GEPI->use_empty()) { 410 LoadInst *LI = cast<LoadInst>(GEPI->use_back()); 411 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI); 412 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI); 413 Value *R = new SelectInst(IsOne, One, Zero, LI->getName(), LI); 414 LI->replaceAllUsesWith(R); 415 LI->eraseFromParent(); 416 } 417 GEPI->eraseFromParent(); 418 } 419 } 420 } 421 } 422} 423 424/// MergeInType - Add the 'In' type to the accumulated type so far. If the 425/// types are incompatible, return true, otherwise update Accum and return 426/// false. 427/// 428/// There are three cases we handle here: 429/// 1) An effectively-integer union, where the pieces are stored into as 430/// smaller integers (common with byte swap and other idioms). 431/// 2) A union of vector types of the same size and potentially its elements. 432/// Here we turn element accesses into insert/extract element operations. 433/// 3) A union of scalar types, such as int/float or int/pointer. Here we 434/// merge together into integers, allowing the xform to work with #1 as 435/// well. 436static bool MergeInType(const Type *In, const Type *&Accum, 437 const TargetData &TD) { 438 // If this is our first type, just use it. 439 const PackedType *PTy; 440 if (Accum == Type::VoidTy || In == Accum) { 441 Accum = In; 442 } else if (In == Type::VoidTy) { 443 // Noop. 444 } else if (In->isInteger() && Accum->isInteger()) { // integer union. 445 // Otherwise pick whichever type is larger. 446 if (cast<IntegerType>(In)->getBitWidth() > 447 cast<IntegerType>(Accum)->getBitWidth()) 448 Accum = In; 449 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) { 450 // Pointer unions just stay as one of the pointers. 451 } else if (isa<PackedType>(In) || isa<PackedType>(Accum)) { 452 if ((PTy = dyn_cast<PackedType>(Accum)) && 453 PTy->getElementType() == In) { 454 // Accum is a vector, and we are accessing an element: ok. 455 } else if ((PTy = dyn_cast<PackedType>(In)) && 456 PTy->getElementType() == Accum) { 457 // In is a vector, and accum is an element: ok, remember In. 458 Accum = In; 459 } else if ((PTy = dyn_cast<PackedType>(In)) && isa<PackedType>(Accum) && 460 PTy->getBitWidth() == cast<PackedType>(Accum)->getBitWidth()) { 461 // Two vectors of the same size: keep Accum. 462 } else { 463 // Cannot insert an short into a <4 x int> or handle 464 // <2 x int> -> <4 x int> 465 return true; 466 } 467 } else { 468 // Pointer/FP/Integer unions merge together as integers. 469 switch (Accum->getTypeID()) { 470 case Type::PointerTyID: Accum = TD.getIntPtrType(); break; 471 case Type::FloatTyID: Accum = Type::Int32Ty; break; 472 case Type::DoubleTyID: Accum = Type::Int64Ty; break; 473 default: 474 assert(Accum->isInteger() && "Unknown FP type!"); 475 break; 476 } 477 478 switch (In->getTypeID()) { 479 case Type::PointerTyID: In = TD.getIntPtrType(); break; 480 case Type::FloatTyID: In = Type::Int32Ty; break; 481 case Type::DoubleTyID: In = Type::Int64Ty; break; 482 default: 483 assert(In->isInteger() && "Unknown FP type!"); 484 break; 485 } 486 return MergeInType(In, Accum, TD); 487 } 488 return false; 489} 490 491/// getUIntAtLeastAsBitAs - Return an unsigned integer type that is at least 492/// as big as the specified type. If there is no suitable type, this returns 493/// null. 494const Type *getUIntAtLeastAsBitAs(unsigned NumBits) { 495 if (NumBits > 64) return 0; 496 if (NumBits > 32) return Type::Int64Ty; 497 if (NumBits > 16) return Type::Int32Ty; 498 if (NumBits > 8) return Type::Int16Ty; 499 return Type::Int8Ty; 500} 501 502/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a 503/// single scalar integer type, return that type. Further, if the use is not 504/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If 505/// there are no uses of this pointer, return Type::VoidTy to differentiate from 506/// failure. 507/// 508const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) { 509 const Type *UsedType = Type::VoidTy; // No uses, no forced type. 510 const TargetData &TD = getAnalysis<TargetData>(); 511 const PointerType *PTy = cast<PointerType>(V->getType()); 512 513 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) { 514 Instruction *User = cast<Instruction>(*UI); 515 516 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 517 if (MergeInType(LI->getType(), UsedType, TD)) 518 return 0; 519 520 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 521 // Storing the pointer, not into the value? 522 if (SI->getOperand(0) == V) return 0; 523 524 // NOTE: We could handle storing of FP imms into integers here! 525 526 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD)) 527 return 0; 528 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) { 529 IsNotTrivial = true; 530 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial); 531 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0; 532 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) { 533 // Check to see if this is stepping over an element: GEP Ptr, int C 534 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) { 535 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue(); 536 unsigned ElSize = TD.getTypeSize(PTy->getElementType()); 537 unsigned BitOffset = Idx*ElSize*8; 538 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0; 539 540 IsNotTrivial = true; 541 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial); 542 if (SubElt == 0) return 0; 543 if (SubElt != Type::VoidTy && SubElt->isInteger()) { 544 const Type *NewTy = 545 getUIntAtLeastAsBitAs(TD.getTypeSize(SubElt)*8+BitOffset); 546 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0; 547 continue; 548 } 549 } else if (GEP->getNumOperands() == 3 && 550 isa<ConstantInt>(GEP->getOperand(1)) && 551 isa<ConstantInt>(GEP->getOperand(2)) && 552 cast<Constant>(GEP->getOperand(1))->isNullValue()) { 553 // We are stepping into an element, e.g. a structure or an array: 554 // GEP Ptr, int 0, uint C 555 const Type *AggTy = PTy->getElementType(); 556 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue(); 557 558 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) { 559 if (Idx >= ATy->getNumElements()) return 0; // Out of range. 560 } else if (const PackedType *PackedTy = dyn_cast<PackedType>(AggTy)) { 561 // Getting an element of the packed vector. 562 if (Idx >= PackedTy->getNumElements()) return 0; // Out of range. 563 564 // Merge in the packed type. 565 if (MergeInType(PackedTy, UsedType, TD)) return 0; 566 567 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial); 568 if (SubTy == 0) return 0; 569 570 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD)) 571 return 0; 572 573 // We'll need to change this to an insert/extract element operation. 574 IsNotTrivial = true; 575 continue; // Everything looks ok 576 577 } else if (isa<StructType>(AggTy)) { 578 // Structs are always ok. 579 } else { 580 return 0; 581 } 582 const Type *NTy = getUIntAtLeastAsBitAs(TD.getTypeSize(AggTy)*8); 583 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0; 584 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial); 585 if (SubTy == 0) return 0; 586 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD)) 587 return 0; 588 continue; // Everything looks ok 589 } 590 return 0; 591 } else { 592 // Cannot handle this! 593 return 0; 594 } 595 } 596 597 return UsedType; 598} 599 600/// ConvertToScalar - The specified alloca passes the CanConvertToScalar 601/// predicate and is non-trivial. Convert it to something that can be trivially 602/// promoted into a register by mem2reg. 603void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) { 604 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = " 605 << *ActualTy << "\n"; 606 ++NumConverted; 607 608 BasicBlock *EntryBlock = AI->getParent(); 609 assert(EntryBlock == &EntryBlock->getParent()->front() && 610 "Not in the entry block!"); 611 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program. 612 613 // Create and insert the alloca. 614 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(), 615 EntryBlock->begin()); 616 ConvertUsesToScalar(AI, NewAI, 0); 617 delete AI; 618} 619 620 621/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca 622/// directly. This happens when we are converting an "integer union" to a 623/// single integer scalar, or when we are converting a "vector union" to a 624/// vector with insert/extractelement instructions. 625/// 626/// Offset is an offset from the original alloca, in bits that need to be 627/// shifted to the right. By the end of this, there should be no uses of Ptr. 628void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) { 629 bool isVectorInsert = isa<PackedType>(NewAI->getType()->getElementType()); 630 const TargetData &TD = getAnalysis<TargetData>(); 631 while (!Ptr->use_empty()) { 632 Instruction *User = cast<Instruction>(Ptr->use_back()); 633 634 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 635 // The load is a bit extract from NewAI shifted right by Offset bits. 636 Value *NV = new LoadInst(NewAI, LI->getName(), LI); 637 if (NV->getType() != LI->getType()) { 638 if (const PackedType *PTy = dyn_cast<PackedType>(NV->getType())) { 639 // If the result alloca is a packed type, this is either an element 640 // access or a bitcast to another packed type. 641 if (isa<PackedType>(LI->getType())) { 642 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI); 643 } else { 644 // Must be an element access. 645 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8); 646 NV = new ExtractElementInst( 647 NV, ConstantInt::get(Type::Int32Ty, Elt), "tmp", LI); 648 } 649 } else if (isa<PointerType>(NV->getType())) { 650 assert(isa<PointerType>(LI->getType())); 651 // Must be ptr->ptr cast. Anything else would result in NV being 652 // an integer. 653 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI); 654 } else { 655 assert(NV->getType()->isInteger() && "Unknown promotion!"); 656 if (Offset && Offset < TD.getTypeSize(NV->getType())*8) { 657 NV = BinaryOperator::createLShr(NV, 658 ConstantInt::get(NV->getType(), Offset), 659 LI->getName(), LI); 660 } 661 662 // If the result is an integer, this is a trunc or bitcast. 663 if (LI->getType()->isInteger()) { 664 NV = CastInst::createTruncOrBitCast(NV, LI->getType(), 665 LI->getName(), LI); 666 } else if (LI->getType()->isFloatingPoint()) { 667 // If needed, truncate the integer to the appropriate size. 668 if (NV->getType()->getPrimitiveSizeInBits() > 669 LI->getType()->getPrimitiveSizeInBits()) { 670 switch (LI->getType()->getTypeID()) { 671 default: assert(0 && "Unknown FP type!"); 672 case Type::FloatTyID: 673 NV = new TruncInst(NV, Type::Int32Ty, LI->getName(), LI); 674 break; 675 case Type::DoubleTyID: 676 NV = new TruncInst(NV, Type::Int64Ty, LI->getName(), LI); 677 break; 678 } 679 } 680 681 // Then do a bitcast. 682 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI); 683 } else { 684 // Otherwise must be a pointer. 685 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI); 686 } 687 } 688 } 689 LI->replaceAllUsesWith(NV); 690 LI->eraseFromParent(); 691 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 692 assert(SI->getOperand(0) != Ptr && "Consistency error!"); 693 694 // Convert the stored type to the actual type, shift it left to insert 695 // then 'or' into place. 696 Value *SV = SI->getOperand(0); 697 const Type *AllocaType = NewAI->getType()->getElementType(); 698 if (SV->getType() != AllocaType) { 699 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI); 700 701 if (const PackedType *PTy = dyn_cast<PackedType>(AllocaType)) { 702 // If the result alloca is a packed type, this is either an element 703 // access or a bitcast to another packed type. 704 if (isa<PackedType>(SV->getType())) { 705 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI); 706 } else { 707 // Must be an element insertion. 708 unsigned Elt = Offset/(TD.getTypeSize(PTy->getElementType())*8); 709 SV = new InsertElementInst(Old, SV, 710 ConstantInt::get(Type::Int32Ty, Elt), 711 "tmp", SI); 712 } 713 } else { 714 // If SV is a float, convert it to the appropriate integer type. 715 // If it is a pointer, do the same, and also handle ptr->ptr casts 716 // here. 717 switch (SV->getType()->getTypeID()) { 718 default: 719 assert(!SV->getType()->isFloatingPoint() && "Unknown FP type!"); 720 break; 721 case Type::FloatTyID: 722 SV = new BitCastInst(SV, Type::Int32Ty, SV->getName(), SI); 723 break; 724 case Type::DoubleTyID: 725 SV = new BitCastInst(SV, Type::Int64Ty, SV->getName(), SI); 726 break; 727 case Type::PointerTyID: 728 if (isa<PointerType>(AllocaType)) 729 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI); 730 else 731 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI); 732 break; 733 } 734 735 unsigned SrcSize = TD.getTypeSize(SV->getType())*8; 736 737 // Always zero extend the value if needed. 738 if (SV->getType() != AllocaType) 739 SV = CastInst::createZExtOrBitCast(SV, AllocaType, 740 SV->getName(), SI); 741 if (Offset && Offset < AllocaType->getPrimitiveSizeInBits()) 742 SV = BinaryOperator::createShl(SV, 743 ConstantInt::get(SV->getType(), Offset), 744 SV->getName()+".adj", SI); 745 // Mask out the bits we are about to insert from the old value. 746 unsigned TotalBits = TD.getTypeSize(SV->getType())*8; 747 if (TotalBits != SrcSize) { 748 assert(TotalBits > SrcSize); 749 uint64_t Mask = ~(((1ULL << SrcSize)-1) << Offset); 750 Mask = Mask & cast<IntegerType>(SV->getType())->getBitMask(); 751 Old = BinaryOperator::createAnd(Old, 752 ConstantInt::get(Old->getType(), Mask), 753 Old->getName()+".mask", SI); 754 SV = BinaryOperator::createOr(Old, SV, SV->getName()+".ins", SI); 755 } 756 } 757 } 758 new StoreInst(SV, NewAI, SI); 759 SI->eraseFromParent(); 760 761 } else if (CastInst *CI = dyn_cast<CastInst>(User)) { 762 unsigned NewOff = Offset; 763 const TargetData &TD = getAnalysis<TargetData>(); 764 if (TD.isBigEndian() && !isVectorInsert) { 765 // Adjust the pointer. For example, storing 16-bits into a 32-bit 766 // alloca with just a cast makes it modify the top 16-bits. 767 const Type *SrcTy = cast<PointerType>(Ptr->getType())->getElementType(); 768 const Type *DstTy = cast<PointerType>(CI->getType())->getElementType(); 769 int PtrDiffBits = TD.getTypeSize(SrcTy)*8-TD.getTypeSize(DstTy)*8; 770 NewOff += PtrDiffBits; 771 } 772 ConvertUsesToScalar(CI, NewAI, NewOff); 773 CI->eraseFromParent(); 774 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) { 775 const PointerType *AggPtrTy = 776 cast<PointerType>(GEP->getOperand(0)->getType()); 777 const TargetData &TD = getAnalysis<TargetData>(); 778 unsigned AggSizeInBits = TD.getTypeSize(AggPtrTy->getElementType())*8; 779 780 // Check to see if this is stepping over an element: GEP Ptr, int C 781 unsigned NewOffset = Offset; 782 if (GEP->getNumOperands() == 2) { 783 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue(); 784 unsigned BitOffset = Idx*AggSizeInBits; 785 786 if (TD.isLittleEndian() || isVectorInsert) 787 NewOffset += BitOffset; 788 else 789 NewOffset -= BitOffset; 790 791 } else if (GEP->getNumOperands() == 3) { 792 // We know that operand #2 is zero. 793 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue(); 794 const Type *AggTy = AggPtrTy->getElementType(); 795 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) { 796 unsigned ElSizeBits = TD.getTypeSize(SeqTy->getElementType())*8; 797 798 if (TD.isLittleEndian() || isVectorInsert) 799 NewOffset += ElSizeBits*Idx; 800 else 801 NewOffset += AggSizeInBits-ElSizeBits*(Idx+1); 802 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) { 803 unsigned EltBitOffset = 804 TD.getStructLayout(STy)->getElementOffset(Idx)*8; 805 806 if (TD.isLittleEndian() || isVectorInsert) 807 NewOffset += EltBitOffset; 808 else { 809 const PointerType *ElPtrTy = cast<PointerType>(GEP->getType()); 810 unsigned ElSizeBits = TD.getTypeSize(ElPtrTy->getElementType())*8; 811 NewOffset += AggSizeInBits-(EltBitOffset+ElSizeBits); 812 } 813 814 } else { 815 assert(0 && "Unsupported operation!"); 816 abort(); 817 } 818 } else { 819 assert(0 && "Unsupported operation!"); 820 abort(); 821 } 822 ConvertUsesToScalar(GEP, NewAI, NewOffset); 823 GEP->eraseFromParent(); 824 } else { 825 assert(0 && "Unsupported operation!"); 826 abort(); 827 } 828 } 829} 830