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 /// @brief Get a self referencing id metadata node.
25 ///
26 /// The MDNode looks like this (if arg0/arg1 are not null):
27 ///
28 ///    '!n = metadata !{metadata !n, arg0, arg1}'
29 ///
30 /// @return The self referencing id metadata node.
31 static MDNode *getID(LLVMContext &Ctx, Metadata *arg0 = nullptr,
32                      Metadata *arg1 = nullptr) {
33   MDNode *ID;
34   SmallVector<Metadata *, 3> Args;
35   // Use a temporary node to safely create a unique pointer for the first arg.
36   auto TempNode = MDNode::getTemporary(Ctx, None);
37   // Reserve operand 0 for loop id self reference.
38   Args.push_back(TempNode.get());
39 
40   if (arg0)
41     Args.push_back(arg0);
42   if (arg1)
43     Args.push_back(arg1);
44 
45   ID = MDNode::get(Ctx, Args);
46   ID->replaceOperandWith(0, ID);
47   return ID;
48 }
49 
50 ScopAnnotator::ScopAnnotator() : SE(nullptr), AliasScopeDomain(nullptr) {}
51 
52 void ScopAnnotator::buildAliasScopes(Scop &S) {
53   SE = S.getSE();
54 
55   LLVMContext &Ctx = SE->getContext();
56   AliasScopeDomain = getID(Ctx, MDString::get(Ctx, "polly.alias.scope.domain"));
57 
58   AliasScopeMap.clear();
59   OtherAliasScopeListMap.clear();
60 
61   SetVector<Value *> BasePtrs;
62   for (ScopStmt &Stmt : S)
63     for (MemoryAccess *MA : Stmt)
64       BasePtrs.insert(MA->getBaseAddr());
65 
66   std::string AliasScopeStr = "polly.alias.scope.";
67   for (Value *BasePtr : BasePtrs)
68     AliasScopeMap[BasePtr] = getID(
69         Ctx, AliasScopeDomain,
70         MDString::get(Ctx, (AliasScopeStr + BasePtr->getName()).str().c_str()));
71 
72   for (Value *BasePtr : BasePtrs) {
73     MDNode *AliasScopeList = MDNode::get(Ctx, {});
74     for (const auto &AliasScopePair : AliasScopeMap) {
75       if (BasePtr == AliasScopePair.first)
76         continue;
77 
78       Metadata *Args = {AliasScopePair.second};
79       AliasScopeList =
80           MDNode::concatenate(AliasScopeList, MDNode::get(Ctx, Args));
81     }
82 
83     OtherAliasScopeListMap[BasePtr] = AliasScopeList;
84   }
85 }
86 
87 void ScopAnnotator::pushLoop(Loop *L, bool IsParallel) {
88 
89   ActiveLoops.push_back(L);
90   if (!IsParallel)
91     return;
92 
93   BasicBlock *Header = L->getHeader();
94   MDNode *Id = getID(Header->getContext());
95   assert(Id->getOperand(0) == Id && "Expected Id to be a self-reference");
96   assert(Id->getNumOperands() == 1 && "Unexpected extra operands in Id");
97   MDNode *Ids = ParallelLoops.empty()
98                     ? Id
99                     : MDNode::concatenate(ParallelLoops.back(), Id);
100   ParallelLoops.push_back(Ids);
101 }
102 
103 void ScopAnnotator::popLoop(bool IsParallel) {
104   ActiveLoops.pop_back();
105   if (!IsParallel)
106     return;
107 
108   assert(!ParallelLoops.empty() && "Expected a parallel loop to pop");
109   ParallelLoops.pop_back();
110 }
111 
112 void ScopAnnotator::annotateLoopLatch(BranchInst *B, Loop *L,
113                                       bool IsParallel) const {
114   if (!IsParallel)
115     return;
116 
117   assert(!ParallelLoops.empty() && "Expected a parallel loop to annotate");
118   MDNode *Ids = ParallelLoops.back();
119   MDNode *Id = cast<MDNode>(Ids->getOperand(Ids->getNumOperands() - 1));
120   B->setMetadata("llvm.loop", Id);
121 }
122 
123 void ScopAnnotator::annotate(Instruction *Inst) {
124   if (!Inst->mayReadOrWriteMemory())
125     return;
126 
127   // TODO: Use the ScopArrayInfo once available here.
128   if (AliasScopeDomain) {
129     Value *BasePtr = nullptr;
130     if (isa<StoreInst>(Inst) || isa<LoadInst>(Inst)) {
131       const SCEV *PtrSCEV = SE->getSCEV(getPointerOperand(*Inst));
132       const SCEV *BaseSCEV = SE->getPointerBase(PtrSCEV);
133       if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(BaseSCEV))
134         BasePtr = SU->getValue();
135     }
136 
137     if (BasePtr) {
138       auto *AliasScope = AliasScopeMap[BasePtr];
139 
140       if (!AliasScope)
141         BasePtr = AlternativeAliasBases[BasePtr];
142 
143       AliasScope = AliasScopeMap[BasePtr];
144       auto *OtherAliasScopeList = OtherAliasScopeListMap[BasePtr];
145 
146       Inst->setMetadata("alias.scope", AliasScope);
147       Inst->setMetadata("noalias", OtherAliasScopeList);
148     }
149   }
150 
151   if (ParallelLoops.empty())
152     return;
153 
154   Inst->setMetadata("llvm.mem.parallel_loop_access", ParallelLoops.back());
155 }
156