Coverage Report

Created: 2018-04-24 22:41

/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/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 "json/reader.h"
34
#include "json/writer.h"
35
#include <memory>
36
#include <string>
37
#include <system_error>
38
39
using namespace llvm;
40
using namespace polly;
41
42
#define DEBUG_TYPE "polly-import-jscop"
43
44
STATISTIC(NewAccessMapFound, "Number of updated access functions");
45
46
namespace {
47
static cl::opt<std::string>
48
    ImportDir("polly-import-jscop-dir",
49
              cl::desc("The directory to import the .jscop files from."),
50
              cl::Hidden, cl::value_desc("Directory path"), cl::ValueRequired,
51
              cl::init("."), cl::cat(PollyCategory));
52
53
static cl::opt<std::string>
54
    ImportPostfix("polly-import-jscop-postfix",
55
                  cl::desc("Postfix to append to the import .jsop files."),
56
                  cl::Hidden, cl::value_desc("File postfix"), cl::ValueRequired,
57
                  cl::init(""), cl::cat(PollyCategory));
58
59
struct JSONExporter : public ScopPass {
60
  static char ID;
61
0
  explicit JSONExporter() : ScopPass(ID) {}
62
63
  /// Export the SCoP @p S to a JSON file.
64
  bool runOnScop(Scop &S) override;
65
66
  /// Print the SCoP @p S as it is exported.
67
  void printScop(raw_ostream &OS, Scop &S) const override;
68
69
  /// Register all analyses and transformation required.
70
  void getAnalysisUsage(AnalysisUsage &AU) const override;
71
};
72
73
struct JSONImporter : public ScopPass {
74
  static char ID;
75
  std::vector<std::string> NewAccessStrings;
76
96
  explicit JSONImporter() : ScopPass(ID) {}
77
  /// Import new access functions for SCoP @p S from a JSON file.
78
  bool runOnScop(Scop &S) override;
79
80
  /// Print the SCoP @p S and the imported access functions.
81
  void printScop(raw_ostream &OS, Scop &S) const override;
82
83
  /// Register all analyses and transformation required.
84
  void getAnalysisUsage(AnalysisUsage &AU) const override;
85
};
86
} // namespace
87
88
97
static std::string getFileName(Scop &S, StringRef Suffix = "") {
89
97
  std::string FunctionName = S.getFunction().getName();
90
97
  std::string FileName = FunctionName + "___" + S.getNameStr() + ".jscop";
91
97
92
97
  if (Suffix != "")
93
58
    FileName += "." + Suffix.str();
94
97
95
97
  return FileName;
96
97
}
97
98
/// Export all arrays from the Scop.
99
///
100
/// @param S The Scop containing the arrays.
101
///
102
/// @returns Json::Value containing the arrays.
103
0
static Json::Value exportArrays(const Scop &S) {
104
0
  Json::Value Arrays;
105
0
  std::string Buffer;
106
0
  llvm::raw_string_ostream RawStringOstream(Buffer);
107
0
108
0
  for (auto &SAI : S.arrays()) {
109
0
    if (!SAI->isArrayKind())
110
0
      continue;
111
0
112
0
    Json::Value Array;
113
0
    Array["name"] = SAI->getName();
114
0
    unsigned i = 0;
115
0
    if (!SAI->getDimensionSize(i)) {
116
0
      Array["sizes"].append("*");
117
0
      i++;
118
0
    }
119
0
    for (; i < SAI->getNumberOfDimensions(); i++) {
120
0
      SAI->getDimensionSize(i)->print(RawStringOstream);
121
0
      Array["sizes"].append(RawStringOstream.str());
122
0
      Buffer.clear();
123
0
    }
124
0
    SAI->getElementType()->print(RawStringOstream);
125
0
    Array["type"] = RawStringOstream.str();
126
0
    Buffer.clear();
127
0
    Arrays.append(Array);
128
0
  }
129
0
  return Arrays;
130
0
}
131
132
0
static Json::Value getJSON(Scop &S) {
133
0
  Json::Value 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
  for (ScopStmt &Stmt : S) {
153
0
    Json::Value statement;
154
0
155
0
    statement["name"] = Stmt.getBaseName();
156
0
    statement["domain"] = Stmt.getDomainStr();
157
0
    statement["schedule"] = Stmt.getScheduleStr();
158
0
    statement["accesses"];
159
0
160
0
    for (MemoryAccess *MA : Stmt) {
161
0
      Json::Value access;
162
0
163
0
      access["kind"] = MA->isRead() ? "read" : "write";
164
0
      access["relation"] = MA->getAccessRelationStr();
165
0
166
0
      statement["accesses"].append(access);
167
0
    }
168
0
169
0
    root["statements"].append(statement);
170
0
  }
171
0
172
0
  return root;
173
0
}
174
175
0
static void exportScop(Scop &S) {
176
0
  std::string FileName = ImportDir + "/" + getFileName(S);
177
0
178
0
  Json::Value jscop = getJSON(S);
179
0
  Json::StyledWriter writer;
180
0
  std::string fileContent = writer.write(jscop);
181
0
182
0
  // Write to file.
183
0
  std::error_code EC;
184
0
  ToolOutputFile F(FileName, EC, llvm::sys::fs::F_Text);
185
0
186
0
  std::string FunctionName = S.getFunction().getName();
187
0
  errs() << "Writing JScop '" << S.getNameStr() << "' in function '"
188
0
         << FunctionName << "' to '" << FileName << "'.\n";
189
0
190
0
  if (!EC) {
191
0
    F.os() << fileContent;
192
0
    F.os().close();
193
0
    if (!F.os().has_error()) {
194
0
      errs() << "\n";
195
0
      F.keep();
196
0
      return;
197
0
    }
198
0
  }
199
0
200
0
  errs() << "  error opening file for writing!\n";
201
0
  F.os().clear_error();
202
0
}
203
204
typedef Dependences::StatementToIslMapTy StatementToIslMapTy;
205
206
/// Import a new context from JScop.
207
///
208
/// @param S The scop to update.
209
/// @param JScop The JScop file describing the new schedule.
210
///
211
/// @returns True if the import succeeded, otherwise False.
212
97
static bool importContext(Scop &S, Json::Value &JScop) {
213
97
  isl::set OldContext = S.getContext();
214
97
215
97
  // Check if key 'context' is present.
216
97
  if (!JScop.isMember("context")) {
217
1
    errs() << "JScop file has no key named 'context'.\n";
218
1
    return false;
219
1
  }
220
96
221
96
  isl::set NewContext =
222
96
      isl::set{S.getIslCtx().get(), JScop["context"].asString()};
223
96
224
96
  // Check whether the context was parsed successfully.
225
96
  if (!NewContext) {
226
1
    errs() << "The context was not parsed successfully by ISL.\n";
227
1
    return false;
228
1
  }
229
95
230
95
  // Check if the isl_set is a parameter set.
231
95
  if (!NewContext.is_params()) {
232
1
    errs() << "The isl_set is not a parameter set.\n";
233
1
    return false;
234
1
  }
235
94
236
94
  unsigned OldContextDim = OldContext.dim(isl::dim::param);
237
94
  unsigned NewContextDim = NewContext.dim(isl::dim::param);
238
94
239
94
  // Check if the imported context has the right number of parameters.
240
94
  if (OldContextDim != NewContextDim) {
241
1
    errs() << "Imported context has the wrong number of parameters : "
242
1
           << "Found " << NewContextDim << " Expected " << OldContextDim
243
1
           << "\n";
244
1
    return false;
245
1
  }
246
93
247
153
  
for (unsigned i = 0; 93
i < OldContextDim;
i++60
) {
248
60
    isl::id Id = OldContext.get_dim_id(isl::dim::param, i);
249
60
    NewContext = NewContext.set_dim_id(isl::dim::param, i, Id);
250
60
  }
251
93
252
93
  S.setContext(NewContext);
253
93
  return true;
254
93
}
255
256
/// Import a new schedule from JScop.
257
///
258
/// ... and verify that the new schedule does preserve existing data
259
/// dependences.
260
///
261
/// @param S The scop to update.
262
/// @param JScop The JScop file describing the new schedule.
263
/// @param D The data dependences of the @p S.
264
///
265
/// @returns True if the import succeeded, otherwise False.
266
93
static bool importSchedule(Scop &S, Json::Value &JScop, const Dependences &D) {
267
93
  StatementToIslMapTy NewSchedule;
268
93
269
93
  // Check if key 'statements' is present.
270
93
  if (!JScop.isMember("statements")) {
271
2
    errs() << "JScop file has no key name 'statements'.\n";
272
2
    return false;
273
2
  }
274
91
275
91
  Json::Value statements = JScop["statements"];
276
91
277
91
  // Check whether the number of indices equals the number of statements
278
91
  if (statements.size() != S.getSize()) {
279
2
    errs() << "The number of indices and the number of statements differ.\n";
280
2
    return false;
281
2
  }
282
89
283
89
  int Index = 0;
284
138
  for (ScopStmt &Stmt : S) {
285
138
    // Check if key 'schedule' is present.
286
138
    if (!statements[Index].isMember("schedule")) {
287
1
      errs() << "Statement " << Index << " has no 'schedule' key.\n";
288
1
      for (auto Element : NewSchedule) {
289
0
        isl_map_free(Element.second);
290
0
      }
291
1
      return false;
292
1
    }
293
137
    Json::Value Schedule = statements[Index]["schedule"];
294
137
    assert(!Schedule.asString().empty() &&
295
137
           "Schedules that contain extension nodes require special handling.");
296
137
    isl_map *Map =
297
137
        isl_map_read_from_str(S.getIslCtx().get(), Schedule.asCString());
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
      for (auto Element : NewSchedule) {
304
1
        isl_map_free(Element.second);
305
1
      }
306
1
      return false;
307
1
    }
308
136
309
136
    isl_space *Space = Stmt.getDomainSpace().release();
310
136
311
136
    // Copy the old tuple id. This is necessary to retain the user pointer,
312
136
    // that stores the reference to the ScopStmt this schedule belongs to.
313
136
    Map = isl_map_set_tuple_id(Map, isl_dim_in,
314
136
                               isl_space_get_tuple_id(Space, isl_dim_set));
315
224
    for (unsigned i = 0; i < isl_space_dim(Space, isl_dim_param); 
i++88
) {
316
88
      isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
317
88
      Map = isl_map_set_dim_id(Map, isl_dim_param, i, Id);
318
88
    }
319
136
    isl_space_free(Space);
320
136
    NewSchedule[&Stmt] = Map;
321
136
    Index++;
322
136
  }
