Coverage Report

Created: 2017-06-23 12:40

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/polly/lib/Exchange/JSONExporter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- JSONExporter.cpp  - Export Scops as JSON  -------------------------===//
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
// Export the Scops build by ScopInfo pass as a JSON file.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "polly/DependenceInfo.h"
15
#include "polly/LinkAllPasses.h"
16
#include "polly/Options.h"
17
#include "polly/ScopInfo.h"
18
#include "polly/ScopPass.h"
19
#include "polly/Support/ScopLocation.h"
20
#include "llvm/ADT/Statistic.h"
21
#include "llvm/Analysis/RegionInfo.h"
22
#include "llvm/IR/Module.h"
23
#include "llvm/Support/FileSystem.h"
24
#include "llvm/Support/MemoryBuffer.h"
25
#include "llvm/Support/ToolOutputFile.h"
26
#include "llvm/Support/raw_ostream.h"
27
#include "isl/constraint.h"
28
#include "isl/map.h"
29
#include "isl/printer.h"
30
#include "isl/set.h"
31
#include "isl/union_map.h"
32
#include "json/reader.h"
33
#include "json/writer.h"
34
#include <memory>
35
#include <string>
36
#include <system_error>
37
38
using namespace llvm;
39
using namespace polly;
40
41
#define DEBUG_TYPE "polly-import-jscop"
42
43
STATISTIC(NewAccessMapFound, "Number of updated access functions");
44
45
namespace {
46
static cl::opt<std::string>
47
    ImportDir("polly-import-jscop-dir",
48
              cl::desc("The directory to import the .jscop files from."),
49
              cl::Hidden, cl::value_desc("Directory path"), cl::ValueRequired,
50
              cl::init("."), cl::cat(PollyCategory));
51
52
static cl::opt<std::string>
53
    ImportPostfix("polly-import-jscop-postfix",
54
                  cl::desc("Postfix to append to the import .jsop files."),
55
                  cl::Hidden, cl::value_desc("File postfix"), cl::ValueRequired,
56
                  cl::init(""), cl::cat(PollyCategory));
57
58
struct JSONExporter : public ScopPass {
59
  static char ID;
60
0
  explicit JSONExporter() : ScopPass(ID) {}
61
62
  std::string getFileName(Scop &S) const;
63
  Json::Value getJSON(Scop &S) const;
64
65
  /// Export the SCoP @p S to a JSON file.
66
  bool runOnScop(Scop &S) override;
67
68
  /// Print the SCoP @p S as it is exported.
69
  void printScop(raw_ostream &OS, Scop &S) const override;
70
71
  /// Register all analyses and transformation required.
72
  void getAnalysisUsage(AnalysisUsage &AU) const override;
73
};
74
75
struct JSONImporter : public ScopPass {
76
  static char ID;
77
  std::vector<std::string> NewAccessStrings;
78
71
  explicit JSONImporter() : ScopPass(ID) {}
79
80
  /// Import a new context from JScop.
81
  ///
82
  /// @param S The scop to update.
83
  /// @param JScop The JScop file describing the new schedule.
84
  ///
85
  /// @returns True if the import succeeded, otherwise False.
86
  bool importContext(Scop &S, Json::Value &JScop);
87
88
  /// Import a new schedule from JScop.
89
  ///
90
  /// ... and verify that the new schedule does preserve existing data
91
  /// dependences.
92
  ///
93
  /// @param S The scop to update.
94
  /// @param JScop The JScop file describing the new schedule.
95
  /// @param D The data dependences of the @p S.
96
  ///
97
  /// @returns True if the import succeeded, otherwise False.
98
  bool importSchedule(Scop &S, Json::Value &JScop, const Dependences &D);
99
100
  /// Import new arrays from JScop.
101
  ///
102
  /// @param S The scop to update.
103
  /// @param JScop The JScop file describing new arrays.
104
  ///
105
  /// @returns True if the import succeeded, otherwise False.
106
  bool importArrays(Scop &S, Json::Value &JScop);
107
108
  /// Import new memory accesses from JScop.
109
  ///
110
  /// @param S The scop to update.
111
  /// @param JScop The JScop file describing the new schedule.
112
  /// @param DL The data layout to assume.
113
  ///
114
  /// @returns True if the import succeeded, otherwise False.
115
  bool importAccesses(Scop &S, Json::Value &JScop, const DataLayout &DL);
116
117
  std::string getFileName(Scop &S) const;
118
119
  /// Import new access functions for SCoP @p S from a JSON file.
120
  bool runOnScop(Scop &S) override;
121
122
  /// Print the SCoP @p S and the imported access functions.
123
  void printScop(raw_ostream &OS, Scop &S) const override;
124
125
  /// Register all analyses and transformation required.
126
  void getAnalysisUsage(AnalysisUsage &AU) const override;
127
};
128
} // namespace
129
130
char JSONExporter::ID = 0;
131
0
std::string JSONExporter::getFileName(Scop &S) const {
132
0
  std::string FunctionName = S.getFunction().getName();
133
0
  std::string FileName = FunctionName + "___" + S.getNameStr() + ".jscop";
134
0
  return FileName;
135
0
}
136
137
0
void JSONExporter::printScop(raw_ostream &OS, Scop &S) const { S.print(OS); }
138
139
/// Export all arrays from the Scop.
140
///
141
/// @param S The Scop containing the arrays.
142
///
143
/// @returns Json::Value containing the arrays.
144
0
Json::Value exportArrays(const Scop &S) {
145
0
  Json::Value Arrays;
146
0
  std::string Buffer;
147
0
  llvm::raw_string_ostream RawStringOstream(Buffer);
148
0
149
0
  for (auto &SAI : S.arrays()) {
150
0
    if (!SAI->isArrayKind())
151
0
      continue;
152
0
153
0
    Json::Value Array;
154
0
    Array["name"] = SAI->getName();
155
0
    unsigned i = 0;
156
0
    if (
!SAI->getDimensionSize(i)0
)
{0
157
0
      Array["sizes"].append("*");
158
0
      i++;
159
0
    }
160
0
    for (; 
i < SAI->getNumberOfDimensions()0
;
i++0
)
{0
161
0
      SAI->getDimensionSize(i)->print(RawStringOstream);
162
0
      Array["sizes"].append(RawStringOstream.str());
163
0
      Buffer.clear();
164
0
    }
165
0
    SAI->getElementType()->print(RawStringOstream);
166
0
    Array["type"] = RawStringOstream.str();
167
0
    Buffer.clear();
168
0
    Arrays.append(Array);
169
0
  }
170
0
  return Arrays;
171
0
}
172
173
0
Json::Value JSONExporter::getJSON(Scop &S) const {
174
0
  Json::Value root;
175
0
  unsigned LineBegin, LineEnd;
176
0
  std::string FileName;
177
0
178
0
  getDebugLocation(&S.getRegion(), LineBegin, LineEnd, FileName);
179
0
  std::string Location;
180
0
  if (LineBegin != (unsigned)-1)
181
0
    Location = FileName + ":" + std::to_string(LineBegin) + "-" +
182
0
               std::to_string(LineEnd);
183
0
184
0
  root["name"] = S.getNameStr();
185
0
  root["context"] = S.getContextStr();
186
0
  if (LineBegin != (unsigned)-1)
187
0
    root["location"] = Location;
188
0
189
0
  root["arrays"] = exportArrays(S);
190
0
191
0
  root["statements"];
192
0
193
0
  for (ScopStmt &Stmt : S) {
194
0
    Json::Value statement;
195
0
196
0
    statement["name"] = Stmt.getBaseName();
197
0
    statement["domain"] = Stmt.getDomainStr();
198
0
    statement["schedule"] = Stmt.getScheduleStr();
199
0
    statement["accesses"];
200
0
201
0
    for (MemoryAccess *MA : Stmt) {
202
0
      Json::Value access;
203
0
204
0
      access["kind"] = MA->isRead() ? 
"read"0
:
"write"0
;
205
0
      access["relation"] = MA->getOriginalAccessRelationStr();
206
0
207
0
      statement["accesses"].append(access);
208
0
    }
209
0
210
0
    root["statements"].append(statement);
211
0
  }
212
0
213
0
  return root;
214
0
}
215
216
0
bool JSONExporter::runOnScop(Scop &S) {
217
0
  std::string FileName = ImportDir + "/" + getFileName(S);
218
0
219
0
  Json::Value jscop = getJSON(S);
220
0
  Json::StyledWriter writer;
221
0
  std::string fileContent = writer.write(jscop);
222
0
223
0
  // Write to file.
224
0
  std::error_code EC;
225
0
  tool_output_file F(FileName, EC, llvm::sys::fs::F_Text);
226
0
227
0
  std::string FunctionName = S.getFunction().getName();
228
0
  errs() << "Writing JScop '" << S.getNameStr() << "' in function '"
229
0
         << FunctionName << "' to '" << FileName << "'.\n";
230
0
231
0
  if (
!EC0
)
{0
232
0
    F.os() << fileContent;
233
0
    F.os().close();
234
0
    if (
!F.os().has_error()0
)
{0
235
0
      errs() << "\n";
236
0
      F.keep();
237
0
      return false;
238
0
    }
239
0
  }
240
0
241
0
  errs() << "  error opening file for writing!\n";
242
0
  F.os().clear_error();
243
0
244
0
  return false;
245
0
}
246
247
0
void JSONExporter::getAnalysisUsage(AnalysisUsage &AU) const {
248
0
  AU.setPreservesAll();
249
0
  AU.addRequired<ScopInfoRegionPass>();
250
0
}
251
252
0
Pass *polly::createJSONExporterPass() { return new JSONExporter(); }
253
254
char JSONImporter::ID = 0;
255
72
std::string JSONImporter::getFileName(Scop &S) const {
256
72
  std::string FunctionName = S.getFunction().getName();
257
72
  std::string FileName = FunctionName + "___" + S.getNameStr() + ".jscop";
258
72
259
72
  if (ImportPostfix != "")
260
33
    FileName += "." + ImportPostfix;
261
72
262
72
  return FileName;
263
72
}
264
265
28
void JSONImporter::printScop(raw_ostream &OS, Scop &S) const {
266
28
  S.print(OS);
267
28
  for (std::vector<std::string>::const_iterator I = NewAccessStrings.begin(),
268
28
                                                E = NewAccessStrings.end();
269
58
       
I != E58
;
I++30
)
270
30
    OS << "New access function '" << *I << "' detected in JSCOP file\n";
271
28
}
272
273
typedef Dependences::StatementToIslMapTy StatementToIslMapTy;
274
275
72
bool JSONImporter::importContext(Scop &S, Json::Value &JScop) {
276
72
  isl_set *OldContext = S.getContext();
277
72
278
72
  // Check if key 'context' is present.
279
72
  if (
!JScop.isMember("context")72
)
{1
280
1
    errs() << "JScop file has no key named 'context'.\n";
281
1
    isl_set_free(OldContext);
282
1
    return false;
283
1
  }
284
72
285
71
  isl_set *NewContext =
286
71
      isl_set_read_from_str(S.getIslCtx(), JScop["context"].asCString());
287
71
288
71
  // Check whether the context was parsed successfully.
289
71
  if (
!NewContext71
)
{1
290
1
    errs() << "The context was not parsed successfully by ISL.\n";
291
1
    isl_set_free(NewContext);
292
1
    isl_set_free(OldContext);
293
1
    return false;
294
1
  }
295
71
296
71
  // Check if the isl_set is a parameter set.
297
70
  
if (70
!isl_set_is_params(NewContext)70
)
{1
298
1
    errs() << "The isl_set is not a parameter set.\n";
299
1
    isl_set_free(NewContext);
300
1
    isl_set_free(OldContext);
301
1
    return false;
302
1
  }
303
70
304
69
  unsigned OldContextDim = isl_set_dim(OldContext, isl_dim_param);
305
69
  unsigned NewContextDim = isl_set_dim(NewContext, isl_dim_param);
306
69
307
69
  // Check if the imported context has the right number of parameters.
308
69
  if (
OldContextDim != NewContextDim69
)
{1
309
1
    errs() << "Imported context has the wrong number of parameters : "
310
1
           << "Found " << NewContextDim << " Expected " << OldContextDim
311
1
           << "\n";
312
1
    isl_set_free(NewContext);
313
1
    isl_set_free(OldContext);
314
1
    return false;
315
1
  }
316
69
317
106
  
for (unsigned i = 0; 68
i < OldContextDim106
;
i++38
)
{38
318
38
    isl_id *Id = isl_set_get_dim_id(OldContext, isl_dim_param, i);
319
38
    NewContext = isl_set_set_dim_id(NewContext, isl_dim_param, i, Id);
320
38
  }
321
68
322
68
  isl_set_free(OldContext);
323
68
  S.setContext(NewContext);
324
68
  return true;
325
69
}
326
327
bool JSONImporter::importSchedule(Scop &S, Json::Value &JScop,
328
68
                                  const Dependences &D) {
329
68
  StatementToIslMapTy NewSchedule;
330
68
331
68
  // Check if key 'statements' is present.
332
68
  if (
!JScop.isMember("statements")68
)
{2
333
2
    errs() << "JScop file has no key name 'statements'.\n";
334
2
    return false;
335
2
  }
336
68
337
66
  Json::Value statements = JScop["statements"];
338
66
339
66
  // Check whether the number of indices equals the number of statements
340
66
  if (
statements.size() != S.getSize()66
)
{2
341
2
    errs() << "The number of indices and the number of statements differ.\n";
342
2
    return false;
343
2
  }
344
66
345
64
  int Index = 0;
346
95
  for (ScopStmt &Stmt : S) {
347
95
    // Check if key 'schedule' is present.
348
95
    if (
!statements[Index].isMember("schedule")95
)
{1
349
1
      errs() << "Statement " << Index << " has no 'schedule' key.\n";
350
0
      for (auto Element : NewSchedule) {
351
0
        isl_map_free(Element.second);
352
0
      }
353
1
      return false;
354
1
    }
355
94
    Json::Value Schedule = statements[Index]["schedule"];
356
94
    assert(!Schedule.asString().empty() &&
357
94
           "Schedules that contain extension nodes require special handling.");
358
94
    isl_map *Map = isl_map_read_from_str(S.getIslCtx(), Schedule.asCString());
359
94
360
94
    // Check whether the schedule was parsed successfully
361
94
    if (
!Map94
)
{1
362
1
      errs() << "The schedule was not parsed successfully (index = " << Index
363
1
             << ").\n";
364
1
      for (auto Element : NewSchedule) {
365
1
        isl_map_free(Element.second);
366
1
      }
367
1
      return false;
368
1
    }
369
94
370
93
    isl_space *Space = Stmt.getDomainSpace();
371
93
372
93
    // Copy the old tuple id. This is necessary to retain the user pointer,
373
93
    // that stores the reference to the ScopStmt this schedule belongs to.
374
93
    Map = isl_map_set_tuple_id(Map, isl_dim_in,
375
93
                               isl_space_get_tuple_id(Space, isl_dim_set));
376
143
    for (unsigned i = 0; 
i < isl_space_dim(Space, isl_dim_param)143
;
i++50
)
{50
377
50
      isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
378
50
      Map = isl_map_set_dim_id(Map, isl_dim_param, i, Id);
379
50
    }
380
93
    isl_space_free(Space);
381
93
    NewSchedule[&Stmt] = Map;
382
93
    Index++;
383
93
  }
384
64
385
64
  // Check whether the new schedule is valid or not.
386
62
  
if (62
!D.isValidSchedule(S, &NewSchedule)62
)
{0
387
0
    errs() << "JScop file contains a schedule that changes the "
388
0
           << "dependences. Use -disable-polly-legality to continue anyways\n";
389
0
    for (auto Element : NewSchedule)
390
0
      isl_map_free(Element.second);
391
0
    return false;
392
0
  }
393
62
394
62
  auto ScheduleMap = isl_union_map_empty(S.getParamSpace());
395
92
  for (ScopStmt &Stmt : S) {
396
92
    if (NewSchedule.find(&Stmt) != NewSchedule.end())
397
92
      ScheduleMap = isl_union_map_add_map(ScheduleMap, NewSchedule[&Stmt]);
398
92
    else
399
0
      ScheduleMap = isl_union_map_add_map(ScheduleMap, Stmt.getSchedule());
400
92
  }
401
62
402
62
  S.setSchedule(ScheduleMap);
403
62
404
62
  return true;
405
62
}
406
407
bool JSONImporter::importAccesses(Scop &S, Json::Value &JScop,
408
58
                                  const DataLayout &DL) {
409
58
  int StatementIdx = 0;
410
58
411
58
  // Check if key 'statements' is present.
412
58
  if (
!JScop.isMember("statements")58
)
{0
413
0
    errs() << "JScop file has no key name 'statements'.\n";
414
0
    return false;
415
0
  }
416
58
  Json::Value statements = JScop["statements"];
417
58
418
58
  // Check whether the number of indices equals the number of statements
419
58
  if (
statements.size() != S.getSize()58
)
{0
420
0
    errs() << "The number of indices and the number of statements differ.\n";
421
0
    return false;
422
0
  }
423
58
424
84
  
for (ScopStmt &Stmt : S) 58
{84
425
84
    int MemoryAccessIdx = 0;
426
84
427
84
    // Check if key 'accesses' is present.
428
84
    if (
!statements[StatementIdx].isMember("accesses")84
)
{1
429
1
      errs()
430
1
          << "Statement from JScop file has no key name 'accesses' for index "
431
1
          << StatementIdx << ".\n";
432
1
      return false;
433
1
    }
434
84
435
84
    // Check whether the number of indices equals the number of memory accesses
436
83
    
if (83
Stmt.size() != statements[StatementIdx]["accesses"].size()83
)
{2
437
2
      errs() << "The number of memory accesses in the JSop file and the number "
438
2
                "of memory accesses differ for index "
439
2
             << StatementIdx << ".\n";
440
2
      return false;
441
2
    }
442
83
443
162
    
for (MemoryAccess *MA : Stmt) 81
{162
444
162
      // Check if key 'relation' is present.
445
162
      Json::Value JsonMemoryAccess =
446
162
          statements[StatementIdx]["accesses"][MemoryAccessIdx];
447
162
      if (
!JsonMemoryAccess.isMember("relation")162
)
{1
448
1
        errs() << "Memory access number " << MemoryAccessIdx
449
1
               << " has no key name 'relation' for statement number "
450
1
               << StatementIdx << ".\n";
451
1
        return false;
452
1
      }
453
161
      Json::Value Accesses = JsonMemoryAccess["relation"];
454
161
      isl_map *NewAccessMap =
455
161
          isl_map_read_from_str(S.getIslCtx(), Accesses.asCString());
456
161
457
161
      // Check whether the access was parsed successfully
458
161
      if (
!NewAccessMap161
)
{1
459
1
        errs() << "The access was not parsed successfully by ISL.\n";
460
1
        return false;
461
1
      }
462
160
      isl_map *CurrentAccessMap = MA->getAccessRelation();
463
160
464
160
      // Check if the number of parameter change
465
160
      if (isl_map_dim(NewAccessMap, isl_dim_param) !=
466
1
          isl_map_dim(CurrentAccessMap, isl_dim_param)) {
467
1
        errs() << "JScop file changes the number of parameter dimensions.\n";
468
1
        isl_map_free(CurrentAccessMap);
469
1
        isl_map_free(NewAccessMap);
470
1
        return false;
471
1
      }
472
160
473
159
      isl_id *NewOutId;
474
159
475
159
      // If the NewAccessMap has zero dimensions, it is the scalar access; it
476
159
      // must be the same as before.
477
159
      // If it has at least one dimension, it's an array access; search for its
478
159
      // ScopArrayInfo.
479
159
      if (
isl_map_dim(NewAccessMap, isl_dim_out) >= 1159
)
{152
480
152
        NewOutId = isl_map_get_tuple_id(NewAccessMap, isl_dim_out);
481
152
        auto *SAI = S.getArrayInfoByName(isl_id_get_name(NewOutId));
482
152
        isl_id *OutId = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_out);
483
152
        auto *OutSAI = ScopArrayInfo::getFromId(OutId);
484
152
        if (
!SAI || 152
SAI->getElementType() != OutSAI->getElementType()151
)
{1
485
1
          errs() << "JScop file contains access function with undeclared "
486
1
                    "ScopArrayInfo\n";
487
1
          isl_map_free(CurrentAccessMap);
488
1
          isl_map_free(NewAccessMap);
489
1
          isl_id_free(NewOutId);
490
1
          return false;
491
1
        }
492
151
        isl_id_free(NewOutId);
493
151
        NewOutId = SAI->getBasePtrId();
494
7
      } else {
495
7
        NewOutId = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_out);
496
7
      }
497
159
498
158
      NewAccessMap = isl_map_set_tuple_id(NewAccessMap, isl_dim_out, NewOutId);
499
158
500
158
      if (
MA->isArrayKind()158
)
{116
501
116
        // We keep the old alignment, thus we cannot allow accesses to memory
502
116
        // locations that were not accessed before if the alignment of the
503
116
        // access is not the default alignment.
504
116
        bool SpecialAlignment = true;
505
116
        if (LoadInst *
LoadI116
= dyn_cast<LoadInst>(MA->getAccessInstruction()))
{51
506
51
          SpecialAlignment =
507
51
              LoadI->getAlignment() &&
508
48
              DL.getABITypeAlignment(LoadI->getType()) != LoadI->getAlignment();
509
65
        } else 
if (StoreInst *65
StoreI65
=
510
65
                       dyn_cast<StoreInst>(MA->getAccessInstruction())) {
511
65
          SpecialAlignment =
512
65
              StoreI->getAlignment() &&
513
43
              DL.getABITypeAlignment(StoreI->getValueOperand()->getType()) !=
514
43
                  StoreI->getAlignment();
515
65
        }
516
116
517
116
        if (
SpecialAlignment116
)
{1
518
1
          isl_set *NewAccessSet = isl_map_range(isl_map_copy(NewAccessMap));
519
1
          isl_set *CurrentAccessSet =
520
1
              isl_map_range(isl_map_copy(CurrentAccessMap));
521
1
          bool IsSubset = isl_set_is_subset(NewAccessSet, CurrentAccessSet);
522
1
          isl_set_free(NewAccessSet);
523
1
          isl_set_free(CurrentAccessSet);
524
1
525
1
          // Check if the JScop file changes the accessed memory.
526
1
          if (
!IsSubset1
)
{1
527
1
            errs() << "JScop file changes the accessed memory\n";
528
1
            isl_map_free(CurrentAccessMap);
529
1
            isl_map_free(NewAccessMap);
530
1
            return false;
531
1
          }
532
1
        }
533
116
      }
534
158
535
158
      // We need to copy the isl_ids for the parameter dimensions to the new
536
158
      // map. Without doing this the current map would have different
537
158
      // ids then the new one, even though both are named identically.
538
245
      
for (unsigned i = 0; 157
i < isl_map_dim(CurrentAccessMap, isl_dim_param)245
;
539
88
           
i++88
)
{88
540
88
        isl_id *Id = isl_map_get_dim_id(CurrentAccessMap, isl_dim_param, i);
541
88
        NewAccessMap = isl_map_set_dim_id(NewAccessMap, isl_dim_param, i, Id);
542
88
      }
543
157
544
157
      // Copy the old tuple id. This is necessary to retain the user pointer,
545
157
      // that stores the reference to the ScopStmt this access belongs to.
546
157
      isl_id *Id = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_in);
