blob: fcdb6ab77d4a686c12dc36b5872fc61cefa2b57b [file] [log] [blame]
Michael J. Spencer289067c2014-05-29 01:55:07 +00001//===- LoadCombine.cpp - Combine Adjacent Loads ---------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This transformation combines adjacent loads.
11///
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Transforms/Scalar.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000015#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/Statistic.h"
Hal Finkel840257a2014-11-03 23:19:16 +000017#include "llvm/Analysis/AliasAnalysis.h"
18#include "llvm/Analysis/AliasSetTracker.h"
Chandler Carruth7b560d42015-09-09 17:55:00 +000019#include "llvm/Analysis/GlobalsModRef.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000020#include "llvm/Analysis/TargetFolder.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000021#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Function.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000023#include "llvm/IR/IRBuilder.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000024#include "llvm/IR/Instructions.h"
Mehdi Amini46a43552015-03-04 18:43:29 +000025#include "llvm/IR/Module.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000026#include "llvm/Pass.h"
Michael J. Spencer289067c2014-05-29 01:55:07 +000027#include "llvm/Support/Debug.h"
28#include "llvm/Support/MathExtras.h"
29#include "llvm/Support/raw_ostream.h"
30
31using namespace llvm;
32
33#define DEBUG_TYPE "load-combine"
34
35STATISTIC(NumLoadsAnalyzed, "Number of loads analyzed for combining");
36STATISTIC(NumLoadsCombined, "Number of loads combined");
37
Chad Rosier7ab9a7b2016-05-04 15:19:02 +000038#define LDCOMBINE_NAME "Combine Adjacent Loads"
39
Michael J. Spencer289067c2014-05-29 01:55:07 +000040namespace {
41struct PointerOffsetPair {
42 Value *Pointer;
43 uint64_t Offset;
44};
45
46struct LoadPOPPair {
Benjamin Kramer79de6e62015-04-11 18:57:14 +000047 LoadPOPPair() = default;
Michael J. Spencer289067c2014-05-29 01:55:07 +000048 LoadPOPPair(LoadInst *L, PointerOffsetPair P, unsigned O)
49 : Load(L), POP(P), InsertOrder(O) {}
Michael J. Spencer289067c2014-05-29 01:55:07 +000050 LoadInst *Load;
51 PointerOffsetPair POP;
52 /// \brief The new load needs to be created before the first load in IR order.
53 unsigned InsertOrder;
54};
55
56class LoadCombine : public BasicBlockPass {
57 LLVMContext *C;
Hal Finkel840257a2014-11-03 23:19:16 +000058 AliasAnalysis *AA;
Michael J. Spencer289067c2014-05-29 01:55:07 +000059
60public:
Mehdi Aminia28d91d2015-03-10 02:37:25 +000061 LoadCombine() : BasicBlockPass(ID), C(nullptr), AA(nullptr) {
Chandler Carruth1688a772015-09-09 09:46:16 +000062 initializeLoadCombinePass(*PassRegistry::getPassRegistry());
Michael J. Spencer289067c2014-05-29 01:55:07 +000063 }
Aaron Ballman573f3b52014-07-30 19:23:59 +000064
65 using llvm::Pass::doInitialization;
Michael J. Spencer289067c2014-05-29 01:55:07 +000066 bool doInitialization(Function &) override;
67 bool runOnBasicBlock(BasicBlock &BB) override;
68 void getAnalysisUsage(AnalysisUsage &AU) const override;
69
Chad Rosier7ab9a7b2016-05-04 15:19:02 +000070 const char *getPassName() const override { return LDCOMBINE_NAME; }
Michael J. Spencer289067c2014-05-29 01:55:07 +000071 static char ID;
72
Mehdi Aminiba9fba82016-03-13 21:05:13 +000073 typedef IRBuilder<TargetFolder> BuilderTy;
Michael J. Spencer289067c2014-05-29 01:55:07 +000074
75private:
76 BuilderTy *Builder;
77
78 PointerOffsetPair getPointerOffsetPair(LoadInst &);
79 bool combineLoads(DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> &);
80 bool aggregateLoads(SmallVectorImpl<LoadPOPPair> &);
81 bool combineLoads(SmallVectorImpl<LoadPOPPair> &);
82};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000083}
Michael J. Spencer289067c2014-05-29 01:55:07 +000084
85bool LoadCombine::doInitialization(Function &F) {
86 DEBUG(dbgs() << "LoadCombine function: " << F.getName() << "\n");
87 C = &F.getContext();
Michael J. Spencer289067c2014-05-29 01:55:07 +000088 return true;
89}
90
91PointerOffsetPair LoadCombine::getPointerOffsetPair(LoadInst &LI) {
92 PointerOffsetPair POP;
93 POP.Pointer = LI.getPointerOperand();
94 POP.Offset = 0;
95 while (isa<BitCastInst>(POP.Pointer) || isa<GetElementPtrInst>(POP.Pointer)) {
96 if (auto *GEP = dyn_cast<GetElementPtrInst>(POP.Pointer)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000097 auto &DL = LI.getModule()->getDataLayout();
98 unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
Michael J. Spencer289067c2014-05-29 01:55:07 +000099 APInt Offset(BitWidth, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000100 if (GEP->accumulateConstantOffset(DL, Offset))
Michael J. Spencer289067c2014-05-29 01:55:07 +0000101 POP.Offset += Offset.getZExtValue();
102 else
103 // Can't handle GEPs with variable indices.
104 return POP;
105 POP.Pointer = GEP->getPointerOperand();
106 } else if (auto *BC = dyn_cast<BitCastInst>(POP.Pointer))
107 POP.Pointer = BC->getOperand(0);
108 }
109 return POP;
110}
111
112bool LoadCombine::combineLoads(
113 DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> &LoadMap) {
114 bool Combined = false;
115 for (auto &Loads : LoadMap) {
116 if (Loads.second.size() < 2)
117 continue;
118 std::sort(Loads.second.begin(), Loads.second.end(),
119 [](const LoadPOPPair &A, const LoadPOPPair &B) {
120 return A.POP.Offset < B.POP.Offset;
121 });
122 if (aggregateLoads(Loads.second))
123 Combined = true;
124 }
125 return Combined;
126}
127
128/// \brief Try to aggregate loads from a sorted list of loads to be combined.
129///
130/// It is guaranteed that no writes occur between any of the loads. All loads
131/// have the same base pointer. There are at least two loads.
132bool LoadCombine::aggregateLoads(SmallVectorImpl<LoadPOPPair> &Loads) {
133 assert(Loads.size() >= 2 && "Insufficient loads!");
134 LoadInst *BaseLoad = nullptr;
135 SmallVector<LoadPOPPair, 8> AggregateLoads;
136 bool Combined = false;
137 uint64_t PrevOffset = -1ull;
138 uint64_t PrevSize = 0;
139 for (auto &L : Loads) {
140 if (PrevOffset == -1ull) {
141 BaseLoad = L.Load;
142 PrevOffset = L.POP.Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000143 PrevSize = L.Load->getModule()->getDataLayout().getTypeStoreSize(
144 L.Load->getType());
Michael J. Spencer289067c2014-05-29 01:55:07 +0000145 AggregateLoads.push_back(L);
146 continue;
147 }
148 if (L.Load->getAlignment() > BaseLoad->getAlignment())
149 continue;
150 if (L.POP.Offset > PrevOffset + PrevSize) {
151 // No other load will be combinable
152 if (combineLoads(AggregateLoads))
153 Combined = true;
154 AggregateLoads.clear();
155 PrevOffset = -1;
156 continue;
157 }
158 if (L.POP.Offset != PrevOffset + PrevSize)
159 // This load is offset less than the size of the last load.
160 // FIXME: We may want to handle this case.
161 continue;
162 PrevOffset = L.POP.Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000163 PrevSize = L.Load->getModule()->getDataLayout().getTypeStoreSize(
164 L.Load->getType());
Michael J. Spencer289067c2014-05-29 01:55:07 +0000165 AggregateLoads.push_back(L);
166 }
167 if (combineLoads(AggregateLoads))
168 Combined = true;
169 return Combined;
170}
171
172/// \brief Given a list of combinable load. Combine the maximum number of them.
173bool LoadCombine::combineLoads(SmallVectorImpl<LoadPOPPair> &Loads) {
174 // Remove loads from the end while the size is not a power of 2.
175 unsigned TotalSize = 0;
176 for (const auto &L : Loads)
177 TotalSize += L.Load->getType()->getPrimitiveSizeInBits();
178 while (TotalSize != 0 && !isPowerOf2_32(TotalSize))
179 TotalSize -= Loads.pop_back_val().Load->getType()->getPrimitiveSizeInBits();
180 if (Loads.size() < 2)
181 return false;
182
183 DEBUG({
184 dbgs() << "***** Combining Loads ******\n";
185 for (const auto &L : Loads) {
186 dbgs() << L.POP.Offset << ": " << *L.Load << "\n";
187 }
188 });
189
190 // Find first load. This is where we put the new load.
191 LoadPOPPair FirstLP;
192 FirstLP.InsertOrder = -1u;
193 for (const auto &L : Loads)
194 if (L.InsertOrder < FirstLP.InsertOrder)
195 FirstLP = L;
196
197 unsigned AddressSpace =
198 FirstLP.POP.Pointer->getType()->getPointerAddressSpace();
199
200 Builder->SetInsertPoint(FirstLP.Load);
201 Value *Ptr = Builder->CreateConstGEP1_64(
202 Builder->CreatePointerCast(Loads[0].POP.Pointer,
203 Builder->getInt8PtrTy(AddressSpace)),
204 Loads[0].POP.Offset);
205 LoadInst *NewLoad = new LoadInst(
206 Builder->CreatePointerCast(
207 Ptr, PointerType::get(IntegerType::get(Ptr->getContext(), TotalSize),
208 Ptr->getType()->getPointerAddressSpace())),
209 Twine(Loads[0].Load->getName()) + ".combined", false,
210 Loads[0].Load->getAlignment(), FirstLP.Load);
211
212 for (const auto &L : Loads) {
213 Builder->SetInsertPoint(L.Load);
214 Value *V = Builder->CreateExtractInteger(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000215 L.Load->getModule()->getDataLayout(), NewLoad,
216 cast<IntegerType>(L.Load->getType()),
Michael J. Spencer289067c2014-05-29 01:55:07 +0000217 L.POP.Offset - Loads[0].POP.Offset, "combine.extract");
218 L.Load->replaceAllUsesWith(V);
219 }
220
221 NumLoadsCombined = NumLoadsCombined + Loads.size();
222 return true;
223}
224
225bool LoadCombine::runOnBasicBlock(BasicBlock &BB) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000226 if (skipBasicBlock(BB))
Michael J. Spencer289067c2014-05-29 01:55:07 +0000227 return false;
228
Chandler Carruth7b560d42015-09-09 17:55:00 +0000229 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Hal Finkel840257a2014-11-03 23:19:16 +0000230
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000231 IRBuilder<TargetFolder> TheBuilder(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000232 BB.getContext(), TargetFolder(BB.getModule()->getDataLayout()));
Michael J. Spencer289067c2014-05-29 01:55:07 +0000233 Builder = &TheBuilder;
234
235 DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> LoadMap;
Hal Finkel840257a2014-11-03 23:19:16 +0000236 AliasSetTracker AST(*AA);
Michael J. Spencer289067c2014-05-29 01:55:07 +0000237
238 bool Combined = false;
239 unsigned Index = 0;
240 for (auto &I : BB) {
Hal Finkel840257a2014-11-03 23:19:16 +0000241 if (I.mayThrow() || (I.mayWriteToMemory() && AST.containsUnknown(&I))) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000242 if (combineLoads(LoadMap))
243 Combined = true;
244 LoadMap.clear();
Hal Finkel840257a2014-11-03 23:19:16 +0000245 AST.clear();
Michael J. Spencer289067c2014-05-29 01:55:07 +0000246 continue;
247 }
248 LoadInst *LI = dyn_cast<LoadInst>(&I);
249 if (!LI)
250 continue;
251 ++NumLoadsAnalyzed;
252 if (!LI->isSimple() || !LI->getType()->isIntegerTy())
253 continue;
254 auto POP = getPointerOffsetPair(*LI);
255 if (!POP.Pointer)
256 continue;
257 LoadMap[POP.Pointer].push_back(LoadPOPPair(LI, POP, Index++));
Hal Finkel840257a2014-11-03 23:19:16 +0000258 AST.add(LI);
Michael J. Spencer289067c2014-05-29 01:55:07 +0000259 }
260 if (combineLoads(LoadMap))
261 Combined = true;
262 return Combined;
263}
264
265void LoadCombine::getAnalysisUsage(AnalysisUsage &AU) const {
266 AU.setPreservesCFG();
Hal Finkel840257a2014-11-03 23:19:16 +0000267
Chandler Carruth7b560d42015-09-09 17:55:00 +0000268 AU.addRequired<AAResultsWrapperPass>();
269 AU.addPreserved<GlobalsAAWrapperPass>();
Michael J. Spencer289067c2014-05-29 01:55:07 +0000270}
271
272char LoadCombine::ID = 0;
273
274BasicBlockPass *llvm::createLoadCombinePass() {
275 return new LoadCombine();
276}
277
Chad Rosier7ab9a7b2016-05-04 15:19:02 +0000278INITIALIZE_PASS_BEGIN(LoadCombine, "load-combine", LDCOMBINE_NAME, false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000279INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
280INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
Chad Rosier7ab9a7b2016-05-04 15:19:02 +0000281INITIALIZE_PASS_END(LoadCombine, "load-combine", LDCOMBINE_NAME, false, false)