323
89
324
89
  // Check whether the new schedule is valid or not.
325
89
  
if (87
!D.isValidSchedule(S, &NewSchedule)87
) {
326
0
    errs() << "JScop file contains a schedule that changes the "
327
0
           << "dependences. Use -disable-polly-legality to continue anyways\n";
328
0
    for (auto Element : NewSchedule)
329
0
      isl_map_free(Element.second);
330
0
    return false;
331
0
  }
332
87
333
87
  auto ScheduleMap = isl::union_map::empty(S.getParamSpace());
334
135
  for (ScopStmt &Stmt : S) {
335
135
    if (NewSchedule.find(&Stmt) != NewSchedule.end())
336
135
      ScheduleMap = ScheduleMap.add_map(isl::manage(NewSchedule[&Stmt]));
337
0
    else
338
0
      ScheduleMap = ScheduleMap.add_map(Stmt.getSchedule());
339
135
  }
340
87
341
87
  S.setSchedule(ScheduleMap);
342
87
343
87
  return true;
344
87
}
345
346
/// Import new memory accesses from JScop.
347
///
348
/// @param S The scop to update.
349
/// @param JScop The JScop file describing the new schedule.
350
/// @param DL The data layout to assume.
351
/// @param NewAccessStrings optionally record the imported access strings
352
///
353
/// @returns True if the import succeeded, otherwise False.
354
static bool
355
importAccesses(Scop &S, Json::Value &JScop, const DataLayout &DL,
356
82
               std::vector<std::string> *NewAccessStrings = nullptr) {
357
82
  int StatementIdx = 0;
358
82
359
82
  // Check if key 'statements' is present.
360
82
  if (!JScop.isMember("statements")) {
361
0
    errs() << "JScop file has no key name 'statements'.\n";
362
0
    return false;
363
0
  }
364
82
  Json::Value statements = JScop["statements"];
365
82
366
82
  // Check whether the number of indices equals the number of statements
367
82
  if (statements.size() != S.getSize()) {
368
0
    errs() << "The number of indices and the number of statements differ.\n";
369
0
    return false;
370
0
  }
371
82
372
126
  
for (ScopStmt &Stmt : S)82
{
373
126
    int MemoryAccessIdx = 0;
374
126
375
126
    // Check if key 'accesses' is present.
376
126
    if (!statements[StatementIdx].isMember("accesses")) {
377
1
      errs()
378
1
          << "Statement from JScop file has no key name 'accesses' for index "
379
1
          << StatementIdx << ".\n";
380
1
      return false;
381
1
    }
382
125
383
125
    // Check whether the number of indices equals the number of memory
384
125
    // accesses
385
125
    if (Stmt.size() != statements[StatementIdx]["accesses"].size()) {
386
1
      errs() << "The number of memory accesses in the JSop file and the number "
387
1
                "of memory accesses differ for index "
388
1
             << StatementIdx << ".\n";
389
1
      return false;
390
1
    }
391
124
392
272
    
for (MemoryAccess *MA : Stmt)124
{
393
272
      // Check if key 'relation' is present.
394
272
      Json::Value JsonMemoryAccess =
395
272
          statements[StatementIdx]["accesses"][MemoryAccessIdx];
396
272
      if (!JsonMemoryAccess.isMember("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
      Json::Value Accesses = JsonMemoryAccess["relation"];
403
271
      isl_map *NewAccessMap =
404
271
          isl_map_read_from_str(S.getIslCtx().get(), Accesses.asCString());
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.asCString());
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, Json::Value 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.isMember("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.isMember("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.isMember("name")) {
569
1
    errs() << "Array has no key 'name'.\n";
570
1
    return false;
571
1
  }
572
65
573
65
  if (SAI->getName() != Array["name"].asCString())
574
0
    return false;
575
65
576
65
  if (SAI->getNumberOfDimensions() != Array["sizes"].size())
577
0
    return false;
578
65
579
83
  
for (unsigned i = 1; 65
i < Array["sizes"].size();
i++18
) {
580
18
    SAI->getDimensionSize(i)->print(RawStringOstream);
581
18
    if (RawStringOstream.str() != Array["sizes"][i].asCString())
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["type"].asCString()) {
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, Json::Value &JScop) {
635
87
  Json::Value Arrays = JScop["arrays"];
636
87
  if (Arrays.size() == 0)
637
41
    return true;
638
46
639
46
  unsigned ArrayIdx = 0;
640
108
  for (auto &SAI : S.arrays()) {
641
108
    if (!SAI->isArrayKind())
642
40
      continue;
643
68
    if (ArrayIdx + 1 > Arrays.size()) {
644
0
      errs() << "Not enough array entries in JScop file.\n";
645
0
      return false;
646
0
    }
647
68
    if (!areArraysEqual(SAI, Arrays[ArrayIdx])) {
648
4
      errs() << "No match for array '" << SAI->getName() << "' in JScop.\n";
649
4
      return false;
650
4
    }
651
64
    ArrayIdx++;
652
64
  }
653
46
654
54
  
for (; 42
ArrayIdx < Arrays.size();
ArrayIdx++12
) {
655
13
    auto &Array = Arrays[ArrayIdx];
656
13
    auto *ElementType =
657
13
        parseTextType(Array["type"].asCString(), S.getSE()->getContext());
658
13
    if (!ElementType) {
659
0
      errs() << "Error while parsing element type for new array.\n";
660
0
      return false;
661
0
    }
662
13
    std::vector<unsigned> DimSizes;
663
29
    for (unsigned i = 0; i < Array["sizes"].size(); 
i++16
) {
664
17
      auto Size = std::stoi(Array["sizes"][i].asCString());
665
17
666
17
      // Check if the size if positive.
667
17
      if (Size <= 0) {
668
1
        errs() << "The size at index " << i << " is =< 0.\n";
669
1
        return false;
670
1
      }
671
16
672
16
      DimSizes.push_back(Size);
673
16
    }
674
13
675
13
    auto NewSAI =
676
12
        S.createScopArrayInfo(ElementType, Array["name"].asCString(), DimSizes);
677
12
678
12
    if (Array.isMember("allocation")) {
679
6
      NewSAI->setIsOnHeap(Array["allocation"].asString() == "heap");
680
6
    }
681
12
  }
682
42
683
42
  
return true41
;
684
42
}
685
686
/// Import a Scop from a JSCOP file
687
/// @param S The scop to be modified
688
/// @param D Dependence Info
689
/// @param DL The DataLayout of the function
690
/// @param NewAccessStrings Optionally record the imported access strings
691
///
692
/// @returns true on success, false otherwise. Beware that if this returns
693
/// false, the Scop may still have been modified. In this case the Scop contains
694
/// invalid information.
695
static bool importScop(Scop &S, const Dependences &D, const DataLayout &DL,
696
97
                       std::vector<std::string> *NewAccessStrings = nullptr) {
697
97
  std::string FileName = ImportDir + "/" + getFileName(S, ImportPostfix);
698
97
699
97
  std::string FunctionName = S.getFunction().getName();
700
97
  errs() << "Reading JScop '" << S.getNameStr() << "' in function '"
701
97
         << FunctionName << "' from '" << FileName << "'.\n";
702
97
  ErrorOr<std::unique_ptr<MemoryBuffer>> result =
703
97
      MemoryBuffer::getFile(FileName);
704
97
  std::error_code ec = result.getError();
705
97
706
97
  if (ec) {
707
0
    errs() << "File could not be read: " << ec.message() << "\n";
708
0
    return false;
709
0
  }
710
97
711
97
  Json::Reader reader;
712
97
  Json::Value jscop;
713
97
714
97
  bool parsingSuccessful = reader.parse(result.get()->getBufferStart(), jscop);
715
97
716
97
  if (!parsingSuccessful) {
717
0
    errs() << "JSCoP file could not be parsed\n";
718
0
    return false;
719
0
  }
720
97
721
97
  bool Success = importContext(S, jscop);
722
97
723
97
  if (!Success)
724
4
    return false;
725
93
726
93
  Success = importSchedule(S, jscop, D);
727
93
728
93
  if (!Success)
729
6
    return false;
730
87
731
87
  Success = importArrays(S, jscop);
732
87
733
87
  if (!Success)
734
5
    return false;
735
82
736
82
  Success = importAccesses(S, jscop, DL, NewAccessStrings);
737
82
738
82
  if (!Success)
739
7
    return false;
740
75
  return true;
741
75
}
742
743
char JSONExporter::ID = 0;
744
0
void JSONExporter::printScop(raw_ostream &OS, Scop &S) const { OS << S; }
745
746
0
bool JSONExporter::runOnScop(Scop &S) {
747
0
  exportScop(S);
748
0
  return false;
749
0
}
750
751
0
void JSONExporter::getAnalysisUsage(AnalysisUsage &AU) const {
752
0
  AU.setPreservesAll();
753
0
  AU.addRequired<ScopInfoRegionPass>();
754
0
}
755
756
0
Pass *polly::createJSONExporterPass() { return new JSONExporter(); }
757
758
PreservedAnalyses JSONExportPass::run(Scop &S, ScopAnalysisManager &SAM,
759
                                      ScopStandardAnalysisResults &SAR,
760
0
                                      SPMUpdater &) {
761
0
  exportScop(S);
762
0
  return PreservedAnalyses::all();
763
0
}
764
765
char JSONImporter::ID = 0;
766
767
41
void JSONImporter::printScop(raw_ostream &OS, Scop &S) const {
768
41
  OS << S;
769
41
  for (std::vector<std::string>::const_iterator I = NewAccessStrings.begin(),
770
41
                                                E = NewAccessStrings.end();
771
120
       I != E; 
I++79
)
772
79
    OS << "New access function '" << *I << "' detected in JSCOP file\n";
773
41
}
774
775
97
bool JSONImporter::runOnScop(Scop &S) {
776
97
  const Dependences &D =
777
97
      getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
778
97
  const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
779
97
780
97
  if (!importScop(S, D, DL, &NewAccessStrings))
781
22
    report_fatal_error("Tried to import a malformed jscop file.");
782
75
783
75
  return false;
784
75
}
785
786
96
void JSONImporter::getAnalysisUsage(AnalysisUsage &AU) const {
787
96
  ScopPass::getAnalysisUsage(AU);
788
96
  AU.addRequired<DependenceInfo>();
789
96
790
96
  // TODO: JSONImporter should throw away DependenceInfo.
791
96
  AU.addPreserved<DependenceInfo>();
792
96
}
793
794
0
Pass *polly::createJSONImporterPass() { return new JSONImporter(); }
795
796
PreservedAnalyses JSONImportPass::run(Scop &S, ScopAnalysisManager &SAM,
797
                                      ScopStandardAnalysisResults &SAR,
798
0
                                      SPMUpdater &) {
799
0
  const Dependences &D =
800
0
      SAM.getResult<DependenceAnalysis>(S, SAR).getDependences(
801
0
          Dependences::AL_Statement);
802
0
  const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
803
0
804
0
  if (!importScop(S, D, DL))
805
0
    report_fatal_error("Tried to import a malformed jscop file.");
806
0
807
0
  // This invalidates all analyses on Scop.
808
0
  PreservedAnalyses PA;
809
0
  PA.preserveSet<AllAnalysesOn<Module>>();
810
0
  PA.preserveSet<AllAnalysesOn<Function>>();
811
0
  PA.preserveSet<AllAnalysesOn<Loop>>();
812
0
  return PA;
813
0
}
814
815
43.0k
INITIALIZE_PASS_BEGIN(JSONExporter, "polly-export-jscop",
816
43.0k
                      "Polly - Export Scops as JSON"
817
43.0k
                      " (Writes a .jscop file for each Scop)",
818
43.0k
                      false, false);
819
43.0k
INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
820
43.0k
INITIALIZE_PASS_END(JSONExporter, "polly-export-jscop",
821
                    "Polly - Export Scops as JSON"
822
                    " (Writes a .jscop file for each Scop)",
823
                    false, false)
824
825
43.0k
INITIALIZE_PASS_BEGIN(JSONImporter, "polly-import-jscop",
826
43.0k
                      "Polly - Import Scops from JSON"
827
43.0k
                      " (Reads a .jscop file for each Scop)",
828
43.0k
                      false, false);
829
43.0k
INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
830
43.0k
INITIALIZE_PASS_END(JSONImporter, "polly-import-jscop",
831
                    "Polly - Import Scops from JSON"
832
                    " (Reads a .jscop file for each Scop)",
833
                    false, false)