blob: dfe51a4ce44c5fd49693f8a198e7fe42fa5d75a9 [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;
David Majnemer3ffe2dd2016-06-19 21:36:35 +000043 APInt Offset;
Michael J. Spencer289067c2014-05-29 01:55:07 +000044};
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;
Davide Italiano84e14142016-06-02 22:04:43 +000068 void getAnalysisUsage(AnalysisUsage &AU) const override {
69 AU.setPreservesCFG();
70 AU.addRequired<AAResultsWrapperPass>();
71 AU.addPreserved<GlobalsAAWrapperPass>();
72 }
Michael J. Spencer289067c2014-05-29 01:55:07 +000073
Chad Rosier7ab9a7b2016-05-04 15:19:02 +000074 const char *getPassName() const override { return LDCOMBINE_NAME; }
Michael J. Spencer289067c2014-05-29 01:55:07 +000075 static char ID;
76
Mehdi Aminiba9fba82016-03-13 21:05:13 +000077 typedef IRBuilder<TargetFolder> BuilderTy;
Michael J. Spencer289067c2014-05-29 01:55:07 +000078
79private:
80 BuilderTy *Builder;
81
82 PointerOffsetPair getPointerOffsetPair(LoadInst &);
83 bool combineLoads(DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> &);
84 bool aggregateLoads(SmallVectorImpl<LoadPOPPair> &);
85 bool combineLoads(SmallVectorImpl<LoadPOPPair> &);
86};
Alexander Kornienkof00654e2015-06-23 09:49:53 +000087}
Michael J. Spencer289067c2014-05-29 01:55:07 +000088
89bool LoadCombine::doInitialization(Function &F) {
90 DEBUG(dbgs() << "LoadCombine function: " << F.getName() << "\n");
91 C = &F.getContext();
Michael J. Spencer289067c2014-05-29 01:55:07 +000092 return true;
93}
94
95PointerOffsetPair LoadCombine::getPointerOffsetPair(LoadInst &LI) {
David Majnemer3ffe2dd2016-06-19 21:36:35 +000096 auto &DL = LI.getModule()->getDataLayout();
97
Michael J. Spencer289067c2014-05-29 01:55:07 +000098 PointerOffsetPair POP;
99 POP.Pointer = LI.getPointerOperand();
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000100 unsigned BitWidth = DL.getPointerSizeInBits(LI.getPointerAddressSpace());
101 POP.Offset = APInt(BitWidth, 0);
102
Michael J. Spencer289067c2014-05-29 01:55:07 +0000103 while (isa<BitCastInst>(POP.Pointer) || isa<GetElementPtrInst>(POP.Pointer)) {
104 if (auto *GEP = dyn_cast<GetElementPtrInst>(POP.Pointer)) {
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000105 APInt LastOffset = POP.Offset;
106 if (!GEP->accumulateConstantOffset(DL, POP.Offset)) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000107 // Can't handle GEPs with variable indices.
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000108 POP.Offset = LastOffset;
Michael J. Spencer289067c2014-05-29 01:55:07 +0000109 return POP;
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000110 }
Michael J. Spencer289067c2014-05-29 01:55:07 +0000111 POP.Pointer = GEP->getPointerOperand();
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000112 } else if (auto *BC = dyn_cast<BitCastInst>(POP.Pointer)) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000113 POP.Pointer = BC->getOperand(0);
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000114 }
Michael J. Spencer289067c2014-05-29 01:55:07 +0000115 }
116 return POP;
117}
118
119bool LoadCombine::combineLoads(
120 DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> &LoadMap) {
121 bool Combined = false;
122 for (auto &Loads : LoadMap) {
123 if (Loads.second.size() < 2)
124 continue;
125 std::sort(Loads.second.begin(), Loads.second.end(),
126 [](const LoadPOPPair &A, const LoadPOPPair &B) {
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000127 return A.POP.Offset.slt(B.POP.Offset);
128 });
Michael J. Spencer289067c2014-05-29 01:55:07 +0000129 if (aggregateLoads(Loads.second))
130 Combined = true;
131 }
132 return Combined;
133}
134
135/// \brief Try to aggregate loads from a sorted list of loads to be combined.
136///
137/// It is guaranteed that no writes occur between any of the loads. All loads
138/// have the same base pointer. There are at least two loads.
139bool LoadCombine::aggregateLoads(SmallVectorImpl<LoadPOPPair> &Loads) {
140 assert(Loads.size() >= 2 && "Insufficient loads!");
141 LoadInst *BaseLoad = nullptr;
142 SmallVector<LoadPOPPair, 8> AggregateLoads;
143 bool Combined = false;
David Majnemer31195992016-06-19 06:14:56 +0000144 bool ValidPrevOffset = false;
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000145 APInt PrevOffset;
Michael J. Spencer289067c2014-05-29 01:55:07 +0000146 uint64_t PrevSize = 0;
147 for (auto &L : Loads) {
David Majnemer31195992016-06-19 06:14:56 +0000148 if (ValidPrevOffset == false) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000149 BaseLoad = L.Load;
150 PrevOffset = L.POP.Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000151 PrevSize = L.Load->getModule()->getDataLayout().getTypeStoreSize(
152 L.Load->getType());
Michael J. Spencer289067c2014-05-29 01:55:07 +0000153 AggregateLoads.push_back(L);
David Majnemer31195992016-06-19 06:14:56 +0000154 ValidPrevOffset = true;
Michael J. Spencer289067c2014-05-29 01:55:07 +0000155 continue;
156 }
157 if (L.Load->getAlignment() > BaseLoad->getAlignment())
158 continue;
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000159 APInt PrevEnd = PrevOffset + PrevSize;
160 if (L.POP.Offset.sgt(PrevEnd)) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000161 // No other load will be combinable
162 if (combineLoads(AggregateLoads))
163 Combined = true;
164 AggregateLoads.clear();
David Majnemer31195992016-06-19 06:14:56 +0000165 ValidPrevOffset = false;
Michael J. Spencer289067c2014-05-29 01:55:07 +0000166 continue;
167 }
David Majnemer31195992016-06-19 06:14:56 +0000168 if (L.POP.Offset != PrevEnd)
Michael J. Spencer289067c2014-05-29 01:55:07 +0000169 // This load is offset less than the size of the last load.
170 // FIXME: We may want to handle this case.
171 continue;
172 PrevOffset = L.POP.Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000173 PrevSize = L.Load->getModule()->getDataLayout().getTypeStoreSize(
174 L.Load->getType());
Michael J. Spencer289067c2014-05-29 01:55:07 +0000175 AggregateLoads.push_back(L);
176 }
177 if (combineLoads(AggregateLoads))
178 Combined = true;
179 return Combined;
180}
181
182/// \brief Given a list of combinable load. Combine the maximum number of them.
183bool LoadCombine::combineLoads(SmallVectorImpl<LoadPOPPair> &Loads) {
184 // Remove loads from the end while the size is not a power of 2.
185 unsigned TotalSize = 0;
186 for (const auto &L : Loads)
187 TotalSize += L.Load->getType()->getPrimitiveSizeInBits();
188 while (TotalSize != 0 && !isPowerOf2_32(TotalSize))
189 TotalSize -= Loads.pop_back_val().Load->getType()->getPrimitiveSizeInBits();
190 if (Loads.size() < 2)
191 return false;
192
193 DEBUG({
194 dbgs() << "***** Combining Loads ******\n";
195 for (const auto &L : Loads) {
196 dbgs() << L.POP.Offset << ": " << *L.Load << "\n";
197 }
198 });
199
200 // Find first load. This is where we put the new load.
201 LoadPOPPair FirstLP;
202 FirstLP.InsertOrder = -1u;
203 for (const auto &L : Loads)
204 if (L.InsertOrder < FirstLP.InsertOrder)
205 FirstLP = L;
206
207 unsigned AddressSpace =
208 FirstLP.POP.Pointer->getType()->getPointerAddressSpace();
209
210 Builder->SetInsertPoint(FirstLP.Load);
211 Value *Ptr = Builder->CreateConstGEP1_64(
212 Builder->CreatePointerCast(Loads[0].POP.Pointer,
213 Builder->getInt8PtrTy(AddressSpace)),
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000214 Loads[0].POP.Offset.getSExtValue());
Michael J. Spencer289067c2014-05-29 01:55:07 +0000215 LoadInst *NewLoad = new LoadInst(
216 Builder->CreatePointerCast(
217 Ptr, PointerType::get(IntegerType::get(Ptr->getContext(), TotalSize),
218 Ptr->getType()->getPointerAddressSpace())),
219 Twine(Loads[0].Load->getName()) + ".combined", false,
220 Loads[0].Load->getAlignment(), FirstLP.Load);
221
222 for (const auto &L : Loads) {
223 Builder->SetInsertPoint(L.Load);
224 Value *V = Builder->CreateExtractInteger(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000225 L.Load->getModule()->getDataLayout(), NewLoad,
226 cast<IntegerType>(L.Load->getType()),
David Majnemer3ffe2dd2016-06-19 21:36:35 +0000227 (L.POP.Offset - Loads[0].POP.Offset).getZExtValue(), "combine.extract");
Michael J. Spencer289067c2014-05-29 01:55:07 +0000228 L.Load->replaceAllUsesWith(V);
229 }
230
231 NumLoadsCombined = NumLoadsCombined + Loads.size();
232 return true;
233}
234
235bool LoadCombine::runOnBasicBlock(BasicBlock &BB) {
Andrew Kayloraa641a52016-04-22 22:06:11 +0000236 if (skipBasicBlock(BB))
Michael J. Spencer289067c2014-05-29 01:55:07 +0000237 return false;
238
Chandler Carruth7b560d42015-09-09 17:55:00 +0000239 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
Hal Finkel840257a2014-11-03 23:19:16 +0000240
Mehdi Aminiba9fba82016-03-13 21:05:13 +0000241 IRBuilder<TargetFolder> TheBuilder(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000242 BB.getContext(), TargetFolder(BB.getModule()->getDataLayout()));
Michael J. Spencer289067c2014-05-29 01:55:07 +0000243 Builder = &TheBuilder;
244
245 DenseMap<const Value *, SmallVector<LoadPOPPair, 8>> LoadMap;
Hal Finkel840257a2014-11-03 23:19:16 +0000246 AliasSetTracker AST(*AA);
Michael J. Spencer289067c2014-05-29 01:55:07 +0000247
248 bool Combined = false;
249 unsigned Index = 0;
250 for (auto &I : BB) {
Hal Finkel840257a2014-11-03 23:19:16 +0000251 if (I.mayThrow() || (I.mayWriteToMemory() && AST.containsUnknown(&I))) {
Michael J. Spencer289067c2014-05-29 01:55:07 +0000252 if (combineLoads(LoadMap))
253 Combined = true;
254 LoadMap.clear();
Hal Finkel840257a2014-11-03 23:19:16 +0000255 AST.clear();
Michael J. Spencer289067c2014-05-29 01:55:07 +0000256 continue;
257 }
258 LoadInst *LI = dyn_cast<LoadInst>(&I);
259 if (!LI)
260 continue;
261 ++NumLoadsAnalyzed;
262 if (!LI->isSimple() || !LI->getType()->isIntegerTy())
263 continue;
264 auto POP = getPointerOffsetPair(*LI);
265 if (!POP.Pointer)
266 continue;
267 LoadMap[POP.Pointer].push_back(LoadPOPPair(LI, POP, Index++));
Hal Finkel840257a2014-11-03 23:19:16 +0000268 AST.add(LI);
Michael J. Spencer289067c2014-05-29 01:55:07 +0000269 }
270 if (combineLoads(LoadMap))
271 Combined = true;
272 return Combined;
273}
274
Michael J. Spencer289067c2014-05-29 01:55:07 +0000275char LoadCombine::ID = 0;
276
277BasicBlockPass *llvm::createLoadCombinePass() {
278 return new LoadCombine();
279}
280
Chad Rosier7ab9a7b2016-05-04 15:19:02 +0000281INITIALIZE_PASS_BEGIN(LoadCombine, "load-combine", LDCOMBINE_NAME, false, false)
Chandler Carruth7b560d42015-09-09 17:55:00 +0000282INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
Chad Rosier7ab9a7b2016-05-04 15:19:02 +0000283INITIALIZE_PASS_END(LoadCombine, "load-combine", LDCOMBINE_NAME, false, false)