1 //===- ScopBuilder.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 // Create a polyhedral description for a static control flow region.
11 //
12 // The pass creates a polyhedral description of the Scops detected by the SCoP
13 // detection derived from their LLVM-IR code.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "polly/ScopBuilder.h"
18 #include "polly/Options.h"
19 #include "polly/ScopDetection.h"
20 #include "polly/ScopDetectionDiagnostic.h"
21 #include "polly/ScopInfo.h"
22 #include "polly/Support/SCEVValidator.h"
23 #include "polly/Support/ScopHelper.h"
24 #include "polly/Support/VirtualInstruction.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Analysis/AliasAnalysis.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
33 #include "llvm/Analysis/RegionInfo.h"
34 #include "llvm/Analysis/RegionIterator.h"
35 #include "llvm/Analysis/ScalarEvolution.h"
36 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DataLayout.h"
40 #include "llvm/IR/DebugLoc.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/DiagnosticInfo.h"
43 #include "llvm/IR/Dominators.h"
44 #include "llvm/IR/Function.h"
45 #include "llvm/IR/InstrTypes.h"
46 #include "llvm/IR/Instruction.h"
47 #include "llvm/IR/Instructions.h"
48 #include "llvm/IR/IntrinsicInst.h"
49 #include "llvm/IR/Operator.h"
50 #include "llvm/IR/Type.h"
51 #include "llvm/IR/Use.h"
52 #include "llvm/IR/Value.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/Support/Debug.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include <cassert>
60 #include <string>
61 #include <tuple>
62 #include <vector>
63 
64 using namespace llvm;
65 using namespace polly;
66 
67 #define DEBUG_TYPE "polly-scops"
68 
69 STATISTIC(ScopFound, "Number of valid Scops");
70 STATISTIC(RichScopFound, "Number of Scops containing a loop");
71 STATISTIC(InfeasibleScops,
72           "Number of SCoPs with statically infeasible context.");
73 
74 bool polly::ModelReadOnlyScalars;
75 
76 static cl::opt<bool, true> XModelReadOnlyScalars(
77     "polly-analyze-read-only-scalars",
78     cl::desc("Model read-only scalar values in the scop description"),
79     cl::location(ModelReadOnlyScalars), cl::Hidden, cl::ZeroOrMore,
80     cl::init(true), cl::cat(PollyCategory));
81 
82 static cl::opt<bool> UnprofitableScalarAccs(
83     "polly-unprofitable-scalar-accs",
84     cl::desc("Count statements with scalar accesses as not optimizable"),
85     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
86 
87 static cl::opt<bool> DetectFortranArrays(
88     "polly-detect-fortran-arrays",
89     cl::desc("Detect Fortran arrays and use this for code generation"),
90     cl::Hidden, cl::init(false), cl::cat(PollyCategory));
91 
92 void ScopBuilder::buildPHIAccesses(ScopStmt *PHIStmt, PHINode *PHI,
93                                    Region *NonAffineSubRegion,
94                                    bool IsExitBlock) {
95   // PHI nodes that are in the exit block of the region, hence if IsExitBlock is
96   // true, are not modeled as ordinary PHI nodes as they are not part of the
97   // region. However, we model the operands in the predecessor blocks that are
98   // part of the region as regular scalar accesses.
99 
100   // If we can synthesize a PHI we can skip it, however only if it is in
101   // the region. If it is not it can only be in the exit block of the region.
102   // In this case we model the operands but not the PHI itself.
103   auto *Scope = LI.getLoopFor(PHI->getParent());
104   if (!IsExitBlock && canSynthesize(PHI, *scop, &SE, Scope))
105     return;
106 
107   // PHI nodes are modeled as if they had been demoted prior to the SCoP
108   // detection. Hence, the PHI is a load of a new memory location in which the
109   // incoming value was written at the end of the incoming basic block.
110   bool OnlyNonAffineSubRegionOperands = true;
111   for (unsigned u = 0; u < PHI->getNumIncomingValues(); u++) {
112     Value *Op = PHI->getIncomingValue(u);
113     BasicBlock *OpBB = PHI->getIncomingBlock(u);
114     ScopStmt *OpStmt = scop->getLastStmtFor(OpBB);
115 
116     // Do not build PHI dependences inside a non-affine subregion, but make
117     // sure that the necessary scalar values are still made available.
118     if (NonAffineSubRegion && NonAffineSubRegion->contains(OpBB)) {
119       auto *OpInst = dyn_cast<Instruction>(Op);
120       if (!OpInst || !NonAffineSubRegion->contains(OpInst))
121         ensureValueRead(Op, OpStmt);
122       continue;
123     }
124 
125     OnlyNonAffineSubRegionOperands = false;
126     ensurePHIWrite(PHI, OpStmt, OpBB, Op, IsExitBlock);
127   }
128 
129   if (!OnlyNonAffineSubRegionOperands && !IsExitBlock) {
130     addPHIReadAccess(PHIStmt, PHI);
131   }
132 }
133 
134 void ScopBuilder::buildScalarDependences(ScopStmt *UserStmt,
135                                          Instruction *Inst) {
136   assert(!isa<PHINode>(Inst));
137 
138   // Pull-in required operands.
139   for (Use &Op : Inst->operands())
140     ensureValueRead(Op.get(), UserStmt);
141 }
142 
143 void ScopBuilder::buildEscapingDependences(Instruction *Inst) {
144   // Check for uses of this instruction outside the scop. Because we do not
145   // iterate over such instructions and therefore did not "ensure" the existence
146   // of a write, we must determine such use here.
147   if (scop->isEscaping(Inst))
148     ensureValueWrite(Inst);
149 }
150 
151 /// Check that a value is a Fortran Array descriptor.
152 ///
153 /// We check if V has the following structure:
154 /// %"struct.array1_real(kind=8)" = type { i8*, i<zz>, i<zz>,
155 ///                                   [<num> x %struct.descriptor_dimension] }
156 ///
157 ///
158 /// %struct.descriptor_dimension = type { i<zz>, i<zz>, i<zz> }
159 ///
160 /// 1. V's type name starts with "struct.array"
161 /// 2. V's type has layout as shown.
162 /// 3. Final member of V's type has name "struct.descriptor_dimension",
163 /// 4. "struct.descriptor_dimension" has layout as shown.
164 /// 5. Consistent use of i<zz> where <zz> is some fixed integer number.
165 ///
166 /// We are interested in such types since this is the code that dragonegg
167 /// generates for Fortran array descriptors.
168 ///
169 /// @param V the Value to be checked.
170 ///
171 /// @returns True if V is a Fortran array descriptor, False otherwise.
172 bool isFortranArrayDescriptor(Value *V) {
173   PointerType *PTy = dyn_cast<PointerType>(V->getType());
174 
175   if (!PTy)
176     return false;
177 
178   Type *Ty = PTy->getElementType();
179   assert(Ty && "Ty expected to be initialized");
180   auto *StructArrTy = dyn_cast<StructType>(Ty);
181 
182   if (!(StructArrTy && StructArrTy->hasName()))
183     return false;
184 
185   if (!StructArrTy->getName().startswith("struct.array"))
186     return false;
187 
188   if (StructArrTy->getNumElements() != 4)
189     return false;
190 
191   const ArrayRef<Type *> ArrMemberTys = StructArrTy->elements();
192 
193   // i8* match
194   if (ArrMemberTys[0] != Type::getInt8PtrTy(V->getContext()))
195     return false;
196 
197   // Get a reference to the int type and check that all the members
198   // share the same int type
199   Type *IntTy = ArrMemberTys[1];
200   if (ArrMemberTys[2] != IntTy)
201     return false;
202 
203   // type: [<num> x %struct.descriptor_dimension]
204   ArrayType *DescriptorDimArrayTy = dyn_cast<ArrayType>(ArrMemberTys[3]);
205   if (!DescriptorDimArrayTy)
206     return false;
207 
208   // type: %struct.descriptor_dimension := type { ixx, ixx, ixx }
209   StructType *DescriptorDimTy =
210       dyn_cast<StructType>(DescriptorDimArrayTy->getElementType());
211 
212   if (!(DescriptorDimTy && DescriptorDimTy->hasName()))
213     return false;
214 
215   if (DescriptorDimTy->getName() != "struct.descriptor_dimension")
216     return false;
217 
218   if (DescriptorDimTy->getNumElements() != 3)
219     return false;
220 
221   for (auto MemberTy : DescriptorDimTy->elements()) {
222     if (MemberTy != IntTy)
223       return false;
224   }
225 
226   return true;
227 }
228 
229 Value *ScopBuilder::findFADAllocationVisible(MemAccInst Inst) {
230   // match: 4.1 & 4.2 store/load
231   if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst))
232     return nullptr;
233 
234   // match: 4
235   if (Inst.getAlignment() != 8)
236     return nullptr;
237 
238   Value *Address = Inst.getPointerOperand();
239 
240   const BitCastInst *Bitcast = nullptr;
241   // [match: 3]
242   if (auto *Slot = dyn_cast<GetElementPtrInst>(Address)) {
243     Value *TypedMem = Slot->getPointerOperand();
244     // match: 2
245     Bitcast = dyn_cast<BitCastInst>(TypedMem);
246   } else {
247     // match: 2
248     Bitcast = dyn_cast<BitCastInst>(Address);
249   }
250 
251   if (!Bitcast)
252     return nullptr;
253 
254   auto *MallocMem = Bitcast->getOperand(0);
255 
256   // match: 1
257   auto *MallocCall = dyn_cast<CallInst>(MallocMem);
258   if (!MallocCall)
259     return nullptr;
260 
261   Function *MallocFn = MallocCall->getCalledFunction();
262   if (!(MallocFn && MallocFn->hasName() && MallocFn->getName() == "malloc"))
263     return nullptr;
264 
265   // Find all uses the malloc'd memory.
266   // We are looking for a "store" into a struct with the type being the Fortran
267   // descriptor type
268   for (auto user : MallocMem->users()) {
269     /// match: 5
270     auto *MallocStore = dyn_cast<StoreInst>(user);
271     if (!MallocStore)
272       continue;
273 
274     auto *DescriptorGEP =
275         dyn_cast<GEPOperator>(MallocStore->getPointerOperand());
276     if (!DescriptorGEP)
277       continue;
278 
279     // match: 5
280     auto DescriptorType =
281         dyn_cast<StructType>(DescriptorGEP->getSourceElementType());
282     if (!(DescriptorType && DescriptorType->hasName()))
283       continue;
284 
285     Value *Descriptor = dyn_cast<Value>(DescriptorGEP->getPointerOperand());
286 
287     if (!Descriptor)
288       continue;
289 
290     if (!isFortranArrayDescriptor(Descriptor))
291       continue;
292 
293     return Descriptor;
294   }
295 
296   return nullptr;
297 }
298 
299 Value *ScopBuilder::findFADAllocationInvisible(MemAccInst Inst) {
300   // match: 3
301   if (!isa<LoadInst>(Inst) && !isa<StoreInst>(Inst))
302     return nullptr;
303 
304   Value *Slot = Inst.getPointerOperand();
305 
306   LoadInst *MemLoad = nullptr;
307   // [match: 2]
308   if (auto *SlotGEP = dyn_cast<GetElementPtrInst>(Slot)) {
309     // match: 1
310     MemLoad = dyn_cast<LoadInst>(SlotGEP->getPointerOperand());
311   } else {
312     // match: 1
313     MemLoad = dyn_cast<LoadInst>(Slot);
314   }
315 
316   if (!MemLoad)
317     return nullptr;
318 
319   auto *BitcastOperator =
320       dyn_cast<BitCastOperator>(MemLoad->getPointerOperand());
321   if (!BitcastOperator)
322     return nullptr;
323 
324   Value *Descriptor = dyn_cast<Value>(BitcastOperator->getOperand(0));
325   if (!Descriptor)
326     return nullptr;
327 
328   if (!isFortranArrayDescriptor(Descriptor))
329     return nullptr;
330 
331   return Descriptor;
332 }
333 
334 bool ScopBuilder::buildAccessMultiDimFixed(MemAccInst Inst, ScopStmt *Stmt) {
335   Value *Val = Inst.getValueOperand();
336   Type *ElementType = Val->getType();
337   Value *Address = Inst.getPointerOperand();
338   const SCEV *AccessFunction =
339       SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent()));
340   const SCEVUnknown *BasePointer =
341       dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
342   enum MemoryAccess::AccessType AccType =
343       isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
344 
345   if (auto *BitCast = dyn_cast<BitCastInst>(Address)) {
346     auto *Src = BitCast->getOperand(0);
347     auto *SrcTy = Src->getType();
348     auto *DstTy = BitCast->getType();
349     // Do not try to delinearize non-sized (opaque) pointers.
350     if ((SrcTy->isPointerTy() && !SrcTy->getPointerElementType()->isSized()) ||
351         (DstTy->isPointerTy() && !DstTy->getPointerElementType()->isSized())) {
352       return false;
353     }
354     if (SrcTy->isPointerTy() && DstTy->isPointerTy() &&
355         DL.getTypeAllocSize(SrcTy->getPointerElementType()) ==
356             DL.getTypeAllocSize(DstTy->getPointerElementType()))
357       Address = Src;
358   }
359 
360   auto *GEP = dyn_cast<GetElementPtrInst>(Address);
361   if (!GEP)
362     return false;
363 
364   std::vector<const SCEV *> Subscripts;
365   std::vector<int> Sizes;
366   std::tie(Subscripts, Sizes) = getIndexExpressionsFromGEP(GEP, SE);
367   auto *BasePtr = GEP->getOperand(0);
368 
369   if (auto *BasePtrCast = dyn_cast<BitCastInst>(BasePtr))
370     BasePtr = BasePtrCast->getOperand(0);
371 
372   // Check for identical base pointers to ensure that we do not miss index
373   // offsets that have been added before this GEP is applied.
374   if (BasePtr != BasePointer->getValue())
375     return false;
376 
377   std::vector<const SCEV *> SizesSCEV;
378 
379   const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
380 
381   Loop *SurroundingLoop = Stmt->getSurroundingLoop();
382   for (auto *Subscript : Subscripts) {
383     InvariantLoadsSetTy AccessILS;
384     if (!isAffineExpr(&scop->getRegion(), SurroundingLoop, Subscript, SE,
385                       &AccessILS))
386       return false;
387 
388     for (LoadInst *LInst : AccessILS)
389       if (!ScopRIL.count(LInst))
390         return false;
391   }
392 
393   if (Sizes.empty())
394     return false;
395 
396   SizesSCEV.push_back(nullptr);
397 
398   for (auto V : Sizes)
399     SizesSCEV.push_back(SE.getSCEV(
400         ConstantInt::get(IntegerType::getInt64Ty(BasePtr->getContext()), V)));
401 
402   addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType,
403                  true, Subscripts, SizesSCEV, Val);
404   return true;
405 }
406 
407 bool ScopBuilder::buildAccessMultiDimParam(MemAccInst Inst, ScopStmt *Stmt) {
408   if (!PollyDelinearize)
409     return false;
410 
411   Value *Address = Inst.getPointerOperand();
412   Value *Val = Inst.getValueOperand();
413   Type *ElementType = Val->getType();
414   unsigned ElementSize = DL.getTypeAllocSize(ElementType);
415   enum MemoryAccess::AccessType AccType =
416       isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
417 
418   const SCEV *AccessFunction =
419       SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent()));
420   const SCEVUnknown *BasePointer =
421       dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
422 
423   assert(BasePointer && "Could not find base pointer");
424 
425   auto &InsnToMemAcc = scop->getInsnToMemAccMap();
426   auto AccItr = InsnToMemAcc.find(Inst);
427   if (AccItr == InsnToMemAcc.end())
428     return false;
429 
430   std::vector<const SCEV *> Sizes = {nullptr};
431 
432   Sizes.insert(Sizes.end(), AccItr->second.Shape->DelinearizedSizes.begin(),
433                AccItr->second.Shape->DelinearizedSizes.end());
434 
435   // In case only the element size is contained in the 'Sizes' array, the
436   // access does not access a real multi-dimensional array. Hence, we allow
437   // the normal single-dimensional access construction to handle this.
438   if (Sizes.size() == 1)
439     return false;
440 
441   // Remove the element size. This information is already provided by the
442   // ElementSize parameter. In case the element size of this access and the
443   // element size used for delinearization differs the delinearization is
444   // incorrect. Hence, we invalidate the scop.
445   //
446   // TODO: Handle delinearization with differing element sizes.
447   auto DelinearizedSize =
448       cast<SCEVConstant>(Sizes.back())->getAPInt().getSExtValue();
449   Sizes.pop_back();
450   if (ElementSize != DelinearizedSize)
451     scop->invalidate(DELINEARIZATION, Inst->getDebugLoc(), Inst->getParent());
452 
453   addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType,
454                  true, AccItr->second.DelinearizedSubscripts, Sizes, Val);
455   return true;
456 }
457 
458 bool ScopBuilder::buildAccessMemIntrinsic(MemAccInst Inst, ScopStmt *Stmt) {
459   auto *MemIntr = dyn_cast_or_null<MemIntrinsic>(Inst);
460 
461   if (MemIntr == nullptr)
462     return false;
463 
464   auto *L = LI.getLoopFor(Inst->getParent());
465   auto *LengthVal = SE.getSCEVAtScope(MemIntr->getLength(), L);
466   assert(LengthVal);
467 
468   // Check if the length val is actually affine or if we overapproximate it
469   InvariantLoadsSetTy AccessILS;
470   const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
471 
472   Loop *SurroundingLoop = Stmt->getSurroundingLoop();
473   bool LengthIsAffine = isAffineExpr(&scop->getRegion(), SurroundingLoop,
474                                      LengthVal, SE, &AccessILS);
475   for (LoadInst *LInst : AccessILS)
476     if (!ScopRIL.count(LInst))
477       LengthIsAffine = false;
478   if (!LengthIsAffine)
479     LengthVal = nullptr;
480 
481   auto *DestPtrVal = MemIntr->getDest();
482   assert(DestPtrVal);
483 
484   auto *DestAccFunc = SE.getSCEVAtScope(DestPtrVal, L);
485   assert(DestAccFunc);
486   // Ignore accesses to "NULL".
487   // TODO: We could use this to optimize the region further, e.g., intersect
488   //       the context with
489   //          isl_set_complement(isl_set_params(getDomain()))
490   //       as we know it would be undefined to execute this instruction anyway.
491   if (DestAccFunc->isZero())
492     return true;
493 
494   auto *DestPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(DestAccFunc));
495   assert(DestPtrSCEV);
496   DestAccFunc = SE.getMinusSCEV(DestAccFunc, DestPtrSCEV);
497   addArrayAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, DestPtrSCEV->getValue(),
498                  IntegerType::getInt8Ty(DestPtrVal->getContext()),
499                  LengthIsAffine, {DestAccFunc, LengthVal}, {nullptr},
500                  Inst.getValueOperand());
501 
502   auto *MemTrans = dyn_cast<MemTransferInst>(MemIntr);
503   if (!MemTrans)
504     return true;
505 
506   auto *SrcPtrVal = MemTrans->getSource();
507   assert(SrcPtrVal);
508 
509   auto *SrcAccFunc = SE.getSCEVAtScope(SrcPtrVal, L);
510   assert(SrcAccFunc);
511   // Ignore accesses to "NULL".
512   // TODO: See above TODO
513   if (SrcAccFunc->isZero())
514     return true;
515 
516   auto *SrcPtrSCEV = dyn_cast<SCEVUnknown>(SE.getPointerBase(SrcAccFunc));
517   assert(SrcPtrSCEV);
518   SrcAccFunc = SE.getMinusSCEV(SrcAccFunc, SrcPtrSCEV);
519   addArrayAccess(Stmt, Inst, MemoryAccess::READ, SrcPtrSCEV->getValue(),
520                  IntegerType::getInt8Ty(SrcPtrVal->getContext()),
521                  LengthIsAffine, {SrcAccFunc, LengthVal}, {nullptr},
522                  Inst.getValueOperand());
523 
524   return true;
525 }
526 
527 bool ScopBuilder::buildAccessCallInst(MemAccInst Inst, ScopStmt *Stmt) {
528   auto *CI = dyn_cast_or_null<CallInst>(Inst);
529 
530   if (CI == nullptr)
531     return false;
532 
533   if (CI->doesNotAccessMemory() || isIgnoredIntrinsic(CI))
534     return true;
535 
536   bool ReadOnly = false;
537   auto *AF = SE.getConstant(IntegerType::getInt64Ty(CI->getContext()), 0);
538   auto *CalledFunction = CI->getCalledFunction();
539   switch (AA.getModRefBehavior(CalledFunction)) {
540   case FMRB_UnknownModRefBehavior:
541     llvm_unreachable("Unknown mod ref behaviour cannot be represented.");
542   case FMRB_DoesNotAccessMemory:
543     return true;
544   case FMRB_DoesNotReadMemory:
545   case FMRB_OnlyAccessesInaccessibleMem:
546   case FMRB_OnlyAccessesInaccessibleOrArgMem:
547     return false;
548   case FMRB_OnlyReadsMemory:
549     GlobalReads.emplace_back(Stmt, CI);
550     return true;
551   case FMRB_OnlyReadsArgumentPointees:
552     ReadOnly = true;
553   // Fall through
554   case FMRB_OnlyAccessesArgumentPointees: {
555     auto AccType = ReadOnly ? MemoryAccess::READ : MemoryAccess::MAY_WRITE;
556     Loop *L = LI.getLoopFor(Inst->getParent());
557     for (const auto &Arg : CI->arg_operands()) {
558       if (!Arg->getType()->isPointerTy())
559         continue;
560 
561       auto *ArgSCEV = SE.getSCEVAtScope(Arg, L);
562       if (ArgSCEV->isZero())
563         continue;
564 
565       auto *ArgBasePtr = cast<SCEVUnknown>(SE.getPointerBase(ArgSCEV));
566       addArrayAccess(Stmt, Inst, AccType, ArgBasePtr->getValue(),
567                      ArgBasePtr->getType(), false, {AF}, {nullptr}, CI);
568     }
569     return true;
570   }
571   }
572 
573   return true;
574 }
575 
576 void ScopBuilder::buildAccessSingleDim(MemAccInst Inst, ScopStmt *Stmt) {
577   Value *Address = Inst.getPointerOperand();
578   Value *Val = Inst.getValueOperand();
579   Type *ElementType = Val->getType();
580   enum MemoryAccess::AccessType AccType =
581       isa<LoadInst>(Inst) ? MemoryAccess::READ : MemoryAccess::MUST_WRITE;
582 
583   const SCEV *AccessFunction =
584       SE.getSCEVAtScope(Address, LI.getLoopFor(Inst->getParent()));
585   const SCEVUnknown *BasePointer =
586       dyn_cast<SCEVUnknown>(SE.getPointerBase(AccessFunction));
587 
588   assert(BasePointer && "Could not find base pointer");
589   AccessFunction = SE.getMinusSCEV(AccessFunction, BasePointer);
590 
591   // Check if the access depends on a loop contained in a non-affine subregion.
592   bool isVariantInNonAffineLoop = false;
593   SetVector<const Loop *> Loops;
594   findLoops(AccessFunction, Loops);
595   for (const Loop *L : Loops)
596     if (Stmt->contains(L)) {
597       isVariantInNonAffineLoop = true;
598       break;
599     }
600 
601   InvariantLoadsSetTy AccessILS;
602 
603   Loop *SurroundingLoop = Stmt->getSurroundingLoop();
604   bool IsAffine = !isVariantInNonAffineLoop &&
605                   isAffineExpr(&scop->getRegion(), SurroundingLoop,
606                                AccessFunction, SE, &AccessILS);
607 
608   const InvariantLoadsSetTy &ScopRIL = scop->getRequiredInvariantLoads();
609   for (LoadInst *LInst : AccessILS)
610     if (!ScopRIL.count(LInst))
611       IsAffine = false;
612 
613   if (!IsAffine && AccType == MemoryAccess::MUST_WRITE)
614     AccType = MemoryAccess::MAY_WRITE;
615 
616   addArrayAccess(Stmt, Inst, AccType, BasePointer->getValue(), ElementType,
617                  IsAffine, {AccessFunction}, {nullptr}, Val);
618 }
619 
620 void ScopBuilder::buildMemoryAccess(MemAccInst Inst, ScopStmt *Stmt) {
621   if (buildAccessMemIntrinsic(Inst, Stmt))
622     return;
623 
624   if (buildAccessCallInst(Inst, Stmt))
625     return;
626 
627   if (buildAccessMultiDimFixed(Inst, Stmt))
628     return;
629 
630   if (buildAccessMultiDimParam(Inst, Stmt))
631     return;
632 
633   buildAccessSingleDim(Inst, Stmt);
634 }
635 
636 void ScopBuilder::buildAccessFunctions() {
637   for (auto &Stmt : *scop) {
638     if (Stmt.isBlockStmt()) {
639       buildAccessFunctions(&Stmt, *Stmt.getBasicBlock());
640       continue;
641     }
642 
643     Region *R = Stmt.getRegion();
644     for (BasicBlock *BB : R->blocks())
645       buildAccessFunctions(&Stmt, *BB, R);
646   }
647 }
648 
649 void ScopBuilder::buildStmts(Region &SR) {
650   if (scop->isNonAffineSubRegion(&SR)) {
651     Loop *SurroundingLoop =
652         getFirstNonBoxedLoopFor(SR.getEntry(), LI, scop->getBoxedLoops());
653     scop->addScopStmt(&SR, SurroundingLoop);
654     return;
655   }
656 
657   for (auto I = SR.element_begin(), E = SR.element_end(); I != E; ++I)
658     if (I->isSubRegion())
659       buildStmts(*I->getNodeAs<Region>());
660     else {
661       int Count = 0;
662       std::vector<Instruction *> Instructions;
663       for (Instruction &Inst : *I->getNodeAs<BasicBlock>()) {
664         Loop *L = LI.getLoopFor(Inst.getParent());
665         if (!isa<TerminatorInst>(&Inst) && !isIgnoredIntrinsic(&Inst) &&
666             !canSynthesize(&Inst, *scop, &SE, L))
667           Instructions.push_back(&Inst);
668         if (Inst.getMetadata("polly_split_after")) {
669           Loop *SurroundingLoop = LI.getLoopFor(I->getNodeAs<BasicBlock>());
670           scop->addScopStmt(I->getNodeAs<BasicBlock>(), SurroundingLoop,
671                             Instructions, Count);
672           Count++;
673           Instructions.clear();
674         }
675       }
676       Loop *SurroundingLoop = LI.getLoopFor(I->getNodeAs<BasicBlock>());
677       scop->addScopStmt(I->getNodeAs<BasicBlock>(), SurroundingLoop,
678                         Instructions, Count);
679     }
680 }
681 
682 void ScopBuilder::buildAccessFunctions(ScopStmt *Stmt, BasicBlock &BB,
683                                        Region *NonAffineSubRegion,
684                                        bool IsExitBlock) {
685   assert(
686       !Stmt == IsExitBlock &&
687       "The exit BB is the only one that cannot be represented by a statement");
688   assert(IsExitBlock || Stmt->represents(&BB));
689 
690   // We do not build access functions for error blocks, as they may contain
691   // instructions we can not model.
692   if (isErrorBlock(BB, scop->getRegion(), LI, DT) && !IsExitBlock)
693     return;
694 
695   int Count = 0;
696   bool Split = false;
697   for (Instruction &Inst : BB) {
698     if (Split) {
699       Split = false;
700       Count++;
701     }
702     if (Inst.getMetadata("polly_split_after"))
703       Split = true;
704 
705     if (Stmt && Stmt->isBlockStmt() && Stmt != scop->getStmtListFor(&BB)[Count])
706       continue;
707 
708     PHINode *PHI = dyn_cast<PHINode>(&Inst);
709     if (PHI)
710       buildPHIAccesses(Stmt, PHI, NonAffineSubRegion, IsExitBlock);
711 
712     // For the exit block we stop modeling after the last PHI node.
713     if (!PHI && IsExitBlock)
714       break;
715 
716     if (auto MemInst = MemAccInst::dyn_cast(Inst)) {
717       assert(Stmt && "Cannot build access function in non-existing statement");
718       buildMemoryAccess(MemInst, Stmt);
719     }
720 
721     if (isIgnoredIntrinsic(&Inst))
722       continue;
723 
724     // PHI nodes have already been modeled above and TerminatorInsts that are
725     // not part of a non-affine subregion are fully modeled and regenerated
726     // from the polyhedral domains. Hence, they do not need to be modeled as
727     // explicit data dependences.
728     if (!PHI && (!isa<TerminatorInst>(&Inst) || NonAffineSubRegion))
729       buildScalarDependences(Stmt, &Inst);
730 
731     if (!IsExitBlock)
732       buildEscapingDependences(&Inst);
733   }
734 }
735 
736 MemoryAccess *ScopBuilder::addMemoryAccess(
737     ScopStmt *Stmt, Instruction *Inst, MemoryAccess::AccessType AccType,
738     Value *BaseAddress, Type *ElementType, bool Affine, Value *AccessValue,
739     ArrayRef<const SCEV *> Subscripts, ArrayRef<const SCEV *> Sizes,
740     MemoryKind Kind) {
741   bool isKnownMustAccess = false;
742 
743   // Accesses in single-basic block statements are always executed.
744   if (Stmt->isBlockStmt())
745     isKnownMustAccess = true;
746 
747   if (Stmt->isRegionStmt()) {
748     // Accesses that dominate the exit block of a non-affine region are always
749     // executed. In non-affine regions there may exist MemoryKind::Values that
750     // do not dominate the exit. MemoryKind::Values will always dominate the
751     // exit and MemoryKind::PHIs only if there is at most one PHI_WRITE in the
752     // non-affine region.
753     if (Inst && DT.dominates(Inst->getParent(), Stmt->getRegion()->getExit()))
754       isKnownMustAccess = true;
755   }
756 
757   // Non-affine PHI writes do not "happen" at a particular instruction, but
758   // after exiting the statement. Therefore they are guaranteed to execute and
759   // overwrite the old value.
760   if (Kind == MemoryKind::PHI || Kind == MemoryKind::ExitPHI)
761     isKnownMustAccess = true;
762 
763   if (!isKnownMustAccess && AccType == MemoryAccess::MUST_WRITE)
764     AccType = MemoryAccess::MAY_WRITE;
765 
766   auto *Access = new MemoryAccess(Stmt, Inst, AccType, BaseAddress, ElementType,
767                                   Affine, Subscripts, Sizes, AccessValue, Kind);
768 
769   scop->addAccessFunction(Access);
770   Stmt->addAccess(Access);
771   return Access;
772 }
773 
774 void ScopBuilder::addArrayAccess(ScopStmt *Stmt, MemAccInst MemAccInst,
775                                  MemoryAccess::AccessType AccType,
776                                  Value *BaseAddress, Type *ElementType,
777                                  bool IsAffine,
778                                  ArrayRef<const SCEV *> Subscripts,
779                                  ArrayRef<const SCEV *> Sizes,
780                                  Value *AccessValue) {
781   ArrayBasePointers.insert(BaseAddress);
782   auto *MemAccess = addMemoryAccess(Stmt, MemAccInst, AccType, BaseAddress,
783                                     ElementType, IsAffine, AccessValue,
784                                     Subscripts, Sizes, MemoryKind::Array);
785 
786   if (!DetectFortranArrays)
787     return;
788 
789   if (Value *FAD = findFADAllocationInvisible(MemAccInst))
790     MemAccess->setFortranArrayDescriptor(FAD);
791   else if (Value *FAD = findFADAllocationVisible(MemAccInst))
792     MemAccess->setFortranArrayDescriptor(FAD);
793 }
794 
795 void ScopBuilder::ensureValueWrite(Instruction *Inst) {
796   // Find the statement that defines the value of Inst. That statement has to
797   // write the value to make it available to those statements that read it.
798   ScopStmt *Stmt = scop->getStmtFor(Inst);
799 
800   // It is possible that the value is synthesizable within a loop (such that it
801   // is not part of any statement), but not after the loop (where you need the
802   // number of loop round-trips to synthesize it). In LCSSA-form a PHI node will
803   // avoid this. In case the IR has no such PHI, use the last statement (where
804   // the value is synthesizable) to write the value.
805   if (!Stmt)
806     Stmt = scop->getLastStmtFor(Inst->getParent());
807 
808   // Inst not defined within this SCoP.
809   if (!Stmt)
810     return;
811 
812   // Do not process further if the instruction is already written.
813   if (Stmt->lookupValueWriteOf(Inst))
814     return;
815 
816   addMemoryAccess(Stmt, Inst, MemoryAccess::MUST_WRITE, Inst, Inst->getType(),
817                   true, Inst, ArrayRef<const SCEV *>(),
818                   ArrayRef<const SCEV *>(), MemoryKind::Value);
819 }
820 
821 void ScopBuilder::ensureValueRead(Value *V, ScopStmt *UserStmt) {
822   // TODO: Make ScopStmt::ensureValueRead(Value*) offer the same functionality
823   // to be able to replace this one. Currently, there is a split responsibility.
824   // In a first step, the MemoryAccess is created, but without the
825   // AccessRelation. In the second step by ScopStmt::buildAccessRelations(), the
826   // AccessRelation is created. At least for scalar accesses, there is no new
827   // information available at ScopStmt::buildAccessRelations(), so we could
828   // create the AccessRelation right away. This is what
829   // ScopStmt::ensureValueRead(Value*) does.
830 
831   auto *Scope = UserStmt->getSurroundingLoop();
832   auto VUse = VirtualUse::create(scop.get(), UserStmt, Scope, V, false);
833   switch (VUse.getKind()) {
834   case VirtualUse::Constant:
835   case VirtualUse::Block:
836   case VirtualUse::Synthesizable:
837   case VirtualUse::Hoisted:
838   case VirtualUse::Intra:
839     // Uses of these kinds do not need a MemoryAccess.
840     break;
841 
842   case VirtualUse::ReadOnly:
843     // Add MemoryAccess for invariant values only if requested.
844     if (!ModelReadOnlyScalars)
845       break;
846 
847     LLVM_FALLTHROUGH;
848   case VirtualUse::Inter:
849 
850     // Do not create another MemoryAccess for reloading the value if one already
851     // exists.
852     if (UserStmt->lookupValueReadOf(V))
853       break;
854 
855     addMemoryAccess(UserStmt, nullptr, MemoryAccess::READ, V, V->getType(),
856                     true, V, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
857                     MemoryKind::Value);
858 
859     // Inter-statement uses need to write the value in their defining statement.
860     if (VUse.isInter())
861       ensureValueWrite(cast<Instruction>(V));
862     break;
863   }
864 }
865 
866 void ScopBuilder::ensurePHIWrite(PHINode *PHI, ScopStmt *IncomingStmt,
867                                  BasicBlock *IncomingBlock,
868                                  Value *IncomingValue, bool IsExitBlock) {
869   // As the incoming block might turn out to be an error statement ensure we
870   // will create an exit PHI SAI object. It is needed during code generation
871   // and would be created later anyway.
872   if (IsExitBlock)
873     scop->getOrCreateScopArrayInfo(PHI, PHI->getType(), {},
874                                    MemoryKind::ExitPHI);
875 
876   // This is possible if PHI is in the SCoP's entry block. The incoming blocks
877   // from outside the SCoP's region have no statement representation.
878   if (!IncomingStmt)
879     return;
880 
881   // Take care for the incoming value being available in the incoming block.
882   // This must be done before the check for multiple PHI writes because multiple
883   // exiting edges from subregion each can be the effective written value of the
884   // subregion. As such, all of them must be made available in the subregion
885   // statement.
886   ensureValueRead(IncomingValue, IncomingStmt);
887 
888   // Do not add more than one MemoryAccess per PHINode and ScopStmt.
889   if (MemoryAccess *Acc = IncomingStmt->lookupPHIWriteOf(PHI)) {
890     assert(Acc->getAccessInstruction() == PHI);
891     Acc->addIncoming(IncomingBlock, IncomingValue);
892     return;
893   }
894 
895   MemoryAccess *Acc = addMemoryAccess(
896       IncomingStmt, PHI, MemoryAccess::MUST_WRITE, PHI, PHI->getType(), true,
897       PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
898       IsExitBlock ? MemoryKind::ExitPHI : MemoryKind::PHI);
899   assert(Acc);
900   Acc->addIncoming(IncomingBlock, IncomingValue);
901 }
902 
903 void ScopBuilder::addPHIReadAccess(ScopStmt *PHIStmt, PHINode *PHI) {
904   addMemoryAccess(PHIStmt, PHI, MemoryAccess::READ, PHI, PHI->getType(), true,
905                   PHI, ArrayRef<const SCEV *>(), ArrayRef<const SCEV *>(),
906                   MemoryKind::PHI);
907 }
908 
909 #ifndef NDEBUG
910 static void verifyUse(Scop *S, Use &Op, LoopInfo &LI) {
911   auto PhysUse = VirtualUse::create(S, Op, &LI, false);
912   auto VirtUse = VirtualUse::create(S, Op, &LI, true);
913   assert(PhysUse.getKind() == VirtUse.getKind());
914 }
915 
916 /// Check the consistency of every statement's MemoryAccesses.
917 ///
918 /// The check is carried out by expecting the "physical" kind of use (derived
919 /// from the BasicBlocks instructions resides in) to be same as the "virtual"
920 /// kind of use (derived from a statement's MemoryAccess).
921 ///
922 /// The "physical" uses are taken by ensureValueRead to determine whether to
923 /// create MemoryAccesses. When done, the kind of scalar access should be the
924 /// same no matter which way it was derived.
925 ///
926 /// The MemoryAccesses might be changed by later SCoP-modifying passes and hence
927 /// can intentionally influence on the kind of uses (not corresponding to the
928 /// "physical" anymore, hence called "virtual"). The CodeGenerator therefore has
929 /// to pick up the virtual uses. But here in the code generator, this has not
930 /// happened yet, such that virtual and physical uses are equivalent.
931 static void verifyUses(Scop *S, LoopInfo &LI, DominatorTree &DT) {
932   for (auto *BB : S->getRegion().blocks()) {
933     for (auto &Inst : *BB) {
934       auto *Stmt = S->getStmtFor(&Inst);
935       if (!Stmt)
936         continue;
937 
938       if (isIgnoredIntrinsic(&Inst))
939         continue;
940 
941       // Branch conditions are encoded in the statement domains.
942       if (isa<TerminatorInst>(&Inst) && Stmt->isBlockStmt())
943         continue;
944 
945       // Verify all uses.
946       for (auto &Op : Inst.operands())
947         verifyUse(S, Op, LI);
948 
949       // Stores do not produce values used by other statements.
950       if (isa<StoreInst>(Inst))
951         continue;
952 
953       // For every value defined in the block, also check that a use of that
954       // value in the same statement would not be an inter-statement use. It can
955       // still be synthesizable or load-hoisted, but these kind of instructions
956       // are not directly copied in code-generation.
957       auto VirtDef =
958           VirtualUse::create(S, Stmt, Stmt->getSurroundingLoop(), &Inst, true);
959       assert(VirtDef.getKind() == VirtualUse::Synthesizable ||
960              VirtDef.getKind() == VirtualUse::Intra ||
961              VirtDef.getKind() == VirtualUse::Hoisted);
962     }
963   }
964 
965   if (S->hasSingleExitEdge())
966     return;
967 
968   // PHINodes in the SCoP region's exit block are also uses to be checked.
969   if (!S->getRegion().isTopLevelRegion()) {
970     for (auto &Inst : *S->getRegion().getExit()) {
971       if (!isa<PHINode>(Inst))
972         break;
973 
974       for (auto &Op : Inst.operands())
975         verifyUse(S, Op, LI);
976     }
977   }
978 }
979 #endif
980 
981 /// Return the block that is the representing block for @p RN.
982 static inline BasicBlock *getRegionNodeBasicBlock(RegionNode *RN) {
983   return RN->isSubRegion() ? RN->getNodeAs<Region>()->getEntry()
984                            : RN->getNodeAs<BasicBlock>();
985 }
986 
987 void ScopBuilder::buildScop(Region &R, AssumptionCache &AC,
988                             OptimizationRemarkEmitter &ORE) {
989   scop.reset(new Scop(R, SE, LI, *SD.getDetectionContext(&R), ORE));
990 
991   buildStmts(R);
992   buildAccessFunctions();
993 
994   // In case the region does not have an exiting block we will later (during
995   // code generation) split the exit block. This will move potential PHI nodes
996   // from the current exit block into the new region exiting block. Hence, PHI
997   // nodes that are at this point not part of the region will be.
998   // To handle these PHI nodes later we will now model their operands as scalar
999   // accesses. Note that we do not model anything in the exit block if we have
1000   // an exiting block in the region, as there will not be any splitting later.
1001   if (!R.isTopLevelRegion() && !scop->hasSingleExitEdge())
1002     buildAccessFunctions(nullptr, *R.getExit(), nullptr,
1003                          /* IsExitBlock */ true);
1004 
1005   // Create memory accesses for global reads since all arrays are now known.
1006   auto *AF = SE.getConstant(IntegerType::getInt64Ty(SE.getContext()), 0);
1007   for (auto GlobalReadPair : GlobalReads) {
1008     ScopStmt *GlobalReadStmt = GlobalReadPair.first;
1009     Instruction *GlobalRead = GlobalReadPair.second;
1010     for (auto *BP : ArrayBasePointers)
1011       addArrayAccess(GlobalReadStmt, MemAccInst(GlobalRead), MemoryAccess::READ,
1012                      BP, BP->getType(), false, {AF}, {nullptr}, GlobalRead);
1013   }
1014 
1015   scop->buildInvariantEquivalenceClasses();
1016 
1017   /// A map from basic blocks to their invalid domains.
1018   DenseMap<BasicBlock *, isl::set> InvalidDomainMap;
1019 
1020   if (!scop->buildDomains(&R, DT, LI, InvalidDomainMap))
1021     return;
1022 
1023   scop->addUserAssumptions(AC, DT, LI, InvalidDomainMap);
1024 
1025   // Initialize the invalid domain.
1026   for (ScopStmt &Stmt : scop->Stmts)
1027     if (Stmt.isBlockStmt())
1028       Stmt.setInvalidDomain(InvalidDomainMap[Stmt.getEntryBlock()]);
1029     else
1030       Stmt.setInvalidDomain(InvalidDomainMap[getRegionNodeBasicBlock(
1031           Stmt.getRegion()->getNode())]);
1032 
1033   // Remove empty statements.
1034   // Exit early in case there are no executable statements left in this scop.
1035   scop->removeStmtNotInDomainMap();
1036   scop->simplifySCoP(false);
1037   if (scop->isEmpty())
1038     return;
1039 
1040   // The ScopStmts now have enough information to initialize themselves.
1041   for (ScopStmt &Stmt : *scop)
1042     Stmt.init(LI);
1043 
1044   // Check early for a feasible runtime context.
1045   if (!scop->hasFeasibleRuntimeContext())
1046     return;
1047 
1048   // Check early for profitability. Afterwards it cannot change anymore,
1049   // only the runtime context could become infeasible.
1050   if (!scop->isProfitable(UnprofitableScalarAccs)) {
1051     scop->invalidate(PROFITABLE, DebugLoc());
1052     return;
1053   }
1054 
1055   scop->buildSchedule(LI);
1056 
1057   scop->finalizeAccesses();
1058 
1059   scop->realignParams();
1060   scop->addUserContext();
1061 
1062   // After the context was fully constructed, thus all our knowledge about
1063   // the parameters is in there, we add all recorded assumptions to the
1064   // assumed/invalid context.
1065   scop->addRecordedAssumptions();
1066 
1067   scop->simplifyContexts();
1068   if (!scop->buildAliasChecks(AA))
1069     return;
1070 
1071   scop->hoistInvariantLoads();
1072   scop->canonicalizeDynamicBasePtrs();
1073   scop->verifyInvariantLoads();
1074   scop->simplifySCoP(true);
1075 
1076   // Check late for a feasible runtime context because profitability did not
1077   // change.
1078   if (!scop->hasFeasibleRuntimeContext())
1079     return;
1080 
1081 #ifndef NDEBUG
1082   verifyUses(scop.get(), LI, DT);
1083 #endif
1084 }
1085 
1086 ScopBuilder::ScopBuilder(Region *R, AssumptionCache &AC, AliasAnalysis &AA,
1087                          const DataLayout &DL, DominatorTree &DT, LoopInfo &LI,
1088                          ScopDetection &SD, ScalarEvolution &SE,
1089                          OptimizationRemarkEmitter &ORE)
1090     : AA(AA), DL(DL), DT(DT), LI(LI), SD(SD), SE(SE) {
1091   DebugLoc Beg, End;
1092   auto P = getBBPairForRegion(R);
1093   getDebugLocations(P, Beg, End);
1094 
1095   std::string Msg = "SCoP begins here.";
1096   ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEntry", Beg, P.first)
1097            << Msg);
1098 
1099   buildScop(*R, AC, ORE);
1100 
1101   DEBUG(dbgs() << *scop);
1102 
1103   if (!scop->hasFeasibleRuntimeContext()) {
1104     InfeasibleScops++;
1105     Msg = "SCoP ends here but was dismissed.";
1106     scop.reset();
1107   } else {
1108     Msg = "SCoP ends here.";
1109     ++ScopFound;
1110     if (scop->getMaxLoopDepth() > 0)
1111       ++RichScopFound;
1112   }
1113 
1114   if (R->isTopLevelRegion())
1115     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.first)
1116              << Msg);
1117   else
1118     ORE.emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ScopEnd", End, P.second)
1119              << Msg);
1120 }
1121