Polly 24.0.0git
LoopGenerators.cpp
Go to the documentation of this file.
1//===------ LoopGenerators.cpp - IR helper to create loops ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains functions to create scalar loops and orchestrate the
10// creation of parallel loops as LLVM-IR.
11//
12//===----------------------------------------------------------------------===//
13
15#include "polly/Options.h"
16#include "polly/ScopDetection.h"
17#include "llvm/Analysis/LoopInfo.h"
18#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/DebugInfoMetadata.h"
20#include "llvm/IR/Dominators.h"
21#include "llvm/IR/Module.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Transforms/Utils/BasicBlockUtils.h"
24
25using namespace llvm;
26using namespace polly;
27
31
32static cl::opt<int, true>
33 XPollyNumThreads("polly-num-threads",
34 cl::desc("Number of threads to use (0 = auto)"),
35 cl::Hidden, cl::location(polly::PollyNumThreads),
36 cl::init(0), cl::cat(PollyCategory));
37
39 "polly-annotate-metadata-vectorize",
40 cl::desc("Append vectorize enable/disable metadata from polly"),
41 cl::init(false), cl::cat(PollyCategory));
42
43static cl::opt<OMPGeneralSchedulingType, true> XPollyScheduling(
44 "polly-scheduling",
45 cl::desc("Scheduling type of parallel OpenMP for loops"),
46 cl::values(clEnumValN(OMPGeneralSchedulingType::StaticChunked, "static",
47 "Static scheduling"),
48 clEnumValN(OMPGeneralSchedulingType::Dynamic, "dynamic",
49 "Dynamic scheduling"),
50 clEnumValN(OMPGeneralSchedulingType::Guided, "guided",
51 "Guided scheduling"),
52 clEnumValN(OMPGeneralSchedulingType::Runtime, "runtime",
53 "Runtime determined (OMP_SCHEDULE)")),
54 cl::Hidden, cl::location(polly::PollyScheduling),
56
57static cl::opt<int, true>
58 XPollyChunkSize("polly-scheduling-chunksize",
59 cl::desc("Chunksize to use by the OpenMP runtime calls"),
60 cl::Hidden, cl::location(polly::PollyChunkSize),
61 cl::init(0), cl::cat(PollyCategory));
62
63// We generate a loop of either of the following structures:
64//
65// BeforeBB BeforeBB
66// | |
67// v v
68// GuardBB PreHeaderBB
69// / | | _____
70// __ PreHeaderBB | v \/ |
71// / \ / | HeaderBB latch
72// latch HeaderBB | |\ |
73// \ / \ / | \------/
74// < \ / |
75// \ / v
76// ExitBB ExitBB
77//
78// depending on whether or not we know that it is executed at least once. If
79// not, GuardBB checks if the loop is executed at least once. If this is the
80// case we branch to PreHeaderBB and subsequently to the HeaderBB, which
81// contains the loop iv 'polly.indvar', the incremented loop iv
82// 'polly.indvar_next' as well as the condition to check if we execute another
83// iteration of the loop. After the loop has finished, we branch to ExitBB.
84// We expect the type of UB, LB, UB+Stride to be large enough for values that
85// UB may take throughout the execution of the loop, including the computation
86// of indvar + Stride before the final abort.
88 PollyIRBuilder &Builder, LoopInfo &LI,
89 DominatorTree &DT, BasicBlock *&ExitBB,
90 ICmpInst::Predicate Predicate,
91 ScopAnnotator *Annotator, bool Parallel, bool UseGuard,
92 bool LoopVectDisabled,
93 bool SkipVectorizeEnableMetadata) {
94 Function *F = Builder.GetInsertBlock()->getParent();
95 LLVMContext &Context = F->getContext();
96
97 assert(LB->getType() == UB->getType() && "Types of loop bounds do not match");
98 IntegerType *LoopIVType = dyn_cast<IntegerType>(UB->getType());
99 assert(LoopIVType && "UB is not integer?");
100
101 BasicBlock *BeforeBB = Builder.GetInsertBlock();
102 BasicBlock *GuardBB =
103 UseGuard ? BasicBlock::Create(Context, "polly.loop_if", F) : nullptr;
104 BasicBlock *HeaderBB = BasicBlock::Create(Context, "polly.loop_header", F);
105 BasicBlock *PreHeaderBB =
106 BasicBlock::Create(Context, "polly.loop_preheader", F);
107
108 // Update LoopInfo
109 Loop *OuterLoop = LI.getLoopFor(BeforeBB);
110 Loop *NewLoop = LI.AllocateLoop();
111
112 if (OuterLoop)
113 OuterLoop->addChildLoop(NewLoop);
114 else
115 LI.addTopLevelLoop(NewLoop);
116
117 if (OuterLoop) {
118 if (GuardBB)
119 OuterLoop->addBasicBlockToLoop(GuardBB, LI);
120 OuterLoop->addBasicBlockToLoop(PreHeaderBB, LI);
121 }
122
123 NewLoop->addBasicBlockToLoop(HeaderBB, LI);
124
125 // Notify the annotator (if present) that we have a new loop, but only
126 // after the header block is set.
127 if (Annotator)
128 Annotator->pushLoop(NewLoop, Parallel);
129
130 // ExitBB
131 ExitBB = SplitBlock(BeforeBB, Builder.GetInsertPoint(), &DT, &LI);
132 ExitBB->setName("polly.loop_exit");
133
134 // BeforeBB
135 if (GuardBB) {
136 BeforeBB->getTerminator()->setSuccessor(0, GuardBB);
137 DT.addNewBlock(GuardBB, BeforeBB);
138
139 // GuardBB
140 Builder.SetInsertPoint(GuardBB);
141 Value *LoopGuard;
142 LoopGuard = Builder.CreateICmp(Predicate, LB, UB);
143 LoopGuard->setName("polly.loop_guard");
144 Builder.CreateCondBr(LoopGuard, PreHeaderBB, ExitBB);
145 DT.addNewBlock(PreHeaderBB, GuardBB);
146 } else {
147 BeforeBB->getTerminator()->setSuccessor(0, PreHeaderBB);
148 DT.addNewBlock(PreHeaderBB, BeforeBB);
149 }
150
151 // PreHeaderBB
152 Builder.SetInsertPoint(PreHeaderBB);
153 Builder.CreateBr(HeaderBB);
154
155 // HeaderBB
156 DT.addNewBlock(HeaderBB, PreHeaderBB);
157 Builder.SetInsertPoint(HeaderBB);
158 PHINode *IV = Builder.CreatePHI(LoopIVType, 2, "polly.indvar");
159 IV->addIncoming(LB, PreHeaderBB);
160 Stride = Builder.CreateZExtOrBitCast(Stride, LoopIVType);
161 Value *IncrementedIV = Builder.CreateNSWAdd(IV, Stride, "polly.indvar_next");
162 Value *LoopCondition =
163 Builder.CreateICmp(Predicate, IncrementedIV, UB, "polly.loop_cond");
164
165 // Create the loop latch and annotate it as such.
166 CondBrInst *B = Builder.CreateCondBr(LoopCondition, HeaderBB, ExitBB);
167
168 // Emit vectorize.enable=false only for explicit user disable
169 // (LoopVectDisabled). For dist=1 FP loops (SkipVectorizeEnableMetadata), omit
170 // the annotation and let the Loop Vectorizer decide.
171 if (Annotator) {
172 std::optional<bool> EnableVectorizeMetadata;
173 if (LoopVectDisabled)
174 EnableVectorizeMetadata = false;
175 else if (PollyVectorizeMetadata && !SkipVectorizeEnableMetadata)
176 EnableVectorizeMetadata = true;
177 Annotator->annotateLoopLatch(B, Parallel, EnableVectorizeMetadata);
178 }
179
180 IV->addIncoming(IncrementedIV, HeaderBB);
181 if (GuardBB)
182 DT.changeImmediateDominator(ExitBB, GuardBB);
183 else
184 DT.changeImmediateDominator(ExitBB, HeaderBB);
185
186 // The loop body should be added here.
187 Builder.SetInsertPoint(HeaderBB->getFirstNonPHIIt());
188 return IV;
189}
190
192 Value *LB, Value *UB, Value *Stride, SetVector<Value *> &UsedValues,
193 ValueMapT &Map, BasicBlock::iterator *LoopBody) {
194
195 AllocaInst *Struct = storeValuesIntoStruct(UsedValues);
196 BasicBlock::iterator BeforeLoop = Builder.GetInsertPoint();
197
198 Value *IV;
199 Function *SubFn;
200 std::tie(IV, SubFn) = createSubFn(Stride, Struct, UsedValues, Map);
201 *LoopBody = Builder.GetInsertPoint();
202 Builder.SetInsertPoint(BeforeLoop);
203
204 // Add one as the upper bound provided by OpenMP is a < comparison
205 // whereas the codegenForSequential function creates a <= comparison.
206 UB = Builder.CreateAdd(UB, ConstantInt::get(LongType, 1));
207
208 // Execute the prepared subfunction in parallel.
209 deployParallelExecution(SubFn, Struct, LB, UB, Stride);
210
211 return IV;
212}
213
215 Function *F = Builder.GetInsertBlock()->getParent();
216 Function *SubFn = prepareSubFnDefinition(F);
217
218 // Certain backends (e.g., NVPTX) do not support '.'s in function names.
219 // Hence, we ensure that all '.'s are replaced by '_'s.
220 std::string FunctionName = SubFn->getName().str();
221 std::replace(FunctionName.begin(), FunctionName.end(), '.', '_');
222 SubFn->setName(FunctionName);
223
224 // Do not run any polly pass on the new function.
225 SubFn->addFnAttr(PollySkipFnAttr);
226
227 return SubFn;
228}
229
230AllocaInst *
232 SmallVector<Type *, 8> Members;
233
234 for (Value *V : Values)
235 Members.push_back(V->getType());
236
237 const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout();
238
239 // We do not want to allocate the alloca inside any loop, thus we allocate it
240 // in the entry block of the function and use annotations to denote the actual
241 // live span (similar to clang).
242 BasicBlock &EntryBB = Builder.GetInsertBlock()->getParent()->getEntryBlock();
243 BasicBlock::iterator IP = EntryBB.getFirstInsertionPt();
244 StructType *Ty = StructType::get(Builder.getContext(), Members);
245 AllocaInst *Struct = new AllocaInst(Ty, DL.getAllocaAddrSpace(), nullptr,
246 "polly.par.userContext", IP);
247
248 for (unsigned i = 0; i < Values.size(); i++) {
249 Value *Address = Builder.CreateStructGEP(Ty, Struct, i);
250 Address->setName("polly.subfn.storeaddr." + Values[i]->getName());
251 Builder.CreateStore(Values[i], Address);
252 }
253
254 return Struct;
255}
256
258 SetVector<Value *> OldValues, Type *Ty, Value *Struct, ValueMapT &Map) {
259 for (unsigned i = 0; i < OldValues.size(); i++) {
260 Value *Address = Builder.CreateStructGEP(Ty, Struct, i);
261 Type *ElemTy = cast<GetElementPtrInst>(Address)->getResultElementType();
262 Value *NewValue = Builder.CreateLoad(ElemTy, Address);
263 NewValue->setName("polly.subfunc.arg." + OldValues[i]->getName());
264 Map[OldValues[i]] = NewValue;
265 }
266}
267
269 if (!F)
270 return DebugLoc();
271
272 LLVMContext &Ctx = F->getContext();
273 DISubprogram *DILScope =
274 dyn_cast_or_null<DISubprogram>(F->getMetadata(LLVMContext::MD_dbg));
275 if (!DILScope)
276 return DebugLoc();
277 return DILocation::get(Ctx, 0, 0, DILScope);
278}
cl::opt< bool > PollyVectorizeMetadata
static cl::opt< int, true > XPollyNumThreads("polly-num-threads", cl::desc("Number of threads to use (0 = auto)"), cl::Hidden, cl::location(polly::PollyNumThreads), cl::init(0), cl::cat(PollyCategory))
static cl::opt< int, true > XPollyChunkSize("polly-scheduling-chunksize", cl::desc("Chunksize to use by the OpenMP runtime calls"), cl::Hidden, cl::location(polly::PollyChunkSize), cl::init(0), cl::cat(PollyCategory))
static cl::opt< OMPGeneralSchedulingType, true > XPollyScheduling("polly-scheduling", cl::desc("Scheduling type of parallel OpenMP for loops"), cl::values(clEnumValN(OMPGeneralSchedulingType::StaticChunked, "static", "Static scheduling"), clEnumValN(OMPGeneralSchedulingType::Dynamic, "dynamic", "Dynamic scheduling"), clEnumValN(OMPGeneralSchedulingType::Guided, "guided", "Guided scheduling"), clEnumValN(OMPGeneralSchedulingType::Runtime, "runtime", "Runtime determined (OMP_SCHEDULE)")), cl::Hidden, cl::location(polly::PollyScheduling), cl::init(OMPGeneralSchedulingType::Runtime), cl::cat(PollyCategory))
llvm::cl::OptionCategory PollyCategory
PollyIRBuilder & Builder
The IR builder we use to create instructions.
Function * createSubFnDefinition()
Create the definition of the parallel subfunction.
virtual void deployParallelExecution(Function *SubFn, Value *SubFnParam, Value *LB, Value *UB, Value *Stride)=0
Create the runtime library calls for spawn and join of the worker threads.
Value * createParallelLoop(Value *LB, Value *UB, Value *Stride, SetVector< Value * > &Values, ValueMapT &VMap, BasicBlock::iterator *LoopBody)
Create a parallel loop.
virtual std::tuple< Value *, Function * > createSubFn(Value *Stride, AllocaInst *Struct, SetVector< Value * > UsedValues, ValueMapT &VMap)=0
Create the parallel subfunction.
Type * LongType
The type of a "long" on this hardware used for backend calls.
void extractValuesFromStruct(SetVector< Value * > Values, Type *Ty, Value *Struct, ValueMapT &VMap)
Extract all values from the Struct and construct the mapping.
virtual Function * prepareSubFnDefinition(Function *F) const =0
Prepare the definition of the parallel subfunction.
AllocaInst * storeValuesIntoStruct(SetVector< Value * > &Values)
Create a struct for all Values and store them in there.
Helper class to annotate newly generated SCoPs with metadata.
Definition IRBuilder.h:44
void annotateLoopLatch(llvm::CondBrInst *B, bool IsParallel, std::optional< bool > EnableVectorizeMetadata=std::nullopt) const
Annotate the loop latch B.
void pushLoop(llvm::Loop *L, bool IsParallel)
Add a new loop L which is parallel if IsParallel is true.
B()
#define assert(exp)
OMPGeneralSchedulingType PollyScheduling
StringRef PollySkipFnAttr
A function attribute which will cause Polly to skip the function.
llvm::DebugLoc createDebugLocForGeneratedCode(Function *F)
Create a DebugLoc representing generated instructions.
int PollyNumThreads
@ Value
MemoryKind::Value: Models an llvm::Value.
Definition ScopInfo.h:151
int PollyChunkSize
Value * createLoop(Value *LowerBound, Value *UpperBound, Value *Stride, PollyIRBuilder &Builder, LoopInfo &LI, DominatorTree &DT, BasicBlock *&ExitBlock, ICmpInst::Predicate Predicate, ScopAnnotator *Annotator=nullptr, bool Parallel=false, bool UseGuard=true, bool LoopVectDisabled=false, bool SkipVectorizeEnableMetadata=false)
Create a scalar do/for-style loop.
OMPGeneralSchedulingType
General scheduling types of parallel OpenMP for loops.
llvm::IRBuilder< llvm::ConstantFolder, IRInserter > PollyIRBuilder
Definition IRBuilder.h:143
llvm::DenseMap< llvm::AssertingVH< llvm::Value >, llvm::AssertingVH< llvm::Value > > ValueMapT
Type to remap values.
Definition ScopHelper.h:106
static TupleKindPtr Ctx