547
157
      NewAccessMap = isl_map_set_tuple_id(NewAccessMap, isl_dim_in, Id);
548
157
549
157
      auto NewAccessDomain = isl_map_domain(isl_map_copy(NewAccessMap));
550
157
      auto CurrentAccessDomain = isl_map_domain(isl_map_copy(CurrentAccessMap));
551
157
552
157
      if (
!isl_set_has_equal_space(NewAccessDomain, CurrentAccessDomain)157
)
{0
553
0
        errs() << "JScop file contains access function with incompatible "
554
0
               << "dimensions\n";
555
0
        isl_map_free(CurrentAccessMap);
556
0
        isl_map_free(NewAccessMap);
557
0
        isl_set_free(NewAccessDomain);
558
0
        isl_set_free(CurrentAccessDomain);
559
0
        return false;
560
0
      }
561
157
562
157
      NewAccessDomain =
563
157
          isl_set_intersect_params(NewAccessDomain, S.getContext());
564
157
      CurrentAccessDomain =
565
157
          isl_set_intersect_params(CurrentAccessDomain, S.getContext());
566
157
567
157
      if (MA->isRead() &&
568
73
          isl_set_is_subset(CurrentAccessDomain, NewAccessDomain) ==
569
0
              isl_bool_false) {
570
0
        errs() << "Mapping not defined for all iteration domain elements\n";
571
0
        isl_set_free(CurrentAccessDomain);
572
0
        isl_set_free(NewAccessDomain);
573
0
        isl_map_free(CurrentAccessMap);
574
0
        isl_map_free(NewAccessMap);
575
0
        return false;
576
0
      }
