175805378STobias Grosser //===-- JSONExporter.cpp  - Export Scops as JSON  -------------------------===//
275805378STobias Grosser //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
675805378STobias Grosser //
775805378STobias Grosser //===----------------------------------------------------------------------===//
875805378STobias Grosser //
975805378STobias Grosser // Export the Scops build by ScopInfo pass as a JSON file.
1075805378STobias Grosser //
1175805378STobias Grosser //===----------------------------------------------------------------------===//
1275805378STobias Grosser 
1347bf15c3SPhilip Pfaffe #include "polly/JSONExporter.h"
14f6557f98SJohannes Doerfert #include "polly/DependenceInfo.h"
155624d3c9STobias Grosser #include "polly/LinkAllPasses.h"
16637bd631STobias Grosser #include "polly/Options.h"
1775805378STobias Grosser #include "polly/ScopInfo.h"
1875805378STobias Grosser #include "polly/ScopPass.h"
1944596fe6SRiccardo Mori #include "polly/Support/ISLTools.h"
20a63b7ceeSTobias Grosser #include "polly/Support/ScopLocation.h"
213cb6628dSRaghesh Aloor #include "llvm/ADT/Statistic.h"
22140b394eSTobias Grosser #include "llvm/IR/Module.h"
23ff69b3c2SBenjamin Kramer #include "llvm/Support/FileSystem.h"
2423655020SMichael Kruse #include "llvm/Support/JSON.h"
2583628182STobias Grosser #include "llvm/Support/MemoryBuffer.h"
2683628182STobias Grosser #include "llvm/Support/ToolOutputFile.h"
27d7754a12SRoman Gareev #include "llvm/Support/raw_ostream.h"
28ba0d0922STobias Grosser #include "isl/map.h"
29ba0d0922STobias Grosser #include "isl/set.h"
30e653622bSSaleem Abdulrasool #include <memory>
3175805378STobias Grosser #include <string>
328730ee73SRafael Espindola #include <system_error>
3375805378STobias Grosser 
3475805378STobias Grosser using namespace llvm;
3575805378STobias Grosser using namespace polly;
3675805378STobias Grosser 
3795fef944SChandler Carruth #define DEBUG_TYPE "polly-import-jscop"
3895fef944SChandler Carruth 
393cb6628dSRaghesh Aloor STATISTIC(NewAccessMapFound, "Number of updated access functions");
403cb6628dSRaghesh Aloor 
4175805378STobias Grosser namespace {
42e602a076STobias Grosser static cl::opt<std::string>
43e602a076STobias Grosser     ImportDir("polly-import-jscop-dir",
44e602a076STobias Grosser               cl::desc("The directory to import the .jscop files from."),
45e602a076STobias Grosser               cl::Hidden, cl::value_desc("Directory path"), cl::ValueRequired,
46637bd631STobias Grosser               cl::init("."), cl::cat(PollyCategory));
47ca3bef84STobias Grosser 
48e602a076STobias Grosser static cl::opt<std::string>
49e602a076STobias Grosser     ImportPostfix("polly-import-jscop-postfix",
50e602a076STobias Grosser                   cl::desc("Postfix to append to the import .jsop files."),
51e602a076STobias Grosser                   cl::Hidden, cl::value_desc("File postfix"), cl::ValueRequired,
52637bd631STobias Grosser                   cl::init(""), cl::cat(PollyCategory));
5375805378STobias Grosser 
54bd93df93SMichael Kruse class JSONExporter : public ScopPass {
55bd93df93SMichael Kruse public:
5675805378STobias Grosser   static char ID;
JSONExporter()5775805378STobias Grosser   explicit JSONExporter() : ScopPass(ID) {}
5875805378STobias Grosser 
59c80d6979STobias Grosser   /// Export the SCoP @p S to a JSON file.
6045be6446SJohannes Doerfert   bool runOnScop(Scop &S) override;
6145be6446SJohannes Doerfert 
62c80d6979STobias Grosser   /// Print the SCoP @p S as it is exported.
6345be6446SJohannes Doerfert   void printScop(raw_ostream &OS, Scop &S) const override;
6445be6446SJohannes Doerfert 
65c80d6979STobias Grosser   /// Register all analyses and transformation required.
6645be6446SJohannes Doerfert   void getAnalysisUsage(AnalysisUsage &AU) const override;
6775805378STobias Grosser };
68ca3bef84STobias Grosser 
69bd93df93SMichael Kruse class JSONImporter : public ScopPass {
70bd93df93SMichael Kruse public:
7175805378STobias Grosser   static char ID;
729ea15271STobias Grosser   std::vector<std::string> NewAccessStrings;
JSONImporter()7375805378STobias Grosser   explicit JSONImporter() : ScopPass(ID) {}
74c80d6979STobias Grosser   /// Import new access functions for SCoP @p S from a JSON file.
7545be6446SJohannes Doerfert   bool runOnScop(Scop &S) override;
7645be6446SJohannes Doerfert 
77c80d6979STobias Grosser   /// Print the SCoP @p S and the imported access functions.
7845be6446SJohannes Doerfert   void printScop(raw_ostream &OS, Scop &S) const override;
7945be6446SJohannes Doerfert 
80c80d6979STobias Grosser   /// Register all analyses and transformation required.
8145be6446SJohannes Doerfert   void getAnalysisUsage(AnalysisUsage &AU) const override;
8275805378STobias Grosser };
83522478d2STobias Grosser } // namespace
8475805378STobias Grosser 
getFileName(Scop & S,StringRef Suffix="")8547bf15c3SPhilip Pfaffe static std::string getFileName(Scop &S, StringRef Suffix = "") {
860257a921SEli Friedman   std::string FunctionName = S.getFunction().getName().str();
87f94d5178SJohannes Doerfert   std::string FileName = FunctionName + "___" + S.getNameStr() + ".jscop";
8847bf15c3SPhilip Pfaffe 
8947bf15c3SPhilip Pfaffe   if (Suffix != "")
9047bf15c3SPhilip Pfaffe     FileName += "." + Suffix.str();
9147bf15c3SPhilip Pfaffe 
9275805378STobias Grosser   return FileName;
9375805378STobias Grosser }
9475805378STobias Grosser 
95d7754a12SRoman Gareev /// Export all arrays from the Scop.
96d7754a12SRoman Gareev ///
97d7754a12SRoman Gareev /// @param S The Scop containing the arrays.
98d7754a12SRoman Gareev ///
99d7754a12SRoman Gareev /// @returns Json::Value containing the arrays.
exportArrays(const Scop & S)10023655020SMichael Kruse static json::Array exportArrays(const Scop &S) {
10123655020SMichael Kruse   json::Array Arrays;
102d7754a12SRoman Gareev   std::string Buffer;
103d7754a12SRoman Gareev   llvm::raw_string_ostream RawStringOstream(Buffer);
104d7754a12SRoman Gareev 
105d7754a12SRoman Gareev   for (auto &SAI : S.arrays()) {
106d7754a12SRoman Gareev     if (!SAI->isArrayKind())
107d7754a12SRoman Gareev       continue;
108d7754a12SRoman Gareev 
10923655020SMichael Kruse     json::Object Array;
11023655020SMichael Kruse     json::Array Sizes;
111d7754a12SRoman Gareev     Array["name"] = SAI->getName();
112f5aff704SRoman Gareev     unsigned i = 0;
113f5aff704SRoman Gareev     if (!SAI->getDimensionSize(i)) {
11423655020SMichael Kruse       Sizes.push_back("*");
115f5aff704SRoman Gareev       i++;
116f5aff704SRoman Gareev     }
117f5aff704SRoman Gareev     for (; i < SAI->getNumberOfDimensions(); i++) {
118d7754a12SRoman Gareev       SAI->getDimensionSize(i)->print(RawStringOstream);
11923655020SMichael Kruse       Sizes.push_back(RawStringOstream.str());
120d7754a12SRoman Gareev       Buffer.clear();
121d7754a12SRoman Gareev     }
12223655020SMichael Kruse     Array["sizes"] = std::move(Sizes);
123d7754a12SRoman Gareev     SAI->getElementType()->print(RawStringOstream);
124d7754a12SRoman Gareev     Array["type"] = RawStringOstream.str();
125d7754a12SRoman Gareev     Buffer.clear();
12623655020SMichael Kruse     Arrays.push_back(std::move(Array));
127d7754a12SRoman Gareev   }
128d7754a12SRoman Gareev   return Arrays;
129d7754a12SRoman Gareev }
130d7754a12SRoman Gareev 
getJSON(Scop & S)13123655020SMichael Kruse static json::Value getJSON(Scop &S) {
13223655020SMichael Kruse   json::Object root;
133a63b7ceeSTobias Grosser   unsigned LineBegin, LineEnd;
134a63b7ceeSTobias Grosser   std::string FileName;
135a63b7ceeSTobias Grosser 
136a63b7ceeSTobias Grosser   getDebugLocation(&S.getRegion(), LineBegin, LineEnd, FileName);
137a63b7ceeSTobias Grosser   std::string Location;
138a63b7ceeSTobias Grosser   if (LineBegin != (unsigned)-1)
139a63b7ceeSTobias Grosser     Location = FileName + ":" + std::to_string(LineBegin) + "-" +
140a63b7ceeSTobias Grosser                std::to_string(LineEnd);
14175805378STobias Grosser 
1423f52e354SJohannes Doerfert   root["name"] = S.getNameStr();
143f94d5178SJohannes Doerfert   root["context"] = S.getContextStr();
144a63b7ceeSTobias Grosser   if (LineBegin != (unsigned)-1)
145a63b7ceeSTobias Grosser     root["location"] = Location;
146d7754a12SRoman Gareev 
147d7754a12SRoman Gareev   root["arrays"] = exportArrays(S);
148d7754a12SRoman Gareev 
14975805378STobias Grosser   root["statements"];
15075805378STobias Grosser 
15123655020SMichael Kruse   json::Array Statements;
1527c3bad52STobias Grosser   for (ScopStmt &Stmt : S) {
15323655020SMichael Kruse     json::Object statement;
15475805378STobias Grosser 
1557c3bad52STobias Grosser     statement["name"] = Stmt.getBaseName();
1567c3bad52STobias Grosser     statement["domain"] = Stmt.getDomainStr();
1577c3bad52STobias Grosser     statement["schedule"] = Stmt.getScheduleStr();
15875805378STobias Grosser 
15923655020SMichael Kruse     json::Array Accesses;
1607c3bad52STobias Grosser     for (MemoryAccess *MA : Stmt) {
16123655020SMichael Kruse       json::Object access;
16275805378STobias Grosser 
163f675289dSJohannes Doerfert       access["kind"] = MA->isRead() ? "read" : "write";
1646a4c12fbSTobias Grosser       access["relation"] = MA->getAccessRelationStr();
16575805378STobias Grosser 
16623655020SMichael Kruse       Accesses.push_back(std::move(access));
16723655020SMichael Kruse     }
16823655020SMichael Kruse     statement["accesses"] = std::move(Accesses);
16923655020SMichael Kruse 
17023655020SMichael Kruse     Statements.push_back(std::move(statement));
17175805378STobias Grosser   }
17275805378STobias Grosser 
17323655020SMichael Kruse   root["statements"] = std::move(Statements);
17437b3c177SMichael Kruse   return json::Value(std::move(root));
17575805378STobias Grosser }
17675805378STobias Grosser 
exportScop(Scop & S)17747bf15c3SPhilip Pfaffe static void exportScop(Scop &S) {
17875805378STobias Grosser   std::string FileName = ImportDir + "/" + getFileName(S);
17975805378STobias Grosser 
18023655020SMichael Kruse   json::Value jscop = getJSON(S);
18175805378STobias Grosser 
18275805378STobias Grosser   // Write to file.
183ac27f730SRafael Espindola   std::error_code EC;
18482b3e28eSAbhina Sreeskantharajan   ToolOutputFile F(FileName, EC, llvm::sys::fs::OF_TextWithCRLF);
18575805378STobias Grosser 
1860257a921SEli Friedman   std::string FunctionName = S.getFunction().getName().str();
1873f52e354SJohannes Doerfert   errs() << "Writing JScop '" << S.getNameStr() << "' in function '"
18875805378STobias Grosser          << FunctionName << "' to '" << FileName << "'.\n";
18975805378STobias Grosser 
190ac27f730SRafael Espindola   if (!EC) {
19123655020SMichael Kruse     F.os() << formatv("{0:3}", jscop);
19275805378STobias Grosser     F.os().close();
19375805378STobias Grosser     if (!F.os().has_error()) {
19475805378STobias Grosser       errs() << "\n";
19575805378STobias Grosser       F.keep();
19647bf15c3SPhilip Pfaffe       return;
19775805378STobias Grosser     }
19875805378STobias Grosser   }
19975805378STobias Grosser 
20075805378STobias Grosser   errs() << "  error opening file for writing!\n";
20175805378STobias Grosser   F.os().clear_error();
20275805378STobias Grosser }
20375805378STobias Grosser 
2047e6424baSJohannes Doerfert typedef Dependences::StatementToIslMapTy StatementToIslMapTy;
20575805378STobias Grosser 
20647bf15c3SPhilip Pfaffe /// Import a new context from JScop.
20747bf15c3SPhilip Pfaffe ///
20847bf15c3SPhilip Pfaffe /// @param S The scop to update.
20947bf15c3SPhilip Pfaffe /// @param JScop The JScop file describing the new schedule.
21047bf15c3SPhilip Pfaffe ///
21147bf15c3SPhilip Pfaffe /// @returns True if the import succeeded, otherwise False.
importContext(Scop & S,const json::Object & JScop)21223655020SMichael Kruse static bool importContext(Scop &S, const json::Object &JScop) {
21300fd43b3SPhilip Pfaffe   isl::set OldContext = S.getContext();
214cb58bd6cSMichael Kruse 
215cb58bd6cSMichael Kruse   // Check if key 'context' is present.
21623655020SMichael Kruse   if (!JScop.get("context")) {
217cb58bd6cSMichael Kruse     errs() << "JScop file has no key named 'context'.\n";
218cb58bd6cSMichael Kruse     return false;
219cb58bd6cSMichael Kruse   }
220cb58bd6cSMichael Kruse 
221*5cff5142SKazu Hirata   isl::set NewContext =
222*5cff5142SKazu Hirata       isl::set{S.getIslCtx().get(), JScop.getString("context").value().str()};
223dbe34f7cSTobias Grosser 
224cb58bd6cSMichael Kruse   // Check whether the context was parsed successfully.
2257c7978a1Spatacca   if (NewContext.is_null()) {
226cb58bd6cSMichael Kruse     errs() << "The context was not parsed successfully by ISL.\n";
227cb58bd6cSMichael Kruse     return false;
228cb58bd6cSMichael Kruse   }
229cb58bd6cSMichael Kruse 
230cb58bd6cSMichael Kruse   // Check if the isl_set is a parameter set.
23100fd43b3SPhilip Pfaffe   if (!NewContext.is_params()) {
232cb58bd6cSMichael Kruse     errs() << "The isl_set is not a parameter set.\n";
233cb58bd6cSMichael Kruse     return false;
234cb58bd6cSMichael Kruse   }
235cb58bd6cSMichael Kruse 
23644596fe6SRiccardo Mori   unsigned OldContextDim = unsignedFromIslSize(OldContext.dim(isl::dim::param));
23744596fe6SRiccardo Mori   unsigned NewContextDim = unsignedFromIslSize(NewContext.dim(isl::dim::param));
238cb58bd6cSMichael Kruse 
239cb58bd6cSMichael Kruse   // Check if the imported context has the right number of parameters.
240cb58bd6cSMichael Kruse   if (OldContextDim != NewContextDim) {
241cb58bd6cSMichael Kruse     errs() << "Imported context has the wrong number of parameters : "
242cb58bd6cSMichael Kruse            << "Found " << NewContextDim << " Expected " << OldContextDim
243cb58bd6cSMichael Kruse            << "\n";
244cb58bd6cSMichael Kruse     return false;
245cb58bd6cSMichael Kruse   }
246cb58bd6cSMichael Kruse 
247cb58bd6cSMichael Kruse   for (unsigned i = 0; i < OldContextDim; i++) {
24800fd43b3SPhilip Pfaffe     isl::id Id = OldContext.get_dim_id(isl::dim::param, i);
24900fd43b3SPhilip Pfaffe     NewContext = NewContext.set_dim_id(isl::dim::param, i, Id);
250dbe34f7cSTobias Grosser   }
251dbe34f7cSTobias Grosser 
252dbe34f7cSTobias Grosser   S.setContext(NewContext);
253dbe34f7cSTobias Grosser   return true;
254dbe34f7cSTobias Grosser }
255dbe34f7cSTobias Grosser 
25647bf15c3SPhilip Pfaffe /// Import a new schedule from JScop.
25747bf15c3SPhilip Pfaffe ///
25847bf15c3SPhilip Pfaffe /// ... and verify that the new schedule does preserve existing data
25947bf15c3SPhilip Pfaffe /// dependences.
26047bf15c3SPhilip Pfaffe ///
26147bf15c3SPhilip Pfaffe /// @param S The scop to update.
26247bf15c3SPhilip Pfaffe /// @param JScop The JScop file describing the new schedule.
26347bf15c3SPhilip Pfaffe /// @param D The data dependences of the @p S.
26447bf15c3SPhilip Pfaffe ///
26547bf15c3SPhilip Pfaffe /// @returns True if the import succeeded, otherwise False.
importSchedule(Scop & S,const json::Object & JScop,const Dependences & D)26623655020SMichael Kruse static bool importSchedule(Scop &S, const json::Object &JScop,
26723655020SMichael Kruse                            const Dependences &D) {
268c602d3bcSTobias Grosser   StatementToIslMapTy NewSchedule;
269c602d3bcSTobias Grosser 
270cb58bd6cSMichael Kruse   // Check if key 'statements' is present.
27123655020SMichael Kruse   if (!JScop.get("statements")) {
272cb58bd6cSMichael Kruse     errs() << "JScop file has no key name 'statements'.\n";
273cb58bd6cSMichael Kruse     return false;
274cb58bd6cSMichael Kruse   }
275cb58bd6cSMichael Kruse 
27623655020SMichael Kruse   const json::Array &statements = *JScop.getArray("statements");
277cb58bd6cSMichael Kruse 
278cb58bd6cSMichael Kruse   // Check whether the number of indices equals the number of statements
279cb58bd6cSMichael Kruse   if (statements.size() != S.getSize()) {
280cb58bd6cSMichael Kruse     errs() << "The number of indices and the number of statements differ.\n";
281cb58bd6cSMichael Kruse     return false;
282cb58bd6cSMichael Kruse   }
283cb58bd6cSMichael Kruse 
284c602d3bcSTobias Grosser   int Index = 0;
285c602d3bcSTobias Grosser   for (ScopStmt &Stmt : S) {
286cb58bd6cSMichael Kruse     // Check if key 'schedule' is present.
28723655020SMichael Kruse     if (!statements[Index].getAsObject()->get("schedule")) {
288cb58bd6cSMichael Kruse       errs() << "Statement " << Index << " has no 'schedule' key.\n";
289cb58bd6cSMichael Kruse       return false;
290cb58bd6cSMichael Kruse     }
29123655020SMichael Kruse     Optional<StringRef> Schedule =
29223655020SMichael Kruse         statements[Index].getAsObject()->getString("schedule");
293e5f568a4SKazu Hirata     assert(Schedule.has_value() &&
294b3224adfSRoman Gareev            "Schedules that contain extension nodes require special handling.");
2953b7c3a65SKazu Hirata     isl_map *Map = isl_map_read_from_str(S.getIslCtx().get(),
296*5cff5142SKazu Hirata                                          Schedule.value().str().c_str());
297cb58bd6cSMichael Kruse 
298cb58bd6cSMichael Kruse     // Check whether the schedule was parsed successfully
299cb58bd6cSMichael Kruse     if (!Map) {
300cb58bd6cSMichael Kruse       errs() << "The schedule was not parsed successfully (index = " << Index
301cb58bd6cSMichael Kruse              << ").\n";
302cb58bd6cSMichael Kruse       return false;
303cb58bd6cSMichael Kruse     }
304cb58bd6cSMichael Kruse 
305dcf8d696STobias Grosser     isl_space *Space = Stmt.getDomainSpace().release();
306c602d3bcSTobias Grosser 
307c602d3bcSTobias Grosser     // Copy the old tuple id. This is necessary to retain the user pointer,
308c602d3bcSTobias Grosser     // that stores the reference to the ScopStmt this schedule belongs to.
309c602d3bcSTobias Grosser     Map = isl_map_set_tuple_id(Map, isl_dim_in,
310c602d3bcSTobias Grosser                                isl_space_get_tuple_id(Space, isl_dim_set));
311d0240257SMichael Kruse     for (isl_size i = 0; i < isl_space_dim(Space, isl_dim_param); i++) {
312c602d3bcSTobias Grosser       isl_id *Id = isl_space_get_dim_id(Space, isl_dim_param, i);
313c602d3bcSTobias Grosser       Map = isl_map_set_dim_id(Map, isl_dim_param, i, Id);
314c602d3bcSTobias Grosser     }
315c602d3bcSTobias Grosser     isl_space_free(Space);
3160e4e6e5eSMichael Kruse     NewSchedule[&Stmt] = isl::manage(Map);
317c602d3bcSTobias Grosser     Index++;
318c602d3bcSTobias Grosser   }
319c602d3bcSTobias Grosser 
320cb58bd6cSMichael Kruse   // Check whether the new schedule is valid or not.
3210e4e6e5eSMichael Kruse   if (!D.isValidSchedule(S, NewSchedule)) {
322c602d3bcSTobias Grosser     errs() << "JScop file contains a schedule that changes the "
323c602d3bcSTobias Grosser            << "dependences. Use -disable-polly-legality to continue anyways\n";
324c602d3bcSTobias Grosser     return false;
325c602d3bcSTobias Grosser   }
326c602d3bcSTobias Grosser 
327bad3ebbaSRiccardo Mori   auto ScheduleMap = isl::union_map::empty(S.getIslCtx());
328c602d3bcSTobias Grosser   for (ScopStmt &Stmt : S) {
329c602d3bcSTobias Grosser     if (NewSchedule.find(&Stmt) != NewSchedule.end())
330d5ee355fSRiccardo Mori       ScheduleMap = ScheduleMap.unite(NewSchedule[&Stmt]);
331c602d3bcSTobias Grosser     else
332d5ee355fSRiccardo Mori       ScheduleMap = ScheduleMap.unite(Stmt.getSchedule());
333c602d3bcSTobias Grosser   }
334c602d3bcSTobias Grosser 
335c602d3bcSTobias Grosser   S.setSchedule(ScheduleMap);
336c602d3bcSTobias Grosser 
337c602d3bcSTobias Grosser   return true;
338c602d3bcSTobias Grosser }
339c602d3bcSTobias Grosser 
34047bf15c3SPhilip Pfaffe /// Import new memory accesses from JScop.
34147bf15c3SPhilip Pfaffe ///
34247bf15c3SPhilip Pfaffe /// @param S The scop to update.
34347bf15c3SPhilip Pfaffe /// @param JScop The JScop file describing the new schedule.
34447bf15c3SPhilip Pfaffe /// @param DL The data layout to assume.
34547bf15c3SPhilip Pfaffe /// @param NewAccessStrings optionally record the imported access strings
34647bf15c3SPhilip Pfaffe ///
34747bf15c3SPhilip Pfaffe /// @returns True if the import succeeded, otherwise False.
34847bf15c3SPhilip Pfaffe static bool
importAccesses(Scop & S,const json::Object & JScop,const DataLayout & DL,std::vector<std::string> * NewAccessStrings=nullptr)34923655020SMichael Kruse importAccesses(Scop &S, const json::Object &JScop, const DataLayout &DL,
35047bf15c3SPhilip Pfaffe                std::vector<std::string> *NewAccessStrings = nullptr) {
3519ea15271STobias Grosser   int StatementIdx = 0;
352cb58bd6cSMichael Kruse 
353cb58bd6cSMichael Kruse   // Check if key 'statements' is present.
35423655020SMichael Kruse   if (!JScop.get("statements")) {
355cb58bd6cSMichael Kruse     errs() << "JScop file has no key name 'statements'.\n";
356cb58bd6cSMichael Kruse     return false;
357cb58bd6cSMichael Kruse   }
35823655020SMichael Kruse   const json::Array &statements = *JScop.getArray("statements");
359cb58bd6cSMichael Kruse 
360cb58bd6cSMichael Kruse   // Check whether the number of indices equals the number of statements
361cb58bd6cSMichael Kruse   if (statements.size() != S.getSize()) {
362cb58bd6cSMichael Kruse     errs() << "The number of indices and the number of statements differ.\n";
363cb58bd6cSMichael Kruse     return false;
364cb58bd6cSMichael Kruse   }
365cb58bd6cSMichael Kruse 
3669ea15271STobias Grosser   for (ScopStmt &Stmt : S) {
3679ea15271STobias Grosser     int MemoryAccessIdx = 0;
36823655020SMichael Kruse     const json::Object *Statement = statements[StatementIdx].getAsObject();
36923655020SMichael Kruse     assert(Statement);
370cb58bd6cSMichael Kruse 
371cb58bd6cSMichael Kruse     // Check if key 'accesses' is present.
37223655020SMichael Kruse     if (!Statement->get("accesses")) {
373cb58bd6cSMichael Kruse       errs()
374cb58bd6cSMichael Kruse           << "Statement from JScop file has no key name 'accesses' for index "
375cb58bd6cSMichael Kruse           << StatementIdx << ".\n";
376cb58bd6cSMichael Kruse       return false;
377cb58bd6cSMichael Kruse     }
37823655020SMichael Kruse     const json::Array &JsonAccesses = *Statement->getArray("accesses");
379cb58bd6cSMichael Kruse 
380c3bcdc2fSPhilip Pfaffe     // Check whether the number of indices equals the number of memory
381c3bcdc2fSPhilip Pfaffe     // accesses
38223655020SMichael Kruse     if (Stmt.size() != JsonAccesses.size()) {
383cb58bd6cSMichael Kruse       errs() << "The number of memory accesses in the JSop file and the number "
384cb58bd6cSMichael Kruse                 "of memory accesses differ for index "
385cb58bd6cSMichael Kruse              << StatementIdx << ".\n";
386cb58bd6cSMichael Kruse       return false;
387cb58bd6cSMichael Kruse     }
388cb58bd6cSMichael Kruse 
3899ea15271STobias Grosser     for (MemoryAccess *MA : Stmt) {
390cb58bd6cSMichael Kruse       // Check if key 'relation' is present.
39123655020SMichael Kruse       const json::Object *JsonMemoryAccess =
39223655020SMichael Kruse           JsonAccesses[MemoryAccessIdx].getAsObject();
39323655020SMichael Kruse       assert(JsonMemoryAccess);
39423655020SMichael Kruse       if (!JsonMemoryAccess->get("relation")) {
395cb58bd6cSMichael Kruse         errs() << "Memory access number " << MemoryAccessIdx
396cb58bd6cSMichael Kruse                << " has no key name 'relation' for statement number "
397cb58bd6cSMichael Kruse                << StatementIdx << ".\n";
398cb58bd6cSMichael Kruse         return false;
399cb58bd6cSMichael Kruse       }
400ed8fceaaSKazu Hirata       StringRef Accesses = *JsonMemoryAccess->getString("relation");
4019ea15271STobias Grosser       isl_map *NewAccessMap =
40223655020SMichael Kruse           isl_map_read_from_str(S.getIslCtx().get(), Accesses.str().c_str());
403cb58bd6cSMichael Kruse 
404cb58bd6cSMichael Kruse       // Check whether the access was parsed successfully
405cb58bd6cSMichael Kruse       if (!NewAccessMap) {
406cb58bd6cSMichael Kruse         errs() << "The access was not parsed successfully by ISL.\n";
407cb58bd6cSMichael Kruse         return false;
408cb58bd6cSMichael Kruse       }
4091515f6b9STobias Grosser       isl_map *CurrentAccessMap = MA->getAccessRelation().release();
4109ea15271STobias Grosser 
411cb58bd6cSMichael Kruse       // Check if the number of parameter change
4129ea15271STobias Grosser       if (isl_map_dim(NewAccessMap, isl_dim_param) !=
4139ea15271STobias Grosser           isl_map_dim(CurrentAccessMap, isl_dim_param)) {
414cb58bd6cSMichael Kruse         errs() << "JScop file changes the number of parameter dimensions.\n";
4159ea15271STobias Grosser         isl_map_free(CurrentAccessMap);
4169ea15271STobias Grosser         isl_map_free(NewAccessMap);
4179ea15271STobias Grosser         return false;
4189ea15271STobias Grosser       }
4199ea15271STobias Grosser 
420d7754a12SRoman Gareev       isl_id *NewOutId;
421d7754a12SRoman Gareev 
4222fa35194SMichael Kruse       // If the NewAccessMap has zero dimensions, it is the scalar access; it
4232fa35194SMichael Kruse       // must be the same as before.
424c3bcdc2fSPhilip Pfaffe       // If it has at least one dimension, it's an array access; search for
425c3bcdc2fSPhilip Pfaffe       // its ScopArrayInfo.
4262fa35194SMichael Kruse       if (isl_map_dim(NewAccessMap, isl_dim_out) >= 1) {
427d7754a12SRoman Gareev         NewOutId = isl_map_get_tuple_id(NewAccessMap, isl_dim_out);
428d7754a12SRoman Gareev         auto *SAI = S.getArrayInfoByName(isl_id_get_name(NewOutId));
4299ea15271STobias Grosser         isl_id *OutId = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_out);
430206e9e3bSTobias Grosser         auto *OutSAI = ScopArrayInfo::getFromId(isl::manage(OutId));
431d7754a12SRoman Gareev         if (!SAI || SAI->getElementType() != OutSAI->getElementType()) {
432d7754a12SRoman Gareev           errs() << "JScop file contains access function with undeclared "
433d7754a12SRoman Gareev                     "ScopArrayInfo\n";
434d7754a12SRoman Gareev           isl_map_free(CurrentAccessMap);
435d7754a12SRoman Gareev           isl_map_free(NewAccessMap);
436d7754a12SRoman Gareev           isl_id_free(NewOutId);
437d7754a12SRoman Gareev           return false;
438d7754a12SRoman Gareev         }
439d7754a12SRoman Gareev         isl_id_free(NewOutId);
44077eef90fSTobias Grosser         NewOutId = SAI->getBasePtrId().release();
441d7754a12SRoman Gareev       } else {
442d7754a12SRoman Gareev         NewOutId = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_out);
443d7754a12SRoman Gareev       }
444d7754a12SRoman Gareev 
445d7754a12SRoman Gareev       NewAccessMap = isl_map_set_tuple_id(NewAccessMap, isl_dim_out, NewOutId);
4469ea15271STobias Grosser 
4479ea15271STobias Grosser       if (MA->isArrayKind()) {
4489ea15271STobias Grosser         // We keep the old alignment, thus we cannot allow accesses to memory
4499ea15271STobias Grosser         // locations that were not accessed before if the alignment of the
4509ea15271STobias Grosser         // access is not the default alignment.
4519ea15271STobias Grosser         bool SpecialAlignment = true;
4529ea15271STobias Grosser         if (LoadInst *LoadI = dyn_cast<LoadInst>(MA->getAccessInstruction())) {
4539ea15271STobias Grosser           SpecialAlignment =
4544296f913SGuillaume Chatelet               DL.getABITypeAlign(LoadI->getType()) != LoadI->getAlign();
4559ea15271STobias Grosser         } else if (StoreInst *StoreI =
4569ea15271STobias Grosser                        dyn_cast<StoreInst>(MA->getAccessInstruction())) {
4579ea15271STobias Grosser           SpecialAlignment =
4584296f913SGuillaume Chatelet               DL.getABITypeAlign(StoreI->getValueOperand()->getType()) !=
4594296f913SGuillaume Chatelet               StoreI->getAlign();
4609ea15271STobias Grosser         }
4619ea15271STobias Grosser 
4629ea15271STobias Grosser         if (SpecialAlignment) {
4639ea15271STobias Grosser           isl_set *NewAccessSet = isl_map_range(isl_map_copy(NewAccessMap));
4649ea15271STobias Grosser           isl_set *CurrentAccessSet =
4659ea15271STobias Grosser               isl_map_range(isl_map_copy(CurrentAccessMap));
4669ea15271STobias Grosser           bool IsSubset = isl_set_is_subset(NewAccessSet, CurrentAccessSet);
4679ea15271STobias Grosser           isl_set_free(NewAccessSet);
4689ea15271STobias Grosser           isl_set_free(CurrentAccessSet);
4699ea15271STobias Grosser 
470cb58bd6cSMichael Kruse           // Check if the JScop file changes the accessed memory.
4719ea15271STobias Grosser           if (!IsSubset) {
4729ea15271STobias Grosser             errs() << "JScop file changes the accessed memory\n";
4739ea15271STobias Grosser             isl_map_free(CurrentAccessMap);
4749ea15271STobias Grosser             isl_map_free(NewAccessMap);
4759ea15271STobias Grosser             return false;
4769ea15271STobias Grosser           }
4779ea15271STobias Grosser         }
4789ea15271STobias Grosser       }
4799ea15271STobias Grosser 
4809ea15271STobias Grosser       // We need to copy the isl_ids for the parameter dimensions to the new
4819ea15271STobias Grosser       // map. Without doing this the current map would have different
4829ea15271STobias Grosser       // ids then the new one, even though both are named identically.
483d0240257SMichael Kruse       for (isl_size i = 0; i < isl_map_dim(CurrentAccessMap, isl_dim_param);
4849ea15271STobias Grosser            i++) {
4859ea15271STobias Grosser         isl_id *Id = isl_map_get_dim_id(CurrentAccessMap, isl_dim_param, i);
4869ea15271STobias Grosser         NewAccessMap = isl_map_set_dim_id(NewAccessMap, isl_dim_param, i, Id);
4879ea15271STobias Grosser       }
4889ea15271STobias Grosser 
4899ea15271STobias Grosser       // Copy the old tuple id. This is necessary to retain the user pointer,
4909ea15271STobias Grosser       // that stores the reference to the ScopStmt this access belongs to.
4919ea15271STobias Grosser       isl_id *Id = isl_map_get_tuple_id(CurrentAccessMap, isl_dim_in);
4929ea15271STobias Grosser       NewAccessMap = isl_map_set_tuple_id(NewAccessMap, isl_dim_in, Id);
4939ea15271STobias Grosser 
494d7754a12SRoman Gareev       auto NewAccessDomain = isl_map_domain(isl_map_copy(NewAccessMap));
495d7754a12SRoman Gareev       auto CurrentAccessDomain = isl_map_domain(isl_map_copy(CurrentAccessMap));
496d7754a12SRoman Gareev 
497d7754a12SRoman Gareev       if (!isl_set_has_equal_space(NewAccessDomain, CurrentAccessDomain)) {
4989ea15271STobias Grosser         errs() << "JScop file contains access function with incompatible "
4999ea15271STobias Grosser                << "dimensions\n";
5009ea15271STobias Grosser         isl_map_free(CurrentAccessMap);
5019ea15271STobias Grosser         isl_map_free(NewAccessMap);
502d7754a12SRoman Gareev         isl_set_free(NewAccessDomain);
503d7754a12SRoman Gareev         isl_set_free(CurrentAccessDomain);
5049ea15271STobias Grosser         return false;
5059ea15271STobias Grosser       }
5069ea15271STobias Grosser 
5079ea15271STobias Grosser       NewAccessDomain =
5088ea1fc19STobias Grosser           isl_set_intersect_params(NewAccessDomain, S.getContext().release());
509b65ccc43STobias Grosser       CurrentAccessDomain = isl_set_intersect_params(CurrentAccessDomain,
510b65ccc43STobias Grosser                                                      S.getContext().release());
5114485ae08SMichael Kruse       CurrentAccessDomain =
5124485ae08SMichael Kruse           isl_set_intersect(CurrentAccessDomain, Stmt.getDomain().release());
5139ea15271STobias Grosser 
514706f79abSMichael Kruse       if (MA->isRead() &&
515706f79abSMichael Kruse           isl_set_is_subset(CurrentAccessDomain, NewAccessDomain) ==
5169ea15271STobias Grosser               isl_bool_false) {
5179ea15271STobias Grosser         errs() << "Mapping not defined for all iteration domain elements\n";
5189ea15271STobias Grosser         isl_set_free(CurrentAccessDomain);
5199ea15271STobias Grosser         isl_set_free(NewAccessDomain);
5209ea15271STobias Grosser         isl_map_free(CurrentAccessMap);
5219ea15271STobias Grosser         isl_map_free(NewAccessMap);
5229ea15271STobias Grosser         return false;
5239ea15271STobias Grosser       }
5249ea15271STobias Grosser 
5259ea15271STobias Grosser       isl_set_free(CurrentAccessDomain);
5269ea15271STobias Grosser       isl_set_free(NewAccessDomain);
5279ea15271STobias Grosser 
5289ea15271STobias Grosser       if (!isl_map_is_equal(NewAccessMap, CurrentAccessMap)) {
5299ea15271STobias Grosser         // Statistics.
5309ea15271STobias Grosser         ++NewAccessMapFound;
53147bf15c3SPhilip Pfaffe         if (NewAccessStrings)
5320257a921SEli Friedman           NewAccessStrings->push_back(Accesses.str());
5337b45af13STobias Grosser         MA->setNewAccessRelation(isl::manage(NewAccessMap));
5349ea15271STobias Grosser       } else {
5359ea15271STobias Grosser         isl_map_free(NewAccessMap);
5369ea15271STobias Grosser       }
5379ea15271STobias Grosser       isl_map_free(CurrentAccessMap);
5389ea15271STobias Grosser       MemoryAccessIdx++;
5399ea15271STobias Grosser     }
5409ea15271STobias Grosser     StatementIdx++;
5419ea15271STobias Grosser   }
5429ea15271STobias Grosser 
5439ea15271STobias Grosser   return true;
5449ea15271STobias Grosser }
5459ea15271STobias Grosser 
546c80d6979STobias Grosser /// Check whether @p SAI and @p Array represent the same array.
areArraysEqual(ScopArrayInfo * SAI,const json::Object & Array)54723655020SMichael Kruse static bool areArraysEqual(ScopArrayInfo *SAI, const json::Object &Array) {
548d7754a12SRoman Gareev   std::string Buffer;
549d7754a12SRoman Gareev   llvm::raw_string_ostream RawStringOstream(Buffer);
550d7754a12SRoman Gareev 
551cb58bd6cSMichael Kruse   // Check if key 'type' is present.
55223655020SMichael Kruse   if (!Array.get("type")) {
553cb58bd6cSMichael Kruse     errs() << "Array has no key 'type'.\n";
554cb58bd6cSMichael Kruse     return false;
555cb58bd6cSMichael Kruse   }
556cb58bd6cSMichael Kruse 
557cb58bd6cSMichael Kruse   // Check if key 'sizes' is present.
55823655020SMichael Kruse   if (!Array.get("sizes")) {
559cb58bd6cSMichael Kruse     errs() << "Array has no key 'sizes'.\n";
560cb58bd6cSMichael Kruse     return false;
561cb58bd6cSMichael Kruse   }
562cb58bd6cSMichael Kruse 
563cb58bd6cSMichael Kruse   // Check if key 'name' is present.
56423655020SMichael Kruse   if (!Array.get("name")) {
565cb58bd6cSMichael Kruse     errs() << "Array has no key 'name'.\n";
566cb58bd6cSMichael Kruse     return false;
567cb58bd6cSMichael Kruse   }
568cb58bd6cSMichael Kruse 
569ed8fceaaSKazu Hirata   if (SAI->getName() != *Array.getString("name"))
570d7754a12SRoman Gareev     return false;
571d7754a12SRoman Gareev 
57223655020SMichael Kruse   if (SAI->getNumberOfDimensions() != Array.getArray("sizes")->size())
573d7754a12SRoman Gareev     return false;
574d7754a12SRoman Gareev 
57523655020SMichael Kruse   for (unsigned i = 1; i < Array.getArray("sizes")->size(); i++) {
576f5aff704SRoman Gareev     SAI->getDimensionSize(i)->print(RawStringOstream);
57723655020SMichael Kruse     const json::Array &SizesArray = *Array.getArray("sizes");
578*5cff5142SKazu Hirata     if (RawStringOstream.str() != SizesArray[i].getAsString().value())
579d7754a12SRoman Gareev       return false;
580d7754a12SRoman Gareev     Buffer.clear();
581d7754a12SRoman Gareev   }
582d7754a12SRoman Gareev 
583cb58bd6cSMichael Kruse   // Check if key 'type' differs from the current one or is not valid.
584d7754a12SRoman Gareev   SAI->getElementType()->print(RawStringOstream);
585*5cff5142SKazu Hirata   if (RawStringOstream.str() != Array.getString("type").value()) {
586cb58bd6cSMichael Kruse     errs() << "Array has not a valid type.\n";
587d7754a12SRoman Gareev     return false;
588cb58bd6cSMichael Kruse   }
589d7754a12SRoman Gareev 
590d7754a12SRoman Gareev   return true;
591d7754a12SRoman Gareev }
592d7754a12SRoman Gareev 
593c80d6979STobias Grosser /// Get the accepted primitive type from its textual representation
594d7754a12SRoman Gareev ///        @p TypeTextRepresentation.
595d7754a12SRoman Gareev ///
596d7754a12SRoman Gareev /// @param TypeTextRepresentation The textual representation of the type.
597d7754a12SRoman Gareev /// @return The pointer to the primitive type, if this type is accepted
598d7754a12SRoman Gareev ///         or nullptr otherwise.
parseTextType(const std::string & TypeTextRepresentation,LLVMContext & LLVMContext)59947bf15c3SPhilip Pfaffe static Type *parseTextType(const std::string &TypeTextRepresentation,
600d7754a12SRoman Gareev                            LLVMContext &LLVMContext) {
601d7754a12SRoman Gareev   std::map<std::string, Type *> MapStrToType = {
602d7754a12SRoman Gareev       {"void", Type::getVoidTy(LLVMContext)},
603d7754a12SRoman Gareev       {"half", Type::getHalfTy(LLVMContext)},
604d7754a12SRoman Gareev       {"float", Type::getFloatTy(LLVMContext)},
605d7754a12SRoman Gareev       {"double", Type::getDoubleTy(LLVMContext)},
606d7754a12SRoman Gareev       {"x86_fp80", Type::getX86_FP80Ty(LLVMContext)},
607d7754a12SRoman Gareev       {"fp128", Type::getFP128Ty(LLVMContext)},
608d7754a12SRoman Gareev       {"ppc_fp128", Type::getPPC_FP128Ty(LLVMContext)},
609d7754a12SRoman Gareev       {"i1", Type::getInt1Ty(LLVMContext)},
610d7754a12SRoman Gareev       {"i8", Type::getInt8Ty(LLVMContext)},
611d7754a12SRoman Gareev       {"i16", Type::getInt16Ty(LLVMContext)},
612d7754a12SRoman Gareev       {"i32", Type::getInt32Ty(LLVMContext)},
613d7754a12SRoman Gareev       {"i64", Type::getInt64Ty(LLVMContext)},
614d7754a12SRoman Gareev       {"i128", Type::getInt128Ty(LLVMContext)}};
615d7754a12SRoman Gareev 
616d7754a12SRoman Gareev   auto It = MapStrToType.find(TypeTextRepresentation);
617d7754a12SRoman Gareev   if (It != MapStrToType.end())
618d7754a12SRoman Gareev     return It->second;
619d7754a12SRoman Gareev 
620d7754a12SRoman Gareev   errs() << "Textual representation can not be parsed: "
621d7754a12SRoman Gareev          << TypeTextRepresentation << "\n";
622d7754a12SRoman Gareev   return nullptr;
623d7754a12SRoman Gareev }
624d7754a12SRoman Gareev 
62547bf15c3SPhilip Pfaffe /// Import new arrays from JScop.
62647bf15c3SPhilip Pfaffe ///
62747bf15c3SPhilip Pfaffe /// @param S The scop to update.
62847bf15c3SPhilip Pfaffe /// @param JScop The JScop file describing new arrays.
62947bf15c3SPhilip Pfaffe ///
63047bf15c3SPhilip Pfaffe /// @returns True if the import succeeded, otherwise False.
importArrays(Scop & S,const json::Object & JScop)63123655020SMichael Kruse static bool importArrays(Scop &S, const json::Object &JScop) {
63223655020SMichael Kruse   if (!JScop.get("arrays"))
63323655020SMichael Kruse     return true;
63423655020SMichael Kruse   const json::Array &Arrays = *JScop.getArray("arrays");
635d7754a12SRoman Gareev   if (Arrays.size() == 0)
636d7754a12SRoman Gareev     return true;
637d7754a12SRoman Gareev 
638d7754a12SRoman Gareev   unsigned ArrayIdx = 0;
639d7754a12SRoman Gareev   for (auto &SAI : S.arrays()) {
640d7754a12SRoman Gareev     if (!SAI->isArrayKind())
641d7754a12SRoman Gareev       continue;
642281f414cSMichael Kruse     if (ArrayIdx + 1 > Arrays.size()) {
643281f414cSMichael Kruse       errs() << "Not enough array entries in JScop file.\n";
644d7754a12SRoman Gareev       return false;
645281f414cSMichael Kruse     }
64623655020SMichael Kruse     if (!areArraysEqual(SAI, *Arrays[ArrayIdx].getAsObject())) {
647281f414cSMichael Kruse       errs() << "No match for array '" << SAI->getName() << "' in JScop.\n";
648d7754a12SRoman Gareev       return false;
649281f414cSMichael Kruse     }
650d7754a12SRoman Gareev     ArrayIdx++;
651d7754a12SRoman Gareev   }
652d7754a12SRoman Gareev 
653d7754a12SRoman Gareev   for (; ArrayIdx < Arrays.size(); ArrayIdx++) {
65423655020SMichael Kruse     const json::Object &Array = *Arrays[ArrayIdx].getAsObject();
6553b7c3a65SKazu Hirata     auto *ElementType =
656*5cff5142SKazu Hirata         parseTextType(Array.get("type")->getAsString().value().str(),
6570257a921SEli Friedman                       S.getSE()->getContext());
658281f414cSMichael Kruse     if (!ElementType) {
659281f414cSMichael Kruse       errs() << "Error while parsing element type for new array.\n";
660d7754a12SRoman Gareev       return false;
661281f414cSMichael Kruse     }
66223655020SMichael Kruse     const json::Array &SizesArray = *Array.getArray("sizes");
663d7754a12SRoman Gareev     std::vector<unsigned> DimSizes;
66423655020SMichael Kruse     for (unsigned i = 0; i < SizesArray.size(); i++) {
665ed8fceaaSKazu Hirata       auto Size = std::stoi(SizesArray[i].getAsString()->str());
6666d08ec72SAndreas Simbuerger 
6676d08ec72SAndreas Simbuerger       // Check if the size if positive.
6686d08ec72SAndreas Simbuerger       if (Size <= 0) {
6696d08ec72SAndreas Simbuerger         errs() << "The size at index " << i << " is =< 0.\n";
6706d08ec72SAndreas Simbuerger         return false;
6716d08ec72SAndreas Simbuerger       }
672b738ffa8SMichael Kruse 
673b738ffa8SMichael Kruse       DimSizes.push_back(Size);
6746d08ec72SAndreas Simbuerger     }
675b738ffa8SMichael Kruse 
67623655020SMichael Kruse     auto NewSAI = S.createScopArrayInfo(
677*5cff5142SKazu Hirata         ElementType, Array.getString("name").value().str(), DimSizes);
678b738ffa8SMichael Kruse 
67923655020SMichael Kruse     if (Array.get("allocation")) {
680*5cff5142SKazu Hirata       NewSAI->setIsOnHeap(Array.getString("allocation").value() == "heap");
681b738ffa8SMichael Kruse     }
682d7754a12SRoman Gareev   }
683d7754a12SRoman Gareev 
684d7754a12SRoman Gareev   return true;
685d7754a12SRoman Gareev }
686d7754a12SRoman Gareev 
68747bf15c3SPhilip Pfaffe /// Import a Scop from a JSCOP file
68847bf15c3SPhilip Pfaffe /// @param S The scop to be modified
68947bf15c3SPhilip Pfaffe /// @param D Dependence Info
69047bf15c3SPhilip Pfaffe /// @param DL The DataLayout of the function
69147bf15c3SPhilip Pfaffe /// @param NewAccessStrings Optionally record the imported access strings
69247bf15c3SPhilip Pfaffe ///
69347bf15c3SPhilip Pfaffe /// @returns true on success, false otherwise. Beware that if this returns
69447bf15c3SPhilip Pfaffe /// false, the Scop may still have been modified. In this case the Scop contains
69547bf15c3SPhilip Pfaffe /// invalid information.
importScop(Scop & S,const Dependences & D,const DataLayout & DL,std::vector<std::string> * NewAccessStrings=nullptr)69647bf15c3SPhilip Pfaffe static bool importScop(Scop &S, const Dependences &D, const DataLayout &DL,
69747bf15c3SPhilip Pfaffe                        std::vector<std::string> *NewAccessStrings = nullptr) {
69847bf15c3SPhilip Pfaffe   std::string FileName = ImportDir + "/" + getFileName(S, ImportPostfix);
69975805378STobias Grosser 
7000257a921SEli Friedman   std::string FunctionName = S.getFunction().getName().str();
7013f52e354SJohannes Doerfert   errs() << "Reading JScop '" << S.getNameStr() << "' in function '"
70275805378STobias Grosser          << FunctionName << "' from '" << FileName << "'.\n";
703d432e0f9SRafael Espindola   ErrorOr<std::unique_ptr<MemoryBuffer>> result =
704d432e0f9SRafael Espindola       MemoryBuffer::getFile(FileName);
705d432e0f9SRafael Espindola   std::error_code ec = result.getError();
70675805378STobias Grosser 
70775805378STobias Grosser   if (ec) {
70875805378STobias Grosser     errs() << "File could not be read: " << ec.message() << "\n";
70975805378STobias Grosser     return false;
71075805378STobias Grosser   }
71175805378STobias Grosser 
71223655020SMichael Kruse   Expected<json::Value> ParseResult =
71323655020SMichael Kruse       json::parse(result.get().get()->getBuffer());
71475805378STobias Grosser 
715ebca0f16SMichael Kruse   if (Error E = ParseResult.takeError()) {
71675805378STobias Grosser     errs() << "JSCoP file could not be parsed\n";
717ebca0f16SMichael Kruse     errs() << E << "\n";
718ebca0f16SMichael Kruse     consumeError(std::move(E));
71975805378STobias Grosser     return false;
72075805378STobias Grosser   }
72123655020SMichael Kruse   json::Object &jscop = *ParseResult.get().getAsObject();
72275805378STobias Grosser 
723dbe34f7cSTobias Grosser   bool Success = importContext(S, jscop);
724ff9b54d5STobias Grosser 
725dbe34f7cSTobias Grosser   if (!Success)
726dbe34f7cSTobias Grosser     return false;
727ff9b54d5STobias Grosser 
728dbe34f7cSTobias Grosser   Success = importSchedule(S, jscop, D);
72975805378STobias Grosser 
730c602d3bcSTobias Grosser   if (!Success)
73175805378STobias Grosser     return false;
732808cd69aSTobias Grosser 
733d7754a12SRoman Gareev   Success = importArrays(S, jscop);
734d7754a12SRoman Gareev 
735d7754a12SRoman Gareev   if (!Success)
736d7754a12SRoman Gareev     return false;
737d7754a12SRoman Gareev 
73847bf15c3SPhilip Pfaffe   Success = importAccesses(S, jscop, DL, NewAccessStrings);
73962622746STobias Grosser 
7409ea15271STobias Grosser   if (!Success)
74162622746STobias Grosser     return false;
74247bf15c3SPhilip Pfaffe   return true;
74347bf15c3SPhilip Pfaffe }
7443cb6628dSRaghesh Aloor 
74547bf15c3SPhilip Pfaffe char JSONExporter::ID = 0;
printScop(raw_ostream & OS,Scop & S) const74647bf15c3SPhilip Pfaffe void JSONExporter::printScop(raw_ostream &OS, Scop &S) const { OS << S; }
74747bf15c3SPhilip Pfaffe 
runOnScop(Scop & S)74847bf15c3SPhilip Pfaffe bool JSONExporter::runOnScop(Scop &S) {
74947bf15c3SPhilip Pfaffe   exportScop(S);
75047bf15c3SPhilip Pfaffe   return false;
75147bf15c3SPhilip Pfaffe }
75247bf15c3SPhilip Pfaffe 
getAnalysisUsage(AnalysisUsage & AU) const75347bf15c3SPhilip Pfaffe void JSONExporter::getAnalysisUsage(AnalysisUsage &AU) const {
75447bf15c3SPhilip Pfaffe   AU.setPreservesAll();
75547bf15c3SPhilip Pfaffe   AU.addRequired<ScopInfoRegionPass>();
75647bf15c3SPhilip Pfaffe }
75747bf15c3SPhilip Pfaffe 
createJSONExporterPass()75847bf15c3SPhilip Pfaffe Pass *polly::createJSONExporterPass() { return new JSONExporter(); }
75947bf15c3SPhilip Pfaffe 
run(Scop & S,ScopAnalysisManager & SAM,ScopStandardAnalysisResults & SAR,SPMUpdater &)76047bf15c3SPhilip Pfaffe PreservedAnalyses JSONExportPass::run(Scop &S, ScopAnalysisManager &SAM,
76147bf15c3SPhilip Pfaffe                                       ScopStandardAnalysisResults &SAR,
76247bf15c3SPhilip Pfaffe                                       SPMUpdater &) {
76347bf15c3SPhilip Pfaffe   exportScop(S);
76447bf15c3SPhilip Pfaffe   return PreservedAnalyses::all();
76547bf15c3SPhilip Pfaffe }
76647bf15c3SPhilip Pfaffe 
76747bf15c3SPhilip Pfaffe char JSONImporter::ID = 0;
76847bf15c3SPhilip Pfaffe 
printScop(raw_ostream & OS,Scop & S) const76947bf15c3SPhilip Pfaffe void JSONImporter::printScop(raw_ostream &OS, Scop &S) const {
77047bf15c3SPhilip Pfaffe   OS << S;
77147bf15c3SPhilip Pfaffe   for (std::vector<std::string>::const_iterator I = NewAccessStrings.begin(),
77247bf15c3SPhilip Pfaffe                                                 E = NewAccessStrings.end();
77347bf15c3SPhilip Pfaffe        I != E; I++)
77447bf15c3SPhilip Pfaffe     OS << "New access function '" << *I << "' detected in JSCOP file\n";
77547bf15c3SPhilip Pfaffe }
77647bf15c3SPhilip Pfaffe 
runOnScop(Scop & S)77747bf15c3SPhilip Pfaffe bool JSONImporter::runOnScop(Scop &S) {
77847bf15c3SPhilip Pfaffe   const Dependences &D =
77947bf15c3SPhilip Pfaffe       getAnalysis<DependenceInfo>().getDependences(Dependences::AL_Statement);
78047bf15c3SPhilip Pfaffe   const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
781c3bcdc2fSPhilip Pfaffe 
782c3bcdc2fSPhilip Pfaffe   if (!importScop(S, D, DL, &NewAccessStrings))
783c3bcdc2fSPhilip Pfaffe     report_fatal_error("Tried to import a malformed jscop file.");
784c3bcdc2fSPhilip Pfaffe 
78575805378STobias Grosser   return false;
78675805378STobias Grosser }
78775805378STobias Grosser 
getAnalysisUsage(AnalysisUsage & AU) const78875805378STobias Grosser void JSONImporter::getAnalysisUsage(AnalysisUsage &AU) const {
78975805378STobias Grosser   ScopPass::getAnalysisUsage(AU);
790f6557f98SJohannes Doerfert   AU.addRequired<DependenceInfo>();
791a4f447c2SMichael Kruse 
792a4f447c2SMichael Kruse   // TODO: JSONImporter should throw away DependenceInfo.
793a4f447c2SMichael Kruse   AU.addPreserved<DependenceInfo>();
79475805378STobias Grosser }
79545be6446SJohannes Doerfert 
createJSONImporterPass()7964d96c8d7STobias Grosser Pass *polly::createJSONImporterPass() { return new JSONImporter(); }
7974d96c8d7STobias Grosser 
run(Scop & S,ScopAnalysisManager & SAM,ScopStandardAnalysisResults & SAR,SPMUpdater &)79847bf15c3SPhilip Pfaffe PreservedAnalyses JSONImportPass::run(Scop &S, ScopAnalysisManager &SAM,
79947bf15c3SPhilip Pfaffe                                       ScopStandardAnalysisResults &SAR,
80047bf15c3SPhilip Pfaffe                                       SPMUpdater &) {
80147bf15c3SPhilip Pfaffe   const Dependences &D =
80247bf15c3SPhilip Pfaffe       SAM.getResult<DependenceAnalysis>(S, SAR).getDependences(
80347bf15c3SPhilip Pfaffe           Dependences::AL_Statement);
80447bf15c3SPhilip Pfaffe   const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
80547bf15c3SPhilip Pfaffe 
806c3bcdc2fSPhilip Pfaffe   if (!importScop(S, D, DL))
807c3bcdc2fSPhilip Pfaffe     report_fatal_error("Tried to import a malformed jscop file.");
80847bf15c3SPhilip Pfaffe 
80947bf15c3SPhilip Pfaffe   // This invalidates all analyses on Scop.
81047bf15c3SPhilip Pfaffe   PreservedAnalyses PA;
81147bf15c3SPhilip Pfaffe   PA.preserveSet<AllAnalysesOn<Module>>();
81247bf15c3SPhilip Pfaffe   PA.preserveSet<AllAnalysesOn<Function>>();
81347bf15c3SPhilip Pfaffe   PA.preserveSet<AllAnalysesOn<Loop>>();
81447bf15c3SPhilip Pfaffe   return PA;
81547bf15c3SPhilip Pfaffe }
81647bf15c3SPhilip Pfaffe 
8174d96c8d7STobias Grosser INITIALIZE_PASS_BEGIN(JSONExporter, "polly-export-jscop",
8184d96c8d7STobias Grosser                       "Polly - Export Scops as JSON"
8194d96c8d7STobias Grosser                       " (Writes a .jscop file for each Scop)",
8204d96c8d7STobias Grosser                       false, false);
821f6557f98SJohannes Doerfert INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
8224d96c8d7STobias Grosser INITIALIZE_PASS_END(JSONExporter, "polly-export-jscop",
8234d96c8d7STobias Grosser                     "Polly - Export Scops as JSON"
8244d96c8d7STobias Grosser                     " (Writes a .jscop file for each Scop)",
8254d96c8d7STobias Grosser                     false, false)
8264d96c8d7STobias Grosser 
827ecf6cd06STobias Grosser INITIALIZE_PASS_BEGIN(JSONImporter, "polly-import-jscop",
82875805378STobias Grosser                       "Polly - Import Scops from JSON"
8294d96c8d7STobias Grosser                       " (Reads a .jscop file for each Scop)",
8304d96c8d7STobias Grosser                       false, false);
831f6557f98SJohannes Doerfert INITIALIZE_PASS_DEPENDENCY(DependenceInfo)
832ecf6cd06STobias Grosser INITIALIZE_PASS_END(JSONImporter, "polly-import-jscop",
833ecf6cd06STobias Grosser                     "Polly - Import Scops from JSON"
8344d96c8d7STobias Grosser                     " (Reads a .jscop file for each Scop)",
8354d96c8d7STobias Grosser                     false, false)
8365c028081SMichael Kruse 
8375c028081SMichael Kruse //===----------------------------------------------------------------------===//
8385c028081SMichael Kruse 
8395c028081SMichael Kruse namespace {
8405c028081SMichael Kruse /// Print result from JSONImporter.
841bd93df93SMichael Kruse class JSONImporterPrinterLegacyPass final : public ScopPass {
8425c028081SMichael Kruse public:
8435c028081SMichael Kruse   static char ID;
8445c028081SMichael Kruse 
JSONImporterPrinterLegacyPass()8455c028081SMichael Kruse   JSONImporterPrinterLegacyPass() : JSONImporterPrinterLegacyPass(outs()){};
JSONImporterPrinterLegacyPass(llvm::raw_ostream & OS)8465c028081SMichael Kruse   explicit JSONImporterPrinterLegacyPass(llvm::raw_ostream &OS)
8475c028081SMichael Kruse       : ScopPass(ID), OS(OS) {}
8485c028081SMichael Kruse 
runOnScop(Scop & S)8495c028081SMichael Kruse   bool runOnScop(Scop &S) override {
8505c028081SMichael Kruse     JSONImporter &P = getAnalysis<JSONImporter>();
8515c028081SMichael Kruse 
8525c028081SMichael Kruse     OS << "Printing analysis '" << P.getPassName() << "' for region: '"
8535c028081SMichael Kruse        << S.getRegion().getNameStr() << "' in function '"
8545c028081SMichael Kruse        << S.getFunction().getName() << "':\n";
8555c028081SMichael Kruse     P.printScop(OS, S);
8565c028081SMichael Kruse 
8575c028081SMichael Kruse     return false;
8585c028081SMichael Kruse   }
8595c028081SMichael Kruse 
getAnalysisUsage(AnalysisUsage & AU) const8605c028081SMichael Kruse   void getAnalysisUsage(AnalysisUsage &AU) const override {
8615c028081SMichael Kruse     ScopPass::getAnalysisUsage(AU);
8625c028081SMichael Kruse     AU.addRequired<JSONImporter>();
8635c028081SMichael Kruse     AU.setPreservesAll();
8645c028081SMichael Kruse   }
8655c028081SMichael Kruse 
8665c028081SMichael Kruse private:
8675c028081SMichael Kruse   llvm::raw_ostream &OS;
8685c028081SMichael Kruse };
8695c028081SMichael Kruse 
8705c028081SMichael Kruse char JSONImporterPrinterLegacyPass::ID = 0;
8715c028081SMichael Kruse } // namespace
8725c028081SMichael Kruse 
createJSONImporterPrinterLegacyPass(llvm::raw_ostream & OS)8735c028081SMichael Kruse Pass *polly::createJSONImporterPrinterLegacyPass(llvm::raw_ostream &OS) {
8745c028081SMichael Kruse   return new JSONImporterPrinterLegacyPass(OS);
8755c028081SMichael Kruse }
8765c028081SMichael Kruse 
8775c028081SMichael Kruse INITIALIZE_PASS_BEGIN(JSONImporterPrinterLegacyPass, "polly-print-import-jscop",
8785c028081SMichael Kruse                       "Polly - Print Scop import result", false, false)
8795c028081SMichael Kruse INITIALIZE_PASS_DEPENDENCY(JSONImporter)
8805c028081SMichael Kruse INITIALIZE_PASS_END(JSONImporterPrinterLegacyPass, "polly-print-import-jscop",
8815c028081SMichael Kruse                     "Polly - Print Scop import result", false, false)
882