Coverage Report

Created: 2018-08-14 02:14

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