1 //===------ PollyIRBuilder.cpp --------------------------------------------===//
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 //
10 // The Polly IRBuilder file contains Polly specific extensions for the IRBuilder
11 // that are used e.g. to emit the llvm.loop.parallel metadata.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "polly/CodeGen/IRBuilder.h"
16 #include "polly/ScopInfo.h"
17 #include "polly/Support/ScopHelper.h"
18 #include "llvm/IR/Metadata.h"
19 #include "llvm/Support/Debug.h"
20 
21 using namespace llvm;
22 using namespace polly;
23 
24 static const int MaxArraysInAliasScops = 10;
25 
26 /// Get a self referencing id metadata node.
27 ///
28 /// The MDNode looks like this (if arg0/arg1 are not null):
29 ///
30 ///    '!n = metadata !{metadata !n, arg0, arg1}'
31 ///
32 /// @return The self referencing id metadata node.
33 static MDNode *getID(LLVMContext &Ctx, Metadata *arg0 = nullptr,
34                      Metadata *arg1 = nullptr) {
35   MDNode *ID;
36   SmallVector<Metadata *, 3> Args;
37   // Use a temporary node to safely create a unique pointer for the first arg.
38   auto TempNode = MDNode::getTemporary(Ctx, None);
39   // Reserve operand 0 for loop id self reference.
40   Args.push_back(TempNode.get());
41 
42   if (arg0)
43     Args.push_back(arg0);
44   if (arg1)
45     Args.push_back(arg1);
46 
47   ID = MDNode::get(Ctx, Args);
48   ID->replaceOperandWith(0, ID);
49   return ID;
50 }
51 
52 ScopAnnotator::ScopAnnotator() : SE(nullptr), AliasScopeDomain(nullptr) {}
53 
54 void ScopAnnotator::buildAliasScopes(Scop &S) {
55   SE = S.getSE();
56 
57   LLVMContext &Ctx = SE->getContext();
58   AliasScopeDomain = getID(Ctx, MDString::get(Ctx, "polly.alias.scope.domain"));
59 
60   AliasScopeMap.clear();
61   OtherAliasScopeListMap.clear();
62 
63   // The construction of alias scopes is quadratic in the number of arrays
64   // involved. In case of too many arrays, skip the construction of alias
65   // information to avoid quadratic increases in compile time and code size.
66   if (std::distance(S.array_begin(), S.array_end()) > MaxArraysInAliasScops)
67     return;
68 
69   std::string AliasScopeStr = "polly.alias.scope.";
70   for (const ScopArrayInfo *Array : S.arrays())
71     AliasScopeMap[Array->getBasePtr()] =
72         getID(Ctx, AliasScopeDomain,
73               MDString::get(Ctx, (AliasScopeStr + Array->getName()).c_str()));
74 
75   for (const ScopArrayInfo *Array : S.arrays()) {
76     MDNode *AliasScopeList = MDNode::get(Ctx, {});
77     for (const auto &AliasScopePair : AliasScopeMap) {
78       if (Array->getBasePtr() == AliasScopePair.first)
79         continue;
80 
81       Metadata *Args = {AliasScopePair.second};
82       AliasScopeList =
83           MDNode::concatenate(AliasScopeList, MDNode::get(Ctx, Args));
84     }
85 
86     OtherAliasScopeListMap[Array->getBasePtr()] = AliasScopeList;
87   }
88 }
89 
90 void ScopAnnotator::pushLoop(Loop *L, bool IsParallel) {
91 
92   ActiveLoops.push_back(L);
93   if (!IsParallel)
94     return;
95 
96   BasicBlock *Header = L->getHeader();
97   MDNode *Id = getID(Header->getContext());
98   assert(Id->getOperand(0) == Id && "Expected Id to be a self-reference");
99   assert(Id->getNumOperands() == 1 && "Unexpected extra operands in Id");
100   MDNode *Ids = ParallelLoops.empty()
101                     ? Id
102                     : MDNode::concatenate(ParallelLoops.back(), Id);
103   ParallelLoops.push_back(Ids);
104 }
105 
106 void ScopAnnotator::popLoop(bool IsParallel) {
107   ActiveLoops.pop_back();
108   if (!IsParallel)
109     return;
110 
111   assert(!ParallelLoops.empty() && "Expected a parallel loop to pop");
112   ParallelLoops.pop_back();
113 }
114 
115 void ScopAnnotator::annotateLoopLatch(BranchInst *B, Loop *L,
116                                       bool IsParallel) const {
117   if (!IsParallel)
118     return;
119 
120   assert(!ParallelLoops.empty() && "Expected a parallel loop to annotate");
121   MDNode *Ids = ParallelLoops.back();
122   MDNode *Id = cast<MDNode>(Ids->getOperand(Ids->getNumOperands() - 1));
123   B->setMetadata("llvm.loop", Id);
124 }
125 
126 /// Get the pointer operand
127 ///
128 /// @param Inst The instruction to be analyzed.
129 /// @return the pointer operand in case @p Inst is a memory access
130 ///         instruction and nullptr otherwise.
131 static llvm::Value *getMemAccInstPointerOperand(Instruction *Inst) {
132   auto MemInst = MemAccInst::dyn_cast(Inst);
133   if (!MemInst)
134     return nullptr;
135 
136   return MemInst.getPointerOperand();
137 }
138 
139 void ScopAnnotator::annotateSecondLevel(llvm::Instruction *Inst,
140                                         llvm::Value *BasePtr) {
141   auto *Ptr = getMemAccInstPointerOperand(Inst);
142   if (!Ptr)
143     return;
144   auto SecondLevelAliasScope = SecondLevelAliasScopeMap.lookup(Ptr);
145   auto SecondLevelOtherAliasScopeList =
146       SecondLevelOtherAliasScopeListMap.lookup(Ptr);
147   if (!SecondLevelAliasScope) {
148     auto AliasScope = AliasScopeMap.lookup(BasePtr);
149     if (!AliasScope)
150       return;
151     LLVMContext &Ctx = SE->getContext();
152     SecondLevelAliasScope = getID(
153         Ctx, AliasScope, MDString::get(Ctx, "second level alias metadata"));
154     SecondLevelAliasScopeMap[Ptr] = SecondLevelAliasScope;
155     Metadata *Args = {SecondLevelAliasScope};
156     auto SecondLevelBasePtrAliasScopeList =
157         SecondLevelAliasScopeMap.lookup(BasePtr);
158     SecondLevelAliasScopeMap[BasePtr] = MDNode::concatenate(
159         SecondLevelBasePtrAliasScopeList, MDNode::get(Ctx, Args));
160     auto OtherAliasScopeList = OtherAliasScopeListMap.lookup(BasePtr);
161     SecondLevelOtherAliasScopeList = MDNode::concatenate(
162         OtherAliasScopeList, SecondLevelBasePtrAliasScopeList);
163     SecondLevelOtherAliasScopeListMap[Ptr] = SecondLevelOtherAliasScopeList;
164   }
165   Inst->setMetadata("alias.scope", SecondLevelAliasScope);
166   Inst->setMetadata("noalias", SecondLevelOtherAliasScopeList);
167 }
168 
169 void ScopAnnotator::annotate(Instruction *Inst) {
170   if (!Inst->mayReadOrWriteMemory())
171     return;
172 
173   if (!ParallelLoops.empty())
174     Inst->setMetadata("llvm.mem.parallel_loop_access", ParallelLoops.back());
175 
176   // TODO: Use the ScopArrayInfo once available here.
177   if (!AliasScopeDomain)
178     return;
179 
180   auto *Ptr = getMemAccInstPointerOperand(Inst);
181   if (!Ptr)
182     return;
183 
184   auto *PtrSCEV = SE->getSCEV(Ptr);
185   auto *BaseSCEV = SE->getPointerBase(PtrSCEV);
186   auto *SU = dyn_cast<SCEVUnknown>(BaseSCEV);
187 
188   if (!SU)
189     return;
190 
191   auto *BasePtr = SU->getValue();
192 
193   if (!BasePtr)
194     return;
195 
196   auto AliasScope = AliasScopeMap.lookup(BasePtr);
197 
198   if (!AliasScope) {
199     BasePtr = AlternativeAliasBases.lookup(BasePtr);
200     if (!BasePtr)
201       return;
202 
203     AliasScope = AliasScopeMap.lookup(BasePtr);
204     if (!AliasScope)
205       return;
206   }
207 
208   assert(OtherAliasScopeListMap.count(BasePtr) &&
209          "BasePtr either expected in AliasScopeMap and OtherAlias...Map");
210   auto *OtherAliasScopeList = OtherAliasScopeListMap[BasePtr];
211 
212   if (InterIterationAliasFreeBasePtrs.count(BasePtr)) {
213     annotateSecondLevel(Inst, BasePtr);
214     return;
215   }
216 
217   Inst->setMetadata("alias.scope", AliasScope);
218   Inst->setMetadata("noalias", OtherAliasScopeList);
219 }
220 
221 void ScopAnnotator::addInterIterationAliasFreeBasePtr(llvm::Value *BasePtr) {
222   if (!BasePtr)
223     return;
224 
225   InterIterationAliasFreeBasePtrs.insert(BasePtr);
226 }
227