blob: 30160fa8f1e140e4c04782213dc9c8c4281b435e [file] [log] [blame]
Chris Lattnerfb41a502003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerfb41a502003-05-27 15:45:27 +00009//
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
Chris Lattner5d8a12e2003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
Chad Rosiercc899f32012-04-11 19:21:58 +000016// This combines a simple SRoA algorithm with the Mem2Reg algorithm because they
Chris Lattner5d8a12e2003-09-11 16:45:55 +000017// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnerfb41a502003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include "llvm/ADT/SetVector.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000026#include "llvm/Analysis/AssumptionCache.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/Analysis/Loads.h"
28#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000029#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/Constants.h"
Chandler Carruth12664a02014-03-06 00:22:06 +000031#include "llvm/IR/DIBuilder.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/DataLayout.h"
Chandler Carruth9a4c9e52014-03-06 00:46:21 +000033#include "llvm/IR/DebugInfo.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000035#include "llvm/IR/Dominators.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000037#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/GlobalVariable.h"
39#include "llvm/IR/IRBuilder.h"
40#include "llvm/IR/Instructions.h"
41#include "llvm/IR/IntrinsicInst.h"
42#include "llvm/IR/LLVMContext.h"
43#include "llvm/IR/Module.h"
44#include "llvm/IR/Operator.h"
Chris Lattner66e6a822007-03-05 07:52:57 +000045#include "llvm/Pass.h"
Chris Lattner996795b2006-06-28 23:17:24 +000046#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000047#include "llvm/Support/ErrorHandling.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000048#include "llvm/Support/MathExtras.h"
Chris Lattnerb25de3f2009-08-23 04:37:46 +000049#include "llvm/Support/raw_ostream.h"
Chandler Carruthaafe0912012-06-29 12:38:19 +000050#include "llvm/Transforms/Utils/Local.h"
51#include "llvm/Transforms/Utils/PromoteMemToReg.h"
52#include "llvm/Transforms/Utils/SSAUpdater.h"
Chris Lattner40d2aeb2003-12-02 17:43:55 +000053using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000054
Chandler Carruth964daaa2014-04-22 02:55:47 +000055#define DEBUG_TYPE "scalarrepl"
56
Chris Lattner79a42ac2006-12-19 21:40:18 +000057STATISTIC(NumReplaced, "Number of allocas broken up");
58STATISTIC(NumPromoted, "Number of allocas promoted");
Chris Lattnera9607252011-01-23 22:04:55 +000059STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
Chris Lattner79a42ac2006-12-19 21:40:18 +000060STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattnerfb41a502003-05-27 15:45:27 +000061
Chris Lattner79a42ac2006-12-19 21:40:18 +000062namespace {
NAKAMURA Takumi26c38722015-10-24 06:42:42 +000063#define SROA SROA_
Chris Lattner2dd09db2009-09-02 06:11:42 +000064 struct SROA : public FunctionPass {
Nadav Rotem4e9012c2012-06-21 13:44:31 +000065 SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT)
Cameron Zwarich4694e692011-01-18 03:53:26 +000066 : FunctionPass(ID), HasDomTree(hasDT) {
Devang Patele8ec7662007-07-09 21:19:23 +000067 if (T == -1)
Chris Lattner1f708162007-08-02 21:33:36 +000068 SRThreshold = 128;
Devang Patele8ec7662007-07-09 21:19:23 +000069 else
70 SRThreshold = T;
Nadav Rotem4e9012c2012-06-21 13:44:31 +000071 if (ST == -1)
72 StructMemberThreshold = 32;
73 else
74 StructMemberThreshold = ST;
75 if (AT == -1)
76 ArrayElementThreshold = 8;
77 else
78 ArrayElementThreshold = AT;
79 if (SLT == -1)
80 // Do not limit the scalar integer load size if no threshold is given.
81 ScalarLoadThreshold = -1;
82 else
83 ScalarLoadThreshold = SLT;
Devang Patele8ec7662007-07-09 21:19:23 +000084 }
Devang Patel09f162c2007-05-01 21:15:47 +000085
Craig Topper3e4c6972014-03-05 09:10:37 +000086 bool runOnFunction(Function &F) override;
Chris Lattnerfb41a502003-05-27 15:45:27 +000087
Chris Lattner5d8a12e2003-09-11 16:45:55 +000088 bool performScalarRepl(Function &F);
89 bool performPromotion(Function &F);
90
Chris Lattnerfb41a502003-05-27 15:45:27 +000091 private:
Cameron Zwarich4694e692011-01-18 03:53:26 +000092 bool HasDomTree;
Bob Wilson328e91b2011-01-13 20:59:44 +000093
Bob Wilson532cd232009-12-18 20:14:40 +000094 /// DeadInsts - Keep track of instructions we have made dead, so that
95 /// we can remove them after we are done working.
96 SmallVector<Value*, 32> DeadInsts;
97
Chris Lattner87679202007-05-30 06:11:23 +000098 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
99 /// information about the uses. All these fields are initialized to false
100 /// and set to true when something is learned.
101 struct AllocaInfo {
Chris Lattner8acbb792011-01-23 07:29:29 +0000102 /// The alloca to promote.
103 AllocaInst *AI;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000104
Chris Lattner9491dee2011-01-23 08:27:54 +0000105 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
106 /// looping and avoid redundant work.
107 SmallPtrSet<PHINode*, 8> CheckedPHIs;
Nadav Rotem465834c2012-07-24 10:51:42 +0000108
Chris Lattner87679202007-05-30 06:11:23 +0000109 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
110 bool isUnsafe : 1;
Bob Wilson328e91b2011-01-13 20:59:44 +0000111
Chris Lattner87679202007-05-30 06:11:23 +0000112 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
113 bool isMemCpySrc : 1;
114
Zhou Sheng1ee941d2007-07-06 06:01:16 +0000115 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner87679202007-05-30 06:11:23 +0000116 bool isMemCpyDst : 1;
117
Chris Lattner6fab2e92011-01-16 06:18:28 +0000118 /// hasSubelementAccess - This is true if a subelement of the alloca is
119 /// ever accessed, or false if the alloca is only accessed with mem
120 /// intrinsics or load/store that only access the entire alloca at once.
121 bool hasSubelementAccess : 1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000122
Chris Lattner6fab2e92011-01-16 06:18:28 +0000123 /// hasALoadOrStore - This is true if there are any loads or stores to it.
124 /// The alloca may just be accessed with memcpy, for example, which would
125 /// not set this.
126 bool hasALoadOrStore : 1;
Nadav Rotem465834c2012-07-24 10:51:42 +0000127
Chris Lattner8acbb792011-01-23 07:29:29 +0000128 explicit AllocaInfo(AllocaInst *ai)
129 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
Chris Lattner6fab2e92011-01-16 06:18:28 +0000130 hasSubelementAccess(false), hasALoadOrStore(false) {}
Chris Lattner87679202007-05-30 06:11:23 +0000131 };
Bob Wilson328e91b2011-01-13 20:59:44 +0000132
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000133 /// SRThreshold - The maximum alloca size to considered for SROA.
Devang Patele8ec7662007-07-09 21:19:23 +0000134 unsigned SRThreshold;
135
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000136 /// StructMemberThreshold - The maximum number of members a struct can
137 /// contain to be considered for SROA.
138 unsigned StructMemberThreshold;
139
140 /// ArrayElementThreshold - The maximum number of elements an array can
141 /// have to be considered for SROA.
142 unsigned ArrayElementThreshold;
143
144 /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
145 /// converting to scalar
146 unsigned ScalarLoadThreshold;
147
Chris Lattner3e56c292011-01-23 07:05:44 +0000148 void MarkUnsafe(AllocaInfo &I, Instruction *User) {
149 I.isUnsafe = true;
150 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
151 }
Chris Lattner87679202007-05-30 06:11:23 +0000152
Victor Hernandez1df65182010-01-21 23:05:53 +0000153 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner87679202007-05-30 06:11:23 +0000154
Chris Lattner8acbb792011-01-23 07:29:29 +0000155 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
Chris Lattner9491dee2011-01-23 08:27:54 +0000156 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
157 AllocaInfo &Info);
Chris Lattner8acbb792011-01-23 07:29:29 +0000158 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
159 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattner229907c2011-07-18 04:54:35 +0000160 Type *MemOpType, bool isStore, AllocaInfo &Info,
Chris Lattner9491dee2011-01-23 08:27:54 +0000161 Instruction *TheAccess, bool AllowWholeAccess);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000162 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
163 const DataLayout &DL);
164 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset, Type *&IdxTy,
165 const DataLayout &DL);
Bob Wilson328e91b2011-01-13 20:59:44 +0000166
167 void DoScalarReplacement(AllocaInst *AI,
Victor Hernandez8acf2952009-10-23 21:09:37 +0000168 std::vector<AllocaInst*> &WorkList);
Bob Wilson532cd232009-12-18 20:14:40 +0000169 void DeleteDeadInstructions();
Bob Wilson328e91b2011-01-13 20:59:44 +0000170
Bob Wilson532cd232009-12-18 20:14:40 +0000171 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000172 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000173 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000174 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000175 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000176 SmallVectorImpl<AllocaInst *> &NewElts);
Nick Lewycky15e2d902011-07-25 23:14:22 +0000177 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
178 uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +0000179 SmallVectorImpl<AllocaInst *> &NewElts);
Bob Wilson532cd232009-12-18 20:14:40 +0000180 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez8acf2952009-10-23 21:09:37 +0000181 AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000182 SmallVectorImpl<AllocaInst *> &NewElts);
Victor Hernandez8acf2952009-10-23 21:09:37 +0000183 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000184 SmallVectorImpl<AllocaInst *> &NewElts);
Victor Hernandez8acf2952009-10-23 21:09:37 +0000185 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Craig Topperb94011f2013-07-14 04:42:23 +0000186 SmallVectorImpl<AllocaInst *> &NewElts);
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000187 bool ShouldAttemptScalarRepl(AllocaInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000188 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000189
Cameron Zwarich4694e692011-01-18 03:53:26 +0000190 // SROA_DT - SROA that uses DominatorTree.
191 struct SROA_DT : public SROA {
Chris Lattner9987a6f2011-01-14 08:13:00 +0000192 static char ID;
193 public:
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000194 SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
195 SROA(T, true, ID, ST, AT, SLT) {
Cameron Zwarich4694e692011-01-18 03:53:26 +0000196 initializeSROA_DTPass(*PassRegistry::getPassRegistry());
Chris Lattner9987a6f2011-01-14 08:13:00 +0000197 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000198
Chris Lattner9987a6f2011-01-14 08:13:00 +0000199 // getAnalysisUsage - This pass does not require any passes, but we know it
200 // will not alter the CFG, so say so.
Craig Topper3e4c6972014-03-05 09:10:37 +0000201 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000202 AU.addRequired<AssumptionCacheTracker>();
Chandler Carruth73523022014-01-13 13:07:17 +0000203 AU.addRequired<DominatorTreeWrapperPass>();
Chris Lattner9987a6f2011-01-14 08:13:00 +0000204 AU.setPreservesCFG();
205 }
206 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000207
Chris Lattner9987a6f2011-01-14 08:13:00 +0000208 // SROA_SSAUp - SROA that uses SSAUpdater.
209 struct SROA_SSAUp : public SROA {
210 static char ID;
211 public:
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000212 SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) :
213 SROA(T, false, ID, ST, AT, SLT) {
Chris Lattner9987a6f2011-01-14 08:13:00 +0000214 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
215 }
Nadav Rotem465834c2012-07-24 10:51:42 +0000216
Chris Lattner9987a6f2011-01-14 08:13:00 +0000217 // getAnalysisUsage - This pass does not require any passes, but we know it
218 // will not alter the CFG, so say so.
Craig Topper3e4c6972014-03-05 09:10:37 +0000219 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth66b31302015-01-04 12:03:27 +0000220 AU.addRequired<AssumptionCacheTracker>();
Chris Lattner9987a6f2011-01-14 08:13:00 +0000221 AU.setPreservesCFG();
222 }
223 };
Nadav Rotem465834c2012-07-24 10:51:42 +0000224
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000225}
Chris Lattnerfb41a502003-05-27 15:45:27 +0000226
Cameron Zwarich4694e692011-01-18 03:53:26 +0000227char SROA_DT::ID = 0;
Chris Lattner9987a6f2011-01-14 08:13:00 +0000228char SROA_SSAUp::ID = 0;
229
Cameron Zwarich4694e692011-01-18 03:53:26 +0000230INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl",
231 "Scalar Replacement of Aggregates (DT)", false, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000232INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chandler Carruth73523022014-01-13 13:07:17 +0000233INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Cameron Zwarich4694e692011-01-18 03:53:26 +0000234INITIALIZE_PASS_END(SROA_DT, "scalarrepl",
235 "Scalar Replacement of Aggregates (DT)", false, false)
Chris Lattner9987a6f2011-01-14 08:13:00 +0000236
237INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa",
238 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Chandler Carruth66b31302015-01-04 12:03:27 +0000239INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Chris Lattner9987a6f2011-01-14 08:13:00 +0000240INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa",
241 "Scalar Replacement of Aggregates (SSAUp)", false, false)
Dan Gohmand78c4002008-05-13 00:00:25 +0000242
Brian Gaeke960707c2003-11-11 22:41:34 +0000243// Public interface to the ScalarReplAggregates pass
Chris Lattner9987a6f2011-01-14 08:13:00 +0000244FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold,
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000245 bool UseDomTree,
246 int StructMemberThreshold,
247 int ArrayElementThreshold,
248 int ScalarLoadThreshold) {
Cameron Zwarich4694e692011-01-18 03:53:26 +0000249 if (UseDomTree)
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000250 return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold,
251 ScalarLoadThreshold);
252 return new SROA_SSAUp(Threshold, StructMemberThreshold,
253 ArrayElementThreshold, ScalarLoadThreshold);
Devang Patele8ec7662007-07-09 21:19:23 +0000254}
Chris Lattnerfb41a502003-05-27 15:45:27 +0000255
256
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000257//===----------------------------------------------------------------------===//
258// Convert To Scalar Optimization.
259//===----------------------------------------------------------------------===//
260
261namespace {
Chris Lattnerb7355292010-04-16 00:38:19 +0000262/// ConvertToScalarInfo - This class implements the "Convert To Scalar"
263/// optimization, which scans the uses of an alloca and determines if it can
264/// rewrite it in terms of a single new alloca that can be mem2reg'd.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000265class ConvertToScalarInfo {
Cameron Zwarich63062cc2011-03-16 00:13:35 +0000266 /// AllocaSize - The size of the alloca being considered in bytes.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000267 unsigned AllocaSize;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000268 const DataLayout &DL;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000269 unsigned ScalarLoadThreshold;
Bob Wilson328e91b2011-01-13 20:59:44 +0000270
Chris Lattnerbd2d9432010-04-16 02:32:17 +0000271 /// IsNotTrivial - This is set to true if there is some access to the object
Chris Lattnerb7355292010-04-16 00:38:19 +0000272 /// which means that mem2reg can't promote it.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000273 bool IsNotTrivial;
Bob Wilson328e91b2011-01-13 20:59:44 +0000274
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000275 /// ScalarKind - Tracks the kind of alloca being considered for promotion,
276 /// computed based on the uses of the alloca rather than the LLVM type system.
277 enum {
278 Unknown,
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000279
Cameron Zwarich922e4942011-06-13 23:39:23 +0000280 // Accesses via GEPs that are consistent with element access of a vector
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000281 // type. This will not be converted into a vector unless there is a later
282 // access using an actual vector type.
283 ImplicitVector,
284
Cameron Zwarich922e4942011-06-13 23:39:23 +0000285 // Accesses via vector operations and GEPs that are consistent with the
286 // layout of a vector type.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000287 Vector,
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000288
289 // An integer bag-of-bits with bitwise operations for insertion and
290 // extraction. Any combination of types can be converted into this kind
291 // of scalar.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000292 Integer
293 } ScalarKind;
294
Chris Lattnerb7355292010-04-16 00:38:19 +0000295 /// VectorTy - This tracks the type that we should promote the vector to if
296 /// it is possible to turn it into a vector. This starts out null, and if it
297 /// isn't possible to turn into a vector type, it gets set to VoidTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000298 VectorType *VectorTy;
Bob Wilson328e91b2011-01-13 20:59:44 +0000299
Nadav Rotem465834c2012-07-24 10:51:42 +0000300 /// HadNonMemTransferAccess - True if there is at least one access to the
Cameron Zwarich7599b102011-03-16 08:13:42 +0000301 /// alloca that is not a MemTransferInst. We don't want to turn structs into
302 /// large integers unless there is some potential for optimization.
Cameron Zwarich04542532011-03-16 00:13:44 +0000303 bool HadNonMemTransferAccess;
304
Pete Cooper33ee6c92012-06-17 03:58:26 +0000305 /// HadDynamicAccess - True if some element of this alloca was dynamic.
306 /// We don't yet have support for turning a dynamic access into a large
307 /// integer.
308 bool HadDynamicAccess;
309
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000310public:
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000311 explicit ConvertToScalarInfo(unsigned Size, const DataLayout &DL,
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000312 unsigned SLT)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000313 : AllocaSize(Size), DL(DL), ScalarLoadThreshold(SLT), IsNotTrivial(false),
Craig Topperf40110f2014-04-25 05:29:35 +0000314 ScalarKind(Unknown), VectorTy(nullptr), HadNonMemTransferAccess(false),
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000315 HadDynamicAccess(false) { }
Bob Wilson328e91b2011-01-13 20:59:44 +0000316
Chris Lattnerb7355292010-04-16 00:38:19 +0000317 AllocaInst *TryConvert(AllocaInst *AI);
Bob Wilson328e91b2011-01-13 20:59:44 +0000318
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000319private:
Pete Cooper33ee6c92012-06-17 03:58:26 +0000320 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx);
Chris Lattner229907c2011-07-18 04:54:35 +0000321 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset);
322 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset);
Pete Cooper33ee6c92012-06-17 03:58:26 +0000323 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset,
324 Value *NonConstantIdx);
Bob Wilson328e91b2011-01-13 20:59:44 +0000325
Chris Lattner229907c2011-07-18 04:54:35 +0000326 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000327 uint64_t Offset, Value* NonConstantIdx,
328 IRBuilder<> &Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000329 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000330 uint64_t Offset, Value* NonConstantIdx,
331 IRBuilder<> &Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000332};
333} // end anonymous namespace.
334
Chris Lattner34e53612010-09-01 05:14:33 +0000335
Chris Lattnerb7355292010-04-16 00:38:19 +0000336/// TryConvert - Analyze the specified alloca, and if it is safe to do so,
337/// rewrite it to be a new alloca which is mem2reg'able. This returns the new
338/// alloca if possible or null if not.
339AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) {
340 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
341 // out.
Craig Topperf40110f2014-04-25 05:29:35 +0000342 if (!CanConvertToScalar(AI, 0, nullptr) || !IsNotTrivial)
343 return nullptr;
Bob Wilson328e91b2011-01-13 20:59:44 +0000344
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000345 // If an alloca has only memset / memcpy uses, it may still have an Unknown
346 // ScalarKind. Treat it as an Integer below.
347 if (ScalarKind == Unknown)
348 ScalarKind = Integer;
349
Cameron Zwarich9601ddb2011-06-18 06:17:51 +0000350 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8)
351 ScalarKind = Integer;
352
Chris Lattnerb7355292010-04-16 00:38:19 +0000353 // If we were able to find a vector type that can handle this with
354 // insert/extract elements, and if there was at least one use that had
355 // a vector type, promote this to a vector. We don't want to promote
356 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
357 // we just get a lot of insert/extracts. If at least one vector is
358 // involved, then we probably really do have a union of vector/array.
Chris Lattner229907c2011-07-18 04:54:35 +0000359 Type *NewTy;
Cameron Zwarichb5f19d92011-06-14 06:33:51 +0000360 if (ScalarKind == Vector) {
361 assert(VectorTy && "Missing type for vector scalar.");
Chris Lattnerb7355292010-04-16 00:38:19 +0000362 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
363 << *VectorTy << '\n');
364 NewTy = VectorTy; // Use the vector type.
365 } else {
Cameron Zwarich04542532011-03-16 00:13:44 +0000366 unsigned BitWidth = AllocaSize * 8;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000367
368 // Do not convert to scalar integer if the alloca size exceeds the
369 // scalar load threshold.
370 if (BitWidth > ScalarLoadThreshold)
Craig Topperf40110f2014-04-25 05:29:35 +0000371 return nullptr;
Nadav Rotem4e9012c2012-06-21 13:44:31 +0000372
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000373 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000374 !HadNonMemTransferAccess && !DL.fitsInLegalInteger(BitWidth))
Craig Topperf40110f2014-04-25 05:29:35 +0000375 return nullptr;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000376 // Dynamic accesses on integers aren't yet supported. They need us to shift
377 // by a dynamic amount which could be difficult to work out as we might not
378 // know whether to use a left or right shift.
379 if (ScalarKind == Integer && HadDynamicAccess)
Craig Topperf40110f2014-04-25 05:29:35 +0000380 return nullptr;
Cameron Zwarich04542532011-03-16 00:13:44 +0000381
Chris Lattnerb7355292010-04-16 00:38:19 +0000382 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
383 // Create and insert the integer alloca.
Cameron Zwarich04542532011-03-16 00:13:44 +0000384 NewTy = IntegerType::get(AI->getContext(), BitWidth);
Chris Lattnerb7355292010-04-16 00:38:19 +0000385 }
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +0000386 AllocaInst *NewAI =
387 new AllocaInst(NewTy, nullptr, "", &AI->getParent()->front());
Craig Topperf40110f2014-04-25 05:29:35 +0000388 ConvertUsesToScalar(AI, NewAI, 0, nullptr);
Chris Lattnerb7355292010-04-16 00:38:19 +0000389 return NewAI;
390}
391
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000392/// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type
393/// (VectorTy) so far at the offset specified by Offset (which is specified in
394/// bytes).
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000395///
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000396/// There are two cases we handle here:
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000397/// 1) A union of vector types of the same size and potentially its elements.
398/// Here we turn element accesses into insert/extract element operations.
399/// This promotes a <4 x float> with a store of float to the third element
400/// into a <4 x float> that uses insert element.
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000401/// 2) A fully general blob of memory, which we turn into some (potentially
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000402/// large) integer type with extract and insert operations where the loads
Chris Lattnerb7355292010-04-16 00:38:19 +0000403/// and stores would mutate the memory. We mark this by setting VectorTy
404/// to VoidTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000405void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In,
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000406 uint64_t Offset) {
Chris Lattnerb7355292010-04-16 00:38:19 +0000407 // If we already decided to turn this into a blob of integer memory, there is
408 // nothing to be done.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000409 if (ScalarKind == Integer)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000410 return;
Bob Wilson328e91b2011-01-13 20:59:44 +0000411
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000412 // If this could be contributing to a vector, analyze it.
413
414 // If the In type is a vector that is the same size as the alloca, see if it
415 // matches the existing VecTy.
Chris Lattner229907c2011-07-18 04:54:35 +0000416 if (VectorType *VInTy = dyn_cast<VectorType>(In)) {
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000417 if (MergeInVectorType(VInTy, Offset))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000418 return;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000419 } else if (In->isFloatTy() || In->isDoubleTy() ||
420 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
421 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
Cameron Zwarichff811cc2011-03-29 05:19:52 +0000422 // Full width accesses can be ignored, because they can always be turned
423 // into bitcasts.
424 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Cameron Zwarich8deb6152011-06-13 21:44:31 +0000425 if (EltSize == AllocaSize)
Cameron Zwarichff811cc2011-03-29 05:19:52 +0000426 return;
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000427
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000428 // If we're accessing something that could be an element of a vector, see
429 // if the implied vector agrees with what we already have and if Offset is
430 // compatible with it.
Cameron Zwarich77a699a2011-06-09 01:45:33 +0000431 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000432 (!VectorTy || EltSize == VectorTy->getElementType()
433 ->getPrimitiveSizeInBits()/8)) {
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000434 if (!VectorTy) {
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000435 ScalarKind = ImplicitVector;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000436 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Cameron Zwarich4cd9a4a2011-04-20 21:48:16 +0000437 }
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000438 return;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000439 }
440 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000441
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000442 // Otherwise, we have a case that we can't handle with an optimized vector
443 // form. We can still turn this into a large integer.
Cameron Zwarich5e9a0be2011-06-13 21:44:35 +0000444 ScalarKind = Integer;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000445}
446
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000447/// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore,
448/// returning true if the type was successfully merged and false otherwise.
Chris Lattner229907c2011-07-18 04:54:35 +0000449bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy,
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000450 uint64_t Offset) {
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000451 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
452 // If we're storing/loading a vector of the right size, allow it as a
453 // vector. If this the first vector we see, remember the type so that
454 // we know the element size. If this is a subsequent access, ignore it
455 // even if it is a differing type but the same size. Worst case we can
456 // bitcast the resultant vectors.
457 if (!VectorTy)
458 VectorTy = VInTy;
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000459 ScalarKind = Vector;
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000460 return true;
Cameron Zwarich8cb90ac2011-06-13 21:44:40 +0000461 }
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000462
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000463 return false;
Cameron Zwarich43a241f2011-03-09 05:43:01 +0000464}
465
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000466/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
467/// its accesses to a single vector type, return true and set VecTy to
468/// the new type. If we could convert the alloca into a single promotable
469/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
470/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
471/// is the current offset from the base of the alloca being analyzed.
472///
473/// If we see at least one access to the value that is as a vector type, set the
474/// SawVec flag.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000475bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset,
476 Value* NonConstantIdx) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000477 for (User *U : V->users()) {
478 Instruction *UI = cast<Instruction>(U);
Bob Wilson328e91b2011-01-13 20:59:44 +0000479
Chandler Carruthcdf47882014-03-09 03:16:01 +0000480 if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000481 // Don't break volatile loads.
Eli Friedman7c5dc122011-09-12 20:23:13 +0000482 if (!LI->isSimple())
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000483 return false;
Dale Johannesendd224d22010-09-30 23:57:10 +0000484 // Don't touch MMX operations.
485 if (LI->getType()->isX86_MMXTy())
486 return false;
Cameron Zwarich04542532011-03-16 00:13:44 +0000487 HadNonMemTransferAccess = true;
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000488 MergeInTypeForLoadOrStore(LI->getType(), Offset);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000489 continue;
490 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000491
Chandler Carruthcdf47882014-03-09 03:16:01 +0000492 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000493 // Storing the pointer, not into the value?
Eli Friedman7c5dc122011-09-12 20:23:13 +0000494 if (SI->getOperand(0) == V || !SI->isSimple()) return false;
Dale Johannesendd224d22010-09-30 23:57:10 +0000495 // Don't touch MMX operations.
496 if (SI->getOperand(0)->getType()->isX86_MMXTy())
497 return false;
Cameron Zwarich04542532011-03-16 00:13:44 +0000498 HadNonMemTransferAccess = true;
Cameron Zwarich3ecbd592011-06-13 21:44:43 +0000499 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000500 continue;
501 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000502
Chandler Carruthcdf47882014-03-09 03:16:01 +0000503 if (BitCastInst *BCI = dyn_cast<BitCastInst>(UI)) {
Nick Lewycky15e2d902011-07-25 23:14:22 +0000504 if (!onlyUsedByLifetimeMarkers(BCI))
505 IsNotTrivial = true; // Can't be mem2reg'd.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000506 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000507 return false;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000508 continue;
509 }
510
Chandler Carruthcdf47882014-03-09 03:16:01 +0000511 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000512 // If this is a GEP with a variable indices, we can't handle it.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000513 // Compute the offset that this GEP adds to the pointer.
514 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Craig Topperf40110f2014-04-25 05:29:35 +0000515 Value *GEPNonConstantIdx = nullptr;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000516 if (!GEP->hasAllConstantIndices()) {
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000517 if (!isa<VectorType>(GEP->getSourceElementType()))
Pete Cooper33ee6c92012-06-17 03:58:26 +0000518 return false;
519 if (NonConstantIdx)
520 return false;
521 GEPNonConstantIdx = Indices.pop_back_val();
522 if (!GEPNonConstantIdx->getType()->isIntegerTy(32))
523 return false;
524 HadDynamicAccess = true;
525 } else
526 GEPNonConstantIdx = NonConstantIdx;
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000527 uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foadbf904772011-07-19 14:01:37 +0000528 Indices);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000529 // See if all uses can be converted.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000530 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx))
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000531 return false;
Chris Lattnerb7355292010-04-16 00:38:19 +0000532 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich04542532011-03-16 00:13:44 +0000533 HadNonMemTransferAccess = true;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000534 continue;
535 }
536
537 // If this is a constant sized memset of a constant value (e.g. 0) we can
538 // handle it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000539 if (MemSetInst *MSI = dyn_cast<MemSetInst>(UI)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000540 // Store to dynamic index.
541 if (NonConstantIdx)
542 return false;
Cameron Zwarich2a261002011-06-18 05:47:49 +0000543 // Store of constant value.
544 if (!isa<ConstantInt>(MSI->getValue()))
Chris Lattnerb7355292010-04-16 00:38:19 +0000545 return false;
Cameron Zwarich2a261002011-06-18 05:47:49 +0000546
547 // Store of constant size.
548 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength());
549 if (!Len)
550 return false;
551
552 // If the size differs from the alloca, we can only convert the alloca to
553 // an integer bag-of-bits.
554 // FIXME: This should handle all of the cases that are currently accepted
555 // as vector element insertions.
556 if (Len->getZExtValue() != AllocaSize || Offset != 0)
557 ScalarKind = Integer;
558
Chris Lattnerb7355292010-04-16 00:38:19 +0000559 IsNotTrivial = true; // Can't be mem2reg'd.
Cameron Zwarich04542532011-03-16 00:13:44 +0000560 HadNonMemTransferAccess = true;
Chris Lattnerb7355292010-04-16 00:38:19 +0000561 continue;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000562 }
563
564 // If this is a memcpy or memmove into or out of the whole allocation, we
565 // can handle it like a load or store of the scalar type.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000566 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(UI)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000567 // Store to dynamic index.
568 if (NonConstantIdx)
569 return false;
Chris Lattnerb7355292010-04-16 00:38:19 +0000570 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +0000571 if (!Len || Len->getZExtValue() != AllocaSize || Offset != 0)
Chris Lattnerb7355292010-04-16 00:38:19 +0000572 return false;
Bob Wilson328e91b2011-01-13 20:59:44 +0000573
Chris Lattnerb7355292010-04-16 00:38:19 +0000574 IsNotTrivial = true; // Can't be mem2reg'd.
575 continue;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000576 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000577
Nick Lewycky15e2d902011-07-25 23:14:22 +0000578 // If this is a lifetime intrinsic, we can handle it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000579 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(UI)) {
Nick Lewycky15e2d902011-07-25 23:14:22 +0000580 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
581 II->getIntrinsicID() == Intrinsic::lifetime_end) {
582 continue;
583 }
584 }
585
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000586 // Otherwise, we cannot handle this!
587 return false;
588 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000589
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000590 return true;
591}
592
593/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
594/// directly. This happens when we are converting an "integer union" to a
595/// single integer scalar, or when we are converting a "vector union" to a
596/// vector with insert/extractelement instructions.
597///
598/// Offset is an offset from the original alloca, in bits that need to be
599/// shifted to the right. By the end of this, there should be no uses of Ptr.
600void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000601 uint64_t Offset,
602 Value* NonConstantIdx) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000603 while (!Ptr->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +0000604 Instruction *User = cast<Instruction>(Ptr->user_back());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000605
606 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000607 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000608 CI->eraseFromParent();
609 continue;
610 }
611
612 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
613 // Compute the offset that this GEP adds to the pointer.
614 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Craig Topperf40110f2014-04-25 05:29:35 +0000615 Value* GEPNonConstantIdx = nullptr;
Pete Cooper0deca6b2012-08-10 03:26:36 +0000616 if (!GEP->hasAllConstantIndices()) {
617 assert(!NonConstantIdx &&
618 "Dynamic GEP reading from dynamic GEP unsupported");
619 GEPNonConstantIdx = Indices.pop_back_val();
620 } else
621 GEPNonConstantIdx = NonConstantIdx;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000622 uint64_t GEPOffset = DL.getIndexedOffset(GEP->getPointerOperandType(),
Jay Foadbf904772011-07-19 14:01:37 +0000623 Indices);
Pete Cooper0deca6b2012-08-10 03:26:36 +0000624 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000625 GEP->eraseFromParent();
626 continue;
627 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000628
Chris Lattner6cf8d6c2010-12-26 22:57:41 +0000629 IRBuilder<> Builder(User);
Bob Wilson328e91b2011-01-13 20:59:44 +0000630
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000631 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
632 // The load is a bit extract from NewAI shifted right by Offset bits.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000633 Value *LoadedVal = Builder.CreateLoad(NewAI);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000634 Value *NewLoadVal
Pete Cooper33ee6c92012-06-17 03:58:26 +0000635 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset,
636 NonConstantIdx, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000637 LI->replaceAllUsesWith(NewLoadVal);
638 LI->eraseFromParent();
639 continue;
640 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000641
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000642 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
643 assert(SI->getOperand(0) != Ptr && "Consistency error!");
644 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
645 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000646 NonConstantIdx, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000647 Builder.CreateStore(New, NewAI);
648 SI->eraseFromParent();
Bob Wilson328e91b2011-01-13 20:59:44 +0000649
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000650 // If the load we just inserted is now dead, then the inserted store
651 // overwrote the entire thing.
652 if (Old->use_empty())
653 Old->eraseFromParent();
654 continue;
655 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000656
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000657 // If this is a constant sized memset of a constant value (e.g. 0) we can
658 // transform it into a store of the expanded constant value.
659 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
660 assert(MSI->getRawDest() == Ptr && "Consistency error!");
Pete Cooper33ee6c92012-06-17 03:58:26 +0000661 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert");
Duncan Sands8f897dc2012-03-23 08:29:04 +0000662 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue();
Chris Lattner7d7dba32012-03-22 03:46:58 +0000663 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) {
Aaron Ballmana7332972012-03-15 00:05:31 +0000664 unsigned NumBytes = static_cast<unsigned>(SNumBytes);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000665 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
Bob Wilson328e91b2011-01-13 20:59:44 +0000666
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000667 // Compute the value replicated the right number of times.
668 APInt APVal(NumBytes*8, Val);
669
670 // Splat the value if non-zero.
671 if (Val)
672 for (unsigned i = 1; i != NumBytes; ++i)
673 APVal |= APVal << 8;
Bob Wilson328e91b2011-01-13 20:59:44 +0000674
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000675 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
676 Value *New = ConvertScalar_InsertValue(
677 ConstantInt::get(User->getContext(), APVal),
Craig Topperf40110f2014-04-25 05:29:35 +0000678 Old, Offset, nullptr, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000679 Builder.CreateStore(New, NewAI);
Bob Wilson328e91b2011-01-13 20:59:44 +0000680
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000681 // If the load we just inserted is now dead, then the memset overwrote
682 // the entire thing.
683 if (Old->use_empty())
Bob Wilson328e91b2011-01-13 20:59:44 +0000684 Old->eraseFromParent();
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000685 }
686 MSI->eraseFromParent();
687 continue;
688 }
689
690 // If this is a memcpy or memmove into or out of the whole allocation, we
691 // can handle it like a load or store of the scalar type.
692 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
693 assert(Offset == 0 && "must be store to start of alloca");
Pete Cooper33ee6c92012-06-17 03:58:26 +0000694 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert");
Bob Wilson328e91b2011-01-13 20:59:44 +0000695
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000696 // If the source and destination are both to the same alloca, then this is
697 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
698 // as appropriate.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000699 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, DL, 0));
Bob Wilson328e91b2011-01-13 20:59:44 +0000700
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000701 if (GetUnderlyingObject(MTI->getSource(), DL, 0) != OrigAI) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000702 // Dest must be OrigAI, change this to be a load from the original
703 // pointer (bitcasted), then a store to our new alloca.
704 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
705 Value *SrcPtr = MTI->getSource();
Chris Lattner229907c2011-07-18 04:54:35 +0000706 PointerType* SPTy = cast<PointerType>(SrcPtr->getType());
707 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wang18b762a2010-12-23 01:41:32 +0000708 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
Eduard Burtescu90c44492016-01-18 00:10:01 +0000709 AIPTy = PointerType::get(NewAI->getAllocatedType(),
Mon P Wang18b762a2010-12-23 01:41:32 +0000710 SPTy->getAddressSpace());
711 }
712 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy);
713
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000714 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
Pete Cooper67cf9a72015-11-19 05:56:52 +0000715 SrcVal->setAlignment(MTI->getAlignment());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000716 Builder.CreateStore(SrcVal, NewAI);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000717 } else if (GetUnderlyingObject(MTI->getDest(), DL, 0) != OrigAI) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000718 // Src must be OrigAI, change this to be a load from NewAI then a store
719 // through the original dest pointer (bitcasted).
720 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
721 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
722
Chris Lattner229907c2011-07-18 04:54:35 +0000723 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType());
724 PointerType* AIPTy = cast<PointerType>(NewAI->getType());
Mon P Wang18b762a2010-12-23 01:41:32 +0000725 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) {
Eduard Burtescu90c44492016-01-18 00:10:01 +0000726 AIPTy = PointerType::get(NewAI->getAllocatedType(),
Mon P Wang18b762a2010-12-23 01:41:32 +0000727 DPTy->getAddressSpace());
728 }
729 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy);
730
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000731 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000732 NewStore->setAlignment(MTI->getAlignment());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000733 } else {
734 // Noop transfer. Src == Dst
735 }
736
737 MTI->eraseFromParent();
738 continue;
739 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000740
Nick Lewycky15e2d902011-07-25 23:14:22 +0000741 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
742 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
743 II->getIntrinsicID() == Intrinsic::lifetime_end) {
744 // There's no need to preserve these, as the resulting alloca will be
745 // converted to a register anyways.
746 II->eraseFromParent();
747 continue;
748 }
749 }
750
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000751 llvm_unreachable("Unsupported operation!");
752 }
753}
754
755/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
756/// or vector value FromVal, extracting the bits from the offset specified by
757/// Offset. This returns the value, which is of type ToType.
758///
759/// This happens when we are converting an "integer union" to a single
760/// integer scalar, or when we are converting a "vector union" to a vector with
761/// insert/extractelement instructions.
762///
763/// Offset is an offset from the original alloca, in bits that need to be
764/// shifted to the right.
765Value *ConvertToScalarInfo::
Chris Lattner229907c2011-07-18 04:54:35 +0000766ConvertScalar_ExtractValue(Value *FromVal, Type *ToType,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000767 uint64_t Offset, Value* NonConstantIdx,
768 IRBuilder<> &Builder) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000769 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner229907c2011-07-18 04:54:35 +0000770 Type *FromType = FromVal->getType();
Mon P Wang2e5528f2011-04-13 21:40:02 +0000771 if (FromType == ToType && Offset == 0)
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000772 return FromVal;
773
774 // If the result alloca is a vector type, this is either an element
775 // access or a bitcast to another vector type of the same size.
Chris Lattner229907c2011-07-18 04:54:35 +0000776 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000777 unsigned FromTypeSize = DL.getTypeAllocSize(FromType);
778 unsigned ToTypeSize = DL.getTypeAllocSize(ToType);
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000779 if (FromTypeSize == ToTypeSize)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000780 return Builder.CreateBitCast(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000781
782 // Otherwise it must be an element access.
783 unsigned Elt = 0;
784 if (Offset) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000785 unsigned EltSize = DL.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000786 Elt = Offset/EltSize;
787 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
788 }
789 // Return the element extracted out of it.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000790 Value *Idx;
791 if (NonConstantIdx) {
792 if (Elt)
793 Idx = Builder.CreateAdd(NonConstantIdx,
794 Builder.getInt32(Elt),
795 "dyn.offset");
796 else
797 Idx = NonConstantIdx;
798 } else
799 Idx = Builder.getInt32(Elt);
800 Value *V = Builder.CreateExtractElement(FromVal, Idx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000801 if (V->getType() != ToType)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000802 V = Builder.CreateBitCast(V, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000803 return V;
804 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000805
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000806 // If ToType is a first class aggregate, extract out each of the pieces and
807 // use insertvalue's to form the FCA.
Chris Lattner229907c2011-07-18 04:54:35 +0000808 if (StructType *ST = dyn_cast<StructType>(ToType)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000809 assert(!NonConstantIdx &&
810 "Dynamic indexing into struct types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000811 const StructLayout &Layout = *DL.getStructLayout(ST);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000812 Value *Res = UndefValue::get(ST);
813 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
814 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
815 Offset+Layout.getElementOffsetInBits(i),
Craig Topperf40110f2014-04-25 05:29:35 +0000816 nullptr, Builder);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000817 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000818 }
819 return Res;
820 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000821
Chris Lattner229907c2011-07-18 04:54:35 +0000822 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000823 assert(!NonConstantIdx &&
824 "Dynamic indexing into array types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000825 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000826 Value *Res = UndefValue::get(AT);
827 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
828 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
Craig Topperf40110f2014-04-25 05:29:35 +0000829 Offset+i*EltSize, nullptr,
830 Builder);
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000831 Res = Builder.CreateInsertValue(Res, Elt, i);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000832 }
833 return Res;
834 }
835
836 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner229907c2011-07-18 04:54:35 +0000837 IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000838
839 // If this is a big-endian system and the load is narrower than the
840 // full alloca type, we need to do a shift to get the right bits.
841 int ShAmt = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000842 if (DL.isBigEndian()) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000843 // On big-endian machines, the lowest bit is stored at the bit offset
844 // from the pointer given by getTypeStoreSizeInBits. This matters for
845 // integers with a bitwidth that is not a multiple of 8.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000846 ShAmt = DL.getTypeStoreSizeInBits(NTy) -
847 DL.getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000848 } else {
849 ShAmt = Offset;
850 }
851
852 // Note: we support negative bitwidths (with shl) which are not defined.
853 // We do this to support (f.e.) loads off the end of a structure where
854 // only some bits are used.
855 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
856 FromVal = Builder.CreateLShr(FromVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000857 ConstantInt::get(FromVal->getType(), ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000858 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Bob Wilson328e91b2011-01-13 20:59:44 +0000859 FromVal = Builder.CreateShl(FromVal,
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000860 ConstantInt::get(FromVal->getType(), -ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000861
862 // Finally, unconditionally truncate the integer to the right width.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000863 unsigned LIBitWidth = DL.getTypeSizeInBits(ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000864 if (LIBitWidth < NTy->getBitWidth())
865 FromVal =
Bob Wilson328e91b2011-01-13 20:59:44 +0000866 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000867 LIBitWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000868 else if (LIBitWidth > NTy->getBitWidth())
869 FromVal =
Bob Wilson328e91b2011-01-13 20:59:44 +0000870 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000871 LIBitWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000872
873 // If the result is an integer, this is a trunc or bitcast.
874 if (ToType->isIntegerTy()) {
875 // Should be done.
876 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
877 // Just do a bitcast, we know the sizes match up.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000878 FromVal = Builder.CreateBitCast(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000879 } else {
880 // Otherwise must be a pointer.
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000881 FromVal = Builder.CreateIntToPtr(FromVal, ToType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000882 }
883 assert(FromVal->getType() == ToType && "Didn't convert right?");
884 return FromVal;
885}
886
887/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
888/// or vector value "Old" at the offset specified by Offset.
889///
890/// This happens when we are converting an "integer union" to a
891/// single integer scalar, or when we are converting a "vector union" to a
892/// vector with insert/extractelement instructions.
893///
894/// Offset is an offset from the original alloca, in bits that need to be
895/// shifted to the right.
Pete Cooper33ee6c92012-06-17 03:58:26 +0000896///
897/// NonConstantIdx is an index value if there was a GEP with a non-constant
898/// index value. If this is 0 then all GEPs used to find this insert address
899/// are constant.
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000900Value *ConvertToScalarInfo::
901ConvertScalar_InsertValue(Value *SV, Value *Old,
Pete Cooper33ee6c92012-06-17 03:58:26 +0000902 uint64_t Offset, Value* NonConstantIdx,
903 IRBuilder<> &Builder) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000904 // Convert the stored type to the actual type, shift it left to insert
905 // then 'or' into place.
Chris Lattner229907c2011-07-18 04:54:35 +0000906 Type *AllocaType = Old->getType();
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000907 LLVMContext &Context = Old->getContext();
908
Chris Lattner229907c2011-07-18 04:54:35 +0000909 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000910 uint64_t VecSize = DL.getTypeAllocSizeInBits(VTy);
911 uint64_t ValSize = DL.getTypeAllocSizeInBits(SV->getType());
Bob Wilson328e91b2011-01-13 20:59:44 +0000912
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000913 // Changing the whole vector with memset or with an access of a different
914 // vector type?
Cameron Zwarichd7515cc2011-10-11 06:10:30 +0000915 if (ValSize == VecSize)
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000916 return Builder.CreateBitCast(SV, AllocaType);
Cameron Zwarich3b649f42011-03-09 05:43:05 +0000917
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000918 // Must be an element insertion.
Cameron Zwarich057fbb12011-10-23 07:02:10 +0000919 Type *EltTy = VTy->getElementType();
920 if (SV->getType() != EltTy)
921 SV = Builder.CreateBitCast(SV, EltTy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000922 uint64_t EltSize = DL.getTypeAllocSizeInBits(EltTy);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000923 unsigned Elt = Offset/EltSize;
Pete Cooper33ee6c92012-06-17 03:58:26 +0000924 Value *Idx;
925 if (NonConstantIdx) {
926 if (Elt)
927 Idx = Builder.CreateAdd(NonConstantIdx,
928 Builder.getInt32(Elt),
929 "dyn.offset");
930 else
931 Idx = NonConstantIdx;
932 } else
933 Idx = Builder.getInt32(Elt);
934 return Builder.CreateInsertElement(Old, SV, Idx);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000935 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000936
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000937 // If SV is a first-class aggregate value, insert each value recursively.
Chris Lattner229907c2011-07-18 04:54:35 +0000938 if (StructType *ST = dyn_cast<StructType>(SV->getType())) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000939 assert(!NonConstantIdx &&
940 "Dynamic indexing into struct types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000941 const StructLayout &Layout = *DL.getStructLayout(ST);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000942 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000943 Value *Elt = Builder.CreateExtractValue(SV, i);
Bob Wilson328e91b2011-01-13 20:59:44 +0000944 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000945 Offset+Layout.getElementOffsetInBits(i),
Craig Topperf40110f2014-04-25 05:29:35 +0000946 nullptr, Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000947 }
948 return Old;
949 }
Bob Wilson328e91b2011-01-13 20:59:44 +0000950
Chris Lattner229907c2011-07-18 04:54:35 +0000951 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Pete Cooper33ee6c92012-06-17 03:58:26 +0000952 assert(!NonConstantIdx &&
953 "Dynamic indexing into array types not supported");
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000954 uint64_t EltSize = DL.getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000955 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000956 Value *Elt = Builder.CreateExtractValue(SV, i);
Craig Topperf40110f2014-04-25 05:29:35 +0000957 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, nullptr,
958 Builder);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000959 }
960 return Old;
961 }
962
963 // If SV is a float, convert it to the appropriate integer type.
964 // If it is a pointer, do the same.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000965 unsigned SrcWidth = DL.getTypeSizeInBits(SV->getType());
966 unsigned DestWidth = DL.getTypeSizeInBits(AllocaType);
967 unsigned SrcStoreWidth = DL.getTypeStoreSizeInBits(SV->getType());
968 unsigned DestStoreWidth = DL.getTypeStoreSizeInBits(AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000969 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000970 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000971 else if (SV->getType()->isPointerTy())
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000972 SV = Builder.CreatePtrToInt(SV, DL.getIntPtrType(SV->getType()));
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000973
974 // Zero extend or truncate the value if needed.
975 if (SV->getType() != AllocaType) {
976 if (SV->getType()->getPrimitiveSizeInBits() <
977 AllocaType->getPrimitiveSizeInBits())
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000978 SV = Builder.CreateZExt(SV, AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000979 else {
980 // Truncation may be needed if storing more than the alloca can hold
981 // (undefined behavior).
Benjamin Kramer547b6c52011-09-27 20:39:19 +0000982 SV = Builder.CreateTrunc(SV, AllocaType);
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000983 SrcWidth = DestWidth;
984 SrcStoreWidth = DestStoreWidth;
985 }
986 }
987
988 // If this is a big-endian system and the store is narrower than the
989 // full alloca type, we need to do a shift to get the right bits.
990 int ShAmt = 0;
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000991 if (DL.isBigEndian()) {
Chris Lattner78d7dbb2010-04-16 00:24:57 +0000992 // On big-endian machines, the lowest bit is stored at the bit offset
993 // from the pointer given by getTypeStoreSizeInBits. This matters for
994 // integers with a bitwidth that is not a multiple of 8.
995 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
996 } else {
997 ShAmt = Offset;
998 }
999
1000 // Note: we support negative bitwidths (with shr) which are not defined.
1001 // We do this to support (f.e.) stores off the end of a structure where
1002 // only some bits in the structure are set.
1003 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1004 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001005 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001006 Mask <<= ShAmt;
1007 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001008 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt));
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001009 Mask = Mask.lshr(-ShAmt);
1010 }
1011
1012 // Mask out the bits we are about to insert from the old value, and or
1013 // in the new bits.
1014 if (SrcWidth != DestWidth) {
1015 assert(DestWidth > SrcWidth);
1016 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
1017 SV = Builder.CreateOr(Old, SV, "ins");
1018 }
1019 return SV;
1020}
1021
1022
1023//===----------------------------------------------------------------------===//
1024// SRoA Driver
1025//===----------------------------------------------------------------------===//
1026
1027
Chris Lattnerfb41a502003-05-27 15:45:27 +00001028bool SROA::runOnFunction(Function &F) {
Paul Robinsonaf4e64d2014-02-06 00:07:05 +00001029 if (skipOptnoneFunction(F))
1030 return false;
1031
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001032 bool Changed = performPromotion(F);
Dan Gohman915302c2009-08-19 18:22:18 +00001033
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001034 while (1) {
1035 bool LocalChange = performScalarRepl(F);
1036 if (!LocalChange) break; // No need to repromote if no scalarrepl
1037 Changed = true;
1038 LocalChange = performPromotion(F);
1039 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
1040 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001041
1042 return Changed;
1043}
1044
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001045namespace {
1046class AllocaPromoter : public LoadAndStorePromoter {
1047 AllocaInst *AI;
Devang Patela3cbf522011-07-06 21:09:55 +00001048 DIBuilder *DIB;
Devang Patelc6ee9182011-07-06 22:06:11 +00001049 SmallVector<DbgDeclareInst *, 4> DDIs;
1050 SmallVector<DbgValueInst *, 4> DVIs;
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001051public:
Pete Cooper41e0ee32015-05-13 01:12:16 +00001052 AllocaPromoter(ArrayRef<Instruction*> Insts, SSAUpdater &S,
Devang Patela3cbf522011-07-06 21:09:55 +00001053 DIBuilder *DB)
Craig Topperf40110f2014-04-25 05:29:35 +00001054 : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
Nadav Rotem465834c2012-07-24 10:51:42 +00001055
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001056 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) {
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001057 // Remember which alloca we're promoting (for isInstInList).
1058 this->AI = AI;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001059 if (auto *L = LocalAsMetadata::getIfExists(AI)) {
Duncan P. N. Exon Smitha9308c42015-04-29 16:38:44 +00001060 if (auto *DINode = MetadataAsValue::getIfExists(AI->getContext(), L)) {
1061 for (User *U : DINode->users())
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001062 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
1063 DDIs.push_back(DDI);
1064 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
1065 DVIs.push_back(DVI);
1066 }
Rafael Espindola2b14b802011-12-26 23:12:42 +00001067 }
Devang Patelc6ee9182011-07-06 22:06:11 +00001068
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001069 LoadAndStorePromoter::run(Insts);
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001070 AI->eraseFromParent();
Craig Topper31ee5862013-07-03 15:07:05 +00001071 for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001072 E = DDIs.end(); I != E; ++I) {
1073 DbgDeclareInst *DDI = *I;
Devang Patela3cbf522011-07-06 21:09:55 +00001074 DDI->eraseFromParent();
Devang Patelc6ee9182011-07-06 22:06:11 +00001075 }
Craig Topper31ee5862013-07-03 15:07:05 +00001076 for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001077 E = DVIs.end(); I != E; ++I) {
1078 DbgValueInst *DVI = *I;
1079 DVI->eraseFromParent();
1080 }
Chris Lattner543384e2011-01-14 07:50:47 +00001081 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001082
Craig Topper3e4c6972014-03-05 09:10:37 +00001083 bool isInstInList(Instruction *I,
1084 const SmallVectorImpl<Instruction*> &Insts) const override {
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001085 if (LoadInst *LI = dyn_cast<LoadInst>(I))
1086 return LI->getOperand(0) == AI;
1087 return cast<StoreInst>(I)->getPointerOperand() == AI;
Chris Lattner543384e2011-01-14 07:50:47 +00001088 }
Devang Patela3cbf522011-07-06 21:09:55 +00001089
Craig Topper3e4c6972014-03-05 09:10:37 +00001090 void updateDebugInfo(Instruction *Inst) const override {
Craig Topper31ee5862013-07-03 15:07:05 +00001091 for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001092 E = DDIs.end(); I != E; ++I) {
1093 DbgDeclareInst *DDI = *I;
1094 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
1095 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
1096 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
1097 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
1098 }
Craig Topper31ee5862013-07-03 15:07:05 +00001099 for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
Devang Patelc6ee9182011-07-06 22:06:11 +00001100 E = DVIs.end(); I != E; ++I) {
1101 DbgValueInst *DVI = *I;
Craig Topperf40110f2014-04-25 05:29:35 +00001102 Value *Arg = nullptr;
Devang Patelc6ee9182011-07-06 22:06:11 +00001103 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
Devang Patelc6ee9182011-07-06 22:06:11 +00001104 // If an argument is zero extended then use argument directly. The ZExt
1105 // may be zapped by an optimization pass in future.
Devang Patelc6ee9182011-07-06 22:06:11 +00001106 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
Benjamin Kramer077e5522012-02-23 17:42:19 +00001107 Arg = dyn_cast<Argument>(ZExt->getOperand(0));
Devang Patelc6ee9182011-07-06 22:06:11 +00001108 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
Benjamin Kramer077e5522012-02-23 17:42:19 +00001109 Arg = dyn_cast<Argument>(SExt->getOperand(0));
1110 if (!Arg)
1111 Arg = SI->getOperand(0);
Devang Patelc6ee9182011-07-06 22:06:11 +00001112 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
Benjamin Kramer077e5522012-02-23 17:42:19 +00001113 Arg = LI->getOperand(0);
1114 } else {
1115 continue;
Devang Patelc6ee9182011-07-06 22:06:11 +00001116 }
Duncan P. N. Exon Smith60635e32015-04-21 18:44:06 +00001117 DIB->insertDbgValueIntrinsic(Arg, 0, DVI->getVariable(),
1118 DVI->getExpression(), DVI->getDebugLoc(),
1119 Inst);
Devang Patelc6ee9182011-07-06 22:06:11 +00001120 }
Devang Patela3cbf522011-07-06 21:09:55 +00001121 }
Chris Lattnerb498f9a2011-01-14 19:50:47 +00001122};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001123} // end anon namespace
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001124
Chris Lattnera9607252011-01-23 22:04:55 +00001125/// isSafeSelectToSpeculate - Select instructions that use an alloca and are
1126/// subsequently loaded can be rewritten to load both input pointers and then
1127/// select between the result, allowing the load of the alloca to be promoted.
1128/// From this:
1129/// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
1130/// %V = load i32* %P2
1131/// to:
1132/// %V1 = load i32* %Alloca -> will be mem2reg'd
1133/// %V2 = load i32* %Other
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001134/// %V = select i1 %cond, i32 %V1, i32 %V2
Chris Lattnera9607252011-01-23 22:04:55 +00001135///
1136/// We can do this to a select if its only uses are loads and if the operand to
1137/// the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001138static bool isSafeSelectToSpeculate(SelectInst *SI) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001139 for (User *U : SI->users()) {
1140 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001141 if (!LI || !LI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001142
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001143 // Both operands to the select need to be dereferencable, either absolutely
Chris Lattnera9607252011-01-23 22:04:55 +00001144 // (e.g. allocas) or at this point because we can see other accesses to it.
Artur Pilipenkof84dc062016-01-17 12:35:29 +00001145 if (!isSafeToLoadUnconditionally(SI->getTrueValue(), LI->getAlignment(),
Artur Pilipenko6dd69692016-01-15 15:27:46 +00001146 LI))
Chris Lattnera9607252011-01-23 22:04:55 +00001147 return false;
Artur Pilipenkof84dc062016-01-17 12:35:29 +00001148 if (!isSafeToLoadUnconditionally(SI->getFalseValue(), LI->getAlignment(),
Artur Pilipenko6dd69692016-01-15 15:27:46 +00001149 LI))
Chris Lattnera9607252011-01-23 22:04:55 +00001150 return false;
1151 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001152
Chris Lattnera9607252011-01-23 22:04:55 +00001153 return true;
1154}
1155
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001156/// isSafePHIToSpeculate - PHI instructions that use an alloca and are
1157/// subsequently loaded can be rewritten to load both input pointers in the pred
1158/// blocks and then PHI the results, allowing the load of the alloca to be
1159/// promoted.
1160/// From this:
1161/// %P2 = phi [i32* %Alloca, i32* %Other]
1162/// %V = load i32* %P2
1163/// to:
1164/// %V1 = load i32* %Alloca -> will be mem2reg'd
1165/// ...
1166/// %V2 = load i32* %Other
1167/// ...
1168/// %V = phi [i32 %V1, i32 %V2]
1169///
1170/// We can do this to a select if its only uses are loads and if the operand to
1171/// the select can be loaded unconditionally.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001172static bool isSafePHIToSpeculate(PHINode *PN) {
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001173 // For now, we can only do this promotion if the load is in the same block as
1174 // the PHI, and if there are no stores between the phi and load.
1175 // TODO: Allow recursive phi users.
1176 // TODO: Allow stores.
1177 BasicBlock *BB = PN->getParent();
1178 unsigned MaxAlign = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001179 for (User *U : PN->users()) {
1180 LoadInst *LI = dyn_cast<LoadInst>(U);
Craig Topperf40110f2014-04-25 05:29:35 +00001181 if (!LI || !LI->isSimple()) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001182
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001183 // For now we only allow loads in the same block as the PHI. This is a
1184 // common case that happens when instcombine merges two loads through a PHI.
1185 if (LI->getParent() != BB) return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001186
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001187 // Ensure that there are no instructions between the PHI and the load that
1188 // could store.
Duncan P. N. Exon Smithbe4d8cb2015-10-13 19:26:58 +00001189 for (BasicBlock::iterator BBI(PN); &*BBI != LI; ++BBI)
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001190 if (BBI->mayWriteToMemory())
1191 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001192
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001193 MaxAlign = std::max(MaxAlign, LI->getAlignment());
1194 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001195
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001196 // Okay, we know that we have one or more loads in the same block as the PHI.
1197 // We can transform this if it is safe to push the loads into the predecessor
1198 // blocks. The only thing to watch out for is that we can't put a possibly
1199 // trapping load in the predecessor if it is a critical edge.
1200 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1201 BasicBlock *Pred = PN->getIncomingBlock(i);
Eli Friedmanf9b785f2011-09-22 18:56:30 +00001202 Value *InVal = PN->getIncomingValue(i);
1203
1204 // If the terminator of the predecessor has side-effects (an invoke),
1205 // there is no safe place to put a load in the predecessor.
1206 if (Pred->getTerminator()->mayHaveSideEffects())
1207 return false;
1208
1209 // If the value is produced by the terminator of the predecessor
1210 // (an invoke), there is no valid place to put a load in the predecessor.
1211 if (Pred->getTerminator() == InVal)
1212 return false;
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001213
1214 // If the predecessor has a single successor, then the edge isn't critical.
1215 if (Pred->getTerminator()->getNumSuccessors() == 1)
1216 continue;
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001217
1218 // If this pointer is always safe to load, or if we can prove that there is
1219 // already a load in the block, then we can move the load to the pred block.
Artur Pilipenkof84dc062016-01-17 12:35:29 +00001220 if (isSafeToLoadUnconditionally(InVal, MaxAlign, Pred->getTerminator()))
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001221 continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001222
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001223 return false;
1224 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001225
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001226 return true;
1227}
1228
Chris Lattnera9607252011-01-23 22:04:55 +00001229
1230/// tryToMakeAllocaBePromotable - This returns true if the alloca only has
1231/// direct (non-volatile) loads and stores to it. If the alloca is close but
1232/// not quite there, this will transform the code to allow promotion. As such,
1233/// it is a non-pure predicate.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001234static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout &DL) {
Chris Lattnera9607252011-01-23 22:04:55 +00001235 SetVector<Instruction*, SmallVector<Instruction*, 4>,
1236 SmallPtrSet<Instruction*, 4> > InstsToRewrite;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001237 for (User *U : AI->users()) {
Chris Lattnera9607252011-01-23 22:04:55 +00001238 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001239 if (!LI->isSimple())
Chris Lattnera9607252011-01-23 22:04:55 +00001240 return false;
1241 continue;
1242 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001243
Chris Lattnera9607252011-01-23 22:04:55 +00001244 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001245 if (SI->getOperand(0) == AI || !SI->isSimple())
Chris Lattnera9607252011-01-23 22:04:55 +00001246 return false; // Don't allow a store OF the AI, only INTO the AI.
1247 continue;
1248 }
1249
1250 if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
1251 // If the condition being selected on is a constant, fold the select, yes
1252 // this does (rarely) happen early on.
1253 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
1254 Value *Result = SI->getOperand(1+CI->isZero());
1255 SI->replaceAllUsesWith(Result);
1256 SI->eraseFromParent();
Nadav Rotem465834c2012-07-24 10:51:42 +00001257
Chris Lattnera9607252011-01-23 22:04:55 +00001258 // This is very rare and we just scrambled the use list of AI, start
1259 // over completely.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001260 return tryToMakeAllocaBePromotable(AI, DL);
Chris Lattnera9607252011-01-23 22:04:55 +00001261 }
1262
1263 // If it is safe to turn "load (select c, AI, ptr)" into a select of two
1264 // loads, then we can transform this by rewriting the select.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001265 if (!isSafeSelectToSpeculate(SI))
Chris Lattnera9607252011-01-23 22:04:55 +00001266 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001267
Chris Lattnera9607252011-01-23 22:04:55 +00001268 InstsToRewrite.insert(SI);
1269 continue;
1270 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001271
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001272 if (PHINode *PN = dyn_cast<PHINode>(U)) {
1273 if (PN->use_empty()) { // Dead PHIs can be stripped.
1274 InstsToRewrite.insert(PN);
1275 continue;
1276 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001277
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001278 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
1279 // in the pred blocks, then we can transform this by rewriting the PHI.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001280 if (!isSafePHIToSpeculate(PN))
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001281 return false;
Nadav Rotem465834c2012-07-24 10:51:42 +00001282
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001283 InstsToRewrite.insert(PN);
1284 continue;
1285 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001286
Nick Lewycky15e2d902011-07-25 23:14:22 +00001287 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1288 if (onlyUsedByLifetimeMarkers(BCI)) {
1289 InstsToRewrite.insert(BCI);
1290 continue;
1291 }
1292 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001293
Chris Lattnera9607252011-01-23 22:04:55 +00001294 return false;
1295 }
1296
1297 // If there are no instructions to rewrite, then all uses are load/stores and
1298 // we're done!
1299 if (InstsToRewrite.empty())
1300 return true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001301
Chris Lattnera9607252011-01-23 22:04:55 +00001302 // If we have instructions that need to be rewritten for this to be promotable
1303 // take care of it now.
1304 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
Nick Lewycky15e2d902011-07-25 23:14:22 +00001305 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
1306 // This could only be a bitcast used by nothing but lifetime intrinsics.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001307 for (BitCastInst::user_iterator I = BCI->user_begin(), E = BCI->user_end();
1308 I != E;)
1309 cast<Instruction>(*I++)->eraseFromParent();
Nick Lewycky15e2d902011-07-25 23:14:22 +00001310 BCI->eraseFromParent();
1311 continue;
1312 }
1313
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001314 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
1315 // Selects in InstsToRewrite only have load uses. Rewrite each as two
1316 // loads with a new select.
1317 while (!SI->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001318 LoadInst *LI = cast<LoadInst>(SI->user_back());
Nadav Rotem465834c2012-07-24 10:51:42 +00001319
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001320 IRBuilder<> Builder(LI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001321 LoadInst *TrueLoad =
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001322 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t");
Nadav Rotem465834c2012-07-24 10:51:42 +00001323 LoadInst *FalseLoad =
Nick Lewyckyf64a3972011-07-01 06:27:03 +00001324 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f");
Nadav Rotem465834c2012-07-24 10:51:42 +00001325
Hal Finkelcc39b672014-07-24 12:16:19 +00001326 // Transfer alignment and AA info if present.
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001327 TrueLoad->setAlignment(LI->getAlignment());
1328 FalseLoad->setAlignment(LI->getAlignment());
Hal Finkelcc39b672014-07-24 12:16:19 +00001329
1330 AAMDNodes Tags;
1331 LI->getAAMetadata(Tags);
1332 if (Tags) {
1333 TrueLoad->setAAMetadata(Tags);
1334 FalseLoad->setAAMetadata(Tags);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001335 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001336
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001337 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
1338 V->takeName(LI);
1339 LI->replaceAllUsesWith(V);
1340 LI->eraseFromParent();
Chris Lattnera9607252011-01-23 22:04:55 +00001341 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001342
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001343 // Now that all the loads are gone, the select is gone too.
1344 SI->eraseFromParent();
1345 continue;
1346 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001347
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001348 // Otherwise, we have a PHI node which allows us to push the loads into the
1349 // predecessors.
1350 PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
1351 if (PN->use_empty()) {
1352 PN->eraseFromParent();
1353 continue;
1354 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001355
Eduard Burtescu90c44492016-01-18 00:10:01 +00001356 Type *LoadTy = AI->getAllocatedType();
Jay Foad52131342011-03-30 11:28:46 +00001357 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
1358 PN->getName()+".ld", PN);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001359
Hal Finkelcc39b672014-07-24 12:16:19 +00001360 // Get the AA tags and alignment to use from one of the loads. It doesn't
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001361 // matter which one we get and if any differ, it doesn't matter.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001362 LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
Hal Finkelcc39b672014-07-24 12:16:19 +00001363
1364 AAMDNodes AATags;
1365 SomeLoad->getAAMetadata(AATags);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001366 unsigned Align = SomeLoad->getAlignment();
Nadav Rotem465834c2012-07-24 10:51:42 +00001367
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001368 // Rewrite all loads of the PN to use the new PHI.
1369 while (!PN->use_empty()) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001370 LoadInst *LI = cast<LoadInst>(PN->user_back());
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001371 LI->replaceAllUsesWith(NewPN);
Chris Lattnera9607252011-01-23 22:04:55 +00001372 LI->eraseFromParent();
1373 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001374
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001375 // Inject loads into all of the pred blocks. Keep track of which blocks we
1376 // insert them into in case we have multiple edges from the same block.
1377 DenseMap<BasicBlock*, LoadInst*> InsertedLoads;
Nadav Rotem465834c2012-07-24 10:51:42 +00001378
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001379 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1380 BasicBlock *Pred = PN->getIncomingBlock(i);
1381 LoadInst *&Load = InsertedLoads[Pred];
Craig Topperf40110f2014-04-25 05:29:35 +00001382 if (!Load) {
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001383 Load = new LoadInst(PN->getIncomingValue(i),
1384 PN->getName() + "." + Pred->getName(),
1385 Pred->getTerminator());
1386 Load->setAlignment(Align);
Hal Finkelcc39b672014-07-24 12:16:19 +00001387 if (AATags) Load->setAAMetadata(AATags);
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001388 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001389
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001390 NewPN->addIncoming(Load, Pred);
1391 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001392
Chris Lattnerd83e7b02011-01-24 01:07:11 +00001393 PN->eraseFromParent();
Chris Lattnera9607252011-01-23 22:04:55 +00001394 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001395
Chris Lattnera9607252011-01-23 22:04:55 +00001396 ++NumAdjusted;
1397 return true;
1398}
1399
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001400bool SROA::performPromotion(Function &F) {
1401 std::vector<AllocaInst*> Allocas;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001402 const DataLayout &DL = F.getParent()->getDataLayout();
Craig Topperf40110f2014-04-25 05:29:35 +00001403 DominatorTree *DT = nullptr;
Cameron Zwarich4694e692011-01-18 03:53:26 +00001404 if (HasDomTree)
Chandler Carruth73523022014-01-13 13:07:17 +00001405 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chandler Carruth66b31302015-01-04 12:03:27 +00001406 AssumptionCache &AC =
1407 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001408
Chris Lattner5dac64f2003-09-20 14:39:18 +00001409 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001410 DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
Chris Lattner9a95f2a2003-09-12 15:36:03 +00001411 bool Changed = false;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001412 SmallVector<Instruction*, 64> Insts;
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001413 while (1) {
1414 Allocas.clear();
1415
1416 // Find allocas that are safe to promote, by looking at all instructions in
1417 // the entry node
1418 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
1419 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001420 if (tryToMakeAllocaBePromotable(AI, DL))
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001421 Allocas.push_back(AI);
1422
1423 if (Allocas.empty()) break;
1424
Cameron Zwarich4694e692011-01-18 03:53:26 +00001425 if (HasDomTree)
Chandler Carruth66b31302015-01-04 12:03:27 +00001426 PromoteMemToReg(Allocas, *DT, nullptr, &AC);
Chris Lattner543384e2011-01-14 07:50:47 +00001427 else {
1428 SSAUpdater SSA;
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001429 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
1430 AllocaInst *AI = Allocas[i];
Nadav Rotem465834c2012-07-24 10:51:42 +00001431
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001432 // Build list of instructions to promote.
Chandler Carruthcdf47882014-03-09 03:16:01 +00001433 for (User *U : AI->users())
1434 Insts.push_back(cast<Instruction>(U));
Devang Patela3cbf522011-07-06 21:09:55 +00001435 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts);
Chris Lattnerb68ec5c2011-01-15 00:12:35 +00001436 Insts.clear();
1437 }
Chris Lattner543384e2011-01-14 07:50:47 +00001438 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001439 NumPromoted += Allocas.size();
1440 Changed = true;
1441 }
1442
1443 return Changed;
1444}
1445
Chris Lattner78d7dbb2010-04-16 00:24:57 +00001446
Bob Wilson04365c52010-02-03 17:23:56 +00001447/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
1448/// SROA. It must be a struct or array type with a small number of elements.
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001449bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00001450 Type *T = AI->getAllocatedType();
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001451 // Do not promote any struct that has too many members.
Chris Lattner229907c2011-07-18 04:54:35 +00001452 if (StructType *ST = dyn_cast<StructType>(T))
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001453 return ST->getNumElements() <= StructMemberThreshold;
1454 // Do not promote any array that has too many elements.
Chris Lattner229907c2011-07-18 04:54:35 +00001455 if (ArrayType *AT = dyn_cast<ArrayType>(T))
Nadav Rotem4e9012c2012-06-21 13:44:31 +00001456 return AT->getNumElements() <= ArrayElementThreshold;
Bob Wilson04365c52010-02-03 17:23:56 +00001457 return false;
Chris Lattner6ff85682008-06-22 17:46:21 +00001458}
1459
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001460// performScalarRepl - This algorithm is a simple worklist driven algorithm,
Chris Lattner8cf09412013-04-18 17:42:14 +00001461// which runs on all of the alloca instructions in the entry block, removing
1462// them if they are only used by getelementptr instructions.
Chris Lattner5d8a12e2003-09-11 16:45:55 +00001463//
1464bool SROA::performScalarRepl(Function &F) {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001465 std::vector<AllocaInst*> WorkList;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001466 const DataLayout &DL = F.getParent()->getDataLayout();
Chris Lattnerfb41a502003-05-27 15:45:27 +00001467
Chris Lattner9c1172d2010-04-15 21:59:20 +00001468 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner5dac64f2003-09-20 14:39:18 +00001469 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +00001470 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez8acf2952009-10-23 21:09:37 +00001471 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnerfb41a502003-05-27 15:45:27 +00001472 WorkList.push_back(A);
1473
1474 // Process the worklist
1475 bool Changed = false;
1476 while (!WorkList.empty()) {
Victor Hernandez8acf2952009-10-23 21:09:37 +00001477 AllocaInst *AI = WorkList.back();
Chris Lattnerfb41a502003-05-27 15:45:27 +00001478 WorkList.pop_back();
Bob Wilson328e91b2011-01-13 20:59:44 +00001479
Chris Lattnerf171af92006-12-22 23:14:42 +00001480 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
1481 // with unused elements.
1482 if (AI->use_empty()) {
1483 AI->eraseFromParent();
Chris Lattner9ef4eae2010-04-15 23:50:26 +00001484 Changed = true;
Chris Lattnerf171af92006-12-22 23:14:42 +00001485 continue;
1486 }
Chris Lattner09b65ab2009-02-03 01:30:09 +00001487
1488 // If this alloca is impossible for us to promote, reject it early.
1489 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
1490 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001491
Chris Lattner09b65ab2009-02-03 01:30:09 +00001492 // Check to see if we can perform the core SROA transformation. We cannot
1493 // transform the allocation instruction if it is an array allocation
1494 // (allocations OF arrays are ok though), and an allocation of a scalar
1495 // value cannot be decomposed at all.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001496 uint64_t AllocaSize = DL.getTypeAllocSize(AI->getAllocatedType());
Bill Wendling3e44bf32009-03-03 12:12:58 +00001497
Nick Lewyckyaa464002009-08-17 05:37:31 +00001498 // Do not promote [0 x %struct].
1499 if (AllocaSize == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001500
Chris Lattner9c1172d2010-04-15 21:59:20 +00001501 // Do not promote any struct whose size is too big.
1502 if (AllocaSize > SRThreshold) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001503
Bob Wilson04365c52010-02-03 17:23:56 +00001504 // If the alloca looks like a good candidate for scalar replacement, and if
1505 // all its users can be transformed, then split up the aggregate into its
1506 // separate elements.
1507 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
1508 DoScalarReplacement(AI, WorkList);
1509 Changed = true;
1510 continue;
1511 }
1512
Chris Lattnerdf179872009-01-28 20:16:43 +00001513 // If we can turn this aggregate value (potentially with casts) into a
1514 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattnerec99c462009-01-31 02:28:54 +00001515 // IsNotTrivial tracks whether this is something that mem2reg could have
1516 // promoted itself. If so, we don't want to transform it needlessly. Note
1517 // that we can't just check based on the type: the alloca may be of an i32
1518 // but that has pointer arithmetic to set byte 3 of it or something.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001519 if (AllocaInst *NewAI =
1520 ConvertToScalarInfo((unsigned)AllocaSize, DL, ScalarLoadThreshold)
1521 .TryConvert(AI)) {
Chris Lattner09b65ab2009-02-03 01:30:09 +00001522 NewAI->takeName(AI);
1523 AI->eraseFromParent();
1524 ++NumConverted;
1525 Changed = true;
1526 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00001527 }
1528
Chris Lattner09b65ab2009-02-03 01:30:09 +00001529 // Otherwise, couldn't process this alloca.
Chris Lattnerfb41a502003-05-27 15:45:27 +00001530 }
1531
1532 return Changed;
1533}
Chris Lattner6e5398d2003-05-30 04:15:41 +00001534
Chris Lattner31e5add2007-04-25 05:02:56 +00001535/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
1536/// predicate, do SROA now.
Bob Wilson328e91b2011-01-13 20:59:44 +00001537void SROA::DoScalarReplacement(AllocaInst *AI,
Victor Hernandez8acf2952009-10-23 21:09:37 +00001538 std::vector<AllocaInst*> &WorkList) {
David Greene48c86be2010-01-05 01:27:09 +00001539 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattner31e5add2007-04-25 05:02:56 +00001540 SmallVector<AllocaInst*, 32> ElementAllocas;
Chris Lattner229907c2011-07-18 04:54:35 +00001541 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner31e5add2007-04-25 05:02:56 +00001542 ElementAllocas.reserve(ST->getNumContainedTypes());
1543 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +00001544 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), nullptr,
Chris Lattner31e5add2007-04-25 05:02:56 +00001545 AI->getAlignment(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001546 AI->getName() + "." + Twine(i), AI);
Chris Lattner31e5add2007-04-25 05:02:56 +00001547 ElementAllocas.push_back(NA);
1548 WorkList.push_back(NA); // Add to worklist for recursive processing
1549 }
1550 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00001551 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattner31e5add2007-04-25 05:02:56 +00001552 ElementAllocas.reserve(AT->getNumElements());
Chris Lattner229907c2011-07-18 04:54:35 +00001553 Type *ElTy = AT->getElementType();
Chris Lattner31e5add2007-04-25 05:02:56 +00001554 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Craig Topperf40110f2014-04-25 05:29:35 +00001555 AllocaInst *NA = new AllocaInst(ElTy, nullptr, AI->getAlignment(),
Daniel Dunbar132f7832009-07-30 17:37:43 +00001556 AI->getName() + "." + Twine(i), AI);
Chris Lattner31e5add2007-04-25 05:02:56 +00001557 ElementAllocas.push_back(NA);
1558 WorkList.push_back(NA); // Add to worklist for recursive processing
1559 }
1560 }
1561
Bob Wilson532cd232009-12-18 20:14:40 +00001562 // Now that we have created the new alloca instructions, rewrite all the
1563 // uses of the old alloca.
1564 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001565
Bob Wilson532cd232009-12-18 20:14:40 +00001566 // Now erase any instructions that were made dead while rewriting the alloca.
1567 DeleteDeadInstructions();
Bob Wilsonf3927b72009-12-17 18:34:24 +00001568 AI->eraseFromParent();
Bob Wilson532cd232009-12-18 20:14:40 +00001569
Dan Gohmand2d1ae12010-06-22 15:08:57 +00001570 ++NumReplaced;
Chris Lattner31e5add2007-04-25 05:02:56 +00001571}
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001572
Bob Wilson532cd232009-12-18 20:14:40 +00001573/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
1574/// recursively including all their operands that become trivially dead.
1575void SROA::DeleteDeadInstructions() {
1576 while (!DeadInsts.empty()) {
1577 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001578
Bob Wilson532cd232009-12-18 20:14:40 +00001579 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
1580 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
1581 // Zero out the operand and see if it becomes trivially dead.
1582 // (But, don't add allocas to the dead instruction list -- they are
1583 // already on the worklist and will be deleted separately.)
Craig Topperf40110f2014-04-25 05:29:35 +00001584 *OI = nullptr;
Bob Wilson532cd232009-12-18 20:14:40 +00001585 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
1586 DeadInsts.push_back(U);
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001587 }
Bob Wilson532cd232009-12-18 20:14:40 +00001588
1589 I->eraseFromParent();
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001590 }
Chris Lattneraaa6ac12009-12-14 05:11:02 +00001591}
Bob Wilson328e91b2011-01-13 20:59:44 +00001592
Bob Wilson532cd232009-12-18 20:14:40 +00001593/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
1594/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson88a05982009-12-21 18:39:47 +00001595/// the Info parameter. Offset indicates the position within AI that is
1596/// referenced by this instruction.
Chris Lattner8acbb792011-01-23 07:29:29 +00001597void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
Bob Wilson88a05982009-12-21 18:39:47 +00001598 AllocaInfo &Info) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001599 const DataLayout &DL = I->getModule()->getDataLayout();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001600 for (Use &U : I->uses()) {
1601 Instruction *User = cast<Instruction>(U.getUser());
Chris Lattner52310702003-11-25 21:09:18 +00001602
Bob Wilson532cd232009-12-18 20:14:40 +00001603 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Chris Lattner8acbb792011-01-23 07:29:29 +00001604 isSafeForScalarRepl(BC, Offset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001605 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001606 uint64_t GEPOffset = Offset;
Chris Lattner8acbb792011-01-23 07:29:29 +00001607 isSafeGEP(GEPI, GEPOffset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001608 if (!Info.isUnsafe)
Chris Lattner8acbb792011-01-23 07:29:29 +00001609 isSafeForScalarRepl(GEPI, GEPOffset, Info);
Gabor Greif4300fc72010-06-28 11:20:42 +00001610 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001611 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Craig Topperf40110f2014-04-25 05:29:35 +00001612 if (!Length || Length->isNegative())
Aaron Ballmana7332972012-03-15 00:05:31 +00001613 return MarkUnsafe(Info, User);
1614
Craig Topperf40110f2014-04-25 05:29:35 +00001615 isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
Chandler Carruthcdf47882014-03-09 03:16:01 +00001616 U.getOperandNo() == 0, Info, MI,
Chris Lattner9491dee2011-01-23 08:27:54 +00001617 true /*AllowWholeAccess*/);
Bob Wilson532cd232009-12-18 20:14:40 +00001618 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001619 if (!LI->isSimple())
Chris Lattner3e56c292011-01-23 07:05:44 +00001620 return MarkUnsafe(Info, User);
Chris Lattner229907c2011-07-18 04:54:35 +00001621 Type *LIType = LI->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001622 isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
1623 LI, true /*AllowWholeAccess*/);
Chris Lattner3e56c292011-01-23 07:05:44 +00001624 Info.hasALoadOrStore = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001625
Bob Wilson532cd232009-12-18 20:14:40 +00001626 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1627 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman7c5dc122011-09-12 20:23:13 +00001628 if (!SI->isSimple() || SI->getOperand(0) == I)
Chris Lattner3e56c292011-01-23 07:05:44 +00001629 return MarkUnsafe(Info, User);
Nadav Rotem465834c2012-07-24 10:51:42 +00001630
Chris Lattner229907c2011-07-18 04:54:35 +00001631 Type *SIType = SI->getOperand(0)->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001632 isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
1633 SI, true /*AllowWholeAccess*/);
Chris Lattner3e56c292011-01-23 07:05:44 +00001634 Info.hasALoadOrStore = true;
Nick Lewycky15e2d902011-07-25 23:14:22 +00001635 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1636 if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
1637 II->getIntrinsicID() != Intrinsic::lifetime_end)
1638 return MarkUnsafe(Info, User);
Chris Lattner9491dee2011-01-23 08:27:54 +00001639 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
1640 isSafePHISelectUseForScalarRepl(User, Offset, Info);
1641 } else {
1642 return MarkUnsafe(Info, User);
1643 }
1644 if (Info.isUnsafe) return;
1645 }
1646}
Nadav Rotem465834c2012-07-24 10:51:42 +00001647
Chris Lattner9491dee2011-01-23 08:27:54 +00001648
1649/// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
1650/// derived from the alloca, we can often still split the alloca into elements.
1651/// This is useful if we have a large alloca where one element is phi'd
1652/// together somewhere: we can SRoA and promote all the other elements even if
1653/// we end up not being able to promote this one.
1654///
1655/// All we require is that the uses of the PHI do not index into other parts of
1656/// the alloca. The most important use case for this is single load and stores
1657/// that are PHI'd together, which can happen due to code sinking.
1658void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
1659 AllocaInfo &Info) {
1660 // If we've already checked this PHI, don't do it again.
1661 if (PHINode *PN = dyn_cast<PHINode>(I))
David Blaikie70573dc2014-11-19 07:49:26 +00001662 if (!Info.CheckedPHIs.insert(PN).second)
Chris Lattner9491dee2011-01-23 08:27:54 +00001663 return;
Nadav Rotem465834c2012-07-24 10:51:42 +00001664
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001665 const DataLayout &DL = I->getModule()->getDataLayout();
Chandler Carruthcdf47882014-03-09 03:16:01 +00001666 for (User *U : I->users()) {
1667 Instruction *UI = cast<Instruction>(U);
Nadav Rotem465834c2012-07-24 10:51:42 +00001668
Chandler Carruthcdf47882014-03-09 03:16:01 +00001669 if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001670 isSafePHISelectUseForScalarRepl(BC, Offset, Info);
Chandler Carruthcdf47882014-03-09 03:16:01 +00001671 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001672 // Only allow "bitcast" GEPs for simplicity. We could generalize this,
1673 // but would have to prove that we're staying inside of an element being
1674 // promoted.
1675 if (!GEPI->hasAllZeroIndices())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001676 return MarkUnsafe(Info, UI);
Chris Lattner9491dee2011-01-23 08:27:54 +00001677 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
Chandler Carruthcdf47882014-03-09 03:16:01 +00001678 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Eli Friedman7c5dc122011-09-12 20:23:13 +00001679 if (!LI->isSimple())
Chandler Carruthcdf47882014-03-09 03:16:01 +00001680 return MarkUnsafe(Info, UI);
Chris Lattner229907c2011-07-18 04:54:35 +00001681 Type *LIType = LI->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001682 isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
1683 LI, false /*AllowWholeAccess*/);
Chris Lattner9491dee2011-01-23 08:27:54 +00001684 Info.hasALoadOrStore = true;
Nadav Rotem465834c2012-07-24 10:51:42 +00001685
Chandler Carruthcdf47882014-03-09 03:16:01 +00001686 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner9491dee2011-01-23 08:27:54 +00001687 // Store is ok if storing INTO the pointer, not storing the pointer
Eli Friedman7c5dc122011-09-12 20:23:13 +00001688 if (!SI->isSimple() || SI->getOperand(0) == I)
Chandler Carruthcdf47882014-03-09 03:16:01 +00001689 return MarkUnsafe(Info, UI);
Nadav Rotem465834c2012-07-24 10:51:42 +00001690
Chris Lattner229907c2011-07-18 04:54:35 +00001691 Type *SIType = SI->getOperand(0)->getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001692 isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
1693 SI, false /*AllowWholeAccess*/);
Chris Lattner9491dee2011-01-23 08:27:54 +00001694 Info.hasALoadOrStore = true;
Chandler Carruthcdf47882014-03-09 03:16:01 +00001695 } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
1696 isSafePHISelectUseForScalarRepl(UI, Offset, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00001697 } else {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001698 return MarkUnsafe(Info, UI);
Bob Wilson532cd232009-12-18 20:14:40 +00001699 }
1700 if (Info.isUnsafe) return;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001701 }
Bob Wilson532cd232009-12-18 20:14:40 +00001702}
Bob Wilsonf3927b72009-12-17 18:34:24 +00001703
Bob Wilson532cd232009-12-18 20:14:40 +00001704/// isSafeGEP - Check if a GEP instruction can be handled for scalar
1705/// replacement. It is safe when all the indices are constant, in-bounds
1706/// references, and when the resulting offset corresponds to an element within
1707/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson88a05982009-12-21 18:39:47 +00001708/// return, Offset is adjusted as specified by the GEP indices.
Chris Lattner8acbb792011-01-23 07:29:29 +00001709void SROA::isSafeGEP(GetElementPtrInst *GEPI,
Bob Wilson88a05982009-12-21 18:39:47 +00001710 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilson532cd232009-12-18 20:14:40 +00001711 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
1712 if (GEPIt == E)
1713 return;
Pete Coopere24d6a12012-06-15 18:07:29 +00001714 bool NonConstant = false;
1715 unsigned NonConstantIdxSize = 0;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001716
Chris Lattner3f972c92008-08-23 05:21:06 +00001717 // Walk through the GEP type indices, checking the types that this indexes
1718 // into.
Bob Wilson532cd232009-12-18 20:14:40 +00001719 for (; GEPIt != E; ++GEPIt) {
Chris Lattner3f972c92008-08-23 05:21:06 +00001720 // Ignore struct elements, no extra checking needed for these.
Duncan Sands19d0b472010-02-16 11:11:14 +00001721 if ((*GEPIt)->isStructTy())
Chris Lattner3f972c92008-08-23 05:21:06 +00001722 continue;
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +00001723
Bob Wilson532cd232009-12-18 20:14:40 +00001724 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
Shuxin Yang95adf522013-04-05 21:07:08 +00001725 if (!IdxVal)
1726 return MarkUnsafe(Info, GEPI);
Chris Lattner3f972c92008-08-23 05:21:06 +00001727 }
Bob Wilson532cd232009-12-18 20:14:40 +00001728
Bob Wilson62a84ea2009-12-22 06:57:14 +00001729 // Compute the offset due to this GEP and check if the alloca has a
1730 // component element at that offset.
Bob Wilson88a05982009-12-21 18:39:47 +00001731 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Alp Tokerf907b892013-12-05 05:44:44 +00001732 // If this GEP is non-constant then the last operand must have been a
Pete Coopere24d6a12012-06-15 18:07:29 +00001733 // dynamic index into a vector. Pop this now as it has no impact on the
1734 // constant part of the offset.
1735 if (NonConstant)
1736 Indices.pop_back();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001737
1738 const DataLayout &DL = GEPI->getModule()->getDataLayout();
1739 Offset += DL.getIndexedOffset(GEPI->getPointerOperandType(), Indices);
1740 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, NonConstantIdxSize,
1741 DL))
Chris Lattner3e56c292011-01-23 07:05:44 +00001742 MarkUnsafe(Info, GEPI);
Chris Lattner6e5398d2003-05-30 04:15:41 +00001743}
1744
Bob Wilson08713d32011-01-13 17:45:11 +00001745/// isHomogeneousAggregate - Check if type T is a struct or array containing
1746/// elements of the same type (which is always true for arrays). If so,
1747/// return true with NumElts and EltTy set to the number of elements and the
1748/// element type, respectively.
Chris Lattner229907c2011-07-18 04:54:35 +00001749static bool isHomogeneousAggregate(Type *T, unsigned &NumElts,
1750 Type *&EltTy) {
1751 if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson08713d32011-01-13 17:45:11 +00001752 NumElts = AT->getNumElements();
Craig Topperf40110f2014-04-25 05:29:35 +00001753 EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
Bob Wilson08713d32011-01-13 17:45:11 +00001754 return true;
1755 }
Chris Lattner229907c2011-07-18 04:54:35 +00001756 if (StructType *ST = dyn_cast<StructType>(T)) {
Bob Wilson08713d32011-01-13 17:45:11 +00001757 NumElts = ST->getNumContainedTypes();
Craig Topperf40110f2014-04-25 05:29:35 +00001758 EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
Bob Wilson08713d32011-01-13 17:45:11 +00001759 for (unsigned n = 1; n < NumElts; ++n) {
1760 if (ST->getContainedType(n) != EltTy)
1761 return false;
1762 }
1763 return true;
1764 }
1765 return false;
1766}
1767
1768/// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
1769/// "homogeneous" aggregates with the same element type and number of elements.
Chris Lattner229907c2011-07-18 04:54:35 +00001770static bool isCompatibleAggregate(Type *T1, Type *T2) {
Bob Wilson08713d32011-01-13 17:45:11 +00001771 if (T1 == T2)
1772 return true;
1773
1774 unsigned NumElts1, NumElts2;
Chris Lattner229907c2011-07-18 04:54:35 +00001775 Type *EltTy1, *EltTy2;
Bob Wilson08713d32011-01-13 17:45:11 +00001776 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
1777 isHomogeneousAggregate(T2, NumElts2, EltTy2) &&
1778 NumElts1 == NumElts2 &&
1779 EltTy1 == EltTy2)
1780 return true;
1781
1782 return false;
1783}
1784
Bob Wilson532cd232009-12-18 20:14:40 +00001785/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
1786/// alloca or has an offset and size that corresponds to a component element
1787/// within it. The offset checked here may have been formed from a GEP with a
1788/// pointer bitcasted to a different type.
Chris Lattner9491dee2011-01-23 08:27:54 +00001789///
1790/// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
1791/// unit. If false, it only allows accesses known to be in a single element.
Chris Lattner8acbb792011-01-23 07:29:29 +00001792void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
Chris Lattner229907c2011-07-18 04:54:35 +00001793 Type *MemOpType, bool isStore,
Chris Lattner9491dee2011-01-23 08:27:54 +00001794 AllocaInfo &Info, Instruction *TheAccess,
1795 bool AllowWholeAccess) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001796 const DataLayout &DL = TheAccess->getModule()->getDataLayout();
Bob Wilson532cd232009-12-18 20:14:40 +00001797 // Check if this is a load/store of the entire alloca.
Chris Lattner9491dee2011-01-23 08:27:54 +00001798 if (Offset == 0 && AllowWholeAccess &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001799 MemSize == DL.getTypeAllocSize(Info.AI->getAllocatedType())) {
Bob Wilson08713d32011-01-13 17:45:11 +00001800 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer
1801 // loads/stores (which are essentially the same as the MemIntrinsics with
1802 // regard to copying padding between elements). But, if an alloca is
1803 // flagged as both a source and destination of such operations, we'll need
1804 // to check later for padding between elements.
1805 if (!MemOpType || MemOpType->isIntegerTy()) {
1806 if (isStore)
1807 Info.isMemCpyDst = true;
1808 else
1809 Info.isMemCpySrc = true;
Bob Wilson532cd232009-12-18 20:14:40 +00001810 return;
1811 }
Bob Wilson08713d32011-01-13 17:45:11 +00001812 // This is also safe for references using a type that is compatible with
1813 // the type of the alloca, so that loads/stores can be rewritten using
1814 // insertvalue/extractvalue.
Chris Lattner8acbb792011-01-23 07:29:29 +00001815 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00001816 Info.hasSubelementAccess = true;
Bob Wilson08713d32011-01-13 17:45:11 +00001817 return;
Chris Lattner6fab2e92011-01-16 06:18:28 +00001818 }
Bob Wilson532cd232009-12-18 20:14:40 +00001819 }
1820 // Check if the offset/size correspond to a component within the alloca type.
Chris Lattner229907c2011-07-18 04:54:35 +00001821 Type *T = Info.AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001822 if (TypeHasComponent(T, Offset, MemSize, DL)) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00001823 Info.hasSubelementAccess = true;
Bob Wilson532cd232009-12-18 20:14:40 +00001824 return;
Chris Lattner6fab2e92011-01-16 06:18:28 +00001825 }
Bob Wilson532cd232009-12-18 20:14:40 +00001826
Chris Lattner3e56c292011-01-23 07:05:44 +00001827 return MarkUnsafe(Info, TheAccess);
Bob Wilson532cd232009-12-18 20:14:40 +00001828}
1829
1830/// TypeHasComponent - Return true if T has a component type with the
1831/// specified offset and size. If Size is zero, do not check the size.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001832bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
1833 const DataLayout &DL) {
Chris Lattner229907c2011-07-18 04:54:35 +00001834 Type *EltTy;
Bob Wilson532cd232009-12-18 20:14:40 +00001835 uint64_t EltSize;
Chris Lattner229907c2011-07-18 04:54:35 +00001836 if (StructType *ST = dyn_cast<StructType>(T)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001837 const StructLayout *Layout = DL.getStructLayout(ST);
Bob Wilson532cd232009-12-18 20:14:40 +00001838 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
1839 EltTy = ST->getContainedType(EltIdx);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001840 EltSize = DL.getTypeAllocSize(EltTy);
Bob Wilson532cd232009-12-18 20:14:40 +00001841 Offset -= Layout->getElementOffset(EltIdx);
Chris Lattner229907c2011-07-18 04:54:35 +00001842 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001843 EltTy = AT->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001844 EltSize = DL.getTypeAllocSize(EltTy);
Bob Wilson62a84ea2009-12-22 06:57:14 +00001845 if (Offset >= AT->getNumElements() * EltSize)
1846 return false;
Bob Wilson532cd232009-12-18 20:14:40 +00001847 Offset %= EltSize;
Pete Cooper1d1fa722012-06-14 23:53:53 +00001848 } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
1849 EltTy = VT->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001850 EltSize = DL.getTypeAllocSize(EltTy);
Pete Cooper1d1fa722012-06-14 23:53:53 +00001851 if (Offset >= VT->getNumElements() * EltSize)
1852 return false;
1853 Offset %= EltSize;
Bob Wilson532cd232009-12-18 20:14:40 +00001854 } else {
1855 return false;
1856 }
1857 if (Offset == 0 && (Size == 0 || EltSize == Size))
1858 return true;
1859 // Check if the component spans multiple elements.
1860 if (Offset + Size > EltSize)
1861 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001862 return TypeHasComponent(EltTy, Offset, Size, DL);
Bob Wilson532cd232009-12-18 20:14:40 +00001863}
1864
1865/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
1866/// the instruction I, which references it, to use the separate elements.
1867/// Offset indicates the position within AI that is referenced by this
1868/// instruction.
1869void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00001870 SmallVectorImpl<AllocaInst *> &NewElts) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001871 const DataLayout &DL = I->getModule()->getDataLayout();
Chris Lattner9491dee2011-01-23 08:27:54 +00001872 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00001873 Use &TheUse = *UI++;
1874 Instruction *User = cast<Instruction>(TheUse.getUser());
Bob Wilson532cd232009-12-18 20:14:40 +00001875
1876 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
1877 RewriteBitCast(BC, AI, Offset, NewElts);
Chris Lattner9491dee2011-01-23 08:27:54 +00001878 continue;
1879 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001880
Chris Lattner9491dee2011-01-23 08:27:54 +00001881 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001882 RewriteGEP(GEPI, AI, Offset, NewElts);
Chris Lattner9491dee2011-01-23 08:27:54 +00001883 continue;
1884 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001885
Chris Lattner9491dee2011-01-23 08:27:54 +00001886 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001887 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
1888 uint64_t MemSize = Length->getZExtValue();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001889 if (Offset == 0 && MemSize == DL.getTypeAllocSize(AI->getAllocatedType()))
Bob Wilson532cd232009-12-18 20:14:40 +00001890 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsonc16811b2009-12-19 06:53:17 +00001891 // Otherwise the intrinsic can only touch a single element and the
1892 // address operand will be updated, so nothing else needs to be done.
Chris Lattner9491dee2011-01-23 08:27:54 +00001893 continue;
1894 }
Nick Lewycky15e2d902011-07-25 23:14:22 +00001895
1896 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
1897 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1898 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1899 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts);
1900 }
1901 continue;
1902 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001903
Chris Lattner9491dee2011-01-23 08:27:54 +00001904 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner229907c2011-07-18 04:54:35 +00001905 Type *LIType = LI->getType();
Nadav Rotem465834c2012-07-24 10:51:42 +00001906
Bob Wilson08713d32011-01-13 17:45:11 +00001907 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001908 // Replace:
1909 // %res = load { i32, i32 }* %alloc
1910 // with:
1911 // %load.0 = load i32* %alloc.0
1912 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
1913 // %load.1 = load i32* %alloc.1
1914 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
1915 // (Also works for arrays instead of structs)
1916 Value *Insert = UndefValue::get(LIType);
Devang Patel84bb33a2011-06-03 19:46:19 +00001917 IRBuilder<> Builder(LI);
Bob Wilson532cd232009-12-18 20:14:40 +00001918 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patel84bb33a2011-06-03 19:46:19 +00001919 Value *Load = Builder.CreateLoad(NewElts[i], "load");
1920 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
Bob Wilson532cd232009-12-18 20:14:40 +00001921 }
1922 LI->replaceAllUsesWith(Insert);
1923 DeadInsts.push_back(LI);
Duncan Sands19d0b472010-02-16 11:11:14 +00001924 } else if (LIType->isIntegerTy() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001925 DL.getTypeAllocSize(LIType) ==
1926 DL.getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001927 // If this is a load of the entire alloca to an integer, rewrite it.
1928 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
1929 }
Chris Lattner9491dee2011-01-23 08:27:54 +00001930 continue;
1931 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001932
Chris Lattner9491dee2011-01-23 08:27:54 +00001933 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Bob Wilson532cd232009-12-18 20:14:40 +00001934 Value *Val = SI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00001935 Type *SIType = Val->getType();
Bob Wilson08713d32011-01-13 17:45:11 +00001936 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001937 // Replace:
1938 // store { i32, i32 } %val, { i32, i32 }* %alloc
1939 // with:
1940 // %val.0 = extractvalue { i32, i32 } %val, 0
1941 // store i32 %val.0, i32* %alloc.0
1942 // %val.1 = extractvalue { i32, i32 } %val, 1
1943 // store i32 %val.1, i32* %alloc.1
1944 // (Also works for arrays instead of structs)
Devang Patel84bb33a2011-06-03 19:46:19 +00001945 IRBuilder<> Builder(SI);
Bob Wilson532cd232009-12-18 20:14:40 +00001946 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Devang Patel84bb33a2011-06-03 19:46:19 +00001947 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
1948 Builder.CreateStore(Extract, NewElts[i]);
Bob Wilson532cd232009-12-18 20:14:40 +00001949 }
1950 DeadInsts.push_back(SI);
Duncan Sands19d0b472010-02-16 11:11:14 +00001951 } else if (SIType->isIntegerTy() &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001952 DL.getTypeAllocSize(SIType) ==
1953 DL.getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilson532cd232009-12-18 20:14:40 +00001954 // If this is a store of the entire alloca from an integer, rewrite it.
1955 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
1956 }
Chris Lattner9491dee2011-01-23 08:27:54 +00001957 continue;
1958 }
Nadav Rotem465834c2012-07-24 10:51:42 +00001959
Chris Lattner9491dee2011-01-23 08:27:54 +00001960 if (isa<SelectInst>(User) || isa<PHINode>(User)) {
Nadav Rotem465834c2012-07-24 10:51:42 +00001961 // If we have a PHI user of the alloca itself (as opposed to a GEP or
Chris Lattner9491dee2011-01-23 08:27:54 +00001962 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to
1963 // the new pointer.
1964 if (!isa<AllocaInst>(I)) continue;
Nadav Rotem465834c2012-07-24 10:51:42 +00001965
Chris Lattner9491dee2011-01-23 08:27:54 +00001966 assert(Offset == 0 && NewElts[0] &&
1967 "Direct alloca use should have a zero offset");
Nadav Rotem465834c2012-07-24 10:51:42 +00001968
Chris Lattner9491dee2011-01-23 08:27:54 +00001969 // If we have a use of the alloca, we know the derived uses will be
1970 // utilizing just the first element of the scalarized result. Insert a
1971 // bitcast of the first alloca before the user as required.
1972 AllocaInst *NewAI = NewElts[0];
1973 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI);
1974 NewAI->moveBefore(BCI);
1975 TheUse = BCI;
1976 continue;
Bob Wilson532cd232009-12-18 20:14:40 +00001977 }
Bob Wilsonf3927b72009-12-17 18:34:24 +00001978 }
1979}
1980
Bob Wilson532cd232009-12-18 20:14:40 +00001981/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
1982/// and recursively continue updating all of its uses.
1983void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00001984 SmallVectorImpl<AllocaInst *> &NewElts) {
Bob Wilson532cd232009-12-18 20:14:40 +00001985 RewriteForScalarRepl(BC, AI, Offset, NewElts);
1986 if (BC->getOperand(0) != AI)
1987 return;
Bob Wilsonf3927b72009-12-17 18:34:24 +00001988
Bob Wilson532cd232009-12-18 20:14:40 +00001989 // The bitcast references the original alloca. Replace its uses with
Eli Friedmanecb45382011-11-12 02:07:50 +00001990 // references to the alloca containing offset zero (which is normally at
1991 // index zero, but might not be in cases involving structs with elements
1992 // of size zero).
1993 Type *T = AI->getAllocatedType();
1994 uint64_t EltOffset = 0;
1995 Type *IdxTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001996 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy,
1997 BC->getModule()->getDataLayout());
Eli Friedmanecb45382011-11-12 02:07:50 +00001998 Instruction *Val = NewElts[Idx];
Bob Wilson532cd232009-12-18 20:14:40 +00001999 if (Val->getType() != BC->getDestTy()) {
2000 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
2001 Val->takeName(BC);
Daniel Dunbar133efc32009-12-16 10:56:17 +00002002 }
Bob Wilson532cd232009-12-18 20:14:40 +00002003 BC->replaceAllUsesWith(Val);
2004 DeadInsts.push_back(BC);
Daniel Dunbar133efc32009-12-16 10:56:17 +00002005}
2006
Bob Wilson532cd232009-12-18 20:14:40 +00002007/// FindElementAndOffset - Return the index of the element containing Offset
2008/// within the specified type, which must be either a struct or an array.
2009/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsonc16811b2009-12-19 06:53:17 +00002010/// element. IdxTy is set to the type of the index result to be used in a
2011/// GEP instruction.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002012uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset, Type *&IdxTy,
2013 const DataLayout &DL) {
Bob Wilsonc16811b2009-12-19 06:53:17 +00002014 uint64_t Idx = 0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002015
Chris Lattner229907c2011-07-18 04:54:35 +00002016 if (StructType *ST = dyn_cast<StructType>(T)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002017 const StructLayout *Layout = DL.getStructLayout(ST);
Bob Wilson532cd232009-12-18 20:14:40 +00002018 Idx = Layout->getElementContainingOffset(Offset);
2019 T = ST->getContainedType(Idx);
2020 Offset -= Layout->getElementOffset(Idx);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002021 IdxTy = Type::getInt32Ty(T->getContext());
2022 return Idx;
Pete Cooper1d1fa722012-06-14 23:53:53 +00002023 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
2024 T = AT->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002025 uint64_t EltSize = DL.getTypeAllocSize(T);
Pete Cooper1d1fa722012-06-14 23:53:53 +00002026 Idx = Offset / EltSize;
2027 Offset -= Idx * EltSize;
2028 IdxTy = Type::getInt64Ty(T->getContext());
2029 return Idx;
Chris Lattneraaa6ac12009-12-14 05:11:02 +00002030 }
Pete Cooper1d1fa722012-06-14 23:53:53 +00002031 VectorType *VT = cast<VectorType>(T);
2032 T = VT->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002033 uint64_t EltSize = DL.getTypeAllocSize(T);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002034 Idx = Offset / EltSize;
2035 Offset -= Idx * EltSize;
2036 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilson532cd232009-12-18 20:14:40 +00002037 return Idx;
2038}
2039
2040/// RewriteGEP - Check if this GEP instruction moves the pointer across
2041/// elements of the alloca that are being split apart, and if so, rewrite
2042/// the GEP to be relative to the new element.
2043void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00002044 SmallVectorImpl<AllocaInst *> &NewElts) {
Bob Wilson532cd232009-12-18 20:14:40 +00002045 uint64_t OldOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002046 const DataLayout &DL = GEPI->getModule()->getDataLayout();
Bob Wilson532cd232009-12-18 20:14:40 +00002047 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
Pete Coopere24d6a12012-06-15 18:07:29 +00002048 // If the GEP was dynamic then it must have been a dynamic vector lookup.
2049 // In this case, it must be the last GEP operand which is dynamic so keep that
2050 // aside until we've found the constant GEP offset then add it back in at the
2051 // end.
Craig Topperf40110f2014-04-25 05:29:35 +00002052 Value* NonConstantIdx = nullptr;
Pete Coopere24d6a12012-06-15 18:07:29 +00002053 if (!GEPI->hasAllConstantIndices())
2054 NonConstantIdx = Indices.pop_back_val();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002055 Offset += DL.getIndexedOffset(GEPI->getPointerOperandType(), Indices);
Bob Wilson532cd232009-12-18 20:14:40 +00002056
2057 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
2058
Chris Lattner229907c2011-07-18 04:54:35 +00002059 Type *T = AI->getAllocatedType();
2060 Type *IdxTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002061 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy, DL);
Bob Wilson532cd232009-12-18 20:14:40 +00002062 if (GEPI->getOperand(0) == AI)
Bob Wilsonc16811b2009-12-19 06:53:17 +00002063 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilson532cd232009-12-18 20:14:40 +00002064
2065 T = AI->getAllocatedType();
2066 uint64_t EltOffset = Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002067 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy, DL);
Bob Wilson532cd232009-12-18 20:14:40 +00002068
2069 // If this GEP does not move the pointer across elements of the alloca
2070 // being split, then it does not needs to be rewritten.
2071 if (Idx == OldIdx)
2072 return;
2073
Chris Lattner229907c2011-07-18 04:54:35 +00002074 Type *i32Ty = Type::getInt32Ty(AI->getContext());
Bob Wilson532cd232009-12-18 20:14:40 +00002075 SmallVector<Value*, 8> NewArgs;
2076 NewArgs.push_back(Constant::getNullValue(i32Ty));
2077 while (EltOffset != 0) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002078 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy, DL);
Bob Wilsonc16811b2009-12-19 06:53:17 +00002079 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilson532cd232009-12-18 20:14:40 +00002080 }
Pete Cooper818e9f42012-06-16 01:43:26 +00002081 if (NonConstantIdx) {
2082 Type* GepTy = T;
2083 // This GEP has a dynamic index. We need to add "i32 0" to index through
2084 // any structs or arrays in the original type until we get to the vector
2085 // to index.
2086 while (!isa<VectorType>(GepTy)) {
2087 NewArgs.push_back(Constant::getNullValue(i32Ty));
2088 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U);
2089 }
Pete Coopere24d6a12012-06-15 18:07:29 +00002090 NewArgs.push_back(NonConstantIdx);
Pete Cooper818e9f42012-06-16 01:43:26 +00002091 }
Bob Wilson532cd232009-12-18 20:14:40 +00002092 Instruction *Val = NewElts[Idx];
2093 if (NewArgs.size() > 1) {
Jay Foadd1b78492011-07-25 09:48:08 +00002094 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI);
Bob Wilson532cd232009-12-18 20:14:40 +00002095 Val->takeName(GEPI);
2096 }
2097 if (Val->getType() != GEPI->getType())
Benjamin Kramer40582a82010-01-27 19:46:52 +00002098 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilson532cd232009-12-18 20:14:40 +00002099 GEPI->replaceAllUsesWith(Val);
2100 DeadInsts.push_back(GEPI);
Chris Lattner9a2de652009-01-07 07:18:45 +00002101}
2102
Nick Lewycky15e2d902011-07-25 23:14:22 +00002103/// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it
2104/// to mark the lifetime of the scalarized memory.
2105void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI,
2106 uint64_t Offset,
Craig Topperb94011f2013-07-14 04:42:23 +00002107 SmallVectorImpl<AllocaInst *> &NewElts) {
Nick Lewycky15e2d902011-07-25 23:14:22 +00002108 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0));
2109 // Put matching lifetime markers on everything from Offset up to
2110 // Offset+OldSize.
2111 Type *AIType = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002112 const DataLayout &DL = II->getModule()->getDataLayout();
Nick Lewycky15e2d902011-07-25 23:14:22 +00002113 uint64_t NewOffset = Offset;
2114 Type *IdxTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002115 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy, DL);
Nick Lewycky15e2d902011-07-25 23:14:22 +00002116
2117 IRBuilder<> Builder(II);
2118 uint64_t Size = OldSize->getLimitedValue();
2119
2120 if (NewOffset) {
2121 // Splice the first element and index 'NewOffset' bytes in. SROA will
2122 // split the alloca again later.
Matt Arsenaultbe558882014-04-23 20:58:57 +00002123 unsigned AS = AI->getType()->getAddressSpace();
2124 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy(AS));
David Blaikie93c54442015-04-03 19:41:44 +00002125 V = Builder.CreateGEP(Builder.getInt8Ty(), V, Builder.getInt64(NewOffset));
Nick Lewycky15e2d902011-07-25 23:14:22 +00002126
2127 IdxTy = NewElts[Idx]->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002128 uint64_t EltSize = DL.getTypeAllocSize(IdxTy) - NewOffset;
Nick Lewycky15e2d902011-07-25 23:14:22 +00002129 if (EltSize > Size) {
2130 EltSize = Size;
2131 Size = 0;
2132 } else {
2133 Size -= EltSize;
2134 }
2135 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2136 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize));
2137 else
2138 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize));
2139 ++Idx;
2140 }
2141
2142 for (; Idx != NewElts.size() && Size; ++Idx) {
2143 IdxTy = NewElts[Idx]->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002144 uint64_t EltSize = DL.getTypeAllocSize(IdxTy);
Nick Lewycky15e2d902011-07-25 23:14:22 +00002145 if (EltSize > Size) {
2146 EltSize = Size;
2147 Size = 0;
2148 } else {
2149 Size -= EltSize;
2150 }
2151 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
2152 Builder.CreateLifetimeStart(NewElts[Idx],
2153 Builder.getInt64(EltSize));
2154 else
2155 Builder.CreateLifetimeEnd(NewElts[Idx],
2156 Builder.getInt64(EltSize));
2157 }
2158 DeadInsts.push_back(II);
2159}
2160
Chris Lattner9a2de652009-01-07 07:18:45 +00002161/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
2162/// Rewrite it to copy or set the elements of the scalarized memory.
Craig Topperb94011f2013-07-14 04:42:23 +00002163void
2164SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
2165 AllocaInst *AI,
2166 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattner9a2de652009-01-07 07:18:45 +00002167 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattnera41bb402009-03-04 19:23:25 +00002168 // appropriate type. The "Other" pointer is the pointer that goes to memory
2169 // that doesn't have anything to do with the alloca that we are promoting. For
2170 // memset, this Value* stays null.
Craig Topperf40110f2014-04-25 05:29:35 +00002171 Value *OtherPtr = nullptr;
Pete Cooper67cf9a72015-11-19 05:56:52 +00002172 unsigned MemAlignment = MI->getAlignment();
Chris Lattner334268a2009-03-08 03:37:16 +00002173 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilson532cd232009-12-18 20:14:40 +00002174 if (Inst == MTI->getRawDest())
Chris Lattner334268a2009-03-08 03:37:16 +00002175 OtherPtr = MTI->getRawSource();
Chris Lattner9a2de652009-01-07 07:18:45 +00002176 else {
Bob Wilson532cd232009-12-18 20:14:40 +00002177 assert(Inst == MTI->getRawSource());
Chris Lattner334268a2009-03-08 03:37:16 +00002178 OtherPtr = MTI->getRawDest();
Chris Lattner9a2de652009-01-07 07:18:45 +00002179 }
2180 }
Bob Wilson2029ea02009-12-08 18:22:03 +00002181
Chris Lattner9a2de652009-01-07 07:18:45 +00002182 // If there is an other pointer, we want to convert it to the same pointer
2183 // type as AI has, so we can GEP through it safely.
2184 if (OtherPtr) {
Chris Lattnerefa3c822010-07-08 00:27:05 +00002185 unsigned AddrSpace =
2186 cast<PointerType>(OtherPtr->getType())->getAddressSpace();
Bob Wilson532cd232009-12-18 20:14:40 +00002187
2188 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
2189 // optimization, but it's also required to detect the corner case where
2190 // both pointer operands are referencing the same memory, and where
2191 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
2192 // function is only called for mem intrinsics that access the whole
2193 // aggregate, so non-zero GEPs are not an issue here.)
Chris Lattnerefa3c822010-07-08 00:27:05 +00002194 OtherPtr = OtherPtr->stripPointerCasts();
Bob Wilson328e91b2011-01-13 20:59:44 +00002195
Bob Wilson58d59fe2010-01-19 04:32:48 +00002196 // Copying the alloca to itself is a no-op: just delete it.
2197 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
2198 // This code will run twice for a no-op memcpy -- once for each operand.
2199 // Put only one reference to MI on the DeadInsts list.
Craig Topper31ee5862013-07-03 15:07:05 +00002200 for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
Bob Wilson58d59fe2010-01-19 04:32:48 +00002201 E = DeadInsts.end(); I != E; ++I)
2202 if (*I == MI) return;
2203 DeadInsts.push_back(MI);
Bob Wilson532cd232009-12-18 20:14:40 +00002204 return;
Bob Wilson58d59fe2010-01-19 04:32:48 +00002205 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002206
Chris Lattner9a2de652009-01-07 07:18:45 +00002207 // If the pointer is not the right type, insert a bitcast to the right
2208 // type.
Eduard Burtescu90c44492016-01-18 00:10:01 +00002209 Type *NewTy = PointerType::get(AI->getAllocatedType(), AddrSpace);
Bob Wilson328e91b2011-01-13 20:59:44 +00002210
Chris Lattnerefa3c822010-07-08 00:27:05 +00002211 if (OtherPtr->getType() != NewTy)
2212 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
Chris Lattner9a2de652009-01-07 07:18:45 +00002213 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002214
Chris Lattner9a2de652009-01-07 07:18:45 +00002215 // Process each element of the aggregate.
Bob Wilson532cd232009-12-18 20:14:40 +00002216 bool SROADest = MI->getRawDest() == Inst;
Bob Wilson328e91b2011-01-13 20:59:44 +00002217
Owen Anderson55f1c092009-08-13 21:58:54 +00002218 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002219 const DataLayout &DL = MI->getModule()->getDataLayout();
Chris Lattner9a2de652009-01-07 07:18:45 +00002220
2221 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2222 // If this is a memcpy/memmove, emit a GEP of the other element address.
Craig Topperf40110f2014-04-25 05:29:35 +00002223 Value *OtherElt = nullptr;
Pete Cooper67cf9a72015-11-19 05:56:52 +00002224 unsigned OtherEltAlign = MemAlignment;
Bob Wilson328e91b2011-01-13 20:59:44 +00002225
Bob Wilson58d59fe2010-01-19 04:32:48 +00002226 if (OtherPtr) {
Owen Anderson55f1c092009-08-13 21:58:54 +00002227 Value *Idx[2] = { Zero,
2228 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Jay Foadd1b78492011-07-25 09:48:08 +00002229 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx,
Benjamin Kramer40582a82010-01-27 19:46:52 +00002230 OtherPtr->getName()+"."+Twine(i),
Bob Wilson532cd232009-12-18 20:14:40 +00002231 MI);
Chris Lattner5c204c92009-03-04 19:20:50 +00002232 uint64_t EltOffset;
Eduard Burtescu90c44492016-01-18 00:10:01 +00002233 Type *OtherTy = AI->getAllocatedType();
Chris Lattner229907c2011-07-18 04:54:35 +00002234 if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002235 EltOffset = DL.getStructLayout(ST)->getElementOffset(i);
Chris Lattner5c204c92009-03-04 19:20:50 +00002236 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002237 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002238 EltOffset = DL.getTypeAllocSize(EltTy) * i;
Chris Lattner5c204c92009-03-04 19:20:50 +00002239 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002240
Chris Lattner5c204c92009-03-04 19:20:50 +00002241 // The alignment of the other pointer is the guaranteed alignment of the
2242 // element, which is affected by both the known alignment of the whole
2243 // mem intrinsic and the alignment of the element. If the alignment of
2244 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
2245 // known alignment is just 4 bytes.
Pete Cooper67cf9a72015-11-19 05:56:52 +00002246 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattner9f022d52007-03-08 06:36:54 +00002247 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002248
Eduard Burtescu90c44492016-01-18 00:10:01 +00002249 AllocaInst *EltPtr = NewElts[i];
2250 Type *EltTy = EltPtr->getAllocatedType();
Bob Wilson328e91b2011-01-13 20:59:44 +00002251
Chris Lattner9a2de652009-01-07 07:18:45 +00002252 // If we got down to a scalar, insert a load or store as appropriate.
2253 if (EltTy->isSingleValueType()) {
Chris Lattner334268a2009-03-08 03:37:16 +00002254 if (isa<MemTransferInst>(MI)) {
Chris Lattner5c204c92009-03-04 19:20:50 +00002255 if (SROADest) {
2256 // From Other to Alloca.
Pete Cooper67cf9a72015-11-19 05:56:52 +00002257 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
Chris Lattner5c204c92009-03-04 19:20:50 +00002258 new StoreInst(Elt, EltPtr, MI);
2259 } else {
2260 // From Alloca to Other.
2261 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
Pete Cooper67cf9a72015-11-19 05:56:52 +00002262 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
Chris Lattner5c204c92009-03-04 19:20:50 +00002263 }
Chris Lattner9a2de652009-01-07 07:18:45 +00002264 continue;
2265 }
2266 assert(isa<MemSetInst>(MI));
Bob Wilson328e91b2011-01-13 20:59:44 +00002267
Chris Lattner9a2de652009-01-07 07:18:45 +00002268 // If the stored element is zero (common case), just store a null
2269 // constant.
2270 Constant *StoreVal;
Gabor Greiffe252e62010-06-30 09:16:16 +00002271 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
Chris Lattner9a2de652009-01-07 07:18:45 +00002272 if (CI->isZero()) {
Owen Anderson5a1acd92009-07-31 20:28:14 +00002273 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattner9a2de652009-01-07 07:18:45 +00002274 } else {
2275 // If EltTy is a vector type, get the element type.
Chris Lattner229907c2011-07-18 04:54:35 +00002276 Type *ValTy = EltTy->getScalarType();
Dan Gohmanadfd42a2009-06-16 00:20:26 +00002277
Chris Lattner9a2de652009-01-07 07:18:45 +00002278 // Construct an integer with the right value.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002279 unsigned EltSize = DL.getTypeSizeInBits(ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +00002280 APInt OneVal(EltSize, CI->getZExtValue());
2281 APInt TotalVal(OneVal);
2282 // Set each byte.
2283 for (unsigned i = 0; 8*i < EltSize; ++i) {
2284 TotalVal = TotalVal.shl(8);
2285 TotalVal |= OneVal;
2286 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002287
Chris Lattner9a2de652009-01-07 07:18:45 +00002288 // Convert the integer value to the appropriate type.
Chris Lattner1146d322010-04-16 01:05:38 +00002289 StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
Duncan Sands19d0b472010-02-16 11:11:14 +00002290 if (ValTy->isPointerTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002291 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sands9dff9be2010-02-15 16:12:20 +00002292 else if (ValTy->isFloatingPointTy())
Owen Anderson487375e2009-07-29 18:55:55 +00002293 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +00002294 assert(StoreVal->getType() == ValTy && "Type mismatch!");
Bob Wilson328e91b2011-01-13 20:59:44 +00002295
Chris Lattner9a2de652009-01-07 07:18:45 +00002296 // If the requested value was a vector constant, create it.
Cameron Zwarich1a761dc2011-10-11 21:26:40 +00002297 if (EltTy->isVectorTy()) {
2298 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
Chris Lattner47a86bd2012-01-25 06:02:56 +00002299 StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
Chris Lattner9a2de652009-01-07 07:18:45 +00002300 }
2301 }
2302 new StoreInst(StoreVal, EltPtr, MI);
2303 continue;
2304 }
2305 // Otherwise, if we're storing a byte variable, use a memset call for
2306 // this element.
2307 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002308
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002309 unsigned EltSize = DL.getTypeAllocSize(EltTy);
Eli Friedmanecb45382011-11-12 02:07:50 +00002310 if (!EltSize)
2311 continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002312
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002313 IRBuilder<> Builder(MI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002314
Chris Lattner9a2de652009-01-07 07:18:45 +00002315 // Finally, insert the meminst for this element.
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002316 if (isa<MemSetInst>(MI)) {
2317 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
2318 MI->isVolatile());
Chris Lattner9a2de652009-01-07 07:18:45 +00002319 } else {
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002320 assert(isa<MemTransferInst>(MI));
2321 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
2322 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
Bob Wilson328e91b2011-01-13 20:59:44 +00002323
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002324 if (isa<MemCpyInst>(MI))
Pete Cooper67cf9a72015-11-19 05:56:52 +00002325 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile());
Chris Lattner6cf8d6c2010-12-26 22:57:41 +00002326 else
Pete Cooper67cf9a72015-11-19 05:56:52 +00002327 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile());
Chris Lattner9a2de652009-01-07 07:18:45 +00002328 }
Chris Lattner66e6a822007-03-05 07:52:57 +00002329 }
Bob Wilson532cd232009-12-18 20:14:40 +00002330 DeadInsts.push_back(MI);
Chris Lattner66e6a822007-03-05 07:52:57 +00002331}
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002332
Bob Wilson050b8122009-12-04 21:57:37 +00002333/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002334/// overwrites the entire allocation. Extract out the pieces of the stored
2335/// integer and store them individually.
Craig Topperb94011f2013-07-14 04:42:23 +00002336void
2337SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
2338 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002339 // Extract each element out of the integer according to its structure offset
2340 // and store the element value to the individual alloca.
2341 Value *SrcVal = SI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002342 Type *AllocaEltTy = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002343 const DataLayout &DL = SI->getModule()->getDataLayout();
2344 uint64_t AllocaSizeBits = DL.getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002345
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002346 IRBuilder<> Builder(SI);
Nadav Rotem465834c2012-07-24 10:51:42 +00002347
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002348 // Handle tail padding by extending the operand
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002349 if (DL.getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002350 SrcVal = Builder.CreateZExt(SrcVal,
2351 IntegerType::get(SI->getContext(), AllocaSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002352
David Greene48c86be2010-01-05 01:27:09 +00002353 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky7465cd72009-09-15 07:08:25 +00002354 << '\n');
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002355
2356 // There are two forms here: AI could be an array or struct. Both cases
2357 // have different ways to compute the element offset.
Chris Lattner229907c2011-07-18 04:54:35 +00002358 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002359 const StructLayout *Layout = DL.getStructLayout(EltSTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002360
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002361 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2362 // Get the number of bits to shift SrcVal to get the value.
Chris Lattner229907c2011-07-18 04:54:35 +00002363 Type *FieldTy = EltSTy->getElementType(i);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002364 uint64_t Shift = Layout->getElementOffsetInBits(i);
Bob Wilson328e91b2011-01-13 20:59:44 +00002365
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002366 if (DL.isBigEndian())
2367 Shift = AllocaSizeBits - Shift - DL.getTypeAllocSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002368
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002369 Value *EltVal = SrcVal;
2370 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002371 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002372 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002373 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002374
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002375 // Truncate down to an integer of the right size.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002376 uint64_t FieldSizeBits = DL.getTypeSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002377
Chris Lattnerae0e8572009-01-09 18:18:43 +00002378 // Ignore zero sized fields like {}, they obviously contain no data.
2379 if (FieldSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002380
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002381 if (FieldSizeBits != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002382 EltVal = Builder.CreateTrunc(EltVal,
2383 IntegerType::get(SI->getContext(), FieldSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002384 Value *DestField = NewElts[i];
2385 if (EltVal->getType() == FieldTy) {
2386 // Storing to an integer field of this size, just do it.
Duncan Sands19d0b472010-02-16 11:11:14 +00002387 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002388 // Bitcast to the right element type (for fp/vector values).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002389 EltVal = Builder.CreateBitCast(EltVal, FieldTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002390 } else {
2391 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002392 DestField = Builder.CreateBitCast(DestField,
2393 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002394 }
2395 new StoreInst(EltVal, DestField, SI);
2396 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002397
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002398 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002399 ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
2400 Type *ArrayEltTy = ATy->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002401 uint64_t ElementOffset = DL.getTypeAllocSizeInBits(ArrayEltTy);
2402 uint64_t ElementSizeBits = DL.getTypeSizeInBits(ArrayEltTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002403
2404 uint64_t Shift;
Bob Wilson328e91b2011-01-13 20:59:44 +00002405
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002406 if (DL.isBigEndian())
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002407 Shift = AllocaSizeBits-ElementOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002408 else
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002409 Shift = 0;
Bob Wilson328e91b2011-01-13 20:59:44 +00002410
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002411 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerae0e8572009-01-09 18:18:43 +00002412 // Ignore zero sized fields like {}, they obviously contain no data.
2413 if (ElementSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002414
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002415 Value *EltVal = SrcVal;
2416 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002417 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002418 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt");
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002419 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002420
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002421 // Truncate down to an integer of the right size.
2422 if (ElementSizeBits != AllocaSizeBits)
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002423 EltVal = Builder.CreateTrunc(EltVal,
2424 IntegerType::get(SI->getContext(),
2425 ElementSizeBits));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002426 Value *DestField = NewElts[i];
2427 if (EltVal->getType() == ArrayEltTy) {
2428 // Storing to an integer field of this size, just do it.
Duncan Sands9dff9be2010-02-15 16:12:20 +00002429 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +00002430 ArrayEltTy->isVectorTy()) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002431 // Bitcast to the right element type (for fp/vector values).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002432 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002433 } else {
2434 // Otherwise, bitcast the dest pointer (for aggregates).
Chris Lattner7cd8cf72011-01-16 05:58:24 +00002435 DestField = Builder.CreateBitCast(DestField,
2436 PointerType::getUnqual(EltVal->getType()));
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002437 }
2438 new StoreInst(EltVal, DestField, SI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002439
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002440 if (DL.isBigEndian())
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002441 Shift -= ElementOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002442 else
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002443 Shift += ElementOffset;
2444 }
2445 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002446
Bob Wilson532cd232009-12-18 20:14:40 +00002447 DeadInsts.push_back(SI);
Chris Lattnerf2b8c822009-01-07 08:11:13 +00002448}
2449
Bob Wilson050b8122009-12-04 21:57:37 +00002450/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002451/// an integer. Load the individual pieces to form the aggregate value.
Craig Topperb94011f2013-07-14 04:42:23 +00002452void
2453SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
2454 SmallVectorImpl<AllocaInst *> &NewElts) {
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002455 // Extract each element out of the NewElts according to its structure offset
2456 // and form the result value.
Chris Lattner229907c2011-07-18 04:54:35 +00002457 Type *AllocaEltTy = AI->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002458 const DataLayout &DL = LI->getModule()->getDataLayout();
2459 uint64_t AllocaSizeBits = DL.getTypeAllocSizeInBits(AllocaEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002460
David Greene48c86be2010-01-05 01:27:09 +00002461 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky7465cd72009-09-15 07:08:25 +00002462 << '\n');
Bob Wilson328e91b2011-01-13 20:59:44 +00002463
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002464 // There are two forms here: AI could be an array or struct. Both cases
2465 // have different ways to compute the element offset.
Craig Topperf40110f2014-04-25 05:29:35 +00002466 const StructLayout *Layout = nullptr;
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002467 uint64_t ArrayEltBitOffset = 0;
Chris Lattner229907c2011-07-18 04:54:35 +00002468 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002469 Layout = DL.getStructLayout(EltSTy);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002470 } else {
Chris Lattner229907c2011-07-18 04:54:35 +00002471 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002472 ArrayEltBitOffset = DL.getTypeAllocSizeInBits(ArrayEltTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002473 }
2474
2475 Value *ResultVal =
Owen Anderson55f1c092009-08-13 21:58:54 +00002476 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Bob Wilson328e91b2011-01-13 20:59:44 +00002477
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002478 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
2479 // Load the value from the alloca. If the NewElt is an aggregate, cast
2480 // the pointer to an integer of the same size before doing the load.
2481 Value *SrcField = NewElts[i];
Eduard Burtescu90c44492016-01-18 00:10:01 +00002482 Type *FieldTy = NewElts[i]->getAllocatedType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002483 uint64_t FieldSizeBits = DL.getTypeSizeInBits(FieldTy);
Bob Wilson328e91b2011-01-13 20:59:44 +00002484
Chris Lattnerae0e8572009-01-09 18:18:43 +00002485 // Ignore zero sized fields like {}, they obviously contain no data.
2486 if (FieldSizeBits == 0) continue;
Bob Wilson328e91b2011-01-13 20:59:44 +00002487
Chris Lattner229907c2011-07-18 04:54:35 +00002488 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00002489 FieldSizeBits);
Duncan Sands19d0b472010-02-16 11:11:14 +00002490 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
2491 !FieldTy->isVectorTy())
Owen Anderson340288c2009-07-03 19:42:02 +00002492 SrcField = new BitCastInst(SrcField,
Owen Anderson4056ca92009-07-29 22:17:13 +00002493 PointerType::getUnqual(FieldIntTy),
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002494 "", LI);
2495 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
2496
2497 // If SrcField is a fp or vector of the right size but that isn't an
2498 // integer type, bitcast to an integer so we can shift it.
2499 if (SrcField->getType() != FieldIntTy)
2500 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
2501
2502 // Zero extend the field to be the same size as the final alloca so that
2503 // we can shift and insert it.
2504 if (SrcField->getType() != ResultVal->getType())
2505 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002506
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002507 // Determine the number of bits to shift SrcField.
2508 uint64_t Shift;
2509 if (Layout) // Struct case.
2510 Shift = Layout->getElementOffsetInBits(i);
2511 else // Array case.
2512 Shift = i*ArrayEltBitOffset;
Bob Wilson328e91b2011-01-13 20:59:44 +00002513
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002514 if (DL.isBigEndian())
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002515 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
Bob Wilson328e91b2011-01-13 20:59:44 +00002516
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002517 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00002518 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002519 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
2520 }
2521
Chris Lattner25a843f2010-06-27 07:58:26 +00002522 // Don't create an 'or x, 0' on the first iteration.
2523 if (!isa<Constant>(ResultVal) ||
2524 !cast<Constant>(ResultVal)->isNullValue())
2525 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
2526 else
2527 ResultVal = SrcField;
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002528 }
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002529
2530 // Handle tail padding by truncating the result
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002531 if (DL.getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
Eli Friedmanee94e3c2009-06-01 09:14:32 +00002532 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
2533
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002534 LI->replaceAllUsesWith(ResultVal);
Bob Wilson532cd232009-12-18 20:14:40 +00002535 DeadInsts.push_back(LI);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00002536}
2537
Duncan Sands399d9792007-11-04 14:43:57 +00002538/// HasPadding - Return true if the specified type has any structure or
Bob Wilson12eec402011-01-13 17:45:08 +00002539/// alignment padding in between the elements that would be split apart
2540/// by SROA; return false otherwise.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002541static bool HasPadding(Type *Ty, const DataLayout &DL) {
Chris Lattner229907c2011-07-18 04:54:35 +00002542 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Bob Wilson12eec402011-01-13 17:45:08 +00002543 Ty = ATy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002544 return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
Chris Lattner87679202007-05-30 06:11:23 +00002545 }
Bob Wilson12eec402011-01-13 17:45:08 +00002546
2547 // SROA currently handles only Arrays and Structs.
Chris Lattner229907c2011-07-18 04:54:35 +00002548 StructType *STy = cast<StructType>(Ty);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002549 const StructLayout *SL = DL.getStructLayout(STy);
Bob Wilson12eec402011-01-13 17:45:08 +00002550 unsigned PrevFieldBitOffset = 0;
2551 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
2552 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
2553
2554 // Check to see if there is any padding between this element and the
2555 // previous one.
2556 if (i) {
2557 unsigned PrevFieldEnd =
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002558 PrevFieldBitOffset+DL.getTypeSizeInBits(STy->getElementType(i-1));
Bob Wilson12eec402011-01-13 17:45:08 +00002559 if (PrevFieldEnd < FieldBitOffset)
2560 return true;
2561 }
2562 PrevFieldBitOffset = FieldBitOffset;
2563 }
2564 // Check for tail padding.
2565 if (unsigned EltCount = STy->getNumElements()) {
2566 unsigned PrevFieldEnd = PrevFieldBitOffset +
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002567 DL.getTypeSizeInBits(STy->getElementType(EltCount-1));
Bob Wilson12eec402011-01-13 17:45:08 +00002568 if (PrevFieldEnd < SL->getSizeInBits())
2569 return true;
2570 }
2571 return false;
Chris Lattner87679202007-05-30 06:11:23 +00002572}
Chris Lattner66e6a822007-03-05 07:52:57 +00002573
Chris Lattner88819122004-11-14 04:24:28 +00002574/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
2575/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
2576/// or 1 if safe after canonicalization has been performed.
Victor Hernandez1df65182010-01-21 23:05:53 +00002577bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +00002578 // Loop over the use list of the alloca. We can only transform it if all of
2579 // the users are safe to transform.
Chris Lattner8acbb792011-01-23 07:29:29 +00002580 AllocaInfo Info(AI);
Bob Wilson328e91b2011-01-13 20:59:44 +00002581
Chris Lattner8acbb792011-01-23 07:29:29 +00002582 isSafeForScalarRepl(AI, 0, Info);
Bob Wilson532cd232009-12-18 20:14:40 +00002583 if (Info.isUnsafe) {
David Greene48c86be2010-01-05 01:27:09 +00002584 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez1df65182010-01-21 23:05:53 +00002585 return false;
Chris Lattner88819122004-11-14 04:24:28 +00002586 }
Bob Wilson328e91b2011-01-13 20:59:44 +00002587
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002588 const DataLayout &DL = AI->getModule()->getDataLayout();
2589
Chris Lattner87679202007-05-30 06:11:23 +00002590 // Okay, we know all the users are promotable. If the aggregate is a memcpy
2591 // source and destination, we have to be careful. In particular, the memcpy
2592 // could be moving around elements that live in structure padding of the LLVM
2593 // types, but may actually be used. In these cases, we refuse to promote the
2594 // struct.
2595 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002596 HasPadding(AI->getAllocatedType(), DL))
Victor Hernandez1df65182010-01-21 23:05:53 +00002597 return false;
Duncan Sands399d9792007-11-04 14:43:57 +00002598
Chris Lattner7c9f4c92011-01-16 17:46:19 +00002599 // If the alloca never has an access to just *part* of it, but is accessed
2600 // via loads and stores, then we should use ConvertToScalarInfo to promote
Chris Lattner6fab2e92011-01-16 06:18:28 +00002601 // the alloca instead of promoting each piece at a time and inserting fission
2602 // and fusion code.
2603 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) {
2604 // If the struct/array just has one element, use basic SRoA.
Chris Lattner229907c2011-07-18 04:54:35 +00002605 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
Chris Lattner6fab2e92011-01-16 06:18:28 +00002606 if (ST->getNumElements() > 1) return false;
2607 } else {
2608 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1)
2609 return false;
2610 }
2611 }
Nadav Rotem465834c2012-07-24 10:51:42 +00002612
Victor Hernandez1df65182010-01-21 23:05:53 +00002613 return true;
Chris Lattner6e5398d2003-05-30 04:15:41 +00002614}