577
157
578
157
      isl_set_free(CurrentAccessDomain);
579
157
      isl_set_free(NewAccessDomain);
580
157
581
157
      if (
!isl_map_is_equal(NewAccessMap, CurrentAccessMap)157
)
{84
582
84
        // Statistics.
583
84
        ++NewAccessMapFound;
584
84
        NewAccessStrings.push_back(Accesses.asCString());
585
84
        MA->setNewAccessRelation(NewAccessMap);
586
73
      } else {
587
73
        isl_map_free(NewAccessMap);
588
73
      }
589
157
      isl_map_free(CurrentAccessMap);
590
157
      MemoryAccessIdx++;
591
157
    }
592
76
    StatementIdx++;
593
76
  }
594
58
595
50
  return true;
596
58
}
597
598
/// Check whether @p SAI and @p Array represent the same array.
599
31
bool areArraysEqual(ScopArrayInfo *SAI, Json::Value Array) {
600
31
  std::string Buffer;
601
31
  llvm::raw_string_ostream RawStringOstream(Buffer);
602
31
603
31
  // Check if key 'type' is present.
604
31
  if (
!Array.isMember("type")31
)
{1
605
1
    errs() << "Array has no key 'type'.\n";
606
1
    return false;
607
1
  }
608
31
609
31
  // Check if key 'sizes' is present.
610
30
  
if (30
!Array.isMember("sizes")30
)
{1
611
1
    errs() << "Array has no key 'sizes'.\n";
612
1
    return false;
613
1
  }
614
30
615
30
  // Check if key 'name' is present.
616
29
  
if (29
!Array.isMember("name")29
)
{1
617
1
    errs() << "Array has no key 'name'.\n";
618
1
    return false;
619
1
  }
620
29
621
28
  
if (28
SAI->getName() != Array["name"].asCString()28
)
622
0
    return false;
623
28
624
28
  
if (28
SAI->getNumberOfDimensions() != Array["sizes"].size()28
)
625
0
    return false;
626
28
627
34
  
for (unsigned i = 1; 28
i < Array["sizes"].size()34
;
i++6
)
{6
628
6
    SAI->getDimensionSize(i)->print(RawStringOstream);
629
6
    if (RawStringOstream.str() != Array["sizes"][i].asCString())
630
0
      return false;
631
6
    Buffer.clear();
632
6
  }
633
28
634
28
  // Check if key 'type' differs from the current one or is not valid.
635
28
  SAI->getElementType()->print(RawStringOstream);
636
28
  if (
RawStringOstream.str() != Array["type"].asCString()28
)
{1
637
1
    errs() << "Array has not a valid type.\n";
638
1
    return false;
639
1
  }
640
28
641
27
  return true;
642
28
}
643
644
/// Get the accepted primitive type from its textual representation
645
///        @p TypeTextRepresentation.
646
///
647
/// @param TypeTextRepresentation The textual representation of the type.
648
/// @return The pointer to the primitive type, if this type is accepted
649
///         or nullptr otherwise.
650
Type *parseTextType(const std::string &TypeTextRepresentation,
651
6
                    LLVMContext &LLVMContext) {
652
6
  std::map<std::string, Type *> MapStrToType = {
653
6
      {"void", Type::getVoidTy(LLVMContext)},
654
6
      {"half", Type::getHalfTy(LLVMContext)},
655
6
      {"float", Type::getFloatTy(LLVMContext)},
656
6
      {"double", Type::getDoubleTy(LLVMContext)},
657
6
      {"x86_fp80", Type::getX86_FP80Ty(LLVMContext)},
658
6
      {"fp128", Type::getFP128Ty(LLVMContext)},
659
6
      {"ppc_fp128", Type::getPPC_FP128Ty(LLVMContext)},
660
6
      {"i1", Type::getInt1Ty(LLVMContext)},
661
6
      {"i8", Type::getInt8Ty(LLVMContext)},
662
6
      {"i16", Type::getInt16Ty(LLVMContext)},
663
6
      {"i32", Type::getInt32Ty(LLVMContext)},
664
6
      {"i64", Type::getInt64Ty(LLVMContext)},
665
6
      {"i128", Type::getInt128Ty(LLVMContext)}};
666
6
667
6
  auto It = MapStrToType.find(TypeTextRepresentation);
668
6
  if (It != MapStrToType.end())
669
6
    return It->second;
670
6
671
0
  errs() << "Textual representation can not be parsed: "
672
0
         << TypeTextRepresentation << "\n";
673
0
  return nullptr;
674
6
}
675
676
62
bool JSONImporter::importArrays(Scop &S, Json::Value &JScop) {
677
62
  Json::Value Arrays = JScop["arrays"];
678
62
  if (Arrays.size() == 0)
679
41
    return true;
680
62
681
21
  unsigned ArrayIdx = 0;
682
50
  for (auto &SAI : S.arrays()) {
683
50
    if (!SAI->isArrayKind())
684
19
      continue;
685
31
    
if (31
ArrayIdx + 1 > Arrays.size()31
)
{0
686
0
      errs() << "Not enough array entries in JScop file.\n";
687
0
      return false;
688
0
    }
689
31
    
if (31
!areArraysEqual(SAI, Arrays[ArrayIdx])31
)
{4
690
4
      errs() << "No match for array '" << SAI->getName() << "' in JScop.\n";
691
4
      return false;
692
4
    }
693
27
    ArrayIdx++;
694
27
  }
695
21
696
23
  
for (; 17
ArrayIdx < Arrays.size()23
;
ArrayIdx++6
)
{6
697
6
    auto *ElementType = parseTextType(Arrays[ArrayIdx]["type"].asCString(),
698
6
                                      S.getSE()->getContext());
699
6
    if (
!ElementType6
)
{0
700
0
      errs() << "Error while parsing element type for new array.\n";
701
0
      return false;
702
0
    }
703
6
    std::vector<unsigned> DimSizes;
704
14
    for (unsigned i = 0; 
i < Arrays[ArrayIdx]["sizes"].size()14
;
i++8
)
705
8
      DimSizes.push_back(std::stoi(Arrays[ArrayIdx]["sizes"][i].asCString()));
706
6
    S.createScopArrayInfo(ElementType, Arrays[ArrayIdx]["name"].asCString(),
707
6
                          DimSizes);
708
6
  }
709
17
710
17
  return true;
711
17
}
712
713
72
bool JSONImporter::runOnScop(Scop &S) {
714
72
  const Dependences &D =
715
72
      getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
716
72
  const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
717
72
718
72
  std::string FileName = ImportDir + "/" + getFileName(S);
719
72
720
72
  std::string FunctionName = S.getFunction().getName();
721
72
  errs() << "Reading JScop '" << S.getNameStr() << "' in function '"
722
72
         << FunctionName << "' from '" << FileName << "'.\n";
723
72
  ErrorOr<std::unique_ptr<MemoryBuffer>> result =
724
72
      MemoryBuffer::getFile(FileName);
725
72
  std::error_code ec = result.getError();
726
72
727
72
  if (
ec72
)
{0
728
0
    errs() << "File could not be read: " << ec.message() << "\n";
729
0
    return false;
730
0
  }
731
72
732
72
  Json::Reader reader;
733
72
  Json::Value jscop;
734
72
735
72
  bool parsingSuccessful = reader.parse(result.get()->getBufferStart(), jscop);
736
72
737
72
  if (
!parsingSuccessful72
)
{0
738
0
    errs() << "JSCoP file could not be parsed\n";
739
0
    return false;
740
0
  }
741
72
742
72
  bool Success = importContext(S, jscop);
743
72
744
72
  if (!Success)
745
4
    return false;
746
72
747
68
  Success = importSchedule(S, jscop, D);
748
68
749
68
  if (!Success)
750
6
    return false;
751
68
752
62
  Success = importArrays(S, jscop);
753
62
754
62
  if (!Success)
755
4
    return false;
756
62
757
58
  Success = importAccesses(S, jscop, DL);
758
58
759
58
  if (!Success)
760
8
    return false;
761
58
762
50
  return false;
763
58
}
764
765
71
void JSONImporter::getAnalysisUsage(AnalysisUsage &AU) const {
766
71
  ScopPass::getAnalysisUsage(AU);
767
71
  AU.addRequired<DependenceInfo>();
768
71
}
769
770
0
Pass *polly::createJSONImporterPass() { return new JSONImporter(); }
771
772
41.0k
INITIALIZE_PASS_BEGIN41.0k
(JSONExporter, "polly-export-jscop",41.0k
773
41.0k
                      "Polly - Export Scops as JSON"
774
41.0k
                      " (Writes a .jscop file for each Scop)",
775
41.0k
                      false, false);
776
41.0k
INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
777
41.0k
INITIALIZE_PASS_END(JSONExporter, "polly-export-jscop",
778
                    "Polly - Export Scops as JSON"
779
                    " (Writes a .jscop file for each Scop)",
780
                    false, false)
781
782
41.0k
INITIALIZE_PASS_BEGIN41.0k
(JSONImporter, "polly-import-jscop",41.0k
783
41.0k
                      "Polly - Import Scops from JSON"
784
41.0k
                      " (Reads a .jscop file for each Scop)",
785
41.0k
                      false, false);
786
41.0k
INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
787
41.0k
INITIALIZE_PASS_END(JSONImporter, "polly-import-jscop",
788
                    "Polly - Import Scops from JSON"
789
                    " (Reads a .jscop file for each Scop)",
790
                    false, false)