1 //=== ScopDetectionDiagnostic.cpp - Error diagnostics --------- -*- C++ -*-===//
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 // Small set of diagnostic helper classes to encapsulate any errors occurred
11 // during the detection of Scops.
12 //
13 // The ScopDetection defines a set of error classes (via Statistic variables)
14 // that groups a number of individual errors into a group, e.g. non-affinity
15 // related errors.
16 // On error we generate an object that carries enough additional information
17 // to diagnose the error and generate a helpful error message.
18 //
19 //===----------------------------------------------------------------------===//
20 #include "polly/ScopDetectionDiagnostic.h"
21 #include "polly/Support/ScopLocation.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasSetTracker.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Analysis/RegionInfo.h"
27 #include "llvm/IR/BasicBlock.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/DebugLoc.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Value.h"
33 
34 #define DEBUG_TYPE "polly-detect"
35 #include "llvm/Support/Debug.h"
36 
37 #include <string>
38 
39 using namespace llvm;
40 
41 #define BADSCOP_STAT(NAME, DESC)                                               \
42   STATISTIC(Bad##NAME##ForScop, "Number of bad regions for Scop: " DESC)
43 
44 BADSCOP_STAT(CFG, "CFG too complex");
45 BADSCOP_STAT(LoopBound, "Loop bounds can not be computed");
46 BADSCOP_STAT(FuncCall, "Function call with side effects appeared");
47 BADSCOP_STAT(AffFunc, "Expression not affine");
48 BADSCOP_STAT(Alias, "Found base address alias");
49 BADSCOP_STAT(Other, "Others");
50 
51 namespace polly {
52 /// Small string conversion via raw_string_stream.
53 template <typename T> std::string operator+(Twine LHS, const T &RHS) {
54   std::string Buf;
55   raw_string_ostream fmt(Buf);
56   fmt << RHS;
57   fmt.flush();
58 
59   return LHS.concat(Buf).str();
60 }
61 } // namespace polly
62 
63 namespace llvm {
64 // Lexicographic order on (line, col) of our debug locations.
65 static bool operator<(const llvm::DebugLoc &LHS, const llvm::DebugLoc &RHS) {
66   return LHS.getLine() < RHS.getLine() ||
67          (LHS.getLine() == RHS.getLine() && LHS.getCol() < RHS.getCol());
68 }
69 } // namespace llvm
70 
71 namespace polly {
72 BBPair getBBPairForRegion(const Region *R) {
73   return std::make_pair(R->getEntry(), R->getExit());
74 }
75 
76 void getDebugLocations(const BBPair &P, DebugLoc &Begin, DebugLoc &End) {
77   SmallPtrSet<BasicBlock *, 32> Seen;
78   SmallVector<BasicBlock *, 32> Todo;
79   Todo.push_back(P.first);
80   while (!Todo.empty()) {
81     auto *BB = Todo.pop_back_val();
82     if (BB == P.second)
83       continue;
84     if (!Seen.insert(BB).second)
85       continue;
86     Todo.append(succ_begin(BB), succ_end(BB));
87     for (const Instruction &Inst : *BB) {
88       DebugLoc DL = Inst.getDebugLoc();
89       if (!DL)
90         continue;
91 
92       Begin = Begin ? std::min(Begin, DL) : DL;
93       End = End ? std::max(End, DL) : DL;
94     }
95   }
96 }
97 
98 void emitRejectionRemarks(const BBPair &P, const RejectLog &Log) {
99   Function &F = *P.first->getParent();
100   LLVMContext &Ctx = F.getContext();
101 
102   DebugLoc Begin, End;
103   getDebugLocations(P, Begin, End);
104 
105   emitOptimizationRemarkMissed(
106       Ctx, DEBUG_TYPE, F, Begin,
107       "The following errors keep this region from being a Scop.");
108 
109   for (RejectReasonPtr RR : Log) {
110     if (const DebugLoc &Loc = RR->getDebugLoc())
111       emitOptimizationRemarkMissed(Ctx, DEBUG_TYPE, F, Loc,
112                                    RR->getEndUserMessage());
113   }
114 
115   emitOptimizationRemarkMissed(Ctx, DEBUG_TYPE, F, End,
116                                "Invalid Scop candidate ends here.");
117 }
118 
119 //===----------------------------------------------------------------------===//
120 // RejectReason.
121 const DebugLoc RejectReason::Unknown = DebugLoc();
122 
123 const llvm::DebugLoc &RejectReason::getDebugLoc() const {
124   // Allocate an empty DebugLoc and return it a reference to it.
125   return Unknown;
126 }
127 
128 // RejectLog.
129 void RejectLog::print(raw_ostream &OS, int level) const {
130   int j = 0;
131   for (auto Reason : ErrorReports)
132     OS.indent(level) << "[" << j++ << "] " << Reason->getMessage() << "\n";
133 }
134 
135 //===----------------------------------------------------------------------===//
136 // ReportCFG.
137 
138 ReportCFG::ReportCFG(const RejectReasonKind K) : RejectReason(K) {
139   ++BadCFGForScop;
140 }
141 
142 bool ReportCFG::classof(const RejectReason *RR) {
143   return RR->getKind() >= rrkCFG && RR->getKind() <= rrkLastCFG;
144 }
145 
146 //===----------------------------------------------------------------------===//
147 // ReportInvalidTerminator.
148 
149 std::string ReportInvalidTerminator::getMessage() const {
150   return ("Invalid instruction terminates BB: " + BB->getName()).str();
151 }
152 
153 const DebugLoc &ReportInvalidTerminator::getDebugLoc() const {
154   return BB->getTerminator()->getDebugLoc();
155 }
156 
157 bool ReportInvalidTerminator::classof(const RejectReason *RR) {
158   return RR->getKind() == rrkInvalidTerminator;
159 }
160 
161 //===----------------------------------------------------------------------===//
162 // ReportIrreducibleRegion.
163 
164 std::string ReportIrreducibleRegion::getMessage() const {
165   return "Irreducible region encountered: " + R->getNameStr();
166 }
167 
168 const DebugLoc &ReportIrreducibleRegion::getDebugLoc() const { return DbgLoc; }
169 
170 std::string ReportIrreducibleRegion::getEndUserMessage() const {
171   return "Irreducible region encountered in control flow.";
172 }
173 
174 bool ReportIrreducibleRegion::classof(const RejectReason *RR) {
175   return RR->getKind() == rrkIrreducibleRegion;
176 }
177 
178 //===----------------------------------------------------------------------===//
179 // ReportAffFunc.
180 
181 ReportAffFunc::ReportAffFunc(const RejectReasonKind K, const Instruction *Inst)
182     : RejectReason(K), Inst(Inst) {
183   ++BadAffFuncForScop;
184 }
185 
186 bool ReportAffFunc::classof(const RejectReason *RR) {
187   return RR->getKind() >= rrkAffFunc && RR->getKind() <= rrkLastAffFunc;
188 }
189 
190 //===----------------------------------------------------------------------===//
191 // ReportUndefCond.
192 
193 std::string ReportUndefCond::getMessage() const {
194   return ("Condition based on 'undef' value in BB: " + BB->getName()).str();
195 }
196 
197 bool ReportUndefCond::classof(const RejectReason *RR) {
198   return RR->getKind() == rrkUndefCond;
199 }
200 
201 //===----------------------------------------------------------------------===//
202 // ReportInvalidCond.
203 
204 std::string ReportInvalidCond::getMessage() const {
205   return ("Condition in BB '" + BB->getName()).str() +
206          "' neither constant nor an icmp instruction";
207 }
208 
209 bool ReportInvalidCond::classof(const RejectReason *RR) {
210   return RR->getKind() == rrkInvalidCond;
211 }
212 
213 //===----------------------------------------------------------------------===//
214 // ReportUndefOperand.
215 
216 std::string ReportUndefOperand::getMessage() const {
217   return ("undef operand in branch at BB: " + BB->getName()).str();
218 }
219 
220 bool ReportUndefOperand::classof(const RejectReason *RR) {
221   return RR->getKind() == rrkUndefOperand;
222 }
223 
224 //===----------------------------------------------------------------------===//
225 // ReportNonAffBranch.
226 
227 std::string ReportNonAffBranch::getMessage() const {
228   return ("Non affine branch in BB '" + BB->getName()).str() + "' with LHS: " +
229          *LHS + " and RHS: " + *RHS;
230 }
231 
232 bool ReportNonAffBranch::classof(const RejectReason *RR) {
233   return RR->getKind() == rrkNonAffBranch;
234 }
235 
236 //===----------------------------------------------------------------------===//
237 // ReportNoBasePtr.
238 
239 std::string ReportNoBasePtr::getMessage() const { return "No base pointer"; }
240 
241 bool ReportNoBasePtr::classof(const RejectReason *RR) {
242   return RR->getKind() == rrkNoBasePtr;
243 }
244 
245 //===----------------------------------------------------------------------===//
246 // ReportUndefBasePtr.
247 
248 std::string ReportUndefBasePtr::getMessage() const {
249   return "Undefined base pointer";
250 }
251 
252 bool ReportUndefBasePtr::classof(const RejectReason *RR) {
253   return RR->getKind() == rrkUndefBasePtr;
254 }
255 
256 //===----------------------------------------------------------------------===//
257 // ReportVariantBasePtr.
258 
259 std::string ReportVariantBasePtr::getMessage() const {
260   return "Base address not invariant in current region:" + *BaseValue;
261 }
262 
263 std::string ReportVariantBasePtr::getEndUserMessage() const {
264   return "The base address of this array is not invariant inside the loop";
265 }
266 
267 bool ReportVariantBasePtr::classof(const RejectReason *RR) {
268   return RR->getKind() == rrkVariantBasePtr;
269 }
270 
271 //===----------------------------------------------------------------------===//
272 // ReportDifferentArrayElementSize
273 
274 std::string ReportDifferentArrayElementSize::getMessage() const {
275   return "Access to one array through data types of different size";
276 }
277 
278 bool ReportDifferentArrayElementSize::classof(const RejectReason *RR) {
279   return RR->getKind() == rrkDifferentElementSize;
280 }
281 
282 std::string ReportDifferentArrayElementSize::getEndUserMessage() const {
283   llvm::StringRef BaseName = BaseValue->getName();
284   std::string Name = (BaseName.size() > 0) ? BaseName : "UNKNOWN";
285   return "The array \"" + Name + "\" is accessed through elements that differ "
286                                  "in size";
287 }
288 
289 //===----------------------------------------------------------------------===//
290 // ReportNonAffineAccess.
291 
292 std::string ReportNonAffineAccess::getMessage() const {
293   return "Non affine access function: " + *AccessFunction;
294 }
295 
296 bool ReportNonAffineAccess::classof(const RejectReason *RR) {
297   return RR->getKind() == rrkNonAffineAccess;
298 }
299 
300 std::string ReportNonAffineAccess::getEndUserMessage() const {
301   llvm::StringRef BaseName = BaseValue->getName();
302   std::string Name = (BaseName.size() > 0) ? BaseName : "UNKNOWN";
303   return "The array subscript of \"" + Name + "\" is not affine";
304 }
305 
306 //===----------------------------------------------------------------------===//
307 // ReportLoopBound.
308 
309 ReportLoopBound::ReportLoopBound(Loop *L, const SCEV *LoopCount)
310     : RejectReason(rrkLoopBound), L(L), LoopCount(LoopCount),
311       Loc(L->getStartLoc()) {
312   ++BadLoopBoundForScop;
313 }
314 
315 std::string ReportLoopBound::getMessage() const {
316   return "Non affine loop bound '" + *LoopCount + "' in loop: " +
317          L->getHeader()->getName();
318 }
319 
320 const DebugLoc &ReportLoopBound::getDebugLoc() const { return Loc; }
321 
322 bool ReportLoopBound::classof(const RejectReason *RR) {
323   return RR->getKind() == rrkLoopBound;
324 }
325 
326 std::string ReportLoopBound::getEndUserMessage() const {
327   return "Failed to derive an affine function from the loop bounds.";
328 }
329 
330 //===----------------------------------------------------------------------===//
331 // ReportLoopHasNoExit.
332 
333 std::string ReportLoopHasNoExit::getMessage() const {
334   return "Loop " + L->getHeader()->getName() + " has no exit.";
335 }
336 
337 bool ReportLoopHasNoExit::classof(const RejectReason *RR) {
338   return RR->getKind() == rrkLoopHasNoExit;
339 }
340 
341 const DebugLoc &ReportLoopHasNoExit::getDebugLoc() const { return Loc; }
342 
343 std::string ReportLoopHasNoExit::getEndUserMessage() const {
344   return "Loop cannot be handled because it has no exit.";
345 }
346 
347 //===----------------------------------------------------------------------===//
348 // ReportFuncCall.
349 
350 ReportFuncCall::ReportFuncCall(Instruction *Inst)
351     : RejectReason(rrkFuncCall), Inst(Inst) {
352   ++BadFuncCallForScop;
353 }
354 
355 std::string ReportFuncCall::getMessage() const {
356   return "Call instruction: " + *Inst;
357 }
358 
359 const DebugLoc &ReportFuncCall::getDebugLoc() const {
360   return Inst->getDebugLoc();
361 }
362 
363 std::string ReportFuncCall::getEndUserMessage() const {
364   return "This function call cannot be handled. "
365          "Try to inline it.";
366 }
367 
368 bool ReportFuncCall::classof(const RejectReason *RR) {
369   return RR->getKind() == rrkFuncCall;
370 }
371 
372 //===----------------------------------------------------------------------===//
373 // ReportNonSimpleMemoryAccess
374 
375 ReportNonSimpleMemoryAccess::ReportNonSimpleMemoryAccess(Instruction *Inst)
376     : ReportOther(rrkNonSimpleMemoryAccess), Inst(Inst) {}
377 
378 std::string ReportNonSimpleMemoryAccess::getMessage() const {
379   return "Non-simple memory access: " + *Inst;
380 }
381 
382 const DebugLoc &ReportNonSimpleMemoryAccess::getDebugLoc() const {
383   return Inst->getDebugLoc();
384 }
385 
386 std::string ReportNonSimpleMemoryAccess::getEndUserMessage() const {
387   return "Volatile memory accesses or memory accesses for atomic types "
388          "are not supported.";
389 }
390 
391 bool ReportNonSimpleMemoryAccess::classof(const RejectReason *RR) {
392   return RR->getKind() == rrkNonSimpleMemoryAccess;
393 }
394 
395 //===----------------------------------------------------------------------===//
396 // ReportAlias.
397 
398 ReportAlias::ReportAlias(Instruction *Inst, AliasSet &AS)
399     : RejectReason(rrkAlias), Inst(Inst) {
400 
401   for (const auto &I : AS)
402     Pointers.push_back(I.getValue());
403 
404   ++BadAliasForScop;
405 }
406 
407 std::string ReportAlias::formatInvalidAlias(std::string Prefix,
408                                             std::string Suffix) const {
409   std::string Message;
410   raw_string_ostream OS(Message);
411 
412   OS << Prefix;
413 
414   for (PointerSnapshotTy::const_iterator PI = Pointers.begin(),
415                                          PE = Pointers.end();
416        ;) {
417     const Value *V = *PI;
418     assert(V && "Diagnostic info does not match found LLVM-IR anymore.");
419 
420     if (V->getName().size() == 0)
421       OS << "\"" << *V << "\"";
422     else
423       OS << "\"" << V->getName() << "\"";
424 
425     ++PI;
426 
427     if (PI != PE)
428       OS << ", ";
429     else
430       break;
431   }
432 
433   OS << Suffix;
434 
435   return OS.str();
436 }
437 
438 std::string ReportAlias::getMessage() const {
439   return formatInvalidAlias("Possible aliasing: ");
440 }
441 
442 std::string ReportAlias::getEndUserMessage() const {
443   return formatInvalidAlias("Accesses to the arrays ",
444                             " may access the same memory.");
445 }
446 
447 const DebugLoc &ReportAlias::getDebugLoc() const { return Inst->getDebugLoc(); }
448 
449 bool ReportAlias::classof(const RejectReason *RR) {
450   return RR->getKind() == rrkAlias;
451 }
452 
453 //===----------------------------------------------------------------------===//
454 // ReportOther.
455 
456 std::string ReportOther::getMessage() const { return "Unknown reject reason"; }
457 
458 ReportOther::ReportOther(const RejectReasonKind K) : RejectReason(K) {
459   ++BadOtherForScop;
460 }
461 
462 bool ReportOther::classof(const RejectReason *RR) {
463   return RR->getKind() >= rrkOther && RR->getKind() <= rrkLastOther;
464 }
465 
466 //===----------------------------------------------------------------------===//
467 // ReportIntToPtr.
468 ReportIntToPtr::ReportIntToPtr(Instruction *BaseValue)
469     : ReportOther(rrkIntToPtr), BaseValue(BaseValue) {}
470 
471 std::string ReportIntToPtr::getMessage() const {
472   return "Find bad intToptr prt: " + *BaseValue;
473 }
474 
475 const DebugLoc &ReportIntToPtr::getDebugLoc() const {
476   return BaseValue->getDebugLoc();
477 }
478 
479 bool ReportIntToPtr::classof(const RejectReason *RR) {
480   return RR->getKind() == rrkIntToPtr;
481 }
482 
483 //===----------------------------------------------------------------------===//
484 // ReportAlloca.
485 
486 ReportAlloca::ReportAlloca(Instruction *Inst)
487     : ReportOther(rrkAlloca), Inst(Inst) {}
488 
489 std::string ReportAlloca::getMessage() const {
490   return "Alloca instruction: " + *Inst;
491 }
492 
493 const DebugLoc &ReportAlloca::getDebugLoc() const {
494   return Inst->getDebugLoc();
495 }
496 
497 bool ReportAlloca::classof(const RejectReason *RR) {
498   return RR->getKind() == rrkAlloca;
499 }
500 
501 //===----------------------------------------------------------------------===//
502 // ReportUnknownInst.
503 
504 ReportUnknownInst::ReportUnknownInst(Instruction *Inst)
505     : ReportOther(rrkUnknownInst), Inst(Inst) {}
506 
507 std::string ReportUnknownInst::getMessage() const {
508   return "Unknown instruction: " + *Inst;
509 }
510 
511 const DebugLoc &ReportUnknownInst::getDebugLoc() const {
512   return Inst->getDebugLoc();
513 }
514 
515 bool ReportUnknownInst::classof(const RejectReason *RR) {
516   return RR->getKind() == rrkUnknownInst;
517 }
518 
519 //===----------------------------------------------------------------------===//
520 // ReportEntry.
521 ReportEntry::ReportEntry(BasicBlock *BB) : ReportOther(rrkEntry), BB(BB) {}
522 
523 std::string ReportEntry::getMessage() const {
524   return "Region containing entry block of function is invalid!";
525 }
526 
527 const DebugLoc &ReportEntry::getDebugLoc() const {
528   return BB->getTerminator()->getDebugLoc();
529 }
530 
531 bool ReportEntry::classof(const RejectReason *RR) {
532   return RR->getKind() == rrkEntry;
533 }
534 
535 //===----------------------------------------------------------------------===//
536 // ReportUnprofitable.
537 ReportUnprofitable::ReportUnprofitable(Region *R)
538     : ReportOther(rrkUnprofitable), R(R) {}
539 
540 std::string ReportUnprofitable::getMessage() const {
541   return "Region can not profitably be optimized!";
542 }
543 
544 std::string ReportUnprofitable::getEndUserMessage() const {
545   return "No profitable polyhedral optimization found";
546 }
547 
548 const DebugLoc &ReportUnprofitable::getDebugLoc() const {
549   for (const BasicBlock *BB : R->blocks())
550     for (const Instruction &Inst : *BB)
551       if (const DebugLoc &DL = Inst.getDebugLoc())
552         return DL;
553 
554   return R->getEntry()->getTerminator()->getDebugLoc();
555 }
556 
557 bool ReportUnprofitable::classof(const RejectReason *RR) {
558   return RR->getKind() == rrkUnprofitable;
559 }
560 } // namespace polly
561