Coverage Report

Created: 2019-02-23 12:57

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