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/LinkAllPasses.h"
15 #include "polly/Dependences.h"
16 #include "polly/Options.h"
17 #include "polly/ScopInfo.h"
18 #include "polly/ScopPass.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Assembly/Writer.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/ToolOutputFile.h"
24 #include "llvm/Support/system_error.h"
25 
26 #define DEBUG_TYPE "polly-import-jscop"
27 
28 #include "json/reader.h"
29 #include "json/writer.h"
30 
31 #include "isl/set.h"
32 #include "isl/map.h"
33 #include "isl/constraint.h"
34 #include "isl/printer.h"
35 
36 #include <string>
37 
38 using namespace llvm;
39 using namespace polly;
40 
41 STATISTIC(NewAccessMapFound, "Number of updated access functions");
42 
43 namespace {
44 static cl::opt<std::string>
45 ImportDir("polly-import-jscop-dir",
46           cl::desc("The directory to import the .jscop files from."),
47           cl::Hidden, cl::value_desc("Directory path"), cl::ValueRequired,
48           cl::init("."), cl::cat(PollyCategory));
49 
50 static cl::opt<std::string>
51 ImportPostfix("polly-import-jscop-postfix",
52               cl::desc("Postfix to append to the import .jsop files."),
53               cl::Hidden, cl::value_desc("File postfix"), cl::ValueRequired,
54               cl::init(""), cl::cat(PollyCategory));
55 
56 struct JSONExporter : public ScopPass {
57   static char ID;
58   Scop *S;
59   explicit JSONExporter() : ScopPass(ID) {}
60 
61   std::string getFileName(Scop *S) const;
62   Json::Value getJSON(Scop &scop) const;
63   virtual bool runOnScop(Scop &S);
64   void printScop(raw_ostream &OS) const;
65   void getAnalysisUsage(AnalysisUsage &AU) const;
66 };
67 
68 struct JSONImporter : public ScopPass {
69   static char ID;
70   Scop *S;
71   std::vector<std::string> newAccessStrings;
72   explicit JSONImporter() : ScopPass(ID) {}
73 
74   std::string getFileName(Scop *S) const;
75   virtual bool runOnScop(Scop &S);
76   void printScop(raw_ostream &OS) const;
77   void getAnalysisUsage(AnalysisUsage &AU) const;
78 };
79 
80 }
81 
82 char JSONExporter::ID = 0;
83 std::string JSONExporter::getFileName(Scop *S) const {
84   std::string FunctionName = S->getRegion().getEntry()->getParent()->getName();
85   std::string FileName = FunctionName + "___" + S->getNameStr() + ".jscop";
86   return FileName;
87 }
88 
89 void JSONExporter::printScop(raw_ostream &OS) const { S->print(OS); }
90 
91 Json::Value JSONExporter::getJSON(Scop &scop) const {
92   Json::Value root;
93 
94   root["name"] = S->getRegion().getNameStr();
95   root["context"] = S->getContextStr();
96   root["statements"];
97 
98   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
99     ScopStmt *Stmt = *SI;
100 
101     Json::Value statement;
102 
103     statement["name"] = Stmt->getBaseName();
104     statement["domain"] = Stmt->getDomainStr();
105     statement["schedule"] = Stmt->getScatteringStr();
106     statement["accesses"];
107 
108     for (ScopStmt::memacc_iterator MI = Stmt->memacc_begin(),
109                                    ME = Stmt->memacc_end();
110          MI != ME; ++MI) {
111       Json::Value access;
112 
113       access["kind"] = (*MI)->isRead() ? "read" : "write";
114       access["relation"] = (*MI)->getAccessRelationStr();
115 
116       statement["accesses"].append(access);
117     }
118 
119     root["statements"].append(statement);
120   }
121 
122   return root;
123 }
124 
125 bool JSONExporter::runOnScop(Scop &scop) {
126   S = &scop;
127   Region &R = S->getRegion();
128 
129   std::string FileName = ImportDir + "/" + getFileName(S);
130 
131   Json::Value jscop = getJSON(scop);
132   Json::StyledWriter writer;
133   std::string fileContent = writer.write(jscop);
134 
135   // Write to file.
136   std::string ErrInfo;
137   tool_output_file F(FileName.c_str(), ErrInfo);
138 
139   std::string FunctionName = R.getEntry()->getParent()->getName();
140   errs() << "Writing JScop '" << R.getNameStr() << "' in function '"
141          << FunctionName << "' to '" << FileName << "'.\n";
142 
143   if (ErrInfo.empty()) {
144     F.os() << fileContent;
145     F.os().close();
146     if (!F.os().has_error()) {
147       errs() << "\n";
148       F.keep();
149       return false;
150     }
151   }
152 
153   errs() << "  error opening file for writing!\n";
154   F.os().clear_error();
155 
156   return false;
157 }
158 
159 void JSONExporter::getAnalysisUsage(AnalysisUsage &AU) const {
160   AU.setPreservesAll();
161   AU.addRequired<ScopInfo>();
162 }
163 
164 Pass *polly::createJSONExporterPass() { return new JSONExporter(); }
165 
166 char JSONImporter::ID = 0;
167 std::string JSONImporter::getFileName(Scop *S) const {
168   std::string FunctionName = S->getRegion().getEntry()->getParent()->getName();
169   std::string FileName = FunctionName + "___" + S->getNameStr() + ".jscop";
170 
171   if (ImportPostfix != "")
172     FileName += "." + ImportPostfix;
173 
174   return FileName;
175 }
176 
177 void JSONImporter::printScop(raw_ostream &OS) const {
178   S->print(OS);
179   for (std::vector<std::string>::const_iterator I = newAccessStrings.begin(),
180                                                 E = newAccessStrings.end();
181        I != E; I++)
182     OS << "New access function '" << *I << "'detected in JSCOP file\n";
183 }
184 
185 typedef Dependences::StatementToIslMapTy StatementToIslMapTy;
186 
187 bool JSONImporter::runOnScop(Scop &scop) {
188   S = &scop;
189   Region &R = S->getRegion();
190   Dependences *D = &getAnalysis<Dependences>();
191 
192   std::string FileName = ImportDir + "/" + getFileName(S);
193 
194   std::string FunctionName = R.getEntry()->getParent()->getName();
195   errs() << "Reading JScop '" << R.getNameStr() << "' in function '"
196          << FunctionName << "' from '" << FileName << "'.\n";
197   OwningPtr<MemoryBuffer> result;
198   error_code ec = MemoryBuffer::getFile(FileName, result);
199 
200   if (ec) {
201     errs() << "File could not be read: " << ec.message() << "\n";
202     return false;
203   }
204 
205   Json::Reader reader;
206   Json::Value jscop;
207 
208   bool parsingSuccessful = reader.parse(result->getBufferStart(), jscop);
209 
210   if (!parsingSuccessful) {
211     errs() << "JSCoP file could not be parsed\n";
212     return false;
213   }
214 
215   isl_set *OldContext = S->getContext();
216   isl_set *NewContext =
217       isl_set_read_from_str(S->getIslCtx(), jscop["context"].asCString());
218 
219   for (unsigned i = 0; i < isl_set_dim(OldContext, isl_dim_param); i++) {
220     isl_id *id = isl_set_get_dim_id(OldContext, isl_dim_param, i);
221     NewContext = isl_set_set_dim_id(NewContext, isl_dim_param, i, id);
222 
223   }
224 
225   isl_set_free(OldContext);
226   S->setContext(NewContext);
227 
228   StatementToIslMapTy &NewScattering = *(new StatementToIslMapTy());
229 
230   int index = 0;
231 
232   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
233     Json::Value schedule = jscop["statements"][index]["schedule"];
234     isl_map *m = isl_map_read_from_str(S->getIslCtx(), schedule.asCString());
235     isl_space *Space = (*SI)->getDomainSpace();
236 
237     // Copy the old tuple id. This is necessary to retain the user pointer,
238     // that stores the reference to the ScopStmt this scattering belongs to.
239     m = isl_map_set_tuple_id(m, isl_dim_in,
240                              isl_space_get_tuple_id(Space, isl_dim_set));
241     isl_space_free(Space);
242     NewScattering[*SI] = m;
243     index++;
244   }
245 
246   if (!D->isValidScattering(&NewScattering)) {
247     errs() << "JScop file contains a scattering that changes the "
248            << "dependences. Use -disable-polly-legality to continue anyways\n";
249     return false;
250   }
251 
252   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
253     ScopStmt *Stmt = *SI;
254 
255     if (NewScattering.find(Stmt) != NewScattering.end())
256       Stmt->setScattering(NewScattering[Stmt]);
257   }
258 
259   int statementIdx = 0;
260   for (Scop::iterator SI = S->begin(), SE = S->end(); SI != SE; ++SI) {
261     ScopStmt *Stmt = *SI;
262 
263     int memoryAccessIdx = 0;
264     for (ScopStmt::memacc_iterator MI = Stmt->memacc_begin(),
265                                    ME = Stmt->memacc_end();
266          MI != ME; ++MI) {
267       Json::Value accesses = jscop["statements"][statementIdx]["accesses"][
268           memoryAccessIdx]["relation"];
269       isl_map *newAccessMap =
270           isl_map_read_from_str(S->getIslCtx(), accesses.asCString());
271       isl_map *currentAccessMap = (*MI)->getAccessRelation();
272 
273       if (isl_map_dim(newAccessMap, isl_dim_param) !=
274           isl_map_dim(currentAccessMap, isl_dim_param)) {
275         errs() << "JScop file changes the number of parameter dimensions\n";
276         isl_map_free(currentAccessMap);
277         isl_map_free(newAccessMap);
278         return false;
279 
280       }
281 
282       // We need to copy the isl_ids for the parameter dimensions to the new
283       // map. Without doing this the current map would have different
284       // ids then the new one, even though both are named identically.
285       for (unsigned i = 0; i < isl_map_dim(currentAccessMap, isl_dim_param);
286            i++) {
287         isl_id *id = isl_map_get_dim_id(currentAccessMap, isl_dim_param, i);
288         newAccessMap = isl_map_set_dim_id(newAccessMap, isl_dim_param, i, id);
289       }
290 
291       // Copy the old tuple id. This is necessary to retain the user pointer,
292       // that stores the reference to the ScopStmt this access belongs to.
293       isl_id *Id = isl_map_get_tuple_id(currentAccessMap, isl_dim_in);
294       newAccessMap = isl_map_set_tuple_id(newAccessMap, isl_dim_in, Id);
295 
296       if (!isl_map_has_equal_space(currentAccessMap, newAccessMap)) {
297         errs() << "JScop file contains access function with incompatible "
298                << "dimensions\n";
299         isl_map_free(currentAccessMap);
300         isl_map_free(newAccessMap);
301         return false;
302       }
303       if (isl_map_dim(newAccessMap, isl_dim_out) != 1) {
304         errs() << "New access map in JScop file should be single dimensional\n";
305         isl_map_free(currentAccessMap);
306         isl_map_free(newAccessMap);
307         return false;
308       }
309       if (!isl_map_is_equal(newAccessMap, currentAccessMap)) {
310         // Statistics.
311         ++NewAccessMapFound;
312         newAccessStrings.push_back(accesses.asCString());
313         (*MI)->setNewAccessRelation(newAccessMap);
314       } else {
315         isl_map_free(newAccessMap);
316       }
317       isl_map_free(currentAccessMap);
318       memoryAccessIdx++;
319     }
320     statementIdx++;
321   }
322 
323   return false;
324 }
325 
326 void JSONImporter::getAnalysisUsage(AnalysisUsage &AU) const {
327   ScopPass::getAnalysisUsage(AU);
328   AU.addRequired<Dependences>();
329 }
330 Pass *polly::createJSONImporterPass() { return new JSONImporter(); }
331 
332 INITIALIZE_PASS_BEGIN(JSONExporter, "polly-export-jscop",
333                       "Polly - Export Scops as JSON"
334                       " (Writes a .jscop file for each Scop)",
335                       false, false);
336 INITIALIZE_PASS_DEPENDENCY(Dependences)
337 INITIALIZE_PASS_END(JSONExporter, "polly-export-jscop",
338                     "Polly - Export Scops as JSON"
339                     " (Writes a .jscop file for each Scop)",
340                     false, false)
341 
342 INITIALIZE_PASS_BEGIN(JSONImporter, "polly-import-jscop",
343                       "Polly - Import Scops from JSON"
344                       " (Reads a .jscop file for each Scop)",
345                       false, false);
346 INITIALIZE_PASS_DEPENDENCY(Dependences)
347 INITIALIZE_PASS_END(JSONImporter, "polly-import-jscop",
348                     "Polly - Import Scops from JSON"
349                     " (Reads a .jscop file for each Scop)",
350                     false, false)
351