Rename isSimpleLoad to canFoldAsLoad, to better reflect its meaning.
[oota-llvm.git] / utils / TableGen / LLVMCConfigurationEmitter.cpp
index 43729033c39c4e0ca81189f94421050eb1e7a53e..fc9553ed268843cc99154315dd34bf029c150cf4 100644 (file)
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Streams.h"
+
 #include <algorithm>
 #include <cassert>
 #include <functional>
 #include <stdexcept>
 #include <string>
 #include <typeinfo>
+
 using namespace llvm;
 
 namespace {
@@ -162,8 +164,8 @@ struct OptionDescription {
       else if (cur_char == '+') {
         ret += "_plus_";
       }
-      else if (cur_char == ',') {
-        ret += "_comma_";
+      else if (cur_char == '-') {
+        ret += "_dash_";
       }
       else {
         ret.push_back(cur_char);
@@ -196,7 +198,8 @@ struct OptionDescription {
 // Global option description.
 
 namespace GlobalOptionDescriptionFlags {
-  enum GlobalOptionDescriptionFlags { Required = 0x1 };
+  enum GlobalOptionDescriptionFlags { Required = 0x1, Hidden = 0x2,
+                                      ReallyHidden = 0x4 };
 }
 
 struct GlobalOptionDescription : public OptionDescription {
@@ -220,17 +223,31 @@ struct GlobalOptionDescription : public OptionDescription {
     Flags |= GlobalOptionDescriptionFlags::Required;
   }
 
+  bool isHidden() const {
+    return Flags & GlobalOptionDescriptionFlags::Hidden;
+  }
+  void setHidden() {
+    Flags |= GlobalOptionDescriptionFlags::Hidden;
+  }
+
+  bool isReallyHidden() const {
+    return Flags & GlobalOptionDescriptionFlags::ReallyHidden;
+  }
+  void setReallyHidden() {
+    Flags |= GlobalOptionDescriptionFlags::ReallyHidden;
+  }
+
   /// Merge - Merge two option descriptions.
   void Merge (const GlobalOptionDescription& other)
   {
     if (other.Type != Type)
       throw "Conflicting definitions for the option " + Name + "!";
 
-    if (Help == DefaultHelpString)
+    if (Help == other.Help || Help == DefaultHelpString)
       Help = other.Help;
     else if (other.Help != DefaultHelpString) {
-      llvm::cerr << "Warning: more than one help string defined for option "
-        + Name + "\n";
+      llvm::cerr << "Warning: several different help strings"
+        " defined for option " + Name + "\n";
     }
 
     Flags |= other.Flags;
@@ -410,8 +427,12 @@ public:
         &CollectOptionProperties::onForwardAs;
       optionPropertyHandlers_["help"] =
         &CollectOptionProperties::onHelp;
+      optionPropertyHandlers_["hidden"] =
+        &CollectOptionProperties::onHidden;
       optionPropertyHandlers_["output_suffix"] =
         &CollectOptionProperties::onOutputSuffix;
+      optionPropertyHandlers_["really_hidden"] =
+        &CollectOptionProperties::onReallyHidden;
       optionPropertyHandlers_["required"] =
         &CollectOptionProperties::onRequired;
       optionPropertyHandlers_["stop_compilation"] =
@@ -491,6 +512,18 @@ private:
     optDesc_.Help = help_message;
   }
 
+  void onHidden (const DagInit* d) {
+    checkNumberOfArguments(d, 0);
+    checkToolProps(d);
+    optDesc_.setHidden();
+  }
+
+  void onReallyHidden (const DagInit* d) {
+    checkNumberOfArguments(d, 0);
+    checkToolProps(d);
+    optDesc_.setReallyHidden();
+  }
+
   void onRequired (const DagInit* d) {
     checkNumberOfArguments(d, 0);
     checkToolProps(d);
@@ -748,7 +781,7 @@ void CollectToolProperties (RecordVector::const_iterator B,
 {
   // Iterate over a properties list of every Tool definition
   for (;B!=E;++B) {
-    Record* T = *B;
+    const Record* T = *B;
     // Throws an exception if the value does not exist.
     ListInit* PropList = T->getValueAsListInit("properties");
 
@@ -762,14 +795,14 @@ void CollectToolProperties (RecordVector::const_iterator B,
 }
 
 
-/// CollectPropertiesFromOptionList - Gather information about
-/// *global* option properties from the OptionList.
-void CollectPropertiesFromOptionList (RecordVector::const_iterator B,
-                                      RecordVector::const_iterator E,
-                                      GlobalOptionDescriptions& OptDescs)
+/// CollectPropertiesFromOptionLists - Gather information about
+/// *global* option properties from all OptionLists.
+void CollectPropertiesFromOptionLists (RecordVector::const_iterator B,
+                                       RecordVector::const_iterator E,
+                                       GlobalOptionDescriptions& OptDescs)
 {
   // Iterate over a properties list of every Tool definition
-  for (;B!=E;++B) {
+  for (; B!=E; ++B) {
     RecordVector::value_type T = *B;
     // Throws an exception if the value does not exist.
     ListInit* PropList = T->getValueAsListInit("options");
@@ -803,7 +836,7 @@ void CheckForSuperfluousOptions (const ToolPropertiesList& TPList,
     const GlobalOptionDescription& Val = B->second;
     if (!nonSuperfluousOptions.count(Val.Name)
         && Val.Type != OptionType::Alias)
-      cerr << "Warning: option '-" << Val.Name << "' has no effect! "
+      llvm::cerr << "Warning: option '-" << Val.Name << "' has no effect! "
         "Probable cause: this option is specified only in the OptionList.\n";
   }
 }
@@ -1119,9 +1152,9 @@ std::string SubstituteSpecialCommands(const std::string& cmd) {
     if (cmd.size() == 5)
       throw std::string("$ENV invocation: empty argument list!");
 
-    ret += "std::getenv(\"";
+    ret += "checkCString(std::getenv(\"";
     ret += std::string(cmd.begin() + 5, cmd.begin() + cparen);
-    ret += "\")";
+    ret += "\"))";
   }
   else {
     throw "Unknown special command: " + cmd;
@@ -1211,7 +1244,7 @@ void EmitGenerateActionMethod (const ToolProperties& P,
     << Indent2 << "const InputLanguagesSet& InLangs,\n"
     << Indent2 << "const LanguageMap& LangMap) const\n"
     << Indent1 << "{\n"
-    << Indent2 << "const char* cmd;\n"
+    << Indent2 << "std::string cmd;\n"
     << Indent2 << "std::vector<std::string> vec;\n";
 
   // cmd_line is either a string or a 'case' construct.
@@ -1411,6 +1444,17 @@ void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
       }
     }
 
+    if (val.isReallyHidden() || val.isHidden()) {
+      if (val.isRequired())
+        O << " |";
+      else
+        O << ",";
+      if (val.isReallyHidden())
+        O << " cl::ReallyHidden";
+      else
+        O << " cl::Hidden";
+    }
+
     if (!val.Help.empty())
       O << ", cl::desc(\"" << val.Help << "\")";
 
@@ -1446,29 +1490,31 @@ void EmitOptionDescriptions (const GlobalOptionDescriptions& descs,
 /// EmitPopulateLanguageMap - Emit the PopulateLanguageMap() function.
 void EmitPopulateLanguageMap (const RecordKeeper& Records, std::ostream& O)
 {
-  // Get the relevant field out of RecordKeeper
-  Record* LangMapRecord = Records.getDef("LanguageMap");
-  if (!LangMapRecord)
-    throw std::string("Language map definition not found!");
-
-  ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
-  if (!LangsToSuffixesList)
-    throw std::string("Error in the language map definition!");
-
   // Generate code
   O << "namespace {\n\n";
   O << "void PopulateLanguageMapLocal(LanguageMap& langMap) {\n";
 
-  for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
-    Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
+  // Get the relevant field out of RecordKeeper
+  const Record* LangMapRecord = Records.getDef("LanguageMap");
+
+  // It is allowed for a plugin to have no language map.
+  if (LangMapRecord) {
+
+    ListInit* LangsToSuffixesList = LangMapRecord->getValueAsListInit("map");
+    if (!LangsToSuffixesList)
+      throw std::string("Error in the language map definition!");
+
+    for (unsigned i = 0; i < LangsToSuffixesList->size(); ++i) {
+      const Record* LangToSuffixes = LangsToSuffixesList->getElementAsRecord(i);
 
-    const std::string& Lang = LangToSuffixes->getValueAsString("lang");
-    const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
+      const std::string& Lang = LangToSuffixes->getValueAsString("lang");
+      const ListInit* Suffixes = LangToSuffixes->getValueAsListInit("suffixes");
 
-    for (unsigned i = 0; i < Suffixes->size(); ++i)
-      O << Indent1 << "langMap[\""
-        << InitPtrToString(Suffixes->getElement(i))
-        << "\"] = \"" << Lang << "\";\n";
+      for (unsigned i = 0; i < Suffixes->size(); ++i)
+        O << Indent1 << "langMap[\""
+          << InitPtrToString(Suffixes->getElement(i))
+          << "\"] = \"" << Lang << "\";\n";
+    }
   }
 
   O << "}\n\n}\n\n";
@@ -1490,37 +1536,33 @@ void FillInToolToLang (const ToolPropertiesList& TPList,
 }
 
 /// TypecheckGraph - Check that names for output and input languages
-/// on all edges do match.
-// TOFIX: It would be nice if this function also checked for cycles
-// and multiple default edges in the graph (better error
-// reporting). Unfortunately, it is awkward to do right now because
-// our intermediate representation is not sufficiently
-// sophisticated. Algorithms like these require a real graph instead of
-// an AST.
-void TypecheckGraph (Record* CompilationGraph,
+/// on all edges do match. This doesn't do much when the information
+/// about the whole graph is not available (i.e. when compiling most
+/// plugins).
+void TypecheckGraph (const RecordVector& EdgeVector,
                      const ToolPropertiesList& TPList) {
   StringMap<StringSet<> > ToolToInLang;
   StringMap<std::string> ToolToOutLang;
 
   FillInToolToLang(TPList, ToolToInLang, ToolToOutLang);
-  ListInit* edges = CompilationGraph->getValueAsListInit("edges");
   StringMap<std::string>::iterator IAE = ToolToOutLang.end();
   StringMap<StringSet<> >::iterator IBE = ToolToInLang.end();
 
-  for (unsigned i = 0; i < edges->size(); ++i) {
-    Record* Edge = edges->getElementAsRecord(i);
-    Record* A = Edge->getValueAsDef("a");
-    Record* B = Edge->getValueAsDef("b");
-    StringMap<std::string>::iterator IA = ToolToOutLang.find(A->getName());
-    StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B->getName());
-    if (IA == IAE)
-      throw A->getName() + ": no such tool!";
-    if (IB == IBE)
-      throw B->getName() + ": no such tool!";
-    if (A->getName() != "root" && IB->second.count(IA->second) == 0)
-      throw "Edge " + A->getName() + "->" + B->getName()
-        + ": output->input language mismatch";
-    if (B->getName() == "root")
+  for (RecordVector::const_iterator B = EdgeVector.begin(),
+         E = EdgeVector.end(); B != E; ++B) {
+    const Record* Edge = *B;
+    const std::string& A = Edge->getValueAsString("a");
+    const std::string& B = Edge->getValueAsString("b");
+    StringMap<std::string>::iterator IA = ToolToOutLang.find(A);
+    StringMap<StringSet<> >::iterator IB = ToolToInLang.find(B);
+
+    if (A != "root") {
+      if (IA != IAE && IB != IBE && IB->second.count(IA->second) == 0)
+        throw "Edge " + A + "->" + B
+          + ": output->input language mismatch";
+    }
+
+    if (B == "root")
       throw std::string("Edges back to the root are not allowed!");
   }
 }
@@ -1569,64 +1611,56 @@ void EmitEdgeClass (unsigned N, const std::string& Target,
 }
 
 /// EmitEdgeClasses - Emit Edge* classes that represent graph edges.
-void EmitEdgeClasses (Record* CompilationGraph,
+void EmitEdgeClasses (const RecordVector& EdgeVector,
                       const GlobalOptionDescriptions& OptDescs,
                       std::ostream& O) {
-  ListInit* edges = CompilationGraph->getValueAsListInit("edges");
-
-  for (unsigned i = 0; i < edges->size(); ++i) {
-    Record* Edge = edges->getElementAsRecord(i);
-    Record* B = Edge->getValueAsDef("b");
+  int i = 0;
+  for (RecordVector::const_iterator B = EdgeVector.begin(),
+         E = EdgeVector.end(); B != E; ++B) {
+    const Record* Edge = *B;
+    const std::string& B = Edge->getValueAsString("b");
     DagInit* Weight = Edge->getValueAsDag("weight");
 
-    if (isDagEmpty(Weight))
-      continue;
-
-    EmitEdgeClass(i, B->getName(), Weight, OptDescs, O);
+    if (!isDagEmpty(Weight))
+      EmitEdgeClass(i, B, Weight, OptDescs, O);
+    ++i;
   }
 }
 
 /// EmitPopulateCompilationGraph - Emit the PopulateCompilationGraph()
 /// function.
-void EmitPopulateCompilationGraph (Record* CompilationGraph,
+void EmitPopulateCompilationGraph (const RecordVector& EdgeVector,
+                                   const ToolPropertiesList& ToolProps,
                                    std::ostream& O)
 {
-  ListInit* edges = CompilationGraph->getValueAsListInit("edges");
-
-  // Generate code
   O << "namespace {\n\n";
   O << "void PopulateCompilationGraphLocal(CompilationGraph& G) {\n";
 
-  // Insert vertices
-
-  RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
-  if (Tools.empty())
-    throw std::string("No tool definitions found!");
-
-  for (RecordVector::iterator B = Tools.begin(), E = Tools.end(); B != E; ++B) {
-    const std::string& Name = (*B)->getName();
-    if (Name != "root")
-      O << Indent1 << "G.insertNode(new "
-        << Name << "());\n";
-  }
+  for (ToolPropertiesList::const_iterator B = ToolProps.begin(),
+         E = ToolProps.end(); B != E; ++B)
+    O << Indent1 << "G.insertNode(new " << (*B)->Name << "());\n";
 
   O << '\n';
 
-  // Insert edges
-  for (unsigned i = 0; i < edges->size(); ++i) {
-    Record* Edge = edges->getElementAsRecord(i);
-    Record* A = Edge->getValueAsDef("a");
-    Record* B = Edge->getValueAsDef("b");
+  // Insert edges.
+
+  int i = 0;
+  for (RecordVector::const_iterator B = EdgeVector.begin(),
+         E = EdgeVector.end(); B != E; ++B) {
+    const Record* Edge = *B;
+    const std::string& A = Edge->getValueAsString("a");
+    const std::string& B = Edge->getValueAsString("b");
     DagInit* Weight = Edge->getValueAsDag("weight");
 
-    O << Indent1 << "G.insertEdge(\"" << A->getName() << "\", ";
+    O << Indent1 << "G.insertEdge(\"" << A << "\", ";
 
     if (isDagEmpty(Weight))
-      O << "new SimpleEdge(\"" << B->getName() << "\")";
+      O << "new SimpleEdge(\"" << B << "\")";
     else
       O << "new Edge" << i << "()";
 
     O << ");\n";
+    ++i;
   }
 
   O << "}\n\n}\n\n";
@@ -1707,9 +1741,10 @@ void EmitHookDeclarations(const ToolPropertiesList& ToolProps,
 }
 
 /// EmitRegisterPlugin - Emit code to register this plugin.
-void EmitRegisterPlugin(std::ostream& O) {
+void EmitRegisterPlugin(int Priority, std::ostream& O) {
   O << "namespace {\n\n"
-    << "struct Plugin : public llvmc::BasePlugin {\n"
+    << "struct Plugin : public llvmc::BasePlugin {\n\n"
+    << Indent1 << "int Priority() const { return " << Priority << "; }\n\n"
     << Indent1 << "void PopulateLanguageMap(LanguageMap& langMap) const\n"
     << Indent1 << "{ PopulateLanguageMapLocal(langMap); }\n\n"
     << Indent1
@@ -1720,7 +1755,8 @@ void EmitRegisterPlugin(std::ostream& O) {
     << "static llvmc::RegisterPlugin<Plugin> RP;\n\n}\n\n";
 }
 
-/// EmitInclude - Emit necessary #include directives.
+/// EmitIncludes - Emit necessary #include directives and some
+/// additional declarations.
 void EmitIncludes(std::ostream& O) {
   O << "#include \"llvm/CompilerDriver/CompilationGraph.h\"\n"
     << "#include \"llvm/CompilerDriver/Plugin.h\"\n"
@@ -1735,7 +1771,74 @@ void EmitIncludes(std::ostream& O) {
     << "using namespace llvm;\n"
     << "using namespace llvmc;\n\n"
 
-    << "extern cl::opt<std::string> OutputFilename;\n\n";
+    << "extern cl::opt<std::string> OutputFilename;\n\n"
+
+    << "inline const char* checkCString(const char* s)\n"
+    << "{ return s == NULL ? \"\" : s; }\n\n";
+}
+
+/// NotInGraph - Helper function object for FilterNotInGraph.
+struct NotInGraph {
+private:
+  const llvm::StringSet<>& ToolsInGraph_;
+
+public:
+  NotInGraph(const llvm::StringSet<>& ToolsInGraph)
+  : ToolsInGraph_(ToolsInGraph)
+  {}
+
+  bool operator()(const IntrusiveRefCntPtr<ToolProperties>& x) {
+    return (ToolsInGraph_.count(x->Name) == 0);
+  }
+};
+
+/// FilterNotInGraph - Filter out from ToolProps all Tools not
+/// mentioned in the compilation graph definition.
+void FilterNotInGraph (const RecordVector& EdgeVector,
+                       ToolPropertiesList& ToolProps) {
+
+  // List all tools mentioned in the graph.
+  llvm::StringSet<> ToolsInGraph;
+
+  for (RecordVector::const_iterator B = EdgeVector.begin(),
+         E = EdgeVector.end(); B != E; ++B) {
+
+    const Record* Edge = *B;
+    const std::string& A = Edge->getValueAsString("a");
+    const std::string& B = Edge->getValueAsString("b");
+
+    if (A != "root")
+      ToolsInGraph.insert(A);
+    ToolsInGraph.insert(B);
+  }
+
+  // Filter ToolPropertiesList.
+  ToolPropertiesList::iterator new_end =
+    std::remove_if(ToolProps.begin(), ToolProps.end(),
+                   NotInGraph(ToolsInGraph));
+  ToolProps.erase(new_end, ToolProps.end());
+}
+
+/// CalculatePriority - Calculate the priority of this plugin.
+int CalculatePriority(RecordVector::const_iterator B,
+                      RecordVector::const_iterator E) {
+  int total = 0;
+  for (; B!=E; ++B) {
+    total += static_cast<int>((*B)->getValueAsInt("priority"));
+  }
+  return total;
+}
+
+/// FillInEdgeVector - Merge all compilation graph definitions into
+/// one single edge list.
+void FillInEdgeVector(RecordVector::const_iterator B,
+                      RecordVector::const_iterator E, RecordVector& Out) {
+  for (; B != E; ++B) {
+    const ListInit* edges = (*B)->getValueAsListInit("edges");
+
+    for (unsigned i = 0; i < edges->size(); ++i)
+      Out.push_back(edges->getElementAsRecord(i));
+  }
 }
 
 // End of anonymous namespace
@@ -1749,54 +1852,61 @@ void LLVMCConfigurationEmitter::run (std::ostream &O) {
   EmitSourceFileHeader("LLVMC Configuration Library", O);
   EmitIncludes(O);
 
-  // Get a list of all defined Tools.
+  // Collect tool properties.
   RecordVector Tools = Records.getAllDerivedDefinitions("Tool");
-  if (Tools.empty())
-    throw std::string("No tool definitions found!");
-
-  // Gather information from the Tool description dags.
-  ToolPropertiesList tool_props;
-  GlobalOptionDescriptions opt_descs;
-  CollectToolProperties(Tools.begin(), Tools.end(), tool_props, opt_descs);
+  ToolPropertiesList ToolProps;
+  GlobalOptionDescriptions OptDescs;
+  CollectToolProperties(Tools.begin(), Tools.end(), ToolProps, OptDescs);
+
+  // Collect option properties.
+  const RecordVector& OptionLists =
+    Records.getAllDerivedDefinitions("OptionList");
+  CollectPropertiesFromOptionLists(OptionLists.begin(), OptionLists.end(),
+                                   OptDescs);
+
+  // Collect compilation graph edges.
+  const RecordVector& CompilationGraphs =
+    Records.getAllDerivedDefinitions("CompilationGraph");
+  RecordVector EdgeVector;
+  FillInEdgeVector(CompilationGraphs.begin(), CompilationGraphs.end(),
+                   EdgeVector);
+
+  // Filter out all tools not mentioned in the compilation graph.
+  FilterNotInGraph(EdgeVector, ToolProps);
 
-  RecordVector OptionLists = Records.getAllDerivedDefinitions("OptionList");
-  CollectPropertiesFromOptionList(OptionLists.begin(), OptionLists.end(),
-                                  opt_descs);
+  // Typecheck the compilation graph.
+  TypecheckGraph(EdgeVector, ToolProps);
 
   // Check that there are no options without side effects (specified
   // only in the OptionList).
-  CheckForSuperfluousOptions(tool_props, opt_descs);
+  CheckForSuperfluousOptions(ToolProps, OptDescs);
 
   // Emit global option registration code.
-  EmitOptionDescriptions(opt_descs, O);
+  EmitOptionDescriptions(OptDescs, O);
 
   // Emit hook declarations.
-  EmitHookDeclarations(tool_props, O);
+  EmitHookDeclarations(ToolProps, O);
 
   // Emit PopulateLanguageMap() function
   // (a language map maps from file extensions to language names).
   EmitPopulateLanguageMap(Records, O);
 
   // Emit Tool classes.
-  for (ToolPropertiesList::const_iterator B = tool_props.begin(),
-         E = tool_props.end(); B!=E; ++B)
-    EmitToolClassDefinition(*(*B), opt_descs, O);
-
-  Record* CompilationGraphRecord = Records.getDef("CompilationGraph");
-  if (!CompilationGraphRecord)
-    throw std::string("Compilation graph description not found!");
-
-  // Typecheck the compilation graph.
-  TypecheckGraph(CompilationGraphRecord, tool_props);
+  for (ToolPropertiesList::const_iterator B = ToolProps.begin(),
+         E = ToolProps.end(); B!=E; ++B)
+    EmitToolClassDefinition(*(*B), OptDescs, O);
 
   // Emit Edge# classes.
-  EmitEdgeClasses(CompilationGraphRecord, opt_descs, O);
+  EmitEdgeClasses(EdgeVector, OptDescs, O);
 
   // Emit PopulateCompilationGraph() function.
-  EmitPopulateCompilationGraph(CompilationGraphRecord, O);
+  EmitPopulateCompilationGraph(EdgeVector, ToolProps, O);
 
   // Emit code for plugin registration.
-  EmitRegisterPlugin(O);
+  const RecordVector& Priorities =
+    Records.getAllDerivedDefinitions("PluginPriority");
+  EmitRegisterPlugin(CalculatePriority(Priorities.begin(),
+                                       Priorities.end()), O);
 
   // EOF
   } catch (std::exception& Error) {