[Midnightbsd-cvs] src [7058] trunk/contrib/llvm/utils: remove unused items in utils
laffer1 at midnightbsd.org
laffer1 at midnightbsd.org
Sat Jun 20 19:10:47 EDT 2015
Revision: 7058
http://svnweb.midnightbsd.org/src/?rev=7058
Author: laffer1
Date: 2015-06-20 19:10:46 -0400 (Sat, 20 Jun 2015)
Log Message:
-----------
remove unused items in utils
Modified Paths:
--------------
trunk/contrib/llvm/utils/DSAclean.py
trunk/contrib/llvm/utils/DSAextract.py
trunk/contrib/llvm/utils/FileCheck/FileCheck.cpp
trunk/contrib/llvm/utils/FileUpdate/FileUpdate.cpp
trunk/contrib/llvm/utils/GenLibDeps.pl
trunk/contrib/llvm/utils/GetRepositoryPath
trunk/contrib/llvm/utils/GetSourceVersion
trunk/contrib/llvm/utils/KillTheDoctor/KillTheDoctor.cpp
trunk/contrib/llvm/utils/Misc/zkill
trunk/contrib/llvm/utils/PerfectShuffle/PerfectShuffle.cpp
trunk/contrib/llvm/utils/TableGen/tdtags
trunk/contrib/llvm/utils/Target/ARM/analyze-match-table.py
trunk/contrib/llvm/utils/UpdateCMakeLists.pl
trunk/contrib/llvm/utils/bugpoint/RemoteRunSafely.sh
trunk/contrib/llvm/utils/buildit/GNUmakefile
trunk/contrib/llvm/utils/buildit/build_llvm
trunk/contrib/llvm/utils/check-each-file
trunk/contrib/llvm/utils/clang-parse-diagnostics-file
trunk/contrib/llvm/utils/codegen-diff
trunk/contrib/llvm/utils/count/count.c
trunk/contrib/llvm/utils/countloc.sh
trunk/contrib/llvm/utils/crosstool/ARM/README
trunk/contrib/llvm/utils/crosstool/ARM/build-install-linux.sh
trunk/contrib/llvm/utils/crosstool/create-snapshots.sh
trunk/contrib/llvm/utils/emacs/README
trunk/contrib/llvm/utils/emacs/emacs.el
trunk/contrib/llvm/utils/emacs/llvm-mode.el
trunk/contrib/llvm/utils/emacs/tablegen-mode.el
trunk/contrib/llvm/utils/findmisopt
trunk/contrib/llvm/utils/findoptdiff
trunk/contrib/llvm/utils/findsym.pl
trunk/contrib/llvm/utils/fpcmp/fpcmp.cpp
trunk/contrib/llvm/utils/getsrcs.sh
trunk/contrib/llvm/utils/git/find-rev
trunk/contrib/llvm/utils/git-svn/git-svnrevert
trunk/contrib/llvm/utils/git-svn/git-svnup
trunk/contrib/llvm/utils/jedit/README
trunk/contrib/llvm/utils/jedit/tablegen.xml
trunk/contrib/llvm/utils/kate/README
trunk/contrib/llvm/utils/kate/llvm.xml
trunk/contrib/llvm/utils/lint/common_lint.py
trunk/contrib/llvm/utils/lint/cpp_lint.py
trunk/contrib/llvm/utils/lint/generic_lint.py
trunk/contrib/llvm/utils/lint/remove_trailing_whitespace.sh
trunk/contrib/llvm/utils/lldbDataFormatters.py
trunk/contrib/llvm/utils/llvm-build/llvm-build
trunk/contrib/llvm/utils/llvm-build/llvmbuild/__init__.py
trunk/contrib/llvm/utils/llvm-build/llvmbuild/componentinfo.py
trunk/contrib/llvm/utils/llvm-build/llvmbuild/configutil.py
trunk/contrib/llvm/utils/llvm-build/llvmbuild/main.py
trunk/contrib/llvm/utils/llvm-build/llvmbuild/util.py
trunk/contrib/llvm/utils/llvm-compilers-check
trunk/contrib/llvm/utils/llvm-lit/llvm-lit.in
trunk/contrib/llvm/utils/llvm-native-gcc
trunk/contrib/llvm/utils/llvm-native-gxx
trunk/contrib/llvm/utils/llvm.grm
trunk/contrib/llvm/utils/llvm.natvis
trunk/contrib/llvm/utils/llvmdo
trunk/contrib/llvm/utils/llvmgrep
trunk/contrib/llvm/utils/makellvm
trunk/contrib/llvm/utils/not/not.cpp
trunk/contrib/llvm/utils/profile.pl
trunk/contrib/llvm/utils/release/findRegressions-nightly.py
trunk/contrib/llvm/utils/release/findRegressions-simple.py
trunk/contrib/llvm/utils/release/merge.sh
trunk/contrib/llvm/utils/release/tag.sh
trunk/contrib/llvm/utils/release/test-release.sh
trunk/contrib/llvm/utils/sort_includes.py
trunk/contrib/llvm/utils/test_debuginfo.pl
trunk/contrib/llvm/utils/testgen/mc-bundling-x86-gen.py
trunk/contrib/llvm/utils/textmate/README
trunk/contrib/llvm/utils/textmate/TableGen.tmbundle/Syntaxes/TableGen.tmLanguage
trunk/contrib/llvm/utils/textmate/TableGen.tmbundle/info.plist
trunk/contrib/llvm/utils/unittest/UnitTestMain/TestMain.cpp
trunk/contrib/llvm/utils/wciia.py
Removed Paths:
-------------
trunk/contrib/llvm/utils/lit/
trunk/contrib/llvm/utils/unittest/googletest/
trunk/contrib/llvm/utils/valgrind/
trunk/contrib/llvm/utils/vim/
trunk/contrib/llvm/utils/yaml-bench/
Modified: trunk/contrib/llvm/utils/DSAclean.py
===================================================================
--- trunk/contrib/llvm/utils/DSAclean.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/DSAclean.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,32 +0,0 @@
-#! /usr/bin/python
-
-#changelog:
-#10/13/2005b: replaced the # in tmp(.#*)* with alphanumeric and _, this will then remove
-#nodes such as %tmp.1.i and %tmp._i.3
-#10/13/2005: exntended to remove variables of the form %tmp(.#)* rather than just
-#%tmp.#, i.e. it now will remove %tmp.12.3.15 etc, additionally fixed a spelling error in
-#the comments
-#10/12/2005: now it only removes nodes and edges for which the label is %tmp.# rather
-#than removing all lines for which the lable CONTAINS %tmp.#
-import re
-import sys
-if( len(sys.argv) < 3 ):
- print 'usage is: ./DSAclean <dot_file_to_be_cleaned> <out_put_file>'
- sys.exit(1)
-#get a file object
-input = open(sys.argv[1], 'r')
-output = open(sys.argv[2], 'w')
-#we'll get this one line at a time...while we could just put the whole thing in a string
-#it would kill old computers
-buffer = input.readline()
-while buffer != '':
- if re.compile("label(\s*)=(\s*)\"\s%tmp(.\w*)*(\s*)\"").search(buffer):
- #skip next line, write neither this line nor the next
- buffer = input.readline()
- else:
- #this isn't a tmp Node, we can write it
- output.write(buffer)
- #prepare for the next iteration
- buffer = input.readline()
-input.close()
-output.close()
Modified: trunk/contrib/llvm/utils/DSAextract.py
===================================================================
--- trunk/contrib/llvm/utils/DSAextract.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/DSAextract.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,111 +0,0 @@
-#! /usr/bin/python
-
-#this is a script to extract given named nodes from a dot file, with
-#the associated edges. An edge is kept iff for edge x -> y
-# x and y are both nodes specified to be kept.
-
-#known issues: if a line contains '->' and is not an edge line
-#problems will occur. If node labels do not begin with
-#Node this also will not work. Since this is designed to work
-#on DSA dot output and not general dot files this is ok.
-#If you want to use this on other files rename the node labels
-#to Node[.*] with a script or something. This also relies on
-#the length of a node name being 13 characters (as it is in all
-#DSA dot output files)
-
-#Note that the name of the node can be any substring of the actual
-#name in the dot file. Thus if you say specify COLLAPSED
-#as a parameter this script will pull out all COLLAPSED
-#nodes in the file
-
-#Specifying escape characters in the name like \n also will not work,
-#as Python
-#will make it \\n, I'm not really sure how to fix this
-
-#currently the script prints the names it is searching for
-#to STDOUT, so you can check to see if they are what you intend
-
-import re
-import string
-import sys
-
-
-if len(sys.argv) < 3:
- print 'usage is ./DSAextract <dot_file_to_modify> \
- <output_file> [list of nodes to extract]'
-
-#open the input file
-input = open(sys.argv[1], 'r')
-
-#construct a set of node names
-node_name_set = set()
-for name in sys.argv[3:]:
- node_name_set |= set([name])
-
-#construct a list of compiled regular expressions from the
-#node_name_set
-regexp_list = []
-for name in node_name_set:
- regexp_list.append(re.compile(name))
-
-#used to see what kind of line we are on
-nodeexp = re.compile('Node')
-#used to check to see if the current line is an edge line
-arrowexp = re.compile('->')
-
-node_set = set()
-
-#read the file one line at a time
-buffer = input.readline()
-while buffer != '':
- #filter out the unnecessary checks on all the edge lines
- if not arrowexp.search(buffer):
- #check to see if this is a node we are looking for
- for regexp in regexp_list:
- #if this name is for the current node, add the dot variable name
- #for the node (it will be Node(hex number)) to our set of nodes
- if regexp.search(buffer):
- node_set |= set([re.split('\s+',buffer,2)[1]])
- break
- buffer = input.readline()
-
-
-#test code
-#print '\n'
-
-print node_name_set
-
-#print node_set
-
-
-#open the output file
-output = open(sys.argv[2], 'w')
-#start the second pass over the file
-input = open(sys.argv[1], 'r')
-
-buffer = input.readline()
-while buffer != '':
- #there are three types of lines we are looking for
- #1) node lines, 2) edge lines 3) support lines (like page size, etc)
-
- #is this an edge line?
- #note that this is no completely robust, if a none edge line
- #for some reason contains -> it will be missidentified
- #hand edit the file if this happens
- if arrowexp.search(buffer):
- #check to make sure that both nodes are in the node list
- #if they are print this to output
- nodes = arrowexp.split(buffer)
- nodes[0] = string.strip(nodes[0])
- nodes[1] = string.strip(nodes[1])
- if nodes[0][:13] in node_set and \
- nodes[1][:13] in node_set:
- output.write(buffer)
- elif nodeexp.search(buffer): #this is a node line
- node = re.split('\s+', buffer,2)[1]
- if node in node_set:
- output.write(buffer)
- else: #this is a support line
- output.write(buffer)
- buffer = input.readline()
-
Modified: trunk/contrib/llvm/utils/FileCheck/FileCheck.cpp
===================================================================
--- trunk/contrib/llvm/utils/FileCheck/FileCheck.cpp 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/FileCheck/FileCheck.cpp 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,901 +0,0 @@
-//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// FileCheck does a line-by line check of a file that validates whether it
-// contains the expected content. This is useful for regression tests etc.
-//
-// This program exits with an error status of 2 on error, exit status of 0 if
-// the file matched the expected contents, and exit status of 1 if it did not
-// contain the expected contents.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/ADT/OwningPtr.h"
-#include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/StringExtras.h"
-#include "llvm/ADT/StringMap.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Support/PrettyStackTrace.h"
-#include "llvm/Support/Regex.h"
-#include "llvm/Support/Signals.h"
-#include "llvm/Support/SourceMgr.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/Support/system_error.h"
-#include <algorithm>
-#include <map>
-#include <string>
-#include <vector>
-using namespace llvm;
-
-static cl::opt<std::string>
-CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
-
-static cl::opt<std::string>
-InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
- cl::init("-"), cl::value_desc("filename"));
-
-static cl::opt<std::string>
-CheckPrefix("check-prefix", cl::init("CHECK"),
- cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
-
-static cl::opt<bool>
-NoCanonicalizeWhiteSpace("strict-whitespace",
- cl::desc("Do not treat all horizontal whitespace as equivalent"));
-
-//===----------------------------------------------------------------------===//
-// Pattern Handling Code.
-//===----------------------------------------------------------------------===//
-
-class Pattern {
- SMLoc PatternLoc;
-
- /// MatchEOF - When set, this pattern only matches the end of file. This is
- /// used for trailing CHECK-NOTs.
- bool MatchEOF;
-
- /// FixedStr - If non-empty, this pattern is a fixed string match with the
- /// specified fixed string.
- StringRef FixedStr;
-
- /// RegEx - If non-empty, this is a regex pattern.
- std::string RegExStr;
-
- /// \brief Contains the number of line this pattern is in.
- unsigned LineNumber;
-
- /// VariableUses - Entries in this vector map to uses of a variable in the
- /// pattern, e.g. "foo[[bar]]baz". In this case, the RegExStr will contain
- /// "foobaz" and we'll get an entry in this vector that tells us to insert the
- /// value of bar at offset 3.
- std::vector<std::pair<StringRef, unsigned> > VariableUses;
-
- /// VariableDefs - Maps definitions of variables to their parenthesized
- /// capture numbers.
- /// E.g. for the pattern "foo[[bar:.*]]baz", VariableDefs will map "bar" to 1.
- std::map<StringRef, unsigned> VariableDefs;
-
-public:
-
- Pattern(bool matchEOF = false) : MatchEOF(matchEOF) { }
-
- /// getLoc - Return the location in source code.
- SMLoc getLoc() const { return PatternLoc; }
-
- /// ParsePattern - Parse the given string into the Pattern. SM provides the
- /// SourceMgr used for error reports, and LineNumber is the line number in
- /// the input file from which the pattern string was read.
- /// Returns true in case of an error, false otherwise.
- bool ParsePattern(StringRef PatternStr, SourceMgr &SM, unsigned LineNumber);
-
- /// Match - Match the pattern string against the input buffer Buffer. This
- /// returns the position that is matched or npos if there is no match. If
- /// there is a match, the size of the matched string is returned in MatchLen.
- ///
- /// The VariableTable StringMap provides the current values of filecheck
- /// variables and is updated if this match defines new values.
- size_t Match(StringRef Buffer, size_t &MatchLen,
- StringMap<StringRef> &VariableTable) const;
-
- /// PrintFailureInfo - Print additional information about a failure to match
- /// involving this pattern.
- void PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
- const StringMap<StringRef> &VariableTable) const;
-
-private:
- static void AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr);
- bool AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM);
- void AddBackrefToRegEx(unsigned BackrefNum);
-
- /// ComputeMatchDistance - Compute an arbitrary estimate for the quality of
- /// matching this pattern at the start of \arg Buffer; a distance of zero
- /// should correspond to a perfect match.
- unsigned ComputeMatchDistance(StringRef Buffer,
- const StringMap<StringRef> &VariableTable) const;
-
- /// \brief Evaluates expression and stores the result to \p Value.
- /// \return true on success. false when the expression has invalid syntax.
- bool EvaluateExpression(StringRef Expr, std::string &Value) const;
-
- /// \brief Finds the closing sequence of a regex variable usage or
- /// definition. Str has to point in the beginning of the definition
- /// (right after the opening sequence).
- /// \return offset of the closing sequence within Str, or npos if it was not
- /// found.
- size_t FindRegexVarEnd(StringRef Str);
-};
-
-
-bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM,
- unsigned LineNumber) {
- this->LineNumber = LineNumber;
- PatternLoc = SMLoc::getFromPointer(PatternStr.data());
-
- // Ignore trailing whitespace.
- while (!PatternStr.empty() &&
- (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
- PatternStr = PatternStr.substr(0, PatternStr.size()-1);
-
- // Check that there is something on the line.
- if (PatternStr.empty()) {
- SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
- "found empty check string with prefix '" +
- CheckPrefix+":'");
- return true;
- }
-
- // Check to see if this is a fixed string, or if it has regex pieces.
- if (PatternStr.size() < 2 ||
- (PatternStr.find("{{") == StringRef::npos &&
- PatternStr.find("[[") == StringRef::npos)) {
- FixedStr = PatternStr;
- return false;
- }
-
- // Paren value #0 is for the fully matched string. Any new parenthesized
- // values add from there.
- unsigned CurParen = 1;
-
- // Otherwise, there is at least one regex piece. Build up the regex pattern
- // by escaping scary characters in fixed strings, building up one big regex.
- while (!PatternStr.empty()) {
- // RegEx matches.
- if (PatternStr.startswith("{{")) {
- // This is the start of a regex match. Scan for the }}.
- size_t End = PatternStr.find("}}");
- if (End == StringRef::npos) {
- SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
- SourceMgr::DK_Error,
- "found start of regex string with no end '}}'");
- return true;
- }
-
- // Enclose {{}} patterns in parens just like [[]] even though we're not
- // capturing the result for any purpose. This is required in case the
- // expression contains an alternation like: CHECK: abc{{x|z}}def. We
- // want this to turn into: "abc(x|z)def" not "abcx|zdef".
- RegExStr += '(';
- ++CurParen;
-
- if (AddRegExToRegEx(PatternStr.substr(2, End-2), CurParen, SM))
- return true;
- RegExStr += ')';
-
- PatternStr = PatternStr.substr(End+2);
- continue;
- }
-
- // Named RegEx matches. These are of two forms: [[foo:.*]] which matches .*
- // (or some other regex) and assigns it to the FileCheck variable 'foo'. The
- // second form is [[foo]] which is a reference to foo. The variable name
- // itself must be of the form "[a-zA-Z_][0-9a-zA-Z_]*", otherwise we reject
- // it. This is to catch some common errors.
- if (PatternStr.startswith("[[")) {
- // Find the closing bracket pair ending the match. End is going to be an
- // offset relative to the beginning of the match string.
- size_t End = FindRegexVarEnd(PatternStr.substr(2));
-
- if (End == StringRef::npos) {
- SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
- SourceMgr::DK_Error,
- "invalid named regex reference, no ]] found");
- return true;
- }
-
- StringRef MatchStr = PatternStr.substr(2, End);
- PatternStr = PatternStr.substr(End+4);
-
- // Get the regex name (e.g. "foo").
- size_t NameEnd = MatchStr.find(':');
- StringRef Name = MatchStr.substr(0, NameEnd);
-
- if (Name.empty()) {
- SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
- "invalid name in named regex: empty name");
- return true;
- }
-
- // Verify that the name/expression is well formed. FileCheck currently
- // supports @LINE, @LINE+number, @LINE-number expressions. The check here
- // is relaxed, more strict check is performed in \c EvaluateExpression.
- bool IsExpression = false;
- for (unsigned i = 0, e = Name.size(); i != e; ++i) {
- if (i == 0 && Name[i] == '@') {
- if (NameEnd != StringRef::npos) {
- SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
- SourceMgr::DK_Error,
- "invalid name in named regex definition");
- return true;
- }
- IsExpression = true;
- continue;
- }
- if (Name[i] != '_' && !isalnum(Name[i]) &&
- (!IsExpression || (Name[i] != '+' && Name[i] != '-'))) {
- SM.PrintMessage(SMLoc::getFromPointer(Name.data()+i),
- SourceMgr::DK_Error, "invalid name in named regex");
- return true;
- }
- }
-
- // Name can't start with a digit.
- if (isdigit(static_cast<unsigned char>(Name[0]))) {
- SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
- "invalid name in named regex");
- return true;
- }
-
- // Handle [[foo]].
- if (NameEnd == StringRef::npos) {
- // Handle variables that were defined earlier on the same line by
- // emitting a backreference.
- if (VariableDefs.find(Name) != VariableDefs.end()) {
- unsigned VarParenNum = VariableDefs[Name];
- if (VarParenNum < 1 || VarParenNum > 9) {
- SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
- SourceMgr::DK_Error,
- "Can't back-reference more than 9 variables");
- return true;
- }
- AddBackrefToRegEx(VarParenNum);
- } else {
- VariableUses.push_back(std::make_pair(Name, RegExStr.size()));
- }
- continue;
- }
-
- // Handle [[foo:.*]].
- VariableDefs[Name] = CurParen;
- RegExStr += '(';
- ++CurParen;
-
- if (AddRegExToRegEx(MatchStr.substr(NameEnd+1), CurParen, SM))
- return true;
-
- RegExStr += ')';
- }
-
- // Handle fixed string matches.
- // Find the end, which is the start of the next regex.
- size_t FixedMatchEnd = PatternStr.find("{{");
- FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
- AddFixedStringToRegEx(PatternStr.substr(0, FixedMatchEnd), RegExStr);
- PatternStr = PatternStr.substr(FixedMatchEnd);
- }
-
- return false;
-}
-
-void Pattern::AddFixedStringToRegEx(StringRef FixedStr, std::string &TheStr) {
- // Add the characters from FixedStr to the regex, escaping as needed. This
- // avoids "leaning toothpicks" in common patterns.
- for (unsigned i = 0, e = FixedStr.size(); i != e; ++i) {
- switch (FixedStr[i]) {
- // These are the special characters matched in "p_ere_exp".
- case '(':
- case ')':
- case '^':
- case '$':
- case '|':
- case '*':
- case '+':
- case '?':
- case '.':
- case '[':
- case '\\':
- case '{':
- TheStr += '\\';
- // FALL THROUGH.
- default:
- TheStr += FixedStr[i];
- break;
- }
- }
-}
-
-bool Pattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen,
- SourceMgr &SM) {
- Regex R(RS);
- std::string Error;
- if (!R.isValid(Error)) {
- SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
- "invalid regex: " + Error);
- return true;
- }
-
- RegExStr += RS.str();
- CurParen += R.getNumMatches();
- return false;
-}
-
-void Pattern::AddBackrefToRegEx(unsigned BackrefNum) {
- assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
- std::string Backref = std::string("\\") +
- std::string(1, '0' + BackrefNum);
- RegExStr += Backref;
-}
-
-bool Pattern::EvaluateExpression(StringRef Expr, std::string &Value) const {
- // The only supported expression is @LINE([\+-]\d+)?
- if (!Expr.startswith("@LINE"))
- return false;
- Expr = Expr.substr(StringRef("@LINE").size());
- int Offset = 0;
- if (!Expr.empty()) {
- if (Expr[0] == '+')
- Expr = Expr.substr(1);
- else if (Expr[0] != '-')
- return false;
- if (Expr.getAsInteger(10, Offset))
- return false;
- }
- Value = llvm::itostr(LineNumber + Offset);
- return true;
-}
-
-/// Match - Match the pattern string against the input buffer Buffer. This
-/// returns the position that is matched or npos if there is no match. If
-/// there is a match, the size of the matched string is returned in MatchLen.
-size_t Pattern::Match(StringRef Buffer, size_t &MatchLen,
- StringMap<StringRef> &VariableTable) const {
- // If this is the EOF pattern, match it immediately.
- if (MatchEOF) {
- MatchLen = 0;
- return Buffer.size();
- }
-
- // If this is a fixed string pattern, just match it now.
- if (!FixedStr.empty()) {
- MatchLen = FixedStr.size();
- return Buffer.find(FixedStr);
- }
-
- // Regex match.
-
- // If there are variable uses, we need to create a temporary string with the
- // actual value.
- StringRef RegExToMatch = RegExStr;
- std::string TmpStr;
- if (!VariableUses.empty()) {
- TmpStr = RegExStr;
-
- unsigned InsertOffset = 0;
- for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
- std::string Value;
-
- if (VariableUses[i].first[0] == '@') {
- if (!EvaluateExpression(VariableUses[i].first, Value))
- return StringRef::npos;
- } else {
- StringMap<StringRef>::iterator it =
- VariableTable.find(VariableUses[i].first);
- // If the variable is undefined, return an error.
- if (it == VariableTable.end())
- return StringRef::npos;
-
- // Look up the value and escape it so that we can plop it into the regex.
- AddFixedStringToRegEx(it->second, Value);
- }
-
- // Plop it into the regex at the adjusted offset.
- TmpStr.insert(TmpStr.begin()+VariableUses[i].second+InsertOffset,
- Value.begin(), Value.end());
- InsertOffset += Value.size();
- }
-
- // Match the newly constructed regex.
- RegExToMatch = TmpStr;
- }
-
-
- SmallVector<StringRef, 4> MatchInfo;
- if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
- return StringRef::npos;
-
- // Successful regex match.
- assert(!MatchInfo.empty() && "Didn't get any match");
- StringRef FullMatch = MatchInfo[0];
-
- // If this defines any variables, remember their values.
- for (std::map<StringRef, unsigned>::const_iterator I = VariableDefs.begin(),
- E = VariableDefs.end();
- I != E; ++I) {
- assert(I->second < MatchInfo.size() && "Internal paren error");
- VariableTable[I->first] = MatchInfo[I->second];
- }
-
- MatchLen = FullMatch.size();
- return FullMatch.data()-Buffer.data();
-}
-
-unsigned Pattern::ComputeMatchDistance(StringRef Buffer,
- const StringMap<StringRef> &VariableTable) const {
- // Just compute the number of matching characters. For regular expressions, we
- // just compare against the regex itself and hope for the best.
- //
- // FIXME: One easy improvement here is have the regex lib generate a single
- // example regular expression which matches, and use that as the example
- // string.
- StringRef ExampleString(FixedStr);
- if (ExampleString.empty())
- ExampleString = RegExStr;
-
- // Only compare up to the first line in the buffer, or the string size.
- StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
- BufferPrefix = BufferPrefix.split('\n').first;
- return BufferPrefix.edit_distance(ExampleString);
-}
-
-void Pattern::PrintFailureInfo(const SourceMgr &SM, StringRef Buffer,
- const StringMap<StringRef> &VariableTable) const{
- // If this was a regular expression using variables, print the current
- // variable values.
- if (!VariableUses.empty()) {
- for (unsigned i = 0, e = VariableUses.size(); i != e; ++i) {
- SmallString<256> Msg;
- raw_svector_ostream OS(Msg);
- StringRef Var = VariableUses[i].first;
- if (Var[0] == '@') {
- std::string Value;
- if (EvaluateExpression(Var, Value)) {
- OS << "with expression \"";
- OS.write_escaped(Var) << "\" equal to \"";
- OS.write_escaped(Value) << "\"";
- } else {
- OS << "uses incorrect expression \"";
- OS.write_escaped(Var) << "\"";
- }
- } else {
- StringMap<StringRef>::const_iterator it = VariableTable.find(Var);
-
- // Check for undefined variable references.
- if (it == VariableTable.end()) {
- OS << "uses undefined variable \"";
- OS.write_escaped(Var) << "\"";
- } else {
- OS << "with variable \"";
- OS.write_escaped(Var) << "\" equal to \"";
- OS.write_escaped(it->second) << "\"";
- }
- }
-
- SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
- OS.str());
- }
- }
-
- // Attempt to find the closest/best fuzzy match. Usually an error happens
- // because some string in the output didn't exactly match. In these cases, we
- // would like to show the user a best guess at what "should have" matched, to
- // save them having to actually check the input manually.
- size_t NumLinesForward = 0;
- size_t Best = StringRef::npos;
- double BestQuality = 0;
-
- // Use an arbitrary 4k limit on how far we will search.
- for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
- if (Buffer[i] == '\n')
- ++NumLinesForward;
-
- // Patterns have leading whitespace stripped, so skip whitespace when
- // looking for something which looks like a pattern.
- if (Buffer[i] == ' ' || Buffer[i] == '\t')
- continue;
-
- // Compute the "quality" of this match as an arbitrary combination of the
- // match distance and the number of lines skipped to get to this match.
- unsigned Distance = ComputeMatchDistance(Buffer.substr(i), VariableTable);
- double Quality = Distance + (NumLinesForward / 100.);
-
- if (Quality < BestQuality || Best == StringRef::npos) {
- Best = i;
- BestQuality = Quality;
- }
- }
-
- // Print the "possible intended match here" line if we found something
- // reasonable and not equal to what we showed in the "scanning from here"
- // line.
- if (Best && Best != StringRef::npos && BestQuality < 50) {
- SM.PrintMessage(SMLoc::getFromPointer(Buffer.data() + Best),
- SourceMgr::DK_Note, "possible intended match here");
-
- // FIXME: If we wanted to be really friendly we would show why the match
- // failed, as it can be hard to spot simple one character differences.
- }
-}
-
-size_t Pattern::FindRegexVarEnd(StringRef Str) {
- // Offset keeps track of the current offset within the input Str
- size_t Offset = 0;
- // [...] Nesting depth
- size_t BracketDepth = 0;
-
- while (!Str.empty()) {
- if (Str.startswith("]]") && BracketDepth == 0)
- return Offset;
- if (Str[0] == '\\') {
- // Backslash escapes the next char within regexes, so skip them both.
- Str = Str.substr(2);
- Offset += 2;
- } else {
- switch (Str[0]) {
- default:
- break;
- case '[':
- BracketDepth++;
- break;
- case ']':
- assert(BracketDepth > 0 && "Invalid regex");
- BracketDepth--;
- break;
- }
- Str = Str.substr(1);
- Offset++;
- }
- }
-
- return StringRef::npos;
-}
-
-
-//===----------------------------------------------------------------------===//
-// Check Strings.
-//===----------------------------------------------------------------------===//
-
-/// CheckString - This is a check that we found in the input file.
-struct CheckString {
- /// Pat - The pattern to match.
- Pattern Pat;
-
- /// Loc - The location in the match file that the check string was specified.
- SMLoc Loc;
-
- /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
- /// to a CHECK: directive.
- bool IsCheckNext;
-
- /// NotStrings - These are all of the strings that are disallowed from
- /// occurring between this match string and the previous one (or start of
- /// file).
- std::vector<Pattern> NotStrings;
-
- CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
- : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
-};
-
-/// Canonicalize whitespaces in the input file. Line endings are replaced
-/// with UNIX-style '\n'.
-///
-/// \param PreserveHorizontal Don't squash consecutive horizontal whitespace
-/// characters to a single space.
-static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB,
- bool PreserveHorizontal) {
- SmallString<128> NewFile;
- NewFile.reserve(MB->getBufferSize());
-
- for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
- Ptr != End; ++Ptr) {
- // Eliminate trailing dosish \r.
- if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
- continue;
- }
-
- // If current char is not a horizontal whitespace or if horizontal
- // whitespace canonicalization is disabled, dump it to output as is.
- if (PreserveHorizontal || (*Ptr != ' ' && *Ptr != '\t')) {
- NewFile.push_back(*Ptr);
- continue;
- }
-
- // Otherwise, add one space and advance over neighboring space.
- NewFile.push_back(' ');
- while (Ptr+1 != End &&
- (Ptr[1] == ' ' || Ptr[1] == '\t'))
- ++Ptr;
- }
-
- // Free the old buffer and return a new one.
- MemoryBuffer *MB2 =
- MemoryBuffer::getMemBufferCopy(NewFile.str(), MB->getBufferIdentifier());
-
- delete MB;
- return MB2;
-}
-
-
-/// ReadCheckFile - Read the check file, which specifies the sequence of
-/// expected strings. The strings are added to the CheckStrings vector.
-/// Returns true in case of an error, false otherwise.
-static bool ReadCheckFile(SourceMgr &SM,
- std::vector<CheckString> &CheckStrings) {
- OwningPtr<MemoryBuffer> File;
- if (error_code ec =
- MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), File)) {
- errs() << "Could not open check file '" << CheckFilename << "': "
- << ec.message() << '\n';
- return true;
- }
-
- // If we want to canonicalize whitespace, strip excess whitespace from the
- // buffer containing the CHECK lines. Remove DOS style line endings.
- MemoryBuffer *F =
- CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
-
- SM.AddNewSourceBuffer(F, SMLoc());
-
- // Find all instances of CheckPrefix followed by : in the file.
- StringRef Buffer = F->getBuffer();
- std::vector<Pattern> NotMatches;
-
- // LineNumber keeps track of the line on which CheckPrefix instances are
- // found.
- unsigned LineNumber = 1;
-
- while (1) {
- // See if Prefix occurs in the memory buffer.
- size_t PrefixLoc = Buffer.find(CheckPrefix);
- // If we didn't find a match, we're done.
- if (PrefixLoc == StringRef::npos)
- break;
-
- LineNumber += Buffer.substr(0, PrefixLoc).count('\n');
-
- Buffer = Buffer.substr(PrefixLoc);
-
- const char *CheckPrefixStart = Buffer.data();
-
- // When we find a check prefix, keep track of whether we find CHECK: or
- // CHECK-NEXT:
- bool IsCheckNext = false, IsCheckNot = false;
-
- // Verify that the : is present after the prefix.
- if (Buffer[CheckPrefix.size()] == ':') {
- Buffer = Buffer.substr(CheckPrefix.size()+1);
- } else if (Buffer.size() > CheckPrefix.size()+6 &&
- memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
- Buffer = Buffer.substr(CheckPrefix.size()+6);
- IsCheckNext = true;
- } else if (Buffer.size() > CheckPrefix.size()+5 &&
- memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
- Buffer = Buffer.substr(CheckPrefix.size()+5);
- IsCheckNot = true;
- } else {
- Buffer = Buffer.substr(1);
- continue;
- }
-
- // Okay, we found the prefix, yay. Remember the rest of the line, but
- // ignore leading and trailing whitespace.
- Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
-
- // Scan ahead to the end of line.
- size_t EOL = Buffer.find_first_of("\n\r");
-
- // Remember the location of the start of the pattern, for diagnostics.
- SMLoc PatternLoc = SMLoc::getFromPointer(Buffer.data());
-
- // Parse the pattern.
- Pattern P;
- if (P.ParsePattern(Buffer.substr(0, EOL), SM, LineNumber))
- return true;
-
- Buffer = Buffer.substr(EOL);
-
- // Verify that CHECK-NEXT lines have at least one CHECK line before them.
- if (IsCheckNext && CheckStrings.empty()) {
- SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
- SourceMgr::DK_Error,
- "found '"+CheckPrefix+"-NEXT:' without previous '"+
- CheckPrefix+ ": line");
- return true;
- }
-
- // Handle CHECK-NOT.
- if (IsCheckNot) {
- NotMatches.push_back(P);
- continue;
- }
-
- // Okay, add the string we captured to the output vector and move on.
- CheckStrings.push_back(CheckString(P,
- PatternLoc,
- IsCheckNext));
- std::swap(NotMatches, CheckStrings.back().NotStrings);
- }
-
- // Add an EOF pattern for any trailing CHECK-NOTs.
- if (!NotMatches.empty()) {
- CheckStrings.push_back(CheckString(Pattern(true),
- SMLoc::getFromPointer(Buffer.data()),
- false));
- std::swap(NotMatches, CheckStrings.back().NotStrings);
- }
-
- if (CheckStrings.empty()) {
- errs() << "error: no check strings found with prefix '" << CheckPrefix
- << ":'\n";
- return true;
- }
-
- return false;
-}
-
-static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
- StringRef Buffer,
- StringMap<StringRef> &VariableTable) {
- // Otherwise, we have an error, emit an error message.
- SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
- "expected string not found in input");
-
- // Print the "scanning from here" line. If the current position is at the
- // end of a line, advance to the start of the next line.
- Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
-
- SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), SourceMgr::DK_Note,
- "scanning from here");
-
- // Allow the pattern to print additional information if desired.
- CheckStr.Pat.PrintFailureInfo(SM, Buffer, VariableTable);
-}
-
-/// CountNumNewlinesBetween - Count the number of newlines in the specified
-/// range.
-static unsigned CountNumNewlinesBetween(StringRef Range) {
- unsigned NumNewLines = 0;
- while (1) {
- // Scan for newline.
- Range = Range.substr(Range.find_first_of("\n\r"));
- if (Range.empty()) return NumNewLines;
-
- ++NumNewLines;
-
- // Handle \n\r and \r\n as a single newline.
- if (Range.size() > 1 &&
- (Range[1] == '\n' || Range[1] == '\r') &&
- (Range[0] != Range[1]))
- Range = Range.substr(1);
- Range = Range.substr(1);
- }
-}
-
-int main(int argc, char **argv) {
- sys::PrintStackTraceOnErrorSignal();
- PrettyStackTraceProgram X(argc, argv);
- cl::ParseCommandLineOptions(argc, argv);
-
- SourceMgr SM;
-
- // Read the expected strings from the check file.
- std::vector<CheckString> CheckStrings;
- if (ReadCheckFile(SM, CheckStrings))
- return 2;
-
- // Open the file to check and add it to SourceMgr.
- OwningPtr<MemoryBuffer> File;
- if (error_code ec =
- MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
- errs() << "Could not open input file '" << InputFilename << "': "
- << ec.message() << '\n';
- return 2;
- }
-
- if (File->getBufferSize() == 0) {
- errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
- return 2;
- }
-
- // Remove duplicate spaces in the input file if requested.
- // Remove DOS style line endings.
- MemoryBuffer *F =
- CanonicalizeInputFile(File.take(), NoCanonicalizeWhiteSpace);
-
- SM.AddNewSourceBuffer(F, SMLoc());
-
- /// VariableTable - This holds all the current filecheck variables.
- StringMap<StringRef> VariableTable;
-
- // Check that we have all of the expected strings, in order, in the input
- // file.
- StringRef Buffer = F->getBuffer();
-
- const char *LastMatch = Buffer.data();
-
- for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
- const CheckString &CheckStr = CheckStrings[StrNo];
-
- StringRef SearchFrom = Buffer;
-
- // Find StrNo in the file.
- size_t MatchLen = 0;
- size_t MatchPos = CheckStr.Pat.Match(Buffer, MatchLen, VariableTable);
- Buffer = Buffer.substr(MatchPos);
-
- // If we didn't find a match, reject the input.
- if (MatchPos == StringRef::npos) {
- PrintCheckFailed(SM, CheckStr, SearchFrom, VariableTable);
- return 1;
- }
-
- StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
-
- // If this check is a "CHECK-NEXT", verify that the previous match was on
- // the previous line (i.e. that there is one newline between them).
- if (CheckStr.IsCheckNext) {
- // Count the number of newlines between the previous match and this one.
- assert(LastMatch != F->getBufferStart() &&
- "CHECK-NEXT can't be the first check in a file");
-
- unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
- if (NumNewLines == 0) {
- SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error,
- CheckPrefix+"-NEXT: is on the same line as previous match");
- SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
- SourceMgr::DK_Note, "'next' match was here");
- SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
- "previous match was here");
- return 1;
- }
-
- if (NumNewLines != 1) {
- SM.PrintMessage(CheckStr.Loc, SourceMgr::DK_Error, CheckPrefix+
- "-NEXT: is not on the line after the previous match");
- SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
- SourceMgr::DK_Note, "'next' match was here");
- SM.PrintMessage(SMLoc::getFromPointer(LastMatch), SourceMgr::DK_Note,
- "previous match was here");
- return 1;
- }
- }
-
- // If this match had "not strings", verify that they don't exist in the
- // skipped region.
- for (unsigned ChunkNo = 0, e = CheckStr.NotStrings.size();
- ChunkNo != e; ++ChunkNo) {
- size_t MatchLen = 0;
- size_t Pos = CheckStr.NotStrings[ChunkNo].Match(SkippedRegion, MatchLen,
- VariableTable);
- if (Pos == StringRef::npos) continue;
-
- SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos), SourceMgr::DK_Error,
- CheckPrefix+"-NOT: string occurred!");
- SM.PrintMessage(CheckStr.NotStrings[ChunkNo].getLoc(), SourceMgr::DK_Note,
- CheckPrefix+"-NOT: pattern specified here");
- return 1;
- }
-
-
- // Otherwise, everything is good. Step over the matched text and remember
- // the position after the match as the end of the last match.
- Buffer = Buffer.substr(MatchLen);
- LastMatch = Buffer.data();
- }
-
- return 0;
-}
Modified: trunk/contrib/llvm/utils/FileUpdate/FileUpdate.cpp
===================================================================
--- trunk/contrib/llvm/utils/FileUpdate/FileUpdate.cpp 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/FileUpdate/FileUpdate.cpp 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,87 +0,0 @@
-//===- FileUpdate.cpp - Conditionally update a file -----------------------===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// FileUpdate is a utility for conditionally updating a file from its input
-// based on whether the input differs from the output. It is used to avoid
-// unnecessary modifications in a build system.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/ADT/OwningPtr.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/MemoryBuffer.h"
-#include "llvm/Support/PrettyStackTrace.h"
-#include "llvm/Support/Signals.h"
-#include "llvm/Support/ToolOutputFile.h"
-#include "llvm/Support/system_error.h"
-using namespace llvm;
-
-static cl::opt<bool>
-Quiet("quiet", cl::desc("Don't print unnecessary status information"),
- cl::init(false));
-
-static cl::opt<std::string>
-InputFilename("input-file", cl::desc("Input file (defaults to stdin)"),
- cl::init("-"), cl::value_desc("filename"));
-
-static cl::opt<std::string>
-OutputFilename(cl::Positional, cl::desc("<output-file>"), cl::Required);
-
-int main(int argc, char **argv) {
- sys::PrintStackTraceOnErrorSignal();
- PrettyStackTraceProgram X(argc, argv);
- cl::ParseCommandLineOptions(argc, argv);
-
- if (OutputFilename == "-") {
- errs() << argv[0] << ": error: Can't update standard output\n";
- return 1;
- }
-
- // Get the input data.
- OwningPtr<MemoryBuffer> In;
- if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), In)) {
- errs() << argv[0] << ": error: Unable to get input '"
- << InputFilename << "': " << ec.message() << '\n';
- return 1;
- }
-
- // Get the output data.
- OwningPtr<MemoryBuffer> Out;
- MemoryBuffer::getFile(OutputFilename.c_str(), Out);
-
- // If the output exists and the contents match, we are done.
- if (Out && In->getBufferSize() == Out->getBufferSize() &&
- memcmp(In->getBufferStart(), Out->getBufferStart(),
- Out->getBufferSize()) == 0) {
- if (!Quiet)
- errs() << argv[0] << ": Not updating '" << OutputFilename
- << "', contents match input.\n";
- return 0;
- }
-
- // Otherwise, overwrite the output.
- if (!Quiet)
- errs() << argv[0] << ": Updating '" << OutputFilename
- << "', contents changed.\n";
- std::string ErrorStr;
- tool_output_file OutStream(OutputFilename.c_str(), ErrorStr,
- raw_fd_ostream::F_Binary);
- if (!ErrorStr.empty()) {
- errs() << argv[0] << ": Unable to write output '"
- << OutputFilename << "': " << ErrorStr << '\n';
- return 1;
- }
-
- OutStream.os().write(In->getBufferStart(), In->getBufferSize());
-
- // Declare success.
- OutStream.keep();
-
- return 0;
-}
Modified: trunk/contrib/llvm/utils/GenLibDeps.pl
===================================================================
--- trunk/contrib/llvm/utils/GenLibDeps.pl 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/GenLibDeps.pl 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,384 +0,0 @@
-#!/usr/bin/perl -w
-#
-# Program: GenLibDeps.pl
-#
-# Synopsis: Generate HTML output that shows the dependencies between a set of
-# libraries. The output of this script should periodically replace
-# the similar content in the UsingLibraries.html document.
-#
-# Syntax: GenLibDeps.pl [-flat] <directory_with_libraries_in_it> [path_to_nm_binary]
-#
-use strict;
-use warnings;
-# Parse arguments...
-my $FLAT = 0;
-my $WHY = 0;
-my $PEROBJ = 0;
-my $PEROBJINCL = 0;
-while (scalar(@ARGV) and ($_ = $ARGV[0], /^[-+]/)) {
- shift;
- last if /^--$/; # Stop processing arguments on --
-
- # List command line options here...
- if (/^-flat$/) { $FLAT = 1; next; }
- if (/^-why/) { $WHY = 1; $FLAT = 1; next; }
- if (/^-perobj$/) { $PEROBJ = 1; next; }
- if (/^-perobjincl/) { $PEROBJINCL = 1; next;}
- print "Unknown option: $_ : ignoring!\n";
-}
-
-# Give first option a name.
-my $Directory = $ARGV[0];
-if (!defined($Directory) || ! -d "$Directory") {
- die "First argument must specify the directory containing LLVM libs\n";
-}
-
-my $nmPath = $ARGV[1];
-
-# Find the "dot" program
-my $DotPath="";
-if (!$FLAT) {
- chomp($DotPath = `which dot`);
- die "Can't find 'dot'" if (! -x "$DotPath");
-}
-
-if (defined($ENV{NM})) {
- chomp($nmPath=$ENV{NM});
-}
-
-if (!defined($nmPath) || $nmPath eq "") {
- chomp($nmPath=`which nm`);
- die "Can't find 'nm'" if (! -x "$nmPath");
-}
-
-my $ranlibPath;
-if ($PEROBJ) {
- $ranlibPath = $ARGV[2];
- if (defined($ENV{RANLIB})) {
- chomp($ranlibPath=$ENV{RANLIB});
- }
-
- if (!defined($ranlibPath) || $ranlibPath eq "") {
- chomp($ranlibPath=`which ranlib`);
- die "Can't find 'ranlib'" if (! -x "$ranlibPath");
- }
-}
-
-# Open the directory and read its contents, sorting by name and differentiating
-# by whether its a library (.a) or an object file (.o)
-opendir DIR,$Directory;
-my @files = readdir DIR;
-closedir DIR;
-my @libs = grep(/libLLVM.*\.(dylib|so|a)$/,sort(@files));
-# Omit the all-of-llvm shared library.
- at libs = grep(!/libLLVM-\d\.\d(svn)?\.(dylib|so)/, @libs);
-my @objs = grep(/LLVM.*\.o$/,sort(@files));
-
-# Declare the hashes we will use to keep track of the library and object file
-# symbol definitions.
-my %libdefs;
-my %objdefs;
-
-my %libobjs;
-my %objdeps=();
-# Gather library definitions at object file granularity (optional)
-if ($PEROBJ) {
- foreach my $lib (@libs ) {
- `$ranlibPath $Directory/$lib`;
- my $libpath = $lib;
- $libpath =~ s/^libLLVM(.*)\.a/$1/;
- $libpath =~ s/(.+)CodeGen$/Target\/$1/;
- $libpath =~ s/(.+)AsmPrinter$/Target\/$1\/AsmPrinter/;
- $libpath =~ s/(.+)AsmParser$/Target\/$1\/AsmParser/;
- $libpath =~ s/(.+)Info$/Target\/$1\/TargetInfo/;
- $libpath =~ s/(.+)Disassembler$/Target\/$1\/Disassembler/;
- $libpath =~ s/SelectionDAG/CodeGen\/SelectionDAG/;
- $libpath =~ s/^AsmPrinter/CodeGen\/AsmPrinter/;
- $libpath =~ s/^BitReader/Bitcode\/Reader/;
- $libpath =~ s/^BitWriter/Bitcode\/Writer/;
- $libpath =~ s/^CppBackend/Target\/CppBackend/;
- $libpath =~ s/^MSIL/Target\/MSIL/;
- $libpath =~ s/^Core/IR/;
- $libpath =~ s/^Instrumentation/Transforms\/Instrumentation/;
- $libpath =~ s/^Interpreter/ExecutionEngine\/Interpreter/;
- $libpath =~ s/^JIT/ExecutionEngine\/JIT/;
- $libpath =~ s/^ScalarOpts/Transforms\/Scalar/;
- $libpath =~ s/^TransformUtils/Transforms\/Utils/;
- $libpath =~ s/^ipa/Analysis\/IPA/;
- $libpath =~ s/^ipo/Transforms\/IPO/;
- $libpath = "lib/".$libpath."/";
- open DEFS, "$nmPath -sg $Directory/$lib|";
- while (<DEFS>) {
- chomp;
- if (/^([^ ]*) in ([^ ]*)/) {
- my $objfile = $libpath.$2;
- $objdefs{$1} = $objfile;
- $objdeps{$objfile} = {};
- $libobjs{$lib}{$objfile}=1;
-# my $p = "../llvm/".$objfile;
-# $p =~ s/Support\/reg(.*).o/Support\/reg$1.c/;
-# $p =~ s/.o$/.cpp/;
-# unless (-e $p) {
-# die "$p\n"
-# }
- }
- }
- close DEFS or die "nm failed";
- }
- foreach my $lib (@libs ) {
- my $libpath = $lib;
- $libpath =~ s/^libLLVM(.*)\.a/$1/;
- $libpath =~ s/(.+)CodeGen$/Target\/$1/;
- $libpath =~ s/(.+)AsmPrinter$/Target\/$1\/AsmPrinter/;
- $libpath =~ s/(.+)AsmParser$/Target\/$1\/AsmParser/;
- $libpath =~ s/(.+)Info$/Target\/$1\/TargetInfo/;
- $libpath =~ s/(.+)Disassembler$/Target\/$1\/Disassembler/;
- $libpath =~ s/SelectionDAG/CodeGen\/SelectionDAG/;
- $libpath =~ s/^AsmPrinter/CodeGen\/AsmPrinter/;
- $libpath =~ s/^BitReader/Bitcode\/Reader/;
- $libpath =~ s/^BitWriter/Bitcode\/Writer/;
- $libpath =~ s/^CppBackend/Target\/CppBackend/;
- $libpath =~ s/^MSIL/Target\/MSIL/;
- $libpath =~ s/^Core/VMCore/;
- $libpath =~ s/^Instrumentation/Transforms\/Instrumentation/;
- $libpath =~ s/^Interpreter/ExecutionEngine\/Interpreter/;
- $libpath =~ s/^JIT/ExecutionEngine\/JIT/;
- $libpath =~ s/^ScalarOpts/Transforms\/Scalar/;
- $libpath =~ s/^TransformUtils/Transforms\/Utils/;
- $libpath =~ s/^ipa/Analysis\/IPA/;
- $libpath =~ s/^ipo/Transforms\/IPO/;
- $libpath = "lib/".$libpath."/";
- open UDEFS, "$nmPath -Aup $Directory/$lib|";
- while (<UDEFS>) {
- chomp;
- if (/:([^:]+):/) {
- my $obj = $libpath.$1;
- s/[^ ]+: *U //;
- if (defined($objdefs{$_})) {
- $objdeps{$obj}{$objdefs{$_}}=1;
- }
- }
- }
- close UDEFS or die "nm failed"
- }
-} else {
-# Gather definitions from the libraries
-foreach my $lib (@libs ) {
- open DEFS, "$nmPath -g $Directory/$lib|";
- while (<DEFS>) {
- next if (! / [ABCDGRST] /);
- s/^[^ ]* [ABCDGRST] //;
- s/\015?\012//; # not sure if <DEFS> is in binmode and uses LF or CRLF.
- # this strips both LF and CRLF.
- $libdefs{$_} = $lib;
- }
- close DEFS or die "nm failed";
-}
-}
-
-# Gather definitions from the object files.
-foreach my $obj (@objs ) {
- open DEFS, "$nmPath -g $Directory/$obj |";
- while (<DEFS>) {
- next if (! / [ABCDGRST] /);
- s/^[^ ]* [ABCDGRST] //;
- s/\015?\012//; # not sure if <DEFS> is in binmode and uses LF or CRLF.
- # this strips both LF and CRLF.
- $objdefs{$_} = $obj;
- }
- close DEFS or die "nm failed";
-}
-
-# Generate one entry in the <dl> list. This generates the <dt> and <dd> elements
-# for one library or object file. The <dt> provides the name of the library or
-# object. The <dd> provides a list of the libraries/objects it depends on.
-sub gen_one_entry {
- my $lib = $_[0];
- my $lib_ns = $lib;
- $lib_ns =~ s/(.*)\.[oa]/$1/;
- if ($FLAT) {
- print "$lib:";
- if ($WHY) { print "\n"; }
- } else {
- print " <dt><b>$lib</b></dt><dd><ul>\n";
- }
- open UNDEFS,
- "$nmPath -u $Directory/$lib | sed -e 's/^[ 0]* U //' | sort | uniq |";
- my %DepLibs;
- while (<UNDEFS>) {
- chomp;
- my $lib_printed = 0;
- if (defined($libdefs{$_}) && $libdefs{$_} ne $lib) {
- $DepLibs{$libdefs{$_}} = [] unless exists $DepLibs{$libdefs{$_}};
- push(@{$DepLibs{$libdefs{$_}}}, $_);
- } elsif (defined($objdefs{$_}) && $objdefs{$_} ne $lib) {
- if ($PEROBJ && !$PEROBJINCL) {
- # -perobjincl makes .a files depend on .o files they contain themselves
- # default is don't depend on these.
- next if defined $libobjs{$lib}{$objdefs{$_}};
- }
- my $libroot = $lib;
- $libroot =~ s/lib(.*).a/$1/;
- if ($objdefs{$_} ne "$libroot.o") {
- $DepLibs{$objdefs{$_}} = [] unless exists $DepLibs{$objdefs{$_}};
- push(@{$DepLibs{$objdefs{$_}}}, $_);
- }
- }
- }
- close UNDEFS or die "nm failed";
- unless(keys %DepLibs) {
- # above failed
- open UNDEFS, "$nmPath -u $Directory/$lib |";
- while (<UNDEFS>) {
- # to bypass non-working sed
- if (' ' eq substr($_,0,2) and index($_,'U ')) {
- $_ = substr($_,index($_,'U ')+2)
- };
- $_ = substr($_,index($_,' *U ')+5) if -1!=index($_,' *U ');
-
- chomp;
- my $lib_printed = 0;
- if (defined($libdefs{$_}) && $libdefs{$_} ne $lib) {
- $DepLibs{$libdefs{$_}} = [] unless exists $DepLibs{$libdefs{$_}};
- push(@{$DepLibs{$libdefs{$_}}}, $_);
- } elsif (defined($objdefs{$_}) && $objdefs{$_} ne $lib) {
- my $libroot = $lib;
- $libroot =~ s/lib(.*).a/$1/;
- if ($objdefs{$_} ne "$libroot.o") {
- $DepLibs{$objdefs{$_}} = [] unless exists $DepLibs{$objdefs{$_}};
- push(@{$DepLibs{$objdefs{$_}}}, $_);
- }
- }
- }
- close UNDEFS or die "nm failed";
- }
- if ($PEROBJINCL) {
- # include the .a's objects
- for my $obj (keys %{$libobjs{$lib}}) {
- $DepLibs{$obj} = ["<.a object>"] unless exists $DepLibs{$obj};
- }
- my $madechange = 1;
- while($madechange) {
- $madechange = 0;
- my %temp = %DepLibs;
- foreach my $obj (keys %DepLibs) {
- foreach my $objdeps (keys %{$objdeps{$obj}}) {
- next if defined $temp{$objdeps};
- push(@{$temp{$objdeps}}, $obj);
- $madechange = 1;
- }
- }
- %DepLibs = %temp;
- }
- }
-
- for my $key (sort keys %DepLibs) {
- if ($FLAT) {
- print " $key";
- if ($WHY) {
- print "\n";
- my @syms = @{$DepLibs{$key}};
- foreach my $sym (@syms) {
- print " $sym\n";
- }
- }
- } else {
- print " <li>$key</li>\n";
- }
- my $suffix = substr($key,length($key)-1,1);
- $key =~ s/(.*)\.[oa]/$1/;
- if ($suffix eq "a") {
- if (!$FLAT) { print DOT "$lib_ns -> $key [ weight=0 ];\n" };
- } else {
- if (!$FLAT) { print DOT "$lib_ns -> $key [ weight=10];\n" };
- }
- }
- if ($FLAT) {
- if (!$WHY) {
- print "\n";
- }
- } else {
- print " </ul></dd>\n";
- }
-}
-
-# Make sure we flush on write. This is slower but correct based on the way we
-# write I/O in gen_one_entry.
-$| = 1;
-
-# Print the definition list tag
-if (!$FLAT) {
- print "<dl>\n";
-
- open DOT, "| $DotPath -Tgif > libdeps.gif";
-
- print DOT "digraph LibDeps {\n";
- print DOT " size=\"40,15\"; \n";
- print DOT " ratio=\"1.33333\"; \n";
- print DOT " margin=\"0.25\"; \n";
- print DOT " rankdir=\"LR\"; \n";
- print DOT " mclimit=\"50.0\"; \n";
- print DOT " ordering=\"out\"; \n";
- print DOT " center=\"1\";\n";
- print DOT "node [shape=\"box\",\n";
- print DOT " color=\"#000088\",\n";
- print DOT " fillcolor=\"#FFFACD\",\n";
- print DOT " fontcolor=\"#3355BB\",\n";
- print DOT " style=\"filled\",\n";
- print DOT " fontname=\"sans\",\n";
- print DOT " fontsize=\"24\"\n";
- print DOT "];\n";
- print DOT "edge [dir=\"forward\",style=\"solid\",color=\"#000088\"];\n";
-}
-
-# Print libraries first
-foreach my $lib (@libs) {
- gen_one_entry($lib);
-}
-
-if ($PEROBJ) {
- foreach my $obj (keys %objdeps) {
- print "$obj:";
- if (!$PEROBJINCL) {
- foreach my $dep (keys %{$objdeps{$obj}}) {
- print " $dep";
- }
- }
- print "\n";
- }
-}
-
-if (!$FLAT) {
- print DOT "}\n";
- close DOT;
- open DOT, "| $DotPath -Tgif > objdeps.gif";
- print DOT "digraph ObjDeps {\n";
- print DOT " size=\"8,10\";\n";
- print DOT " margin=\"0.25\";\n";
- print DOT " rankdir=\"LR\";\n";
- print DOT " mclimit=\"50.0\";\n";
- print DOT " ordering=\"out\";\n";
- print DOT " center=\"1\";\n";
- print DOT "node [shape=\"box\",\n";
- print DOT " color=\"#000088\",\n";
- print DOT " fillcolor=\"#FFFACD\",\n";
- print DOT " fontcolor=\"#3355BB\",\n";
- print DOT " fontname=\"sans\",\n";
- print DOT " style=\"filled\",\n";
- print DOT " fontsize=\"24\"\n";
- print DOT "];\n";
- print DOT "edge [dir=\"forward\",style=\"solid\",color=\"#000088\"];\n";
-}
-
-# Print objects second
-foreach my $obj (@objs) {
- gen_one_entry($obj);
-}
-
-if (!$FLAT) {
- print DOT "}\n";
- close DOT;
-
-# Print end tag of definition list element
- print "</dl>\n";
-}
Modified: trunk/contrib/llvm/utils/GetRepositoryPath
===================================================================
--- trunk/contrib/llvm/utils/GetRepositoryPath 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/GetRepositoryPath 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,27 +0,0 @@
-#!/bin/sh
-
-usage() {
- echo "usage: $0 <source root>"
- echo " Prints the source control repository path of the given source"
- echo " directory, the exact format of the revision string depends on the"
- echo " source control system. If the source control system isn't known,"
- echo " the output is empty and the exit code is 1."
- exit 1
-}
-
-if [ $# != 1 ] || [ ! -d $1 ]; then
- usage;
-fi
-
-cd $1
-if [ -d .svn ]; then
- svn info | grep 'URL:' | cut -d: -f2-
-elif [ -f .git/svn/.metadata ]; then
- git svn info | grep 'URL:' | cut -d: -f2-
-elif [ -d .git ]; then
- git remote -v | grep 'fetch' | awk '{ print $2 }'
-else
- exit 1;
-fi
-
-exit 0
Modified: trunk/contrib/llvm/utils/GetSourceVersion
===================================================================
--- trunk/contrib/llvm/utils/GetSourceVersion 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/GetSourceVersion 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,27 +0,0 @@
-#!/bin/sh
-
-usage() {
- echo "usage: $0 <source root>"
- echo " Prints the source control revision of the given source directory,"
- echo " the exact format of the revision string depends on the source "
- echo " control system. If the source control system isn't known, the output"
- echo " is empty and the exit code is 1."
- exit 1
-}
-
-if [ $# != 1 ] || [ ! -d $1 ]; then
- usage;
-fi
-
-cd $1
-if [ -d .svn ]; then
- svnversion | sed -e "s#\([0-9]*\)[A-Z]*#\1#"
-elif [ -f .git/svn/.metadata ]; then
- git svn info | grep 'Revision:' | cut -d: -f2-
-elif [ -d .git ]; then
- git log -1 --pretty=format:%H
-else
- exit 1;
-fi
-
-exit 0
Modified: trunk/contrib/llvm/utils/KillTheDoctor/KillTheDoctor.cpp
===================================================================
--- trunk/contrib/llvm/utils/KillTheDoctor/KillTheDoctor.cpp 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/KillTheDoctor/KillTheDoctor.cpp 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,553 +0,0 @@
-//===- KillTheDoctor - Prevent Dr. Watson from stopping tests ---*- C++ -*-===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This program provides an extremely hacky way to stop Dr. Watson from starting
-// due to unhandled exceptions in child processes.
-//
-// This simply starts the program named in the first positional argument with
-// the arguments following it under a debugger. All this debugger does is catch
-// any unhandled exceptions thrown in the child process and close the program
-// (and hopefully tells someone about it).
-//
-// This also provides another really hacky method to prevent assert dialog boxes
-// from popping up. When --no-user32 is passed, if any process loads user32.dll,
-// we assume it is trying to call MessageBoxEx and terminate it. The proper way
-// to do this would be to actually set a break point, but there's quite a bit
-// of code involved to get the address of MessageBoxEx in the remote process's
-// address space due to Address space layout randomization (ASLR). This can be
-// added if it's ever actually needed.
-//
-// If the subprocess exits for any reason other than successful termination, -1
-// is returned. If the process exits normally the value it returned is returned.
-//
-// I hate Windows.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/ADT/STLExtras.h"
-#include "llvm/ADT/SmallString.h"
-#include "llvm/ADT/SmallVector.h"
-#include "llvm/ADT/StringExtras.h"
-#include "llvm/ADT/StringRef.h"
-#include "llvm/ADT/Twine.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/ManagedStatic.h"
-#include "llvm/Support/PrettyStackTrace.h"
-#include "llvm/Support/Signals.h"
-#include "llvm/Support/raw_ostream.h"
-#include "llvm/Support/system_error.h"
-#include "llvm/Support/type_traits.h"
-#include <algorithm>
-#include <cerrno>
-#include <cstdlib>
-#include <map>
-#include <string>
-
-// These includes must be last.
-#include <Windows.h>
-#include <WinError.h>
-#include <Dbghelp.h>
-#include <psapi.h>
-
-using namespace llvm;
-
-#undef max
-
-namespace {
- cl::opt<std::string> ProgramToRun(cl::Positional,
- cl::desc("<program to run>"));
- cl::list<std::string> Argv(cl::ConsumeAfter,
- cl::desc("<program arguments>..."));
- cl::opt<bool> TraceExecution("x",
- cl::desc("Print detailed output about what is being run to stderr."));
- cl::opt<unsigned> Timeout("t", cl::init(0),
- cl::desc("Set maximum runtime in seconds. Defaults to infinite."));
- cl::opt<bool> NoUser32("no-user32",
- cl::desc("Terminate process if it loads user32.dll."));
-
- StringRef ToolName;
-
- template <typename HandleType>
- class ScopedHandle {
- typedef typename HandleType::handle_type handle_type;
-
- handle_type Handle;
-
- public:
- ScopedHandle()
- : Handle(HandleType::GetInvalidHandle()) {}
-
- explicit ScopedHandle(handle_type handle)
- : Handle(handle) {}
-
- ~ScopedHandle() {
- HandleType::Destruct(Handle);
- }
-
- ScopedHandle& operator=(handle_type handle) {
- // Cleanup current handle.
- if (!HandleType::isValid(Handle))
- HandleType::Destruct(Handle);
- Handle = handle;
- return *this;
- }
-
- operator bool() const {
- return HandleType::isValid(Handle);
- }
-
- operator handle_type() {
- return Handle;
- }
- };
-
- // This implements the most common handle in the Windows API.
- struct CommonHandle {
- typedef HANDLE handle_type;
-
- static handle_type GetInvalidHandle() {
- return INVALID_HANDLE_VALUE;
- }
-
- static void Destruct(handle_type Handle) {
- ::CloseHandle(Handle);
- }
-
- static bool isValid(handle_type Handle) {
- return Handle != GetInvalidHandle();
- }
- };
-
- struct FileMappingHandle {
- typedef HANDLE handle_type;
-
- static handle_type GetInvalidHandle() {
- return NULL;
- }
-
- static void Destruct(handle_type Handle) {
- ::CloseHandle(Handle);
- }
-
- static bool isValid(handle_type Handle) {
- return Handle != GetInvalidHandle();
- }
- };
-
- struct MappedViewOfFileHandle {
- typedef LPVOID handle_type;
-
- static handle_type GetInvalidHandle() {
- return NULL;
- }
-
- static void Destruct(handle_type Handle) {
- ::UnmapViewOfFile(Handle);
- }
-
- static bool isValid(handle_type Handle) {
- return Handle != GetInvalidHandle();
- }
- };
-
- struct ProcessHandle : CommonHandle {};
- struct ThreadHandle : CommonHandle {};
- struct TokenHandle : CommonHandle {};
- struct FileHandle : CommonHandle {};
-
- typedef ScopedHandle<FileMappingHandle> FileMappingScopedHandle;
- typedef ScopedHandle<MappedViewOfFileHandle> MappedViewOfFileScopedHandle;
- typedef ScopedHandle<ProcessHandle> ProcessScopedHandle;
- typedef ScopedHandle<ThreadHandle> ThreadScopedHandle;
- typedef ScopedHandle<TokenHandle> TokenScopedHandle;
- typedef ScopedHandle<FileHandle> FileScopedHandle;
-}
-
-static error_code GetFileNameFromHandle(HANDLE FileHandle,
- std::string& Name) {
- char Filename[MAX_PATH+1];
- bool Success = false;
- Name.clear();
-
- // Get the file size.
- LARGE_INTEGER FileSize;
- Success = ::GetFileSizeEx(FileHandle, &FileSize);
-
- if (!Success)
- return windows_error(::GetLastError());
-
- // Create a file mapping object.
- FileMappingScopedHandle FileMapping(
- ::CreateFileMappingA(FileHandle,
- NULL,
- PAGE_READONLY,
- 0,
- 1,
- NULL));
-
- if (!FileMapping)
- return windows_error(::GetLastError());
-
- // Create a file mapping to get the file name.
- MappedViewOfFileScopedHandle MappedFile(
- ::MapViewOfFile(FileMapping, FILE_MAP_READ, 0, 0, 1));
-
- if (!MappedFile)
- return windows_error(::GetLastError());
-
- Success = ::GetMappedFileNameA(::GetCurrentProcess(),
- MappedFile,
- Filename,
- array_lengthof(Filename) - 1);
-
- if (!Success)
- return windows_error(::GetLastError());
- else {
- Name = Filename;
- return windows_error::success;
- }
-}
-
-/// @brief Find program using shell lookup rules.
-/// @param Program This is either an absolute path, relative path, or simple a
-/// program name. Look in PATH for any programs that match. If no
-/// extension is present, try all extensions in PATHEXT.
-/// @return If ec == errc::success, The absolute path to the program. Otherwise
-/// the return value is undefined.
-static std::string FindProgram(const std::string &Program, error_code &ec) {
- char PathName[MAX_PATH + 1];
- typedef SmallVector<StringRef, 12> pathext_t;
- pathext_t pathext;
- // Check for the program without an extension (in case it already has one).
- pathext.push_back("");
- SplitString(std::getenv("PATHEXT"), pathext, ";");
-
- for (pathext_t::iterator i = pathext.begin(), e = pathext.end(); i != e; ++i){
- SmallString<5> ext;
- for (std::size_t ii = 0, e = i->size(); ii != e; ++ii)
- ext.push_back(::tolower((*i)[ii]));
- LPCSTR Extension = NULL;
- if (ext.size() && ext[0] == '.')
- Extension = ext.c_str();
- DWORD length = ::SearchPathA(NULL,
- Program.c_str(),
- Extension,
- array_lengthof(PathName),
- PathName,
- NULL);
- if (length == 0)
- ec = windows_error(::GetLastError());
- else if (length > array_lengthof(PathName)) {
- // This may have been the file, return with error.
- ec = windows_error::buffer_overflow;
- break;
- } else {
- // We found the path! Return it.
- ec = windows_error::success;
- break;
- }
- }
-
- // Make sure PathName is valid.
- PathName[MAX_PATH] = 0;
- return PathName;
-}
-
-static StringRef ExceptionCodeToString(DWORD ExceptionCode) {
- switch(ExceptionCode) {
- case EXCEPTION_ACCESS_VIOLATION: return "EXCEPTION_ACCESS_VIOLATION";
- case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
- return "EXCEPTION_ARRAY_BOUNDS_EXCEEDED";
- case EXCEPTION_BREAKPOINT: return "EXCEPTION_BREAKPOINT";
- case EXCEPTION_DATATYPE_MISALIGNMENT:
- return "EXCEPTION_DATATYPE_MISALIGNMENT";
- case EXCEPTION_FLT_DENORMAL_OPERAND: return "EXCEPTION_FLT_DENORMAL_OPERAND";
- case EXCEPTION_FLT_DIVIDE_BY_ZERO: return "EXCEPTION_FLT_DIVIDE_BY_ZERO";
- case EXCEPTION_FLT_INEXACT_RESULT: return "EXCEPTION_FLT_INEXACT_RESULT";
- case EXCEPTION_FLT_INVALID_OPERATION:
- return "EXCEPTION_FLT_INVALID_OPERATION";
- case EXCEPTION_FLT_OVERFLOW: return "EXCEPTION_FLT_OVERFLOW";
- case EXCEPTION_FLT_STACK_CHECK: return "EXCEPTION_FLT_STACK_CHECK";
- case EXCEPTION_FLT_UNDERFLOW: return "EXCEPTION_FLT_UNDERFLOW";
- case EXCEPTION_ILLEGAL_INSTRUCTION: return "EXCEPTION_ILLEGAL_INSTRUCTION";
- case EXCEPTION_IN_PAGE_ERROR: return "EXCEPTION_IN_PAGE_ERROR";
- case EXCEPTION_INT_DIVIDE_BY_ZERO: return "EXCEPTION_INT_DIVIDE_BY_ZERO";
- case EXCEPTION_INT_OVERFLOW: return "EXCEPTION_INT_OVERFLOW";
- case EXCEPTION_INVALID_DISPOSITION: return "EXCEPTION_INVALID_DISPOSITION";
- case EXCEPTION_NONCONTINUABLE_EXCEPTION:
- return "EXCEPTION_NONCONTINUABLE_EXCEPTION";
- case EXCEPTION_PRIV_INSTRUCTION: return "EXCEPTION_PRIV_INSTRUCTION";
- case EXCEPTION_SINGLE_STEP: return "EXCEPTION_SINGLE_STEP";
- case EXCEPTION_STACK_OVERFLOW: return "EXCEPTION_STACK_OVERFLOW";
- default: return "<unknown>";
- }
-}
-
-int main(int argc, char **argv) {
- // Print a stack trace if we signal out.
- sys::PrintStackTraceOnErrorSignal();
- PrettyStackTraceProgram X(argc, argv);
- llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
-
- ToolName = argv[0];
-
- cl::ParseCommandLineOptions(argc, argv, "Dr. Watson Assassin.\n");
- if (ProgramToRun.size() == 0) {
- cl::PrintHelpMessage();
- return -1;
- }
-
- if (Timeout > std::numeric_limits<uint32_t>::max() / 1000) {
- errs() << ToolName << ": Timeout value too large, must be less than: "
- << std::numeric_limits<uint32_t>::max() / 1000
- << '\n';
- return -1;
- }
-
- std::string CommandLine(ProgramToRun);
-
- error_code ec;
- ProgramToRun = FindProgram(ProgramToRun, ec);
- if (ec) {
- errs() << ToolName << ": Failed to find program: '" << CommandLine
- << "': " << ec.message() << '\n';
- return -1;
- }
-
- if (TraceExecution)
- errs() << ToolName << ": Found Program: " << ProgramToRun << '\n';
-
- for (std::vector<std::string>::iterator i = Argv.begin(),
- e = Argv.end();
- i != e; ++i) {
- CommandLine.push_back(' ');
- CommandLine.append(*i);
- }
-
- if (TraceExecution)
- errs() << ToolName << ": Program Image Path: " << ProgramToRun << '\n'
- << ToolName << ": Command Line: " << CommandLine << '\n';
-
- STARTUPINFO StartupInfo;
- PROCESS_INFORMATION ProcessInfo;
- std::memset(&StartupInfo, 0, sizeof(StartupInfo));
- StartupInfo.cb = sizeof(StartupInfo);
- std::memset(&ProcessInfo, 0, sizeof(ProcessInfo));
-
- // Set error mode to not display any message boxes. The child process inherits
- // this.
- ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
- ::_set_error_mode(_OUT_TO_STDERR);
-
- BOOL success = ::CreateProcessA(ProgramToRun.c_str(),
- LPSTR(CommandLine.c_str()),
- NULL,
- NULL,
- FALSE,
- DEBUG_PROCESS,
- NULL,
- NULL,
- &StartupInfo,
- &ProcessInfo);
- if (!success) {
- errs() << ToolName << ": Failed to run program: '" << ProgramToRun
- << "': " << error_code(windows_error(::GetLastError())).message()
- << '\n';
- return -1;
- }
-
- // Make sure ::CloseHandle is called on exit.
- std::map<DWORD, HANDLE> ProcessIDToHandle;
-
- DEBUG_EVENT DebugEvent;
- std::memset(&DebugEvent, 0, sizeof(DebugEvent));
- DWORD dwContinueStatus = DBG_CONTINUE;
-
- // Run the program under the debugger until either it exits, or throws an
- // exception.
- if (TraceExecution)
- errs() << ToolName << ": Debugging...\n";
-
- while(true) {
- DWORD TimeLeft = INFINITE;
- if (Timeout > 0) {
- FILETIME CreationTime, ExitTime, KernelTime, UserTime;
- ULARGE_INTEGER a, b;
- success = ::GetProcessTimes(ProcessInfo.hProcess,
- &CreationTime,
- &ExitTime,
- &KernelTime,
- &UserTime);
- if (!success) {
- ec = windows_error(::GetLastError());
-
- errs() << ToolName << ": Failed to get process times: "
- << ec.message() << '\n';
- return -1;
- }
- a.LowPart = KernelTime.dwLowDateTime;
- a.HighPart = KernelTime.dwHighDateTime;
- b.LowPart = UserTime.dwLowDateTime;
- b.HighPart = UserTime.dwHighDateTime;
- // Convert 100-nanosecond units to milliseconds.
- uint64_t TotalTimeMiliseconds = (a.QuadPart + b.QuadPart) / 10000;
- // Handle the case where the process has been running for more than 49
- // days.
- if (TotalTimeMiliseconds > std::numeric_limits<uint32_t>::max()) {
- errs() << ToolName << ": Timeout Failed: Process has been running for"
- "more than 49 days.\n";
- return -1;
- }
-
- // We check with > instead of using Timeleft because if
- // TotalTimeMiliseconds is greater than Timeout * 1000, TimeLeft would
- // underflow.
- if (TotalTimeMiliseconds > (Timeout * 1000)) {
- errs() << ToolName << ": Process timed out.\n";
- ::TerminateProcess(ProcessInfo.hProcess, -1);
- // Otherwise other stuff starts failing...
- return -1;
- }
-
- TimeLeft = (Timeout * 1000) - static_cast<uint32_t>(TotalTimeMiliseconds);
- }
- success = WaitForDebugEvent(&DebugEvent, TimeLeft);
-
- if (!success) {
- ec = windows_error(::GetLastError());
-
- if (ec == errc::timed_out) {
- errs() << ToolName << ": Process timed out.\n";
- ::TerminateProcess(ProcessInfo.hProcess, -1);
- // Otherwise other stuff starts failing...
- return -1;
- }
-
- errs() << ToolName << ": Failed to wait for debug event in program: '"
- << ProgramToRun << "': " << ec.message() << '\n';
- return -1;
- }
-
- switch(DebugEvent.dwDebugEventCode) {
- case CREATE_PROCESS_DEBUG_EVENT:
- // Make sure we remove the handle on exit.
- if (TraceExecution)
- errs() << ToolName << ": Debug Event: CREATE_PROCESS_DEBUG_EVENT\n";
- ProcessIDToHandle[DebugEvent.dwProcessId] =
- DebugEvent.u.CreateProcessInfo.hProcess;
- ::CloseHandle(DebugEvent.u.CreateProcessInfo.hFile);
- break;
- case EXIT_PROCESS_DEBUG_EVENT: {
- if (TraceExecution)
- errs() << ToolName << ": Debug Event: EXIT_PROCESS_DEBUG_EVENT\n";
-
- // If this is the process we originally created, exit with its exit
- // code.
- if (DebugEvent.dwProcessId == ProcessInfo.dwProcessId)
- return DebugEvent.u.ExitProcess.dwExitCode;
-
- // Otherwise cleanup any resources we have for it.
- std::map<DWORD, HANDLE>::iterator ExitingProcess =
- ProcessIDToHandle.find(DebugEvent.dwProcessId);
- if (ExitingProcess == ProcessIDToHandle.end()) {
- errs() << ToolName << ": Got unknown process id!\n";
- return -1;
- }
- ::CloseHandle(ExitingProcess->second);
- ProcessIDToHandle.erase(ExitingProcess);
- }
- break;
- case CREATE_THREAD_DEBUG_EVENT:
- ::CloseHandle(DebugEvent.u.CreateThread.hThread);
- break;
- case LOAD_DLL_DEBUG_EVENT: {
- // Cleanup the file handle.
- FileScopedHandle DLLFile(DebugEvent.u.LoadDll.hFile);
- std::string DLLName;
- ec = GetFileNameFromHandle(DLLFile, DLLName);
- if (ec) {
- DLLName = "<failed to get file name from file handle> : ";
- DLLName += ec.message();
- }
- if (TraceExecution) {
- errs() << ToolName << ": Debug Event: LOAD_DLL_DEBUG_EVENT\n";
- errs().indent(ToolName.size()) << ": DLL Name : " << DLLName << '\n';
- }
-
- if (NoUser32 && sys::path::stem(DLLName) == "user32") {
- // Program is loading user32.dll, in the applications we are testing,
- // this only happens if an assert has fired. By now the message has
- // already been printed, so simply close the program.
- errs() << ToolName << ": user32.dll loaded!\n";
- errs().indent(ToolName.size())
- << ": This probably means that assert was called. Closing "
- "program to prevent message box from popping up.\n";
- dwContinueStatus = DBG_CONTINUE;
- ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1);
- return -1;
- }
- }
- break;
- case EXCEPTION_DEBUG_EVENT: {
- // Close the application if this exception will not be handled by the
- // child application.
- if (TraceExecution)
- errs() << ToolName << ": Debug Event: EXCEPTION_DEBUG_EVENT\n";
-
- EXCEPTION_DEBUG_INFO &Exception = DebugEvent.u.Exception;
- if (Exception.dwFirstChance > 0) {
- if (TraceExecution) {
- errs().indent(ToolName.size()) << ": Debug Info : ";
- errs() << "First chance exception at "
- << Exception.ExceptionRecord.ExceptionAddress
- << ", exception code: "
- << ExceptionCodeToString(
- Exception.ExceptionRecord.ExceptionCode)
- << " (" << Exception.ExceptionRecord.ExceptionCode << ")\n";
- }
- dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED;
- } else {
- errs() << ToolName << ": Unhandled exception in: " << ProgramToRun
- << "!\n";
- errs().indent(ToolName.size()) << ": location: ";
- errs() << Exception.ExceptionRecord.ExceptionAddress
- << ", exception code: "
- << ExceptionCodeToString(
- Exception.ExceptionRecord.ExceptionCode)
- << " (" << Exception.ExceptionRecord.ExceptionCode
- << ")\n";
- dwContinueStatus = DBG_CONTINUE;
- ::TerminateProcess(ProcessIDToHandle[DebugEvent.dwProcessId], -1);
- return -1;
- }
- }
- break;
- default:
- // Do nothing.
- if (TraceExecution)
- errs() << ToolName << ": Debug Event: <unknown>\n";
- break;
- }
-
- success = ContinueDebugEvent(DebugEvent.dwProcessId,
- DebugEvent.dwThreadId,
- dwContinueStatus);
- if (!success) {
- ec = windows_error(::GetLastError());
- errs() << ToolName << ": Failed to continue debugging program: '"
- << ProgramToRun << "': " << ec.message() << '\n';
- return -1;
- }
-
- dwContinueStatus = DBG_CONTINUE;
- }
-
- assert(0 && "Fell out of debug loop. This shouldn't be possible!");
- return -1;
-}
Modified: trunk/contrib/llvm/utils/Misc/zkill
===================================================================
--- trunk/contrib/llvm/utils/Misc/zkill 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/Misc/zkill 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,276 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import re
-import sys
-
-def _write_message(kind, message):
- import inspect, os, sys
-
- # Get the file/line where this message was generated.
- f = inspect.currentframe()
- # Step out of _write_message, and then out of wrapper.
- f = f.f_back.f_back
- file,line,_,_,_ = inspect.getframeinfo(f)
- location = '%s:%d' % (os.path.basename(file), line)
-
- print >>sys.stderr, '%s: %s: %s' % (location, kind, message)
-
-note = lambda message: _write_message('note', message)
-warning = lambda message: _write_message('warning', message)
-error = lambda message: (_write_message('error', message), sys.exit(1))
-
-def re_full_match(pattern, str):
- m = re.match(pattern, str)
- if m and m.end() != len(str):
- m = None
- return m
-
-def parse_time(value):
- minutes,value = value.split(':',1)
- if '.' in value:
- seconds,fseconds = value.split('.',1)
- else:
- seconds = value
- return int(minutes) * 60 + int(seconds) + float('.'+fseconds)
-
-def extractExecutable(command):
- """extractExecutable - Given a string representing a command line, attempt
- to extract the executable path, even if it includes spaces."""
-
- # Split into potential arguments.
- args = command.split(' ')
-
- # Scanning from the beginning, try to see if the first N args, when joined,
- # exist. If so that's probably the executable.
- for i in range(1,len(args)):
- cmd = ' '.join(args[:i])
- if os.path.exists(cmd):
- return cmd
-
- # Otherwise give up and return the first "argument".
- return args[0]
-
-class Struct:
- def __init__(self, **kwargs):
- self.fields = kwargs.keys()
- self.__dict__.update(kwargs)
-
- def __repr__(self):
- return 'Struct(%s)' % ', '.join(['%s=%r' % (k,getattr(self,k))
- for k in self.fields])
-
-kExpectedPSFields = [('PID', int, 'pid'),
- ('USER', str, 'user'),
- ('COMMAND', str, 'command'),
- ('%CPU', float, 'cpu_percent'),
- ('TIME', parse_time, 'cpu_time'),
- ('VSZ', int, 'vmem_size'),
- ('RSS', int, 'rss')]
-def getProcessTable():
- import subprocess
- p = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE,
- stderr=subprocess.PIPE)
- out,err = p.communicate()
- res = p.wait()
- if p.wait():
- error('unable to get process table')
- elif err.strip():
- error('unable to get process table: %s' % err)
-
- lns = out.split('\n')
- it = iter(lns)
- header = it.next().split()
- numRows = len(header)
-
- # Make sure we have the expected fields.
- indexes = []
- for field in kExpectedPSFields:
- try:
- indexes.append(header.index(field[0]))
- except:
- if opts.debug:
- raise
- error('unable to get process table, no %r field.' % field[0])
-
- table = []
- for i,ln in enumerate(it):
- if not ln.strip():
- continue
-
- fields = ln.split(None, numRows - 1)
- if len(fields) != numRows:
- warning('unable to process row: %r' % ln)
- continue
-
- record = {}
- for field,idx in zip(kExpectedPSFields, indexes):
- value = fields[idx]
- try:
- record[field[2]] = field[1](value)
- except:
- if opts.debug:
- raise
- warning('unable to process %r in row: %r' % (field[0], ln))
- break
- else:
- # Add our best guess at the executable.
- record['executable'] = extractExecutable(record['command'])
- table.append(Struct(**record))
-
- return table
-
-def getSignalValue(name):
- import signal
- if name.startswith('SIG'):
- value = getattr(signal, name)
- if value and isinstance(value, int):
- return value
- error('unknown signal: %r' % name)
-
-import signal
-kSignals = {}
-for name in dir(signal):
- if name.startswith('SIG') and name == name.upper() and name.isalpha():
- kSignals[name[3:]] = getattr(signal, name)
-
-def main():
- global opts
- from optparse import OptionParser, OptionGroup
- parser = OptionParser("usage: %prog [options] {pid}*")
-
- # FIXME: Add -NNN and -SIGNAME options.
-
- parser.add_option("-s", "", dest="signalName",
- help="Name of the signal to use (default=%default)",
- action="store", default='INT',
- choices=kSignals.keys())
- parser.add_option("-l", "", dest="listSignals",
- help="List known signal names",
- action="store_true", default=False)
-
- parser.add_option("-n", "--dry-run", dest="dryRun",
- help="Only print the actions that would be taken",
- action="store_true", default=False)
- parser.add_option("-v", "--verbose", dest="verbose",
- help="Print more verbose output",
- action="store_true", default=False)
- parser.add_option("", "--debug", dest="debug",
- help="Enable debugging output",
- action="store_true", default=False)
- parser.add_option("", "--force", dest="force",
- help="Perform the specified commands, even if it seems like a bad idea",
- action="store_true", default=False)
-
- inf = float('inf')
- group = OptionGroup(parser, "Process Filters")
- group.add_option("", "--name", dest="execName", metavar="REGEX",
- help="Kill processes whose name matches the given regexp",
- action="store", default=None)
- group.add_option("", "--exec", dest="execPath", metavar="REGEX",
- help="Kill processes whose executable matches the given regexp",
- action="store", default=None)
- group.add_option("", "--user", dest="userName", metavar="REGEX",
- help="Kill processes whose user matches the given regexp",
- action="store", default=None)
- group.add_option("", "--min-cpu", dest="minCPU", metavar="PCT",
- help="Kill processes with CPU usage >= PCT",
- action="store", type=float, default=None)
- group.add_option("", "--max-cpu", dest="maxCPU", metavar="PCT",
- help="Kill processes with CPU usage <= PCT",
- action="store", type=float, default=inf)
- group.add_option("", "--min-mem", dest="minMem", metavar="N",
- help="Kill processes with virtual size >= N (MB)",
- action="store", type=float, default=None)
- group.add_option("", "--max-mem", dest="maxMem", metavar="N",
- help="Kill processes with virtual size <= N (MB)",
- action="store", type=float, default=inf)
- group.add_option("", "--min-rss", dest="minRSS", metavar="N",
- help="Kill processes with RSS >= N",
- action="store", type=float, default=None)
- group.add_option("", "--max-rss", dest="maxRSS", metavar="N",
- help="Kill processes with RSS <= N",
- action="store", type=float, default=inf)
- group.add_option("", "--min-time", dest="minTime", metavar="N",
- help="Kill processes with CPU time >= N (seconds)",
- action="store", type=float, default=None)
- group.add_option("", "--max-time", dest="maxTime", metavar="N",
- help="Kill processes with CPU time <= N (seconds)",
- action="store", type=float, default=inf)
- parser.add_option_group(group)
-
- (opts, args) = parser.parse_args()
-
- if opts.listSignals:
- items = [(v,k) for k,v in kSignals.items()]
- items.sort()
- for i in range(0, len(items), 4):
- print '\t'.join(['%2d) SIG%s' % (k,v)
- for k,v in items[i:i+4]])
- sys.exit(0)
-
- # Figure out the signal to use.
- signal = kSignals[opts.signalName]
- signalValueName = str(signal)
- if opts.verbose:
- name = dict((v,k) for k,v in kSignals.items()).get(signal,None)
- if name:
- signalValueName = name
- note('using signal %d (SIG%s)' % (signal, name))
- else:
- note('using signal %d' % signal)
-
- # Get the pid list to consider.
- pids = set()
- for arg in args:
- try:
- pids.add(int(arg))
- except:
- parser.error('invalid positional argument: %r' % arg)
-
- filtered = ps = getProcessTable()
-
- # Apply filters.
- if pids:
- filtered = [p for p in filtered
- if p.pid in pids]
- if opts.execName is not None:
- filtered = [p for p in filtered
- if re_full_match(opts.execName,
- os.path.basename(p.executable))]
- if opts.execPath is not None:
- filtered = [p for p in filtered
- if re_full_match(opts.execPath, p.executable)]
- if opts.userName is not None:
- filtered = [p for p in filtered
- if re_full_match(opts.userName, p.user)]
- filtered = [p for p in filtered
- if opts.minCPU <= p.cpu_percent <= opts.maxCPU]
- filtered = [p for p in filtered
- if opts.minMem <= float(p.vmem_size) / (1<<20) <= opts.maxMem]
- filtered = [p for p in filtered
- if opts.minRSS <= p.rss <= opts.maxRSS]
- filtered = [p for p in filtered
- if opts.minTime <= p.cpu_time <= opts.maxTime]
-
- if len(filtered) == len(ps):
- if not opts.force and not opts.dryRun:
- error('refusing to kill all processes without --force')
-
- if not filtered:
- warning('no processes selected')
-
- for p in filtered:
- if opts.verbose:
- note('kill(%r, %s) # (user=%r, executable=%r, CPU=%2.2f%%, time=%r, vmem=%r, rss=%r)' %
- (p.pid, signalValueName, p.user, p.executable, p.cpu_percent, p.cpu_time, p.vmem_size, p.rss))
- if not opts.dryRun:
- try:
- os.kill(p.pid, signal)
- except OSError:
- if opts.debug:
- raise
- warning('unable to kill PID: %r' % p.pid)
-
-if __name__ == '__main__':
- main()
Modified: trunk/contrib/llvm/utils/PerfectShuffle/PerfectShuffle.cpp
===================================================================
--- trunk/contrib/llvm/utils/PerfectShuffle/PerfectShuffle.cpp 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/PerfectShuffle/PerfectShuffle.cpp 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,572 +0,0 @@
-//===-- PerfectShuffle.cpp - Perfect Shuffle Generator --------------------===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// This file computes an optimal sequence of instructions for doing all shuffles
-// of two 4-element vectors. With a release build and when configured to emit
-// an altivec instruction table, this takes about 30s to run on a 2.7Ghz
-// PowerPC G5.
-//
-//===----------------------------------------------------------------------===//
-
-#include <cassert>
-#include <cstdlib>
-#include <iomanip>
-#include <iostream>
-#include <vector>
-struct Operator;
-
-// Masks are 4-nibble hex numbers. Values 0-7 in any nibble means that it takes
-// an element from that value of the input vectors. A value of 8 means the
-// entry is undefined.
-
-// Mask manipulation functions.
-static inline unsigned short MakeMask(unsigned V0, unsigned V1,
- unsigned V2, unsigned V3) {
- return (V0 << (3*4)) | (V1 << (2*4)) | (V2 << (1*4)) | (V3 << (0*4));
-}
-
-/// getMaskElt - Return element N of the specified mask.
-static unsigned getMaskElt(unsigned Mask, unsigned Elt) {
- return (Mask >> ((3-Elt)*4)) & 0xF;
-}
-
-static unsigned setMaskElt(unsigned Mask, unsigned Elt, unsigned NewVal) {
- unsigned FieldShift = ((3-Elt)*4);
- return (Mask & ~(0xF << FieldShift)) | (NewVal << FieldShift);
-}
-
-// Reject elements where the values are 9-15.
-static bool isValidMask(unsigned short Mask) {
- unsigned short UndefBits = Mask & 0x8888;
- return (Mask & ((UndefBits >> 1)|(UndefBits>>2)|(UndefBits>>3))) == 0;
-}
-
-/// hasUndefElements - Return true if any of the elements in the mask are undefs
-///
-static bool hasUndefElements(unsigned short Mask) {
- return (Mask & 0x8888) != 0;
-}
-
-/// isOnlyLHSMask - Return true if this mask only refers to its LHS, not
-/// including undef values..
-static bool isOnlyLHSMask(unsigned short Mask) {
- return (Mask & 0x4444) == 0;
-}
-
-/// getLHSOnlyMask - Given a mask that refers to its LHS and RHS, modify it to
-/// refer to the LHS only (for when one argument value is passed into the same
-/// function twice).
-#if 0
-static unsigned short getLHSOnlyMask(unsigned short Mask) {
- return Mask & 0xBBBB; // Keep only LHS and Undefs.
-}
-#endif
-
-/// getCompressedMask - Turn a 16-bit uncompressed mask (where each elt uses 4
-/// bits) into a compressed 13-bit mask, where each elt is multiplied by 9.
-static unsigned getCompressedMask(unsigned short Mask) {
- return getMaskElt(Mask, 0)*9*9*9 + getMaskElt(Mask, 1)*9*9 +
- getMaskElt(Mask, 2)*9 + getMaskElt(Mask, 3);
-}
-
-static void PrintMask(unsigned i, std::ostream &OS) {
- OS << "<" << (char)(getMaskElt(i, 0) == 8 ? 'u' : ('0'+getMaskElt(i, 0)))
- << "," << (char)(getMaskElt(i, 1) == 8 ? 'u' : ('0'+getMaskElt(i, 1)))
- << "," << (char)(getMaskElt(i, 2) == 8 ? 'u' : ('0'+getMaskElt(i, 2)))
- << "," << (char)(getMaskElt(i, 3) == 8 ? 'u' : ('0'+getMaskElt(i, 3)))
- << ">";
-}
-
-/// ShuffleVal - This represents a shufflevector operation.
-struct ShuffleVal {
- unsigned Cost; // Number of instrs used to generate this value.
- Operator *Op; // The Operation used to generate this value.
- unsigned short Arg0, Arg1; // Input operands for this value.
-
- ShuffleVal() : Cost(1000000) {}
-};
-
-
-/// ShufTab - This is the actual shuffle table that we are trying to generate.
-///
-static ShuffleVal ShufTab[65536];
-
-/// TheOperators - All of the operators that this target supports.
-static std::vector<Operator*> TheOperators;
-
-/// Operator - This is a vector operation that is available for use.
-struct Operator {
- unsigned short ShuffleMask;
- unsigned short OpNum;
- const char *Name;
- unsigned Cost;
-
- Operator(unsigned short shufflemask, const char *name, unsigned opnum,
- unsigned cost = 1)
- : ShuffleMask(shufflemask), OpNum(opnum), Name(name), Cost(cost) {
- TheOperators.push_back(this);
- }
- ~Operator() {
- assert(TheOperators.back() == this);
- TheOperators.pop_back();
- }
-
- bool isOnlyLHSOperator() const {
- return isOnlyLHSMask(ShuffleMask);
- }
-
- const char *getName() const { return Name; }
- unsigned getCost() const { return Cost; }
-
- unsigned short getTransformedMask(unsigned short LHSMask, unsigned RHSMask) {
- // Extract the elements from LHSMask and RHSMask, as appropriate.
- unsigned Result = 0;
- for (unsigned i = 0; i != 4; ++i) {
- unsigned SrcElt = (ShuffleMask >> (4*i)) & 0xF;
- unsigned ResElt;
- if (SrcElt < 4)
- ResElt = getMaskElt(LHSMask, SrcElt);
- else if (SrcElt < 8)
- ResElt = getMaskElt(RHSMask, SrcElt-4);
- else {
- assert(SrcElt == 8 && "Bad src elt!");
- ResElt = 8;
- }
- Result |= ResElt << (4*i);
- }
- return Result;
- }
-};
-
-static const char *getZeroCostOpName(unsigned short Op) {
- if (ShufTab[Op].Arg0 == 0x0123)
- return "LHS";
- else if (ShufTab[Op].Arg0 == 0x4567)
- return "RHS";
- else {
- assert(0 && "bad zero cost operation");
- abort();
- }
-}
-
-static void PrintOperation(unsigned ValNo, unsigned short Vals[]) {
- unsigned short ThisOp = Vals[ValNo];
- std::cerr << "t" << ValNo;
- PrintMask(ThisOp, std::cerr);
- std::cerr << " = " << ShufTab[ThisOp].Op->getName() << "(";
-
- if (ShufTab[ShufTab[ThisOp].Arg0].Cost == 0) {
- std::cerr << getZeroCostOpName(ShufTab[ThisOp].Arg0);
- PrintMask(ShufTab[ThisOp].Arg0, std::cerr);
- } else {
- // Figure out what tmp # it is.
- for (unsigned i = 0; ; ++i)
- if (Vals[i] == ShufTab[ThisOp].Arg0) {
- std::cerr << "t" << i;
- break;
- }
- }
-
- if (!ShufTab[Vals[ValNo]].Op->isOnlyLHSOperator()) {
- std::cerr << ", ";
- if (ShufTab[ShufTab[ThisOp].Arg1].Cost == 0) {
- std::cerr << getZeroCostOpName(ShufTab[ThisOp].Arg1);
- PrintMask(ShufTab[ThisOp].Arg1, std::cerr);
- } else {
- // Figure out what tmp # it is.
- for (unsigned i = 0; ; ++i)
- if (Vals[i] == ShufTab[ThisOp].Arg1) {
- std::cerr << "t" << i;
- break;
- }
- }
- }
- std::cerr << ") ";
-}
-
-static unsigned getNumEntered() {
- unsigned Count = 0;
- for (unsigned i = 0; i != 65536; ++i)
- Count += ShufTab[i].Cost < 100;
- return Count;
-}
-
-static void EvaluateOps(unsigned short Elt, unsigned short Vals[],
- unsigned &NumVals) {
- if (ShufTab[Elt].Cost == 0) return;
-
- // If this value has already been evaluated, it is free. FIXME: match undefs.
- for (unsigned i = 0, e = NumVals; i != e; ++i)
- if (Vals[i] == Elt) return;
-
- // Otherwise, get the operands of the value, then add it.
- unsigned Arg0 = ShufTab[Elt].Arg0, Arg1 = ShufTab[Elt].Arg1;
- if (ShufTab[Arg0].Cost)
- EvaluateOps(Arg0, Vals, NumVals);
- if (Arg0 != Arg1 && ShufTab[Arg1].Cost)
- EvaluateOps(Arg1, Vals, NumVals);
-
- Vals[NumVals++] = Elt;
-}
-
-
-int main() {
- // Seed the table with accesses to the LHS and RHS.
- ShufTab[0x0123].Cost = 0;
- ShufTab[0x0123].Op = 0;
- ShufTab[0x0123].Arg0 = 0x0123;
- ShufTab[0x4567].Cost = 0;
- ShufTab[0x4567].Op = 0;
- ShufTab[0x4567].Arg0 = 0x4567;
-
- // Seed the first-level of shuffles, shuffles whose inputs are the input to
- // the vectorshuffle operation.
- bool MadeChange = true;
- unsigned OpCount = 0;
- while (MadeChange) {
- MadeChange = false;
- ++OpCount;
- std::cerr << "Starting iteration #" << OpCount << " with "
- << getNumEntered() << " entries established.\n";
-
- // Scan the table for two reasons: First, compute the maximum cost of any
- // operation left in the table. Second, make sure that values with undefs
- // have the cheapest alternative that they match.
- unsigned MaxCost = ShufTab[0].Cost;
- for (unsigned i = 1; i != 0x8889; ++i) {
- if (!isValidMask(i)) continue;
- if (ShufTab[i].Cost > MaxCost)
- MaxCost = ShufTab[i].Cost;
-
- // If this value has an undef, make it be computed the cheapest possible
- // way of any of the things that it matches.
- if (hasUndefElements(i)) {
- // This code is a little bit tricky, so here's the idea: consider some
- // permutation, like 7u4u. To compute the lowest cost for 7u4u, we
- // need to take the minimum cost of all of 7[0-8]4[0-8], 81 entries. If
- // there are 3 undefs, the number rises to 729 entries we have to scan,
- // and for the 4 undef case, we have to scan the whole table.
- //
- // Instead of doing this huge amount of scanning, we process the table
- // entries *in order*, and use the fact that 'u' is 8, larger than any
- // valid index. Given an entry like 7u4u then, we only need to scan
- // 7[0-7]4u - 8 entries. We can get away with this, because we already
- // know that each of 704u, 714u, 724u, etc contain the minimum value of
- // all of the 704[0-8], 714[0-8] and 724[0-8] entries respectively.
- unsigned UndefIdx;
- if (i & 0x8000)
- UndefIdx = 0;
- else if (i & 0x0800)
- UndefIdx = 1;
- else if (i & 0x0080)
- UndefIdx = 2;
- else if (i & 0x0008)
- UndefIdx = 3;
- else
- abort();
-
- unsigned MinVal = i;
- unsigned MinCost = ShufTab[i].Cost;
-
- // Scan the 8 entries.
- for (unsigned j = 0; j != 8; ++j) {
- unsigned NewElt = setMaskElt(i, UndefIdx, j);
- if (ShufTab[NewElt].Cost < MinCost) {
- MinCost = ShufTab[NewElt].Cost;
- MinVal = NewElt;
- }
- }
-
- // If we found something cheaper than what was here before, use it.
- if (i != MinVal) {
- MadeChange = true;
- ShufTab[i] = ShufTab[MinVal];
- }
- }
- }
-
- for (unsigned LHS = 0; LHS != 0x8889; ++LHS) {
- if (!isValidMask(LHS)) continue;
- if (ShufTab[LHS].Cost > 1000) continue;
-
- // If nothing involving this operand could possibly be cheaper than what
- // we already have, don't consider it.
- if (ShufTab[LHS].Cost + 1 >= MaxCost)
- continue;
-
- for (unsigned opnum = 0, e = TheOperators.size(); opnum != e; ++opnum) {
- Operator *Op = TheOperators[opnum];
-
- // Evaluate op(LHS,LHS)
- unsigned ResultMask = Op->getTransformedMask(LHS, LHS);
-
- unsigned Cost = ShufTab[LHS].Cost + Op->getCost();
- if (Cost < ShufTab[ResultMask].Cost) {
- ShufTab[ResultMask].Cost = Cost;
- ShufTab[ResultMask].Op = Op;
- ShufTab[ResultMask].Arg0 = LHS;
- ShufTab[ResultMask].Arg1 = LHS;
- MadeChange = true;
- }
-
- // If this is a two input instruction, include the op(x,y) cases. If
- // this is a one input instruction, skip this.
- if (Op->isOnlyLHSOperator()) continue;
-
- for (unsigned RHS = 0; RHS != 0x8889; ++RHS) {
- if (!isValidMask(RHS)) continue;
- if (ShufTab[RHS].Cost > 1000) continue;
-
- // If nothing involving this operand could possibly be cheaper than
- // what we already have, don't consider it.
- if (ShufTab[RHS].Cost + 1 >= MaxCost)
- continue;
-
-
- // Evaluate op(LHS,RHS)
- unsigned ResultMask = Op->getTransformedMask(LHS, RHS);
-
- if (ShufTab[ResultMask].Cost <= OpCount ||
- ShufTab[ResultMask].Cost <= ShufTab[LHS].Cost ||
- ShufTab[ResultMask].Cost <= ShufTab[RHS].Cost)
- continue;
-
- // Figure out the cost to evaluate this, knowing that CSE's only need
- // to be evaluated once.
- unsigned short Vals[30];
- unsigned NumVals = 0;
- EvaluateOps(LHS, Vals, NumVals);
- EvaluateOps(RHS, Vals, NumVals);
-
- unsigned Cost = NumVals + Op->getCost();
- if (Cost < ShufTab[ResultMask].Cost) {
- ShufTab[ResultMask].Cost = Cost;
- ShufTab[ResultMask].Op = Op;
- ShufTab[ResultMask].Arg0 = LHS;
- ShufTab[ResultMask].Arg1 = RHS;
- MadeChange = true;
- }
- }
- }
- }
- }
-
- std::cerr << "Finished Table has " << getNumEntered()
- << " entries established.\n";
-
- unsigned CostArray[10] = { 0 };
-
- // Compute a cost histogram.
- for (unsigned i = 0; i != 65536; ++i) {
- if (!isValidMask(i)) continue;
- if (ShufTab[i].Cost > 9)
- ++CostArray[9];
- else
- ++CostArray[ShufTab[i].Cost];
- }
-
- for (unsigned i = 0; i != 9; ++i)
- if (CostArray[i])
- std::cout << "// " << CostArray[i] << " entries have cost " << i << "\n";
- if (CostArray[9])
- std::cout << "// " << CostArray[9] << " entries have higher cost!\n";
-
-
- // Build up the table to emit.
- std::cout << "\n// This table is 6561*4 = 26244 bytes in size.\n";
- std::cout << "static const unsigned PerfectShuffleTable[6561+1] = {\n";
-
- for (unsigned i = 0; i != 0x8889; ++i) {
- if (!isValidMask(i)) continue;
-
- // CostSat - The cost of this operation saturated to two bits.
- unsigned CostSat = ShufTab[i].Cost;
- if (CostSat > 4) CostSat = 4;
- if (CostSat == 0) CostSat = 1;
- --CostSat; // Cost is now between 0-3.
-
- unsigned OpNum = ShufTab[i].Op ? ShufTab[i].Op->OpNum : 0;
- assert(OpNum < 16 && "Too few bits to encode operation!");
-
- unsigned LHS = getCompressedMask(ShufTab[i].Arg0);
- unsigned RHS = getCompressedMask(ShufTab[i].Arg1);
-
- // Encode this as 2 bits of saturated cost, 4 bits of opcodes, 13 bits of
- // LHS, and 13 bits of RHS = 32 bits.
- unsigned Val = (CostSat << 30) | (OpNum << 26) | (LHS << 13) | RHS;
-
- std::cout << " " << std::setw(10) << Val << "U, // ";
- PrintMask(i, std::cout);
- std::cout << ": Cost " << ShufTab[i].Cost;
- std::cout << " " << (ShufTab[i].Op ? ShufTab[i].Op->getName() : "copy");
- std::cout << " ";
- if (ShufTab[ShufTab[i].Arg0].Cost == 0) {
- std::cout << getZeroCostOpName(ShufTab[i].Arg0);
- } else {
- PrintMask(ShufTab[i].Arg0, std::cout);
- }
-
- if (ShufTab[i].Op && !ShufTab[i].Op->isOnlyLHSOperator()) {
- std::cout << ", ";
- if (ShufTab[ShufTab[i].Arg1].Cost == 0) {
- std::cout << getZeroCostOpName(ShufTab[i].Arg1);
- } else {
- PrintMask(ShufTab[i].Arg1, std::cout);
- }
- }
- std::cout << "\n";
- }
- std::cout << " 0\n};\n";
-
- if (0) {
- // Print out the table.
- for (unsigned i = 0; i != 0x8889; ++i) {
- if (!isValidMask(i)) continue;
- if (ShufTab[i].Cost < 1000) {
- PrintMask(i, std::cerr);
- std::cerr << " - Cost " << ShufTab[i].Cost << " - ";
-
- unsigned short Vals[30];
- unsigned NumVals = 0;
- EvaluateOps(i, Vals, NumVals);
-
- for (unsigned j = 0, e = NumVals; j != e; ++j)
- PrintOperation(j, Vals);
- std::cerr << "\n";
- }
- }
- }
-}
-
-
-#ifdef GENERATE_ALTIVEC
-
-///===---------------------------------------------------------------------===//
-/// The altivec instruction definitions. This is the altivec-specific part of
-/// this file.
-///===---------------------------------------------------------------------===//
-
-// Note that the opcode numbers here must match those in the PPC backend.
-enum {
- OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
- OP_VMRGHW,
- OP_VMRGLW,
- OP_VSPLTISW0,
- OP_VSPLTISW1,
- OP_VSPLTISW2,
- OP_VSPLTISW3,
- OP_VSLDOI4,
- OP_VSLDOI8,
- OP_VSLDOI12
-};
-
-struct vmrghw : public Operator {
- vmrghw() : Operator(0x0415, "vmrghw", OP_VMRGHW) {}
-} the_vmrghw;
-
-struct vmrglw : public Operator {
- vmrglw() : Operator(0x2637, "vmrglw", OP_VMRGLW) {}
-} the_vmrglw;
-
-template<unsigned Elt>
-struct vspltisw : public Operator {
- vspltisw(const char *N, unsigned Opc)
- : Operator(MakeMask(Elt, Elt, Elt, Elt), N, Opc) {}
-};
-
-vspltisw<0> the_vspltisw0("vspltisw0", OP_VSPLTISW0);
-vspltisw<1> the_vspltisw1("vspltisw1", OP_VSPLTISW1);
-vspltisw<2> the_vspltisw2("vspltisw2", OP_VSPLTISW2);
-vspltisw<3> the_vspltisw3("vspltisw3", OP_VSPLTISW3);
-
-template<unsigned N>
-struct vsldoi : public Operator {
- vsldoi(const char *Name, unsigned Opc)
- : Operator(MakeMask(N&7, (N+1)&7, (N+2)&7, (N+3)&7), Name, Opc) {
- }
-};
-
-vsldoi<1> the_vsldoi1("vsldoi4" , OP_VSLDOI4);
-vsldoi<2> the_vsldoi2("vsldoi8" , OP_VSLDOI8);
-vsldoi<3> the_vsldoi3("vsldoi12", OP_VSLDOI12);
-
-#endif
-
-#define GENERATE_NEON
-
-#ifdef GENERATE_NEON
-enum {
- OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
- OP_VREV,
- OP_VDUP0,
- OP_VDUP1,
- OP_VDUP2,
- OP_VDUP3,
- OP_VEXT1,
- OP_VEXT2,
- OP_VEXT3,
- OP_VUZPL, // VUZP, left result
- OP_VUZPR, // VUZP, right result
- OP_VZIPL, // VZIP, left result
- OP_VZIPR, // VZIP, right result
- OP_VTRNL, // VTRN, left result
- OP_VTRNR // VTRN, right result
-};
-
-struct vrev : public Operator {
- vrev() : Operator(0x1032, "vrev", OP_VREV) {}
-} the_vrev;
-
-template<unsigned Elt>
-struct vdup : public Operator {
- vdup(const char *N, unsigned Opc)
- : Operator(MakeMask(Elt, Elt, Elt, Elt), N, Opc) {}
-};
-
-vdup<0> the_vdup0("vdup0", OP_VDUP0);
-vdup<1> the_vdup1("vdup1", OP_VDUP1);
-vdup<2> the_vdup2("vdup2", OP_VDUP2);
-vdup<3> the_vdup3("vdup3", OP_VDUP3);
-
-template<unsigned N>
-struct vext : public Operator {
- vext(const char *Name, unsigned Opc)
- : Operator(MakeMask(N&7, (N+1)&7, (N+2)&7, (N+3)&7), Name, Opc) {
- }
-};
-
-vext<1> the_vext1("vext1", OP_VEXT1);
-vext<2> the_vext2("vext2", OP_VEXT2);
-vext<3> the_vext3("vext3", OP_VEXT3);
-
-struct vuzpl : public Operator {
- vuzpl() : Operator(0x0246, "vuzpl", OP_VUZPL, 2) {}
-} the_vuzpl;
-
-struct vuzpr : public Operator {
- vuzpr() : Operator(0x1357, "vuzpr", OP_VUZPR, 2) {}
-} the_vuzpr;
-
-struct vzipl : public Operator {
- vzipl() : Operator(0x0415, "vzipl", OP_VZIPL, 2) {}
-} the_vzipl;
-
-struct vzipr : public Operator {
- vzipr() : Operator(0x2637, "vzipr", OP_VZIPR, 2) {}
-} the_vzipr;
-
-struct vtrnl : public Operator {
- vtrnl() : Operator(0x0426, "vtrnl", OP_VTRNL, 2) {}
-} the_vtrnl;
-
-struct vtrnr : public Operator {
- vtrnr() : Operator(0x1537, "vtrnr", OP_VTRNR, 2) {}
-} the_vtrnr;
-
-#endif
Modified: trunk/contrib/llvm/utils/TableGen/tdtags
===================================================================
--- trunk/contrib/llvm/utils/TableGen/tdtags 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/TableGen/tdtags 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,453 +0,0 @@
-#!/bin/sh
-#===-- tdtags - TableGen tags wrapper ---------------------------*- sh -*-===#
-# vim:set sts=2 sw=2 et:
-#===----------------------------------------------------------------------===#
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-#===----------------------------------------------------------------------===#
-#
-# This is a wrapper script to simplify generating ctags(1)-compatible index
-# files for target .td files. Run tdtags -H for more documentation.
-#
-# For portability, this script is intended to conform to IEEE Std 1003.1-2008.
-#
-#===----------------------------------------------------------------------===#
-
-SELF=${0##*/}
-
-usage() {
-cat <<END
-Usage: $SELF [ <options> ] tdfile
- or: $SELF [ <options> ] -x recipe [arg ...]
-OPTIONS
- -H Display further help.
- -a Append the tags to an existing tags file.
- -f <file> Write tags to the specified file (defaults to 'tags').
- -I <dir> Add the directory to the search path for tblgen include files.
- -x <recipe> Generate tags file(s) for a common use case:
- -q Suppress $TBLGEN error messages.
- -v Be verbose; report progress.
-END
- usage_recipes
-}
-
-usage_recipes() {
-cat <<END
- all - Generate an index in each directory that contains .td files
- in the LLVM source tree.
- here - Generate an index for all .td files in the current directory.
- recurse - Generate an index in each directory that contains .td files
- in and under the current directory.
- target [<target> ...]
- - Generate a tags file for each specified LLVM code generator
- target, or if none are specified, all targets.
-END
-}
-
-help() {
-cat <<END
-NAME
- $SELF - generate ctags(1)-compatible index files for tblgen .td source
-
-SYNOPSIS
- $SELF [ options ] -x recipe [arg ...]
- $SELF [ options ] [file ...]
-
-DESCRIPTION
- With the '-x' option, $SELF produces one or more tags files for a
- particular common use case. See the RECIPES section below for details.
-
- Without the '-x' option, $SELF provides a ctags(1)-like interface to
- $TBLGEN.
-
-OPTIONS
- -a Append newly generated tags to those already in an existing
- tags file. Without ths option, any and all existing tags are
- replaced. NOTE: When building a mixed tags file, using ${SELF}
- for tblgen tags and ctags(1) for other languages, it is best
- to run ${SELF} first without '-a', and ctags(1) second with '-a',
- because ctags(1) handling is more capable.
- -f <file> Use the name <file> for the tags file, rather than the default
- "tags". If the <file> is "-", then the tag index is written to
- standard output.
- -H Display this document.
- -I <dir> Add the directory <dir> to the search path for 'include'
- statements in tblgen source.
- -x Run a canned recipe, rather than operate on specified files.
- When '-x' is present, the first non-option argument is the
- name of a recipe, and any further arguments are arguments to
- that recipe. With no arguments, lists the available recipes.
- -q Suppress $TBLGEN error messages. Not all .td files are well-
- formed outside a specific context, so recipes will sometimes
- produce error messages for certain .td files. These errors
- do not affect the indices produced for valid files.
- -v Be verbose; report progress.
-
-RECIPES
- $SELF -x all
- Produce a tags file in every directory in the LLVM source tree
- that contains any .td files.
- $SELF -x here
- Produce a tags file from .td files in the current directory.
- $SELF -x recurse
- Produce a tags file in every directory that contains any .td
- files, in and under the current directory.
- $SELF -x target [<target> ...]
- Produce a tags file for each named code generator target, or
- if none are named, for all code generator targets.
-END
-}
-
-# Temporary file management.
-#
-# Since SUS sh(1) has no arrays, this script makes extensive use of
-# temporary files. The follow are 'global' and used to carry information
-# across functions:
-# $TMP:D Include directories.
-# $TMP:I Included files.
-# $TMP:T Top-level files, that are not included by another.
-# $TMP:W Directories in which to generate tags (Worklist).
-# For portability to OS X, names must not differ only in case.
-#
-TMP=${TMPDIR:-/tmp}/$SELF:$$
-trap "rm -f $TMP*" 0
-trap exit 1 2 13 15
->$TMP:D
-
-td_dump()
-{
- if [ $OPT_VERBOSE -gt 1 ]
- then
- printf '===== %s =====\n' "$1"
- cat <"$1"
- fi
-}
-
-# Escape the arguments, taken as a whole.
-e() {
- printf '%s' "$*" |
- sed -e "s/'/'\\\\''/g" -e "1s/^/'/" -e "\$s/\$/'/"
-}
-
-# Determine whether the given directory contains at least one .td file.
-dir_has_td() {
- for i in $1/*.td
- do
- [ -f "$i" ] && return 0
- done
- return 1
-}
-
-# Partition the supplied list of files, plus any files included from them,
-# into two groups:
-# $TMP:T Top-level files, that are not included by another.
-# $TMP:I Included files.
-# Add standard directories to the include paths in $TMP:D if this would
-# benefit the any of the included files.
-td_prep() {
- >$TMP:E
- >$TMP:J
- for i in *.td
- do
- [ "x$i" = 'x*.td' ] && return 1
- if [ -f "$i" ]
- then
- printf '%s\n' "$i" >>$TMP:E
- sed -n -e 's/include[[:space:]]"\(.*\)".*/\1/p' <"$i" >>$TMP:J
- else
- printf >&2 '%s: "%s" not found.\n' "$SELF" "$i"
- exit 7
- fi
- done
- sort -u <$TMP:E >$TMP:X
- sort -u <$TMP:J >$TMP:I
- # A file that exists but is not included is toplevel.
- comm -23 $TMP:X $TMP:I >$TMP:T
- td_dump $TMP:T
- td_dump $TMP:I
- # Check include files.
- while read i
- do
- [ -f "$i" ] && continue
- while read d
- do
- [ -f "$d/$i" ] && break
- done <$TMP:D
- if [ -z "$d" ]
- then
- # See whether this include file can be found in a common location.
- for d in $LLVM_SRC_ROOT/include \
- $LLVM_SRC_ROOT/tools/clang/include
- do
- if [ -f "$d/$i" ]
- then
- printf '%s\n' "$d" >>$TMP:D
- break
- fi
- done
- fi
- done <$TMP:I
- td_dump $TMP:D
-}
-
-# Generate tags for the list of files in $TMP:T.
-td_tag() {
- # Collect include directories.
- inc=
- while read d
- do
- inc="${inc}${inc:+ }$(e "-I=$d")"
- done <$TMP:D
-
- if [ $OPT_VERBOSE -ne 0 ]
- then
- printf >&2 'In "%s",\n' "$PWD"
- fi
-
- # Generate tags for each file.
- n=0
- while read i
- do
- if [ $OPT_VERBOSE -ne 0 ]
- then
- printf >&2 ' generating tags from "%s"\n' "$i"
- fi
- n=$((n + 1))
- t=$(printf '%s:A:%05u' "$TMP" $n)
- eval $TBLGEN --gen-ctags $inc "$i" >$t 2>$TMP:F
- [ $OPT_NOTBLGENERR -eq 1 ] || cat $TMP:F
- done <$TMP:T
-
- # Add existing tags if requested.
- if [ $OPT_APPEND -eq 1 -a -f "$OPT_TAGSFILE" ]
- then
- if [ $OPT_VERBOSE -ne 0 ]
- then
- printf >&2 ' and existing tags from "%s"\n' "$OPT_TAGSFILE"
- fi
- n=$((n + 1))
- t=$(printf '%s:A:%05u' "$TMP" $n)
- sed -e '/^!_TAG_/d' <"$OPT_TAGSFILE" | sort -u >$t
- fi
-
- # Merge tags.
- if [ $n = 1 ]
- then
- mv -f "$t" $TMP:M
- else
- sort -m -u $TMP:A:* >$TMP:M
- fi
-
- # Emit tags.
- if [ x${OPT_TAGSFILE}x = x-x ]
- then
- cat $TMP:M
- else
- if [ $OPT_VERBOSE -ne 0 ]
- then
- printf >&2 ' into "%s".\n' "$OPT_TAGSFILE"
- fi
- mv -f $TMP:M "$OPT_TAGSFILE"
- fi
-}
-
-# Generate tags for the current directory.
-td_here() {
- td_prep
- [ -s $TMP:T ] || return 1
- td_tag
-}
-
-# Generate tags for the current directory, and report an error if there are
-# no .td files present.
-do_here()
-{
- if ! td_here
- then
- printf >&2 '%s: Nothing to do here.\n' "$SELF"
- exit 1
- fi
-}
-
-# Generate tags for all .td files under the current directory.
-do_recurse()
-{
- td_find "$PWD"
- td_dirs
-}
-
-# Generate tags for all .td files in LLVM.
-do_all()
-{
- td_find "$LLVM_SRC_ROOT"
- td_dirs
-}
-
-# Generate tags for each directory in the worklist $TMP:W.
-td_dirs()
-{
- while read d
- do
- (cd "$d" && td_here)
- done <$TMP:W
-}
-
-# Find directories containing .td files within the specified directory,
-# and record them in the worklist $TMP:W.
-td_find()
-{
- find -L "$1" -type f -name '*.td' |
- sed -e 's:/[^/]*$::' |
- sort -u >$TMP:W
- td_dump $TMP:W
-}
-
-# Generate tags for the specified code generator targets, or
-# if there are no arguments, all targets.
-do_targets() {
- cd $LLVM_SRC_ROOT/lib/Target
- if [ -z "$*" ]
- then
- td_find "$PWD"
- else
- # Check that every specified argument is a target directory;
- # if not, list all target directories.
- for d
- do
- if [ -d "$d" ] && dir_has_td "$d"
- then
- printf '%s/%s\n' "$PWD" "$d"
- else
- printf >&2 '%s: "%s" is not a target. Targets are:\n' "$SELF" "$d"
- for d in *
- do
- [ -d "$d" ] || continue
- dir_has_td "$d" && printf >&2 ' %s\n' "$d"
- done
- exit 2
- fi
- done >$TMP:W
- fi
- td_dirs
-}
-
-# Change to the directory at the top of the enclosing LLVM source tree,
-# if possible.
-llvm_src_root() {
- while [ "$PWD" != / ]
- do
- # Use this directory if multiple notable subdirectories are present.
- [ -d include/llvm -a -d lib/Target ] && return 0
- cd ..
- done
- return 1
-}
-
-# Ensure sort(1) behaves consistently.
-LC_ALL=C
-export LC_ALL
-
-# Globals.
-TBLGEN=llvm-tblgen
-LLVM_SRC_ROOT=
-
-# Command options.
-OPT_TAGSFILE=tags
-OPT_RECIPES=0
-OPT_APPEND=0
-OPT_VERBOSE=0
-OPT_NOTBLGENERR=0
-
-while getopts 'af:hxqvHI:' opt
-do
- case $opt in
- a)
- OPT_APPEND=1
- ;;
- f)
- OPT_TAGSFILE="$OPTARG"
- ;;
- x)
- OPT_RECIPES=1
- ;;
- q)
- OPT_NOTBLGENERR=1
- ;;
- v)
- OPT_VERBOSE=$((OPT_VERBOSE + 1))
- ;;
- I)
- printf '%s\n' "$OPTARG" >>$TMP:D
- ;;
- [hH])
- help
- exit 0
- ;;
- *)
- usage >&2
- exit 4
- ;;
- esac
-done
-shift $((OPTIND - 1))
-
-# Handle the case where tdtags is a simple ctags(1)-like wrapper for tblgen.
-if [ $OPT_RECIPES -eq 0 ]
-then
- if [ -z "$*" ]
- then
- help >&2
- exit 5
- fi
- for i
- do
- printf '%s\n' "$i"
- done >$TMP:T
- td_tag
- exit $?
-fi
-
-# Find the directory at the top of the enclosing LLVM source tree.
-if ! LLVM_SRC_ROOT=$(llvm_src_root && pwd)
-then
- printf >&2 '%s: Run from within the LLVM source tree.\n' "$SELF"
- exit 3
-fi
-
-# Select canned actions.
-RECIPE="$1"
-case "$RECIPE" in
-all)
- shift
- do_all
- ;;
-.|cwd|here)
- shift
- do_here
- ;;
-recurse)
- shift
- do_recurse
- ;;
-target)
- shift
- do_targets "$@"
- ;;
-*)
- if [ -n "$RECIPE" ]
- then
- shift
- printf >&2 '%s: Unknown recipe "-x %s". ' "$SELF" "$RECIPE"
- fi
- printf >&2 'Recipes:\n'
- usage_recipes >&2
- printf >&2 'Run "%s -H" for help.\n' "$SELF"
- exit 6
- ;;
-esac
-
-exit $?
Modified: trunk/contrib/llvm/utils/Target/ARM/analyze-match-table.py
===================================================================
--- trunk/contrib/llvm/utils/Target/ARM/analyze-match-table.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/Target/ARM/analyze-match-table.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,61 +0,0 @@
-#!/usr/bin/env python
-
-def analyze_match_table(path):
- # Extract the instruction table.
- data = open(path).read()
- start = data.index("static const MatchEntry MatchTable")
- end = data.index("\n};\n", start)
- lines = data[start:end].split("\n")[1:]
-
- # Parse the instructions.
- insns = []
- for ln in lines:
- ln = ln.split("{", 1)[1]
- ln = ln.rsplit("}", 1)[0]
- a,bc = ln.split("{", 1)
- b,c = bc.split("}", 1)
- code, string, converter, _ = [s.strip()
- for s in a.split(",")]
- items = [s.strip() for s in b.split(",")]
- _,features = [s.strip() for s in c.split(",")]
- assert string[0] == string[-1] == '"'
- string = string[1:-1]
- insns.append((code,string,converter,items,features))
-
- # For every mnemonic, compute whether or not it can have a carry setting
- # operand and whether or not it can have a predication code.
- mnemonic_flags = {}
- for insn in insns:
- mnemonic = insn[1]
- items = insn[3]
- flags = mnemonic_flags[mnemonic] = mnemonic_flags.get(mnemonic, set())
- flags.update(items)
-
- mnemonics = set(mnemonic_flags)
- ccout_mnemonics = set(m for m in mnemonics
- if 'MCK_CCOut' in mnemonic_flags[m])
- condcode_mnemonics = set(m for m in mnemonics
- if 'MCK_CondCode' in mnemonic_flags[m])
- noncondcode_mnemonics = mnemonics - condcode_mnemonics
- print ' || '.join('Mnemonic == "%s"' % m
- for m in ccout_mnemonics)
- print ' || '.join('Mnemonic == "%s"' % m
- for m in noncondcode_mnemonics)
-
-def main():
- import sys
- if len(sys.argv) == 1:
- import os
- from lit.Util import capture
- llvm_obj_root = capture(["llvm-config", "--obj-root"])
- file = os.path.join(llvm_obj_root,
- "lib/Target/ARM/ARMGenAsmMatcher.inc")
- elif len(sys.argv) == 2:
- file = sys.argv[1]
- else:
- raise NotImplementedError
-
- analyze_match_table(file)
-
-if __name__ == '__main__':
- main()
Modified: trunk/contrib/llvm/utils/UpdateCMakeLists.pl
===================================================================
--- trunk/contrib/llvm/utils/UpdateCMakeLists.pl 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/UpdateCMakeLists.pl 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,118 +0,0 @@
-#!/usr/bin/env perl
-use strict;
-use File::Find;
-use File::Copy;
-use Digest::MD5;
-
-my @fileTypes = ("cpp", "c");
-my %dirFiles;
-my %dirCMake;
-
-sub GetFiles {
- my $dir = shift;
- my $x = $dirFiles{$dir};
- if (!defined $x) {
- $x = [];
- $dirFiles{$dir} = $x;
- }
- return $x;
-}
-
-sub ProcessFile {
- my $file = $_;
- my $dir = $File::Find::dir;
- # Record if a CMake file was found.
- if ($file eq "CMakeLists.txt") {
- $dirCMake{$dir} = $File::Find::name;
- return 0;
- }
- # Grab the extension of the file.
- $file =~ /\.([^.]+)$/;
- my $ext = $1;
- my $files;
- foreach my $x (@fileTypes) {
- if ($ext eq $x) {
- if (!defined $files) {
- $files = GetFiles($dir);
- }
- push @$files, $file;
- return 0;
- }
- }
- return 0;
-}
-
-sub EmitCMakeList {
- my $dir = shift;
- my $files = $dirFiles{$dir};
-
- if (!defined $files) {
- return;
- }
-
- foreach my $file (sort @$files) {
- print OUT " ";
- print OUT $file;
- print OUT "\n";
- }
-}
-
-sub UpdateCMake {
- my $cmakeList = shift;
- my $dir = shift;
- my $cmakeListNew = $cmakeList . ".new";
- open(IN, $cmakeList);
- open(OUT, ">", $cmakeListNew);
- my $foundLibrary = 0;
-
- while(<IN>) {
- if (!$foundLibrary) {
- print OUT $_;
- if (/^add_[^_]+_library\(/ || /^add_llvm_target\(/ || /^add_[^_]+_executable\(/) {
- $foundLibrary = 1;
- EmitCMakeList($dir);
- }
- }
- else {
- if (/\)/) {
- print OUT $_;
- $foundLibrary = 0;
- }
- }
- }
-
- close(IN);
- close(OUT);
-
- open(FILE, $cmakeList) or
- die("Cannot open $cmakeList when computing digest\n");
- binmode FILE;
- my $digestA = Digest::MD5->new->addfile(*FILE)->hexdigest;
- close(FILE);
-
- open(FILE, $cmakeListNew) or
- die("Cannot open $cmakeListNew when computing digest\n");
- binmode FILE;
- my $digestB = Digest::MD5->new->addfile(*FILE)->hexdigest;
- close(FILE);
-
- if ($digestA ne $digestB) {
- move($cmakeListNew, $cmakeList);
- return 1;
- }
-
- unlink($cmakeListNew);
- return 0;
-}
-
-sub UpdateCMakeFiles {
- foreach my $dir (sort keys %dirCMake) {
- if (UpdateCMake($dirCMake{$dir}, $dir)) {
- print "Updated: $dir\n";
- }
- }
-}
-
-find({ wanted => \&ProcessFile, follow => 1 }, '.');
-UpdateCMakeFiles();
-
Modified: trunk/contrib/llvm/utils/bugpoint/RemoteRunSafely.sh
===================================================================
--- trunk/contrib/llvm/utils/bugpoint/RemoteRunSafely.sh 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/bugpoint/RemoteRunSafely.sh 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,105 +0,0 @@
-#!/bin/sh
-#
-# Program: RemoteRunSafely.sh
-#
-# Synopsis: This script simply runs another program remotely using ssh.
-# It always returns the another program exit code or exit with
-# code 255 which indicates that the program could not be executed.
-#
-# Syntax:
-#
-# RemoteRunSafely.sh <hostname> [-l <login_name>] [-p <port>]
-# <program> <args...>
-#
-# where:
-# <hostname> is the remote host to execute the program,
-# <login_name> is the username on the remote host,
-# <port> is the port used by the remote client,
-# <program> is the path to the program to run,
-# <args...> are the arguments to pass to the program.
-#
-
-printUsageAndExit()
-{
- echo "Usage:"
- echo "./RemoteRunSafely.sh <hostname> [-l <login_name>] [-p <port>] " \
- "<program> <args...>"
- exit 255
-}
-
-moreArgsExpected()
-{
- # $1 - remaining number of arguments
- # $2 - number of arguments to shift
- if [ $1 -lt $2 ]
- then
- echo "Error: Wrong number of argumants."
- printUsageAndExit
- fi
-}
-
-# Save a copy of the original arguments in a string before we
-# clobber them with the shift command.
-ORIG_ARGS="$*"
-#DEBUG: echo 'GOT: '$ORIG_ARGS
-
-moreArgsExpected $# 1
-RHOST=$1
-shift 1
-
-RUSER=`id -un`
-RCLIENT=ssh
-RPORT=
-WORKING_DIR=
-
-moreArgsExpected $# 1
-if [ $1 = "-l" ]; then
- moreArgsExpected $# 2
- RUSER=$2
- shift 2
-fi
-moreArgsExpected $# 1
-if [ $1 = "-p" ]; then
- moreArgsExpected $# 2
- RPORT="-p $2"
- shift 2
-fi
-
-moreArgsExpected $# 1
-PROGRAM=$(basename $1)
-WORKING_DIR=$(dirname $1)
-shift 1
-
-#DEBUG: echo 'DIR='${0%%`basename $0`}
-#DEBUG: echo 'RHOST='$RHOST
-#DEBUG: echo 'RUSER='$RUSER
-#DEBUG: echo 'PROGRAM='$PROGRAM
-#DEBUG: echo 'WORKING_DIR='$WORKING_DIR
-#DEBUG: echo 'ARGS='$*
-
-# Sanity check
-if [ "$RHOST" = "" -o "$PROGRAM" = "" ]; then
- printUsageAndExit
-fi
-
-# Local program file must exist and be execuatble
-local_program=$WORKING_DIR"/"$PROGRAM
-if [ ! -x "$local_program" ]; then
- echo "File "$local_program" does not exist or is not an executable.."
- exit 255
-fi
-
-connection=$RUSER'@'$RHOST
-remote="./"$PROGRAM
-(
- cat $local_program | \
- $RCLIENT $connection $RPORT \
- 'rm -f '$remote' ; ' \
- 'cat > '$remote' ; chmod +x '$remote' ; '$remote' '$*' ; ' \
- 'err=$? ; rm -f '$remote' ; exit $err'
-)
-err=$?
-
-#DEBUG: echo script exit $err
-exit $err
-
Modified: trunk/contrib/llvm/utils/buildit/GNUmakefile
===================================================================
--- trunk/contrib/llvm/utils/buildit/GNUmakefile 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/buildit/GNUmakefile 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,132 +0,0 @@
-# LLVM LOCAL file build machinery
-# LLVM Compiler Makefile for use by buildit.
-#
-# This makefile is intended only for use with B&I buildit. For "normal" builds
-# use the conventional top-level makefile.
-#
-# You can specify TARGETS=ppc (or i386) on the buildit command line to limit the
-# build to just one target. The default is for ppc and i386. The compiler
-# targeted at this host gets built anyway, but not installed unless it's listed
-# in TARGETS.
-
-# Include the set of standard Apple makefile definitions.
-ifndef CoreOSMakefiles
-CoreOSMakefiles = $(MAKEFILEPATH)/CoreOS
-endif
-include $(CoreOSMakefiles)/Standard/Standard.make
-
-# Enable Apple extensions to (gnu)make.
-USE_APPLE_PB_SUPPORT = all
-
-RC_ARCHS := ppc i386
-HOSTS = $(RC_ARCHS)
-targets = echo $(RC_ARCHS)
-TARGETS := $(shell $(targets))
-
-SRCROOT = .
-
-SRC = $(shell cd $(SRCROOT) && pwd | sed s,/private,,)
-OBJROOT = $(SRC)/obj
-SYMROOT = $(OBJROOT)/../sym
-DSTROOT = $(OBJROOT)/../dst
-
-#######################################################################
-
-PREFIX = /usr/local
-
-# Unless assertions are forced on in the GMAKE command line, disable them.
-ifndef ENABLE_ASSERTIONS
-ENABLE_ASSERTIONS := no
-endif
-
-# Default is optimized build.
-ifeq ($(LLVM_DEBUG),1)
-LLVM_OPTIMIZED := no
-else
-LLVM_OPTIMIZED := yes
-endif
-
-# Default to do a native build, not a cross-build for an ARM host or simulator.
-ARM_HOSTED_BUILD := no
-IOS_SIM_BUILD := no
-
-ifndef RC_ProjectSourceVersion
-RC_ProjectSourceVersion = 9999
-endif
-
-ifndef RC_ProjectSourceSubversion
-RC_ProjectSourceSubversion = 0
-endif
-
-# NOTE : Always put version numbers at the end because they are optional.
-install: $(OBJROOT) $(SYMROOT) $(DSTROOT)
- cd $(OBJROOT) && \
- $(SRC)/utils/buildit/build_llvm "$(RC_ARCHS)" "$(TARGETS)" \
- $(SRC) $(PREFIX) $(DSTROOT) $(SYMROOT) \
- $(ENABLE_ASSERTIONS) $(LLVM_OPTIMIZED) \
- $(ARM_HOSTED_BUILD) $(IOS_SIM_BUILD) \
- $(RC_ProjectSourceVersion) $(RC_ProjectSourceSubversion)
-
-EmbeddedHosted:
- $(MAKE) ARM_HOSTED_BUILD=yes PREFIX=/usr/local install
-
-# When building for the iOS simulator, MACOSX_DEPLOYMENT_TARGET is not set
-# by default, but it needs to be set when building tools that run on the host
-# (e.g., tblgen), so set it here.
-EmbeddedSim:
- export MACOSX_DEPLOYMENT_TARGET=`sw_vers -productVersion`; \
- $(MAKE) IOS_SIM_BUILD=yes PREFIX=$(SDKROOT)/usr/local install
-
-Embedded:
- ARM_PLATFORM=`xcodebuild -version -sdk iphoneos PlatformPath` && \
- $(MAKE) DSTROOT=$(DSTROOT)$$ARM_PLATFORM/Developer install
-
-# installhdrs does nothing, because the headers aren't useful until
-# the compiler is installed.
-installhdrs:
-
-# We build and install in one shell script.
-build:
-
-installsrc:
- @echo
- @echo ++++++++++++++++++++++
- @echo + Installing sources +
- @echo ++++++++++++++++++++++
- @echo
- if [ $(SRCROOT) != . ]; then \
- $(PAX) -rw . $(SRCROOT); \
- fi
- find -d "$(SRCROOT)" \( -type d -a -name .svn -o \
- -type f -a -name .DS_Store -o \
- -name \*~ -o -name .\#\* \) \
- -exec rm -rf {} \;
- rm -rf "$(SRCROOT)/test"
-
-#######################################################################
-
-clean:
- @echo
- @echo ++++++++++++
- @echo + Cleaning +
- @echo ++++++++++++
- @echo
- @if [ -d $(OBJROOT) -a "$(OBJROOT)" != / ]; then \
- echo '*** DELETING ' $(OBJROOT); \
- rm -rf $(OBJROOT); \
- fi
- @if [ -d $(SYMROOT) -a "$(SYMROOT)" != / ]; then \
- echo '*** DELETING ' $(SYMROOT); \
- rm -rf $(SYMROOT); \
- fi
- @if [ -d $(DSTROOT) -a "$(DSTROOT)" != / ]; then \
- echo '*** DELETING ' $(DSTROOT); \
- rm -rf $(DSTROOT); \
- fi
-
-#######################################################################
-
-$(OBJROOT) $(SYMROOT) $(DSTROOT):
- mkdir -p $@
-
-.PHONY: install installsrc clean EmbeddedHosted EmbeddedSim Embedded
Modified: trunk/contrib/llvm/utils/buildit/build_llvm
===================================================================
--- trunk/contrib/llvm/utils/buildit/build_llvm 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/buildit/build_llvm 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,354 +0,0 @@
-#!/bin/sh
-# LLVM LOCAL file B&I
-
-set -x
-
-# Build LLVM the "Apple way".
-# Parameters:
-
-# The first parameter is a space-separated list of the architectures the
-# compilers will run on. For instance, "ppc i386". If the current machine
-# isn't in the list, it will (effectively) be added.
-HOSTS="$1"
-
-# The second parameter is a space-separated list of the architectures the
-# compilers will generate code for. If the current machine isn't in the list, a
-# compiler for it will get built anyway, but won't be installed.
-# FIXME: The list of targets is currently hard-coded and TARGETS is not used.
-TARGETS="$2"
-
-# The third parameter is the path to the compiler sources. There should be a
-# shell script named 'configure' in this directory. This script makes a copy...
-ORIG_SRC_DIR="$3"
-
-# The fourth parameter is the location where the LLVM will be installed. You can
-# move it once it's built, so this mostly controls the layout of $DEST_DIR.
-DEST_ROOT="$4"
-
-# The fifth parameter is the place where the compiler will be copied once it's
-# built.
-DEST_DIR="$5"
-
-# The sixth parameter is a directory in which to place information (like
-# unstripped executables and generated source files) helpful in debugging the
-# resulting compiler.
-SYM_DIR="$6"
-
-# The seventh parameter is a yes/no that indicates whether assertions should be
-# enabled in the LLVM libs/tools.
-LLVM_ASSERTIONS="$7"
-
-# The eighth parameter is a yes/no that indicates whether this is an optimized
-# build.
-LLVM_OPTIMIZED="$8"
-
-# A yes/no parameter that controls whether to cross-build for an ARM host.
-ARM_HOSTED_BUILD="$9"
-
-# A yes/no parameter that controls whether to cross-build for the iOS simulator
-IOS_SIM_BUILD="${10}"
-
-# The version number of the submission, e.g. 1007.
-LLVM_SUBMIT_VERSION="${11}"
-
-# The subversion number of the submission, e.g. 03.
-LLVM_SUBMIT_SUBVERSION="${12}"
-
-# The current working directory is where the build will happen. It may already
-# contain a partial result of an interrupted build, in which case this script
-# will continue where it left off.
-DIR=`pwd`
-
-DARWIN_VERS=`uname -r | sed 's/\..*//'`
-echo DARWIN_VERS = $DARWIN_VERS
-
-################################################################################
-# Run the build.
-
-# Create the source tree we'll actually use to build, deleting
-# tcl since it doesn't actually build properly in a cross environment
-# and we don't really need it.
-SRC_DIR=$DIR/src
-rm -rf $SRC_DIR || exit 1
-mkdir $SRC_DIR || exit 1
-ln -s $ORIG_SRC_DIR/* $SRC_DIR/ || exit 1
-# We can't use the top-level Makefile as-is. Remove the soft link:
-rm $SRC_DIR/Makefile || exit 1
-# Now create our own by editing the top-level Makefile, deleting every line marked "Apple-style":
-sed -e '/[Aa]pple-style/d' -e '/include.*GNUmakefile/d' $ORIG_SRC_DIR/Makefile > $SRC_DIR/Makefile || exit 1
-
-SUBVERSION=`echo $RC_ProjectSourceVersion | sed -e 's/.*\.\([0-9]*\).*/\1/'`
-if [ "x$SUBVERSION" != "x$RC_ProjectSourceVersion" ]; then
- LLVM_SUBMIT_SUBVERSION=`printf "%02d" $SUBVERSION`
- RC_ProjectSourceVersion=`echo $RC_ProjectSourceVersion | sed -e 's/\..*//'`
- LLVM_SUBMIT_VERSION=$RC_ProjectSourceVersion
-fi
-if [ "x$LLVM_SUBMIT_SUBVERSION" = "x00" -o "x$LLVM_SUBMIT_SUBVERSION" = "x0" ]; then
- LLVM_VERSION="$LLVM_SUBMIT_VERSION"
-else
- LLVM_VERSION="$LLVM_SUBMIT_VERSION-$LLVM_SUBMIT_SUBVERSION"
-fi
-
-# Figure out how many make processes to run.
-SYSCTL=`sysctl -n hw.activecpu`
-# sysctl -n hw.* does not work when invoked via B&I chroot /BuildRoot.
-# Builders can default to 2, since even if they are single processor,
-# nothing else is running on the machine.
-if [ -z "$SYSCTL" ]; then
- SYSCTL=2
-fi
-JOBS_FLAG="-j $SYSCTL"
-
-COMMON_CONFIGURE_OPTS="\
- --prefix=$DEST_DIR$DEST_ROOT \
- --enable-assertions=$LLVM_ASSERTIONS \
- --enable-optimized=$LLVM_OPTIMIZED \
- --disable-bindings"
-
-COMMON_MAKEFLAGS="\
- UNIVERSAL=1 \
- UNIVERSAL_SDK_PATH=$SDKROOT \
- NO_RUNTIME_LIBS=1 \
- DISABLE_EDIS=1 \
- REQUIRES_RTTI=1 \
- DEBUG_SYMBOLS=1 \
- LLVM_SUBMIT_VERSION=$LLVM_SUBMIT_VERSION \
- LLVM_SUBMIT_SUBVERSION=$LLVM_SUBMIT_SUBVERSION \
- VERBOSE=1"
-
-# Build the LLVM tree universal.
-mkdir -p $DIR/obj-llvm || exit 1
-cd $DIR/obj-llvm || exit 1
-
-if [ "$ARM_HOSTED_BUILD" = yes ]; then
- # The cross-tools' build process expects to find an existing cross toolchain
- # under names like 'arm-apple-darwin$DARWIN_VERS-as'; so make them.
- rm -rf $DIR/bin || exit 1
- mkdir $DIR/bin || exit 1
- for prog in ar nm ranlib strip lipo ld as ; do
- P=$DIR/bin/arm-apple-darwin$DARWIN_VERS-${prog}
- T=`xcrun -sdk $SDKROOT -find ${prog}`
- ln -s $T $DIR/bin/$prog
- echo '#!/bin/sh' > $P || exit 1
- echo 'exec '$T' "$@"' >> $P || exit 1
- chmod a+x $P || exit 1
- done
- # Set up the links for clang.
- for prog in clang clang++ ; do
- P=$DIR/bin/arm-apple-darwin$DARWIN_VERS-${prog}
- T=`xcrun -sdk $SDKROOT -find ${prog}`
- ln -s $T $DIR/bin/$prog
- echo '#!/bin/sh' > $P || exit 1
- echo 'exec '$T' -arch armv7 -isysroot '${SDKROOT}' "$@"' >> $P || exit 1
- chmod a+x $P || exit 1
- done
-
- PATH=$DIR/bin:$PATH
-
- unset SDKROOT && \
- $SRC_DIR/configure $COMMON_CONFIGURE_OPTS \
- --enable-targets=arm \
- --host=arm-apple-darwin10 \
- --target=arm-apple-darwin10 \
- --build=i686-apple-darwin10 \
- --program-prefix="" \
- || exit 1
-
- if [ -n "$IPHONEOS_DEPLOYMENT_TARGET" ]; then
- COMMON_MAKEFLAGS="$COMMON_MAKEFLAGS \
- DEPLOYMENT_TARGET=-mios-version-min=$IPHONEOS_DEPLOYMENT_TARGET"
- fi
-
- make $JOBS_FLAG $COMMON_MAKEFLAGS SDKROOT= UNIVERSAL_ARCH="$HOSTS" \
- CXXFLAGS="-DLLVM_VERSION_INFO='\" Apple Build #$LLVM_VERSION\"'"
- if [ $? != 0 ] ; then
- echo "error: LLVM 'make' failed!"
- exit 1
- fi
-
-else
-# not $ARM_HOSTED_BUILD
-
- export CC=`xcrun -find clang`
- export CXX=`xcrun -find clang++`
-
- if [ "$IOS_SIM_BUILD" = yes ]; then
- # Use a non-standard "darwin_sim" host triple to trigger a cross-build.
- configure_opts="--enable-targets=x86 --host=i686-apple-darwin_sim \
- --build=i686-apple-darwin10"
- if [ -n "$IPHONEOS_DEPLOYMENT_TARGET" ]; then
- COMMON_MAKEFLAGS="$COMMON_MAKEFLAGS \
- DEPLOYMENT_TARGET=-mios-simulator-version-min=$IPHONEOS_DEPLOYMENT_TARGET"
- fi
- else
- configure_opts="--enable-targets=arm,x86"
- if [ -n "$MACOSX_DEPLOYMENT_TARGET" ]; then
- COMMON_MAKEFLAGS="$COMMON_MAKEFLAGS \
- DEPLOYMENT_TARGET=-mmacosx-version-min=$MACOSX_DEPLOYMENT_TARGET"
- fi
- fi
-
- if [ $SDKROOT ]; then
- CPPFLAGS="$CPPFLAGS -isysroot $SDKROOT"
- fi
- for host in $HOSTS; do :; done
- CPPFLAGS="$CPPFLAGS -arch $host"
-
- $SRC_DIR/configure $COMMON_CONFIGURE_OPTS $configure_opts \
- --program-prefix="" \
- CPPFLAGS="$CPPFLAGS" \
- || exit 1
-
- make $JOBS_FLAG $COMMON_MAKEFLAGS UNIVERSAL_ARCH="$HOSTS" \
- CXXFLAGS="-DLLVM_VERSION_INFO='\" Apple Build #$LLVM_VERSION\"'"
- if [ $? != 0 ] ; then
- echo "error: LLVM 'make' failed!"
- exit 1
- fi
-fi
-
-################################################################################
-# Construct the actual destination root, by copying stuff from $DIR/dst-* to
-# $DEST_DIR, with occasional 'lipo' commands.
-
-cd $DEST_DIR || exit 1
-
-# Clean out DEST_DIR in case -noclean was passed to buildit.
-rm -rf * || exit 1
-
-cd $DIR/obj-llvm || exit 1
-
-# Install the tree into the destination directory.
-make $JOBS_FLAG $COMMON_MAKEFLAGS UNIVERSAL_ARCH="$HOSTS" install
-if ! test $? == 0 ; then
- echo "error: LLVM 'make install' failed!"
- exit 1
-fi
-
-# Install Version.h
-LLVM_MINOR_VERSION=`echo $LLVM_SUBMIT_SUBVERSION | sed -e 's,0*\([1-9][0-9]*\),\1,'`
-if [ "x$LLVM_MINOR_VERSION" = "x" ]; then
- LLVM_MINOR_VERSION=0
-fi
-RC_ProjectSourceSubversion=`printf "%d" $LLVM_MINOR_VERSION`
-echo "#define LLVM_VERSION ${RC_ProjectSourceVersion}" > $DEST_DIR$DEST_ROOT/include/llvm/Version.h
-echo "#define LLVM_MINOR_VERSION ${RC_ProjectSourceSubversion}" >> $DEST_DIR$DEST_ROOT/include/llvm/Version.h
-
-# Run unifdef to preprocess the installed headers to reflect whether this
-# was a debug or release build.
-for file in `find $DEST_DIR$DEST_ROOT/include -type f -print`; do
- if [ "$LLVM_ASSERTIONS" = yes ]; then
- unifdef -UNDEBUG -D_DEBUG -o $file $file
- else
- unifdef -DNDEBUG -U_DEBUG -ULLVM_ENABLE_DUMP -o $file $file
- fi
-done
-
-# Find the right version of strip to use.
-STRIP=strip
-if [ -n "$SDKROOT" ]; then
- STRIP=`xcrun -sdk $SDKROOT -find strip`
-fi
-
-if [ "x$LLVM_DEBUG" != "x1" ]; then
- # Strip local symbols from llvm libraries.
- #
- # Use '-l' to strip i386 modules. N.B. that flag doesn't work with kext or
- # PPC objects!
- $STRIP -Sl $DEST_DIR$DEST_ROOT/lib/*.[oa]
- for f in `ls $DEST_DIR$DEST_ROOT/lib/*.so`; do
- $STRIP -Sxl $f
- done
-fi
-
-# Remove .dir files
-cd $DEST_DIR$DEST_ROOT
-rm -f bin/.dir etc/llvm/.dir lib/.dir
-
-# The Hello dylib is an example of how to build a pass.
-# The BugpointPasses module is only used to test bugpoint.
-# These unversioned dylibs cause verification failures, so do not install them.
-# (The wildcards are used to match a "lib" prefix if it is present.)
-rm $DEST_DIR$DEST_ROOT/lib/*LLVMHello.dylib
-rm $DEST_DIR$DEST_ROOT/lib/*BugpointPasses.dylib
-
-# Compress manpages
-MDIR=$DEST_DIR$DEST_ROOT/share/man/man1
-gzip -f $MDIR/*
-
-################################################################################
-# Create SYM_DIR with information required for debugging.
-
-# Figure out how many make processes to run.
-SYSCTL=`sysctl -n hw.activecpu`
-
-# hw.activecpu only available in 10.2.6 and later
-if [ -z "$SYSCTL" ]; then
- SYSCTL=`sysctl -n hw.ncpu`
-fi
-
-# sysctl -n hw.* does not work when invoked via B&I chroot /BuildRoot. Builders
-# can default to 2, since even if they are single processor, nothing else is
-# running on the machine.
-if [ -z "$SYSCTL" ]; then
- SYSCTL=2
-fi
-
-cd $SYM_DIR || exit 1
-
-# Clean out SYM_DIR in case -noclean was passed to buildit.
-rm -rf * || exit 1
-
-# Generate .dSYM files
-DSYMUTIL=`xcrun -find dsymutil`
-find $DEST_DIR -perm -0111 -type f \
- ! \( -name '*.la' -o -name gccas -o -name gccld -o -name llvm-config -o -name '*.a' \) \
- -print | xargs -n 1 -P ${SYSCTL} ${DSYMUTIL}
-
-# Save .dSYM files and .a archives
-cd $DEST_DIR || exit 1
-find . \( -path \*.dSYM/\* -or -name \*.a \) -print \
- | cpio -pdml $SYM_DIR || exit 1
-
-# Save source files.
-mkdir $SYM_DIR/src || exit 1
-cd $DIR || exit 1
-find obj-* -name \*.\[chy\] -o -name \*.cpp -print \
- | cpio -pdml $SYM_DIR/src || exit 1
-
-################################################################################
-# Remove libLTO.dylib and lto.h. Those are installed by clang.
-
-cd $DEST_DIR$DEST_ROOT
-rm -f lib/libLTO.dylib
-rm -f lib/libLTO.a lib/libLTO.la
-find $DEST_DIR$DEST_ROOT -name lto.h -delete
-
-################################################################################
-# Remove debugging information from DEST_DIR.
-
-cd $DIR || exit 1
-
-find $DEST_DIR -name \*.a -print | xargs ranlib || exit 1
-find $DEST_DIR -name \*.dSYM -print | xargs rm -r || exit 1
-
-# Strip debugging information from files
-#
-# Use '-l' to strip i386 modules. N.B. that flag doesn't work with kext or
-# PPC objects!
-find $DEST_DIR -perm -0111 -type f \
- ! \( -name '*.la' -o -name gccas -o -name gccld -o -name llvm-config \) \
- -print | xargs -n 1 -P ${SYSCTL} $STRIP -arch all -Sl
-
-chgrp -h -R wheel $DEST_DIR
-chgrp -R wheel $DEST_DIR
-
-################################################################################
-# Remove the docs directory
-
-rm -rf $DEST_DIR$DEST_ROOT/docs
-
-################################################################################
-# w00t! Done!
-
-exit 0
Modified: trunk/contrib/llvm/utils/check-each-file
===================================================================
--- trunk/contrib/llvm/utils/check-each-file 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/check-each-file 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,150 +0,0 @@
-#!/bin/sh
-# check-each-file
-# Used to narrow down a miscompilation to one .o file from a list. Please read
-# the usage procedure, below, for command-line syntax (or run it with --help).
-# This script depends on the llvm-native-gcc script.
-
-if [ x$1 = x--make-linker-script ]
-then
- program=$2
- linker=./link-$program
- echo "Building $program with llvm-native-gcc"
- rm -f $program
- gmake -e $program CC=llvm-native-gcc CXX=llvm-native-gxx
- echo "Erasing $program and re-linking it"
- rm -f $program
- echo "rm -f $program" > $linker
- gmake -n $program >> $linker
- chmod 755 $linker
- echo "Linker script created in $linker; testing it out"
- output=`./$linker 2>&1`
- case "$output" in
- *undefined*reference*__main*)
- echo "$program appears to need a dummy __main function; adding one"
- echo "void __main () { }" > __main.c
- gcc -c __main.c
- echo "Done; rebuilding $linker"
- echo "rm -f $program" > $linker
- gmake -n $program 2>&1 | sed '/gcc/s/$/__main.o/' >> $linker
- ./$linker > /dev/null 2>&1
- if [ ! -x $program ]
- then
- echo "WARNING: linker script didn't work"
- fi
- ;;
- *)
- if [ ! -x $program ]
- then
- echo "WARNING: linker script didn't work"
- fi
- ;;
- esac
- echo "Linker script created in $linker; please check it manually"
- exit 0
-fi
-
-checkfiles="$1"
-program="$2"
-linker="$3"
-checker="$4"
-
-usage () {
- myname=`basename $0`
- echo "$myname --make-linker-script PROGRAM"
- echo "$myname OBJECTS-FILE PROGRAM LINKER CHECKER"
- echo ""
- echo "OBJECTS-FILE is a text file containing the names of all the .o files"
- echo "PROGRAM is the name of the executable under test"
- echo "(there must also exist a Makefile in the current directory which"
- echo "has PROGRAM as a target)"
- echo "LINKER is the script that builds PROGRAM; try --make-linker-script"
- echo "to automatically generate it"
- echo "CHECKER is the script that exits 0 if PROGRAM is ok, 1 if it is not OK"
- echo "(LINKER and CHECKER must be in your PATH, or you should specify ./)"
- echo ""
- echo "Bugs to <gaeke at uiuc.edu>."
- exit 1
-}
-
-if [ x$1 = x--help ]
-then
- usage
-fi
-
-if [ -z "$checkfiles" ]
-then
- echo "ERROR: Must specify name of file w/ list of objects as 1st arg."
- echo "(got \"$checkfiles\")"
- usage
-fi
-if [ ! -f "$checkfiles" ]
-then
- echo "ERROR: $checkfiles not found"
- usage
-fi
-if [ -z "$program" ]
-then
- echo "ERROR: Must specify name of program as 2nd arg."
- usage
-fi
-if [ -z "$linker" ]
-then
- echo "ERROR: Must specify name of link script as 3rd arg."
- usage
-fi
-if [ ! -x "$linker" ]
-then
- echo "ERROR: $linker not found or not executable"
- echo "You may wish to try: $0 --make-linker-script $program"
- usage
-fi
-if [ -z "$checker" ]
-then
- echo "ERROR: Must specify name of $program check script as 3rd arg."
- usage
-fi
-if [ ! -x "$checker" ]
-then
- echo "ERROR: $checker not found or not executable"
- usage
-fi
-
-files=`cat $checkfiles`
-echo "Recompiling everything with llvm-native-gcc"
-for f in $files
-do
- rm -f $f
- gmake $f CC=llvm-native-gcc CXX=llvm-native-gxx
-done
-rm -f $program
-$linker
-if $checker
-then
- echo "Sorry, I can't help you, $program is OK when compiled with llvm-native-gcc"
- exit 1
-fi
-for f in $files
-do
- echo Trying to compile $f with native gcc and rebuild $program
- mv ${f} ${f}__OLD__
- gmake ${f} CC=gcc > /dev/null 2>&1
- $linker
- echo Checking validity of new $program
- if $checker
- then
- echo Program is OK
- okfiles="$okfiles $f"
- else
- echo Program is not OK
- notokfiles="$notokfiles $f"
- fi
- mv ${f}__OLD__ ${f}
-done
-echo ""
-echo "Program is OK when these files are recompiled with native gcc: "
-echo "$okfiles"
-echo ""
-echo "Program is not OK when these files are recompiled with native gcc: "
-echo "$notokfiles"
-echo ""
-exit 0
Modified: trunk/contrib/llvm/utils/clang-parse-diagnostics-file
===================================================================
--- trunk/contrib/llvm/utils/clang-parse-diagnostics-file 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/clang-parse-diagnostics-file 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,96 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import plistlib
-
-def main():
- from optparse import OptionParser, OptionGroup
- parser = OptionParser("""\
-Usage: %prog [options] <path>
-
-Utility for dumping Clang-style logged diagnostics.\
-""")
- parser.add_option("-a", "--all", action="store_true", dest="all",
- default=False, help="dump all messages.")
- parser.add_option("-e", "--error", action="store_true", dest="error",
- default=False, help="dump 'error' messages.")
- parser.add_option("-f", "--fatal", action="store_true", dest="fatal",
- default=False, help="dump 'fatal error' messages.")
- parser.add_option("-i", "--ignored", action="store_true", dest="ignored",
- default=False, help="dump 'ignored' messages.")
- parser.add_option("-n", "--note", action="store_true", dest="note",
- default=False, help="dump 'note' messages.")
- parser.add_option("-w", "--warning", action="store_true", dest="warning",
- default=False, help="dump 'warning' messages.")
- (opts, args) = parser.parse_args()
-
- if len(args) != 1:
- parser.error("invalid number of arguments")
-
- levels = {'error': False, 'fatal error': False, 'ignored': False,
- 'note': False, 'warning': False}
- if opts.error:
- levels['error'] = True
- if opts.fatal:
- levels['fatal error'] = True
- if opts.ignored:
- levels['ignored'] = True
- if opts.note:
- levels['note'] = True
- if opts.warning:
- levels['warning'] = True
-
- path, = args
-
- # Read the diagnostics log.
- f = open(path)
- try:
- data = f.read()
- finally:
- f.close()
-
- # Complete the plist (the log itself is just the chunks).
- data = """\
-<?xml version="1.0" encoding="UTF-8"?>
-<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" \
- "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<plist version="1.0">
-<array>
-%s
-</array>
-</plist>""" % data
-
- # Get the list of files and diagnostics to report.
- to_report = []
- diags = plistlib.readPlistFromString(data)
- for file_diags in diags:
- file = file_diags.get('main-file')
-
- # Ignore diagnostics for 'conftest.c', which is the file autoconf uses
- # for its tests (which frequently will have warnings).
- if os.path.basename(file) == 'conftest.c':
- continue
-
- # Get the diagnostics for the selected levels.
- selected_diags = [d
- for d in file_diags.get('diagnostics', ())
- if levels[d.get('level')] or opts.all]
- if selected_diags:
- to_report.append((file, selected_diags))
-
- # If there are no diagnostics to report, show nothing.
- if not to_report:
- return
-
- # Otherwise, print out the diagnostics.
- print
- print "**** BUILD DIAGNOSTICS ****"
- for file,selected_diags in to_report:
- print "*** %s ***" % file
- for d in selected_diags:
- print " %s:%s:%s: %s: %s" % (
- d.get('filename'), d.get('line'), d.get('column'),
- d.get('level'), d.get('message'))
-
-if __name__ == "__main__":
- main()
Modified: trunk/contrib/llvm/utils/codegen-diff
===================================================================
--- trunk/contrib/llvm/utils/codegen-diff 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/codegen-diff 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,135 +0,0 @@
-#!/usr/bin/perl
-
-use Getopt::Std;
-$DEBUG = 0;
-
-sub parse_objdump_file {
- my ($filename) = @_;
- my @result;
- open (INPUT, $filename) or die "$filename: $!\n";
- print "opened objdump output file $filename\n" if $DEBUG;
- while (<INPUT>) {
- if (/\s*([0-9a-f]*):\t(([0-9a-f]{2} )+) *\t(.*)$/) {
- my ($addr, $bytes, $instr) = ($1, $2, $4);
- $addr = "0x" . $addr;
- $bytes =~ s/\s*(.*\S)\s*/$1/; # trim any remaining whitespace
- $instr =~ s/\s*(.*\S)\s*/$1/;
- push (@result, {'addr' => $addr, 'bytes' => $bytes, 'instr' => $instr});
- print "addr=$addr bytes='$bytes' instr='$instr'\n" if $DEBUG;
- }
- }
- close INPUT;
- return @result;
-}
-
-sub parse_gdb_file {
- my ($filename) = @_;
- my @result;
- my $got_addr;
- open (INPUT, $filename) or die "$filename: $!\n";
- print "opened gdb output file $filename\n" if $DEBUG;
- while (<INPUT>) {
- if (/^(0x[0-9a-f]*):\t([^\t]*)\t[^:]*:\t((0x[0-9a-f]{2}\s*)+)\s*$/) {
- my ($addr, $bytes, $instr) = ($1, $3, $2);
- $bytes =~ s/0x//g;
- $bytes =~ s/\s+/ /g; # regularize whitespace
- $bytes =~ s/\s*(.*\S)\s*/$1/; # trim any remaining whitespace
- $instr =~ s/\s*(.*\S)\s*/$1/;
- push (@result, {'addr' => $addr, 'bytes' => $bytes, 'instr' => $instr});
- print "addr=$addr bytes='$bytes' instr='$instr'\n" if $DEBUG;
- } elsif (/^(0x[0-9a-f]*):\t$/) { # deal with gdb's line breaker
- $got_addr = $1;
- } elsif ($got_addr && /^ ([^\t]*)\t[^:]*:\t((0x[0-9a-f]{2}\s*)+)\s*$/) {
- my ($addr, $bytes, $instr) = ($got_addr, $2, $1);
- $bytes =~ s/0x//g;
- $bytes =~ s/\s+/ /g; # regularize whitespace
- $bytes =~ s/\s*(.*\S)\s*/$1/; # trim any remaining whitespace
- $instr =~ s/\s*(.*\S)\s*/$1/;
- push (@result, {'addr' => $addr, 'bytes' => $bytes, 'instr' => $instr});
- print "addr=$addr bytes='$bytes' instr='$instr'\n" if $DEBUG;
- undef $got_addr;
- }
- }
- close INPUT;
- return @result;
-}
-
-sub binary_diffs {
- my ($objdump_file, $gdb_file) = @_;
- my @file1 = parse_objdump_file ($objdump_file);
- my @file2 = parse_gdb_file ($gdb_file);
- my $lastrecord = ($#file1 >= $#file2) ? ($#file1) : ($#file2);
- for (my $i = 0; $i <= $lastrecord; ++$i) {
- my $d1 = $file1[$i];
- my $d2 = $file2[$i];
- if ($d1->{'bytes'} ne $d2->{'bytes'}) {
- next if (($d1->{'instr'} eq $d2->{'instr'}) && $opt_d);
- printf "0x%08x:\t%30s \t%s\n", 0+$d1->{'addr'}, $d1->{'bytes'}, $d1->{'instr'};
- printf "0x%08x:\t%30s \t%s\n\n", 0+$d2->{'addr'}, $d2->{'bytes'}, $d2->{'instr'};
- }
- }
-}
-
-&getopts('d');
-$objdump_file = $ARGV[0];
-$gdb_file = $ARGV[1];
-binary_diffs ($objdump_file, $gdb_file);
-exit (0);
-__END__
-=pod
-
-=head1 NAME
-
-codegen-diff
-
-=head1 SYNOPSIS
-
-codegen-diff [-d] I<OBJDUMP-OUTPUT-FILE> I<GDB-DISASSEMBLY-FILE>
-
-=head1 DESCRIPTION
-
-B<codegen-diff> is a program that tries to show you the differences
-between the code that B<llc> generated and the code that B<lli> generated.
-
-The way you use it is as follows: first, you create I<OBJDUMP-OUTPUT-FILE>
-by running B<objdump> on the B<llc> compiled and linked binary. You need to
-trim down the result so it contains only the function of interest.
-
-Second, you create I<GDB-DISASSEMBLY-FILE> by running B<gdb>, with my patch
-to print out hex bytes in the B<disassemble> command output, on
-B<lli>. Set a breakpoint in C<Emitter::finishFunction()> and wait until
-the function you want is compiled. Then use the B<disassemble> command
-to print out the assembly dump of the function B<lli> just compiled.
-(Use C<lli -debug> to find out where the function starts and ends in memory.)
-It's easiest to save this output by using B<script>.
-
-Finally, you run B<codegen-diff>, as indicated in the Synopsis section of
-this manpage. It will print out a two-line stanza for each mismatched
-instruction, with the B<llc> version first, and the B<lli> version second.
-
-=head1 OPTIONS
-
-=over 4
-
-=item -d
-
-Don't show instructions where the bytes are different but they
-disassemble to the same thing. This puts a lot of trust in the
-disassembler, but it might help you highlight the more egregious cases
-of misassembly.
-
-=back
-
-=head1 AUTHOR
-
-B<codegen-diff> was written by Brian Gaeke.
-
-=head1 SEE ALSO
-
-L<gdb(1)>, L<objdump(1)>, L<script(1)>.
-
-You will need my B<gdb> patch:
-
- http://llvm.cs.uiuc.edu/~gaeke/gdb-disassembly-print-bytes.patch
-
-=cut
Modified: trunk/contrib/llvm/utils/count/count.c
===================================================================
--- trunk/contrib/llvm/utils/count/count.c 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/count/count.c 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,50 +0,0 @@
-/*===- count.c - The 'count' testing tool ---------------------------------===*\
- *
- * The LLVM Compiler Infrastructure
- *
- * This file is distributed under the University of Illinois Open Source
- * License. See LICENSE.TXT for details.
- *
-\*===----------------------------------------------------------------------===*/
-
-#include <stdlib.h>
-#include <stdio.h>
-
-int main(int argc, char **argv) {
- unsigned Count, NumLines, NumRead;
- char Buffer[4096], *End;
-
- if (argc != 2) {
- fprintf(stderr, "usage: %s <expected line count>\n", argv[0]);
- return 2;
- }
-
- Count = strtol(argv[1], &End, 10);
- if (*End != '\0' && End != argv[1]) {
- fprintf(stderr, "%s: invalid count argument '%s'\n", argv[0], argv[1]);
- return 2;
- }
-
- NumLines = 0;
- do {
- unsigned i;
-
- NumRead = fread(Buffer, 1, sizeof(Buffer), stdin);
-
- for (i = 0; i != NumRead; ++i)
- if (Buffer[i] == '\n')
- ++NumLines;
- } while (NumRead == sizeof(Buffer));
-
- if (!feof(stdin)) {
- fprintf(stderr, "%s: error reading stdin\n", argv[0]);
- return 3;
- }
-
- if (Count != NumLines) {
- fprintf(stderr, "Expected %d lines, got %d.\n", Count, NumLines);
- return 1;
- }
-
- return 0;
-}
Modified: trunk/contrib/llvm/utils/countloc.sh
===================================================================
--- trunk/contrib/llvm/utils/countloc.sh 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/countloc.sh 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,40 +0,0 @@
-#!/bin/sh
-##===- utils/countloc.sh - Counts Lines Of Code --------------*- Script -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-#
-# This script finds all the source code files in the source code directories
-# (excluding certain things), runs "wc -l" on them to get the number of lines in
-# each file and then sums up and prints the total with awk.
-#
-# The script takes one optional option, -topdir, which specifies the top llvm
-# source directory. If it is not specified then the llvm-config tool is
-# consulted to find top source dir.
-#
-# Note that the implementation is based on llvmdo. See that script for more
-# details.
-##===----------------------------------------------------------------------===##
-
-if test $# -gt 1 ; then
- if test "$1" = "-topdir" ; then
- TOPDIR="$2"
- shift; shift;
- else
- TOPDIR=`llvm-config --src-root`
- fi
-fi
-
-if test -d "$TOPDIR" ; then
- cd $TOPDIR
- ./utils/llvmdo -topdir "$TOPDIR" -dirs "include lib tools test utils examples" -code-only wc -l | awk '\
- BEGIN { loc=0; } \
- { loc += $1; } \
- END { print loc; }'
-else
- echo "Can't find LLVM top directory"
-fi
Modified: trunk/contrib/llvm/utils/crosstool/ARM/README
===================================================================
--- trunk/contrib/llvm/utils/crosstool/ARM/README 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/crosstool/ARM/README 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,37 +0,0 @@
-HOWTO create an LLVM crosstool from x86_64/Linux to ARM/Linux
-=============================================================
-
-1. % llvm/utils/crosstool/create-snapshots.sh
-
- This will create llvm-[REV_L].tar.bz2 and llvm-gcc-4.2-[REV_G].tar.bz2,
- where:
- REV_L is the revision at which "llvm" was checked out, and
- REV_G is the revision at which "llvm-gcc-4.2" was checked out
-
- Note that REV_L might REV_G might not be the same revision.
-
-2. Download CodeSourcery toolchain. The exact location depends on your
- $CROSS_TARGET but the script will tell you what the location of the file is
- if you run it without having the file available.
-
- For example, if you're using $CROSS_TARGET == "arm-none-linux-gnueabi" then
- you need to download:
-
- http://www.codesourcery.com/sgpp/lite/arm/portal/package1787/public/arm-none-linux-gnueabi/arm-2007q3-51-arm-none-linux-gnueabi-i686-pc-linux-gnu.tar.bz2
-
- NOTE: simply changing $CROSS_TARGET and modifying the URL accordingly will
- not work -- you'll need to go to http://www.codesourcery.com and find the
- correct file, as the release number in the file will also be different (e.g.,
- in the file above, the release number is "51").
-
-3. You can override most values in the script without modifying it, e.g.
- $INSTALL_ROOT (if you want to install in directory other than /usr/local).
-
- Run the script as:
-
- % env INSTALL_ROOT=[dir to install in] \
- CODE_SOURCERY_PKG_PATH=[dir where you downloaded CodeSourcery tarball] \
- LLVM_PKG_PATH=[dir where you stored your LLVM and LLVM-GCC snapshots] \
- LLVM_SVN_REV=${REV_L} \
- LLVMGCC_SVN_REV=${REV_G} \
- build-install-linux.sh
Modified: trunk/contrib/llvm/utils/crosstool/ARM/build-install-linux.sh
===================================================================
--- trunk/contrib/llvm/utils/crosstool/ARM/build-install-linux.sh 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/crosstool/ARM/build-install-linux.sh 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,200 +0,0 @@
-#!/bin/bash
-#
-# Compiles and installs a Linux/x86_64 -> Linux/ARM crosstool based on LLVM and
-# LLVM-GCC-4.2 using SVN snapshots in provided tarballs.
-
-set -o nounset
-set -o errexit
-
-echo -n "Welcome to LLVM Linux/X86_64 -> Linux/ARM crosstool "
-echo "builder/installer; some steps will require sudo privileges."
-
-readonly INSTALL_ROOT="${INSTALL_ROOT:-/usr/local/crosstool}"
-# Both $USER and root *must* have read/write access to this dir.
-readonly SCRATCH_ROOT=$(mktemp -d "${TMPDIR:-/tmp}/llvm-project.XXXXXX")
-readonly SRC_ROOT="${SCRATCH_ROOT}/src"
-readonly OBJ_ROOT="${SCRATCH_ROOT}/obj"
-
-readonly CROSS_HOST="x86_64-unknown-linux-gnu"
-readonly CROSS_TARGET="arm-none-linux-gnueabi"
-readonly CROSS_MARCH="${CROSS_MARCH:-armv6}"
-
-readonly CODE_SOURCERY="${INSTALL_ROOT}/codesourcery"
-readonly CODE_SOURCERY_PKG_PATH="${CODE_SOURCERY_PKG_PATH:-${HOME}/codesourcery}"
-readonly CODE_SOURCERY_HTTP="http://www.codesourcery.com/sgpp/lite/arm/portal/package1787/public"
-readonly CODE_SOURCERY_PKG="arm-2007q3-51-arm-none-linux-gnueabi-i686-pc-linux-gnu.tar.bz2"
-readonly CODE_SOURCERY_ROOT="${CODE_SOURCERY}/arm-2007q3"
-readonly CODE_SOURCERY_BIN="${CODE_SOURCERY_ROOT}/bin"
-# Make sure ${CROSS_TARGET}-* binutils are in command path
-export PATH="${CODE_SOURCERY_BIN}:${PATH}"
-
-readonly CROSS_TARGET_AS="${CODE_SOURCERY_BIN}/${CROSS_TARGET}-as"
-readonly CROSS_TARGET_LD="${CODE_SOURCERY_BIN}/${CROSS_TARGET}-ld"
-
-readonly SYSROOT="${CODE_SOURCERY_ROOT}/${CROSS_TARGET}/libc"
-
-readonly LLVM_PKG_PATH="${LLVM_PKG_PATH:-${HOME}/llvm-project/snapshots}"
-
-# Latest SVN revisions known to be working in this configuration.
-readonly LLVM_DEFAULT_REV="74530"
-readonly LLVMGCC_DEFAULT_REV="74535"
-
-readonly LLVM_PKG="llvm-${LLVM_SVN_REV:-${LLVM_DEFAULT_REV}}.tar.bz2"
-readonly LLVM_SRC_DIR="${SRC_ROOT}/llvm"
-readonly LLVM_OBJ_DIR="${OBJ_ROOT}/llvm"
-readonly LLVM_INSTALL_DIR="${INSTALL_ROOT}/${CROSS_TARGET}/llvm"
-
-readonly LLVMGCC_PKG="llvm-gcc-4.2-${LLVMGCC_SVN_REV:-${LLVMGCC_DEFAULT_REV}}.tar.bz2"
-readonly LLVMGCC_SRC_DIR="${SRC_ROOT}/llvm-gcc-4.2"
-readonly LLVMGCC_OBJ_DIR="${OBJ_ROOT}/llvm-gcc-4.2"
-readonly LLVMGCC_INSTALL_DIR="${INSTALL_ROOT}/${CROSS_TARGET}/llvm-gcc-4.2"
-
-readonly MAKE_OPTS="${MAKE_OPTS:--j2}"
-
-# Params:
-# $1: directory to be created
-# $2: optional mkdir command prefix, e.g. "sudo"
-createDir() {
- if [[ ! -e $1 ]]; then
- ${2:-} mkdir -p $1
- elif [[ -e $1 && ! -d $1 ]]; then
- echo "$1 exists but is not a directory; exiting."
- exit 3
- fi
-}
-
-sudoCreateDir() {
- createDir $1 sudo
- sudo chown ${USER} $1
-}
-
-# Prints out and runs the command, but without logging -- intended for use with
-# lightweight commands that don't have useful output to parse, e.g. mkdir, tar,
-# etc.
-runCommand() {
- local message="$1"
- shift
- echo "=> $message"
- echo "==> Running: $*"
- $*
-}
-
-runAndLog() {
- local message="$1"
- local log_file="$2"
- shift 2
- echo "=> $message; log in $log_file"
- echo "==> Running: $*"
- # Pop-up a terminal with the output of the current command?
- # e.g.: xterm -e /bin/bash -c "$* >| tee $log_file"
- $* &> $log_file
- if [[ $? != 0 ]]; then
- echo "Error occurred: see most recent log file for details."
- exit
- fi
-}
-
-installCodeSourcery() {
- # Unpack the tarball, creating the CodeSourcery dir, if necessary.
- if [[ ! -d ${CODE_SOURCERY_ROOT} ]]; then
- sudoCreateDir ${CODE_SOURCERY}
- cd ${CODE_SOURCERY}
- if [[ -e ${CODE_SOURCERY_PKG_PATH}/${CODE_SOURCERY_PKG} ]]; then
- runCommand "Unpacking CodeSourcery in ${CODE_SOURCERY}" \
- tar jxf ${CODE_SOURCERY_PKG_PATH}/${CODE_SOURCERY_PKG}
- else
- echo -n "CodeSourcery tarball not found in "
- echo "${CODE_SOURCERY_PKG_PATH}/${CODE_SOURCERY_PKG}"
- echo -n "Fix the path or download it from "
- echo "${CODE_SOURCERY_HTTP}/${CROSS_TARGET}/${CODE_SOURCERY_PKG}"
- exit
- fi
- else
- echo "CodeSourcery install dir already exists; skipping."
- fi
-
- # Verify our CodeSourcery toolchain installation.
- if [[ ! -d "${SYSROOT}" ]]; then
- echo -n "Error: CodeSourcery does not contain libc for ${CROSS_TARGET}: "
- echo "${SYSROOT} not found."
- exit
- fi
-
- for tool in ${CROSS_TARGET_AS} ${CROSS_TARGET_LD}; do
- if [[ ! -e $tool ]]; then
- echo "${tool} not found; exiting."
- exit
- fi
- done
-}
-
-installLLVM() {
- if [[ -d ${LLVM_INSTALL_DIR} ]]; then
- echo "LLVM install dir ${LLVM_INSTALL_DIR} exists; skipping."
- return
- fi
-
- sudoCreateDir ${LLVM_INSTALL_DIR}
-
- # Unpack LLVM tarball; should create the directory "llvm".
- cd ${SRC_ROOT}
- runCommand "Unpacking LLVM" tar jxf ${LLVM_PKG_PATH}/${LLVM_PKG}
-
- # Configure, build, and install LLVM.
- createDir ${LLVM_OBJ_DIR}
- cd ${LLVM_OBJ_DIR}
- runAndLog "Configuring LLVM" ${LLVM_OBJ_DIR}/llvm-configure.log \
- ${LLVM_SRC_DIR}/configure \
- --disable-jit \
- --enable-optimized \
- --prefix=${LLVM_INSTALL_DIR} \
- --target=${CROSS_TARGET} \
- --with-llvmgccdir=${LLVMGCC_INSTALL_DIR}
- runAndLog "Building LLVM" ${LLVM_OBJ_DIR}/llvm-build.log \
- make ${MAKE_OPTS}
- runAndLog "Installing LLVM" ${LLVM_OBJ_DIR}/llvm-install.log \
- make ${MAKE_OPTS} install
-}
-
-installLLVMGCC() {
- if [[ -d ${LLVMGCC_INSTALL_DIR} ]]; then
- echo "LLVM-GCC install dir ${LLVMGCC_INSTALL_DIR} exists; skipping."
- return
- fi
-
- sudoCreateDir ${LLVMGCC_INSTALL_DIR}
-
- # Unpack LLVM-GCC tarball; should create the directory "llvm-gcc-4.2".
- cd ${SRC_ROOT}
- runCommand "Unpacking LLVM-GCC" tar jxf ${LLVM_PKG_PATH}/${LLVMGCC_PKG}
-
- # Configure, build, and install LLVM-GCC.
- createDir ${LLVMGCC_OBJ_DIR}
- cd ${LLVMGCC_OBJ_DIR}
- runAndLog "Configuring LLVM-GCC" ${LLVMGCC_OBJ_DIR}/llvmgcc-configure.log \
- ${LLVMGCC_SRC_DIR}/configure \
- --enable-languages=c,c++ \
- --enable-llvm=${LLVM_INSTALL_DIR} \
- --prefix=${LLVMGCC_INSTALL_DIR} \
- --program-prefix=llvm- \
- --target=${CROSS_TARGET} \
- --with-arch=${CROSS_MARCH} \
- --with-as=${CROSS_TARGET_AS} \
- --with-ld=${CROSS_TARGET_LD} \
- --with-sysroot=${SYSROOT}
- runAndLog "Building LLVM-GCC" ${LLVMGCC_OBJ_DIR}/llvmgcc-build.log \
- make
- runAndLog "Installing LLVM-GCC" ${LLVMGCC_OBJ_DIR}/llvmgcc-install.log \
- make install
-}
-
-echo "Building in ${SCRATCH_ROOT}; installing in ${INSTALL_ROOT}"
-
-createDir ${SRC_ROOT}
-createDir ${OBJ_ROOT}
-
-installCodeSourcery
-installLLVM
-installLLVMGCC
-
-echo "Done."
Modified: trunk/contrib/llvm/utils/crosstool/create-snapshots.sh
===================================================================
--- trunk/contrib/llvm/utils/crosstool/create-snapshots.sh 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/crosstool/create-snapshots.sh 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,41 +0,0 @@
-#!/bin/bash
-#
-# Creates LLVM SVN snapshots: llvm-$REV.tar.bz2 and llvm-gcc-4.2-$REV.tar.bz2,
-# where $REV is an SVN revision of LLVM. This is used for creating stable
-# tarballs which can be used to build known-to-work crosstools.
-#
-# Syntax:
-# $0 [REV] -- grabs the revision $REV from SVN; if not specified, grabs the
-# latest SVN revision.
-
-set -o nounset
-set -o errexit
-
-readonly LLVM_PROJECT_SVN="http://llvm.org/svn/llvm-project"
-
-getLatestRevisionFromSVN() {
- svn info ${LLVM_PROJECT_SVN} | egrep ^Revision | sed 's/^Revision: //'
-}
-
-readonly REV="${1:-$(getLatestRevisionFromSVN)}"
-
-createTarballFromSVN() {
- local module=$1
- local log="${module}.log"
- echo "Running: svn export -r ${REV} ${module}; log in ${log}"
- svn -q export -r ${REV} ${LLVM_PROJECT_SVN}/${module}/trunk \
- ${module} > ${log} 2>&1
-
- # Create "module-revision.tar.bz2" packages from the SVN checkout dirs.
- local tarball="${module}-${REV}.tar.bz2"
- echo "Creating tarball: ${tarball}"
- tar cjf ${tarball} ${module}
-
- echo "Cleaning up '${module}'"
- rm -rf ${module} ${log}
-}
-
-for module in "llvm" "llvm-gcc-4.2"; do
- createTarballFromSVN ${module}
-done
-
Modified: trunk/contrib/llvm/utils/emacs/README
===================================================================
--- trunk/contrib/llvm/utils/emacs/README 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/emacs/README 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,27 +0,0 @@
--*- llvm/utils/emacs/README -*-
-
-These are syntax highlighting files for the Emacs and XEmacs editors. Included
-are:
-
-* llvm-mode.el
-
- Syntax highlighting mode for LLVM assembly files. To use, add this code to
- your ~/.emacs :
-
- (setq load-path
- (cons (expand-file-name "path-to-llvm/utils/emacs") load-path))
- (require 'llvm-mode)
-
-* tablegen-mode.el
-
- Syntax highlighting mode for TableGen description files. To use, add this code
- to your ~/.emacs:
-
- (setq load-path
- (cons (expand-file-name "path-to-llvm/utils/emacs") load-path))
- (require 'tablegen-mode)
-
-
-Note: If you notice missing or incorrect syntax highlighting, please contact
-<llvmbugs [at] cs.uiuc.edu>; if you wish to provide a patch to improve the
-functionality, it will be most appreciated. Thank you.
Modified: trunk/contrib/llvm/utils/emacs/emacs.el
===================================================================
--- trunk/contrib/llvm/utils/emacs/emacs.el 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/emacs/emacs.el 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,39 +0,0 @@
-;; LLVM coding style guidelines in emacs
-;; Maintainer: LLVM Team, http://llvm.org/
-;; Modified: 2009-07-28
-
-;; Max 80 cols per line, indent by two spaces, no tabs.
-;; Apparently, this does not affect tabs in Makefiles.
-(custom-set-variables
- '(fill-column 80)
- '(c++-indent-level 2)
- '(c-basic-offset 2)
- '(indent-tabs-mode nil))
-
-
-;; Alternative to setting the global style. Only files with "llvm" in
-;; their names will automatically set to the llvm.org coding style.
-(c-add-style "llvm.org"
- '((fill-column . 80)
- (c++-indent-level . 2)
- (c-basic-offset . 2)
- (indent-tabs-mode . nil)
- (c-offsets-alist . ((innamespace 0)))))
-
-(add-hook 'c-mode-hook
- (function
- (lambda nil
- (if (string-match "llvm" buffer-file-name)
- (progn
- (c-set-style "llvm.org")
- )
- ))))
-
-(add-hook 'c++-mode-hook
- (function
- (lambda nil
- (if (string-match "llvm" buffer-file-name)
- (progn
- (c-set-style "llvm.org")
- )
- ))))
Modified: trunk/contrib/llvm/utils/emacs/llvm-mode.el
===================================================================
--- trunk/contrib/llvm/utils/emacs/llvm-mode.el 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/emacs/llvm-mode.el 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,134 +0,0 @@
-;; Maintainer: The LLVM team, http://llvm.org/
-;; Description: Major mode for the LLVM assembler language.
-;; Updated: 2007-09-19
-
-;; Create mode-specific tables.
-(defvar llvm-mode-syntax-table nil
- "Syntax table used while in LLVM mode.")
-(defvar llvm-font-lock-keywords
- (list
- ;; Comments
- '(";.*" . font-lock-comment-face)
- ;; Variables
- '("%[-a-zA-Z$\._][-a-zA-Z$\._0-9]*" . font-lock-variable-name-face)
- ;; Labels
- '("[-a-zA-Z$\._0-9]+:" . font-lock-variable-name-face)
- ;; Strings
- '("\"[^\"]+\"" . font-lock-string-face)
- ;; Unnamed variable slots
- '("%[-]?[0-9]+" . font-lock-variable-name-face)
- ;; Types
- `(,(regexp-opt '("void" "i[0-9]+" "float" "double" "type" "label" "opaque") 'words) . font-lock-type-face)
- ;; Integer literals
- '("\\b[-]?[0-9]+\\b" . font-lock-preprocessor-face)
- ;; Floating point constants
- '("\\b[-+]?[0-9]+\.[0-9]*\([eE][-+]?[0-9]+\)?\\b" . font-lock-preprocessor-face)
- ;; Hex constants
- '("\\b0x[0-9A-Fa-f]+\\b" . font-lock-preprocessor-face)
- ;; Keywords
- `(,(regexp-opt '("begin" "end" "true" "false" "zeroinitializer" "declare"
- "define" "global" "constant" "const" "internal" "linkonce" "linkonce_odr"
- "weak" "weak_odr" "appending" "uninitialized" "implementation" "..."
- "null" "undef" "to" "except" "not" "target" "endian" "little" "big"
- "pointersize" "volatile" "fastcc" "coldcc" "cc") 'words) . font-lock-keyword-face)
- ;; Arithmetic and Logical Operators
- `(,(regexp-opt '("add" "sub" "mul" "div" "rem" "and" "or" "xor"
- "setne" "seteq" "setlt" "setgt" "setle" "setge") 'words) . font-lock-keyword-face)
- ;; Floating-point operators
- `(,(regexp-opt '("fadd" "fsub" "fmul" "fdiv" "frem") 'words) . font-lock-keyword-face)
- ;; Special instructions
- `(,(regexp-opt '("phi" "tail" "call" "cast" "select" "to" "shl" "shr" "fcmp" "icmp" "vaarg" "vanext") 'words) . font-lock-keyword-face)
- ;; Control instructions
- `(,(regexp-opt '("ret" "br" "switch" "invoke" "unwind" "unreachable") 'words) . font-lock-keyword-face)
- ;; Memory operators
- `(,(regexp-opt '("malloc" "alloca" "free" "load" "store" "getelementptr") 'words) . font-lock-keyword-face)
- )
- "Syntax highlighting for LLVM"
- )
-
-;; ---------------------- Syntax table ---------------------------
-;; Shamelessly ripped from jasmin.el
-;; URL: http://www.neilvandyke.org/jasmin-emacs/jasmin.el.html
-
-(if (not llvm-mode-syntax-table)
- (progn
- (setq llvm-mode-syntax-table (make-syntax-table))
- (mapcar (function (lambda (n)
- (modify-syntax-entry (aref n 0)
- (aref n 1)
- llvm-mode-syntax-table)))
- '(
- ;; whitespace (` ')
- [?\^m " "]
- [?\f " "]
- [?\n " "]
- [?\t " "]
- [?\ " "]
- ;; word constituents (`w')
- ;;[?< "w"]
- ;;[?> "w"]
- [?\% "w"]
- ;;[?_ "w "]
- ;; comments
- [?\; "< "]
- [?\n "> "]
- ;;[?\r "> "]
- ;;[?\^m "> "]
- ;; symbol constituents (`_')
- ;; punctuation (`.')
- ;; open paren (`(')
- [?\( "("]
- [?\[ "("]
- [?\{ "("]
- ;; close paren (`)')
- [?\) ")"]
- [?\] ")"]
- [?\} ")"]
- ;; string quote ('"')
- [?\" "\""]
- ))))
-
-;; --------------------- Abbrev table -----------------------------
-
-(defvar llvm-mode-abbrev-table nil
- "Abbrev table used while in LLVM mode.")
-(define-abbrev-table 'llvm-mode-abbrev-table ())
-
-(defvar llvm-mode-hook nil)
-(defvar llvm-mode-map nil) ; Create a mode-specific keymap.
-
-(if (not llvm-mode-map)
- () ; Do not change the keymap if it is already set up.
- (setq llvm-mode-map (make-sparse-keymap))
- (define-key llvm-mode-map "\t" 'tab-to-tab-stop)
- (define-key llvm-mode-map "\es" 'center-line)
- (define-key llvm-mode-map "\eS" 'center-paragraph))
-
-
-(defun llvm-mode ()
- "Major mode for editing LLVM source files.
- \\{llvm-mode-map}
- Runs llvm-mode-hook on startup."
- (interactive)
- (kill-all-local-variables)
- (use-local-map llvm-mode-map) ; Provides the local keymap.
- (setq major-mode 'llvm-mode)
-
- (make-local-variable 'font-lock-defaults)
- (setq major-mode 'llvm-mode ; This is how describe-mode
- ; finds the doc string to print.
- mode-name "LLVM" ; This name goes into the modeline.
- font-lock-defaults `(llvm-font-lock-keywords))
-
- (setq local-abbrev-table llvm-mode-abbrev-table)
- (set-syntax-table llvm-mode-syntax-table)
- (setq comment-start ";")
- (run-hooks 'llvm-mode-hook)) ; Finally, this permits the user to
- ; customize the mode with a hook.
-
-;; Associate .ll files with llvm-mode
-(setq auto-mode-alist
- (append '(("\\.ll$" . llvm-mode)) auto-mode-alist))
-
-(provide 'llvm-mode)
-;; end of llvm-mode.el
Modified: trunk/contrib/llvm/utils/emacs/tablegen-mode.el
===================================================================
--- trunk/contrib/llvm/utils/emacs/tablegen-mode.el 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/emacs/tablegen-mode.el 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,122 +0,0 @@
-;; Maintainer: The LLVM team, http://llvm.org/
-;; Description: Major mode for TableGen description files (part of LLVM project)
-;; Updated: 2007-12-18
-
-(require 'comint)
-(require 'custom)
-(require 'ansi-color)
-
-;; Create mode-specific tables.
-(defvar td-decorators-face 'td-decorators-face
- "Face method decorators.")
-(make-face 'td-decorators-face)
-
-(defvar tablegen-font-lock-keywords
- (let ((kw (regexp-opt '("class" "defm" "def" "field" "include" "in"
- "let" "multiclass" "foreach")
- 'words))
- (type-kw (regexp-opt '("bit" "bits" "code" "dag" "int" "list" "string")
- 'words))
- )
- (list
- ;; Comments
-;; '("\/\/" . font-lock-comment-face)
- ;; Strings
- '("\"[^\"]+\"" . font-lock-string-face)
- ;; Hex constants
- '("\\<0x[0-9A-Fa-f]+\\>" . font-lock-preprocessor-face)
- ;; Binary constants
- '("\\<0b[01]+\\>" . font-lock-preprocessor-face)
- ;; Integer literals
- '("\\<[-]?[0-9]+\\>" . font-lock-preprocessor-face)
- ;; Floating point constants
- '("\\<[-+]?[0-9]+\.[0-9]*\([eE][-+]?[0-9]+\)?\\>" . font-lock-preprocessor-face)
-
- '("^[ \t]*\\(@.+\\)" 1 'td-decorators-face)
- ;; Keywords
- (cons (concat kw "[ \n\t(]") 1)
-
- ;; Type keywords
- (cons (concat type-kw "[ \n\t(]") 1)
- ))
- "Additional expressions to highlight in TableGen mode.")
-(put 'tablegen-mode 'font-lock-defaults '(tablegen-font-lock-keywords))
-
-;; ---------------------- Syntax table ---------------------------
-;; Shamelessly ripped from jasmin.el
-;; URL: http://www.neilvandyke.org/jasmin-emacs/jasmin.el
-
-(defvar tablegen-mode-syntax-table nil
- "Syntax table used in `tablegen-mode' buffers.")
-(when (not tablegen-mode-syntax-table)
- (setq tablegen-mode-syntax-table (make-syntax-table))
- ;; whitespace (` ')
- (modify-syntax-entry ?\ " " tablegen-mode-syntax-table)
- (modify-syntax-entry ?\t " " tablegen-mode-syntax-table)
- (modify-syntax-entry ?\r " " tablegen-mode-syntax-table)
- (modify-syntax-entry ?\n " " tablegen-mode-syntax-table)
- (modify-syntax-entry ?\f " " tablegen-mode-syntax-table)
- ;; word constituents (`w')
- (modify-syntax-entry ?\% "w" tablegen-mode-syntax-table)
- (modify-syntax-entry ?\_ "w" tablegen-mode-syntax-table)
- ;; comments
- (modify-syntax-entry ?/ ". 124b" tablegen-mode-syntax-table)
- (modify-syntax-entry ?* ". 23" tablegen-mode-syntax-table)
- (modify-syntax-entry ?\n "> b" tablegen-mode-syntax-table)
- ;; open paren (`(')
- (modify-syntax-entry ?\( "(" tablegen-mode-syntax-table)
- (modify-syntax-entry ?\[ "(" tablegen-mode-syntax-table)
- (modify-syntax-entry ?\{ "(" tablegen-mode-syntax-table)
- (modify-syntax-entry ?\< "(" tablegen-mode-syntax-table)
- ;; close paren (`)')
- (modify-syntax-entry ?\) ")" tablegen-mode-syntax-table)
- (modify-syntax-entry ?\] ")" tablegen-mode-syntax-table)
- (modify-syntax-entry ?\} ")" tablegen-mode-syntax-table)
- (modify-syntax-entry ?\> ")" tablegen-mode-syntax-table)
- ;; string quote ('"')
- (modify-syntax-entry ?\" "\"" tablegen-mode-syntax-table)
- )
-
-;; --------------------- Abbrev table -----------------------------
-
-(defvar tablegen-mode-abbrev-table nil
- "Abbrev table used while in TableGen mode.")
-(define-abbrev-table 'tablegen-mode-abbrev-table ())
-
-(defvar tablegen-mode-hook nil)
-(defvar tablegen-mode-map nil) ; Create a mode-specific keymap.
-
-(if (not tablegen-mode-map)
- () ; Do not change the keymap if it is already set up.
- (setq tablegen-mode-map (make-sparse-keymap))
- (define-key tablegen-mode-map "\t" 'tab-to-tab-stop)
- (define-key tablegen-mode-map "\es" 'center-line)
- (define-key tablegen-mode-map "\eS" 'center-paragraph))
-
-(defun tablegen-mode ()
- "Major mode for editing TableGen description files.
- \\{tablegen-mode-map}
- Runs tablegen-mode-hook on startup."
- (interactive)
- (kill-all-local-variables)
- (use-local-map tablegen-mode-map) ; Provides the local keymap.
- (make-local-variable 'font-lock-defaults)
- (setq major-mode 'tablegen-mode ; This is how describe-mode
- ; finds the doc string to print.
- mode-name "TableGen" ; This name goes into the modeline.
- local-abbrev-table tablegen-mode-abbrev-table
- font-lock-defaults `(tablegen-font-lock-keywords)
- require-final-newline t
- )
-
- (set-syntax-table tablegen-mode-syntax-table)
- (make-local-variable 'comment-start)
- (setq comment-start "//")
- (run-hooks 'tablegen-mode-hook)) ; Finally, this permits the user to
- ; customize the mode with a hook.
-
-;; Associate .td files with tablegen-mode
-(setq auto-mode-alist (append '(("\\.td$" . tablegen-mode)) auto-mode-alist))
-
-(provide 'tablegen-mode)
-;; end of tablegen-mode.el
Modified: trunk/contrib/llvm/utils/findmisopt
===================================================================
--- trunk/contrib/llvm/utils/findmisopt 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/findmisopt 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,177 +0,0 @@
-#!/bin/bash
-#
-# findmisopt
-#
-# This is a quick and dirty hack to potentially find a misoptimization
-# problem. Mostly its to work around problems in bugpoint that prevent
-# it from finding a problem unless the set of failing optimizations are
-# known and given to it on the command line.
-#
-# Given a bitcode file that produces correct output (or return code),
-# this script will run through all the optimizations passes that gccas
-# uses (in the same order) and will narrow down which optimizations
-# cause the program either generate different output or return a
-# different result code. When the passes have been narrowed down,
-# bugpoint is invoked to further refine the problem to its origin. If a
-# release version of bugpoint is available it will be used, otherwise
-# debug.
-#
-# Usage:
-# findmisopt bcfile outdir progargs [match]
-#
-# Where:
-# bcfile
-# is the bitcode file input (the unoptimized working case)
-# outdir
-# is a directory into which intermediate results are placed
-# progargs
-# is a single argument containing all the arguments the program needs
-# proginput
-# is a file name from which stdin should be directed
-# match
-# if specified to any value causes the result code of the program to
-# be used to determine success/fail. If not specified success/fail is
-# determined by diffing the program's output with the non-optimized
-# output.
-#
-if [ "$#" -lt 3 ] ; then
- echo "usage: findmisopt bcfile outdir progargs [match]"
- exit 1
-fi
-
-dir="${0%%/utils/findmisopt}"
-if [ -x "$dir/Release/bin/bugpoint" ] ; then
- bugpoint="$dir/Release/bin/bugpoint"
-elif [ -x "$dir/Debug/bin/bugpoint" ] ; then
- bugpoint="$dir/Debug/bin/bugpoint"
-else
- echo "findmisopt: bugpoint not found"
- exit 1
-fi
-
-bcfile="$1"
-outdir="$2"
-args="$3"
-input="$4"
-if [ ! -f "$input" ] ; then
- input="/dev/null"
-fi
-match="$5"
-name=`basename $bcfile .bc`
-ll="$outdir/${name}.ll"
-s="$outdir/${name}.s"
-prog="$outdir/${name}"
-out="$outdir/${name}.out"
-optbc="$outdir/${name}.opt.bc"
-optll="$outdir/${name}.opt.ll"
-opts="$outdir/${name}.opt.s"
-optprog="$outdir/${name}.opt"
-optout="$outdir/${name}.opt.out"
-ldflags="-lstdc++ -lm -ldl -lc"
-
-echo "Test Name: $name"
-echo "Unoptimized program: $prog"
-echo " Optimized program: $optprog"
-
-# Define the list of optimizations to run. This comprises the same set of
-# optimizations that opt -std-compile-opts and gccld run, in the same order.
-opt_switches=`llvm-as < /dev/null -o - | opt -std-compile-opts -disable-output -debug-pass=Arguments 2>&1 | sed 's/Pass Arguments: //'`
-all_switches="$opt_switches"
-echo "Passes : $all_switches"
-
-# Create output directory if it doesn't exist
-if [ -f "$outdir" ] ; then
- echo "$outdir is not a directory"
- exit 1
-fi
-
-if [ ! -d "$outdir" ] ; then
- mkdir "$outdir" || exit 1
-fi
-
-# Generate the disassembly
-llvm-dis "$bcfile" -o "$ll" -f || exit 1
-
-# Generate the non-optimized program and its output
-llc "$bcfile" -o "$s" -f || exit 1
-gcc "$s" -o "$prog" $ldflags || exit 1
-"$prog" $args > "$out" 2>&1 <$input
-ex1=$?
-
-# Current set of switches is empty
-function tryit {
- switches_to_use="$1"
- opt $switches_to_use "$bcfile" -o "$optbc" -f || exit
- llvm-dis "$optbc" -o "$optll" -f || exit
- llc "$optbc" -o "$opts" -f || exit
- gcc "$opts" -o "$optprog" $ldflags || exit
- "$optprog" $args > "$optout" 2>&1 <"$input"
- ex2=$?
-
- if [ -n "$match" ] ; then
- if [ "$ex1" -ne "$ex2" ] ; then
- echo "Return code not the same with these switches:"
- echo $switches
- echo "Unoptimized returned: $ex1"
- echo "Optimized returned: $ex2"
- return 0
- fi
- else
- diff "$out" "$optout" > /dev/null
- if [ $? -ne 0 ] ; then
- echo "Diff fails with these switches:"
- echo $switches
- echo "Differences:"
- diff "$out" "$optout" | head
- return 0;
- fi
- fi
- return 1
-}
-
-echo "Trying to find optimization that breaks program:"
-for sw in $all_switches ; do
- echo -n " $sw"
- switches="$switches $sw"
- if tryit "$switches" ; then
- break;
- fi
-done
-
-# Terminate the previous output with a newline
-echo ""
-
-# Determine if we're done because none of the optimizations broke the program
-if [ "$switches" == " $all_switches" ] ; then
- echo "The program did not miscompile"
- exit 0
-fi
-
-final=""
-while [ ! -z "$switches" ] ; do
- trimmed=`echo "$switches" | sed -e 's/^ *\(-[^ ]*\).*/\1/'`
- switches=`echo "$switches" | sed -e 's/^ *-[^ ]* *//'`
- echo "Trimmed $trimmed from left"
- tryit "$final $switches"
- if [ "$?" -eq "0" ] ; then
- echo "Still Failing .. continuing ..."
- continue
- else
- echo "Found required early pass: $trimmed"
- final="$final $trimmed"
- continue
- fi
- echo "Next Loop"
-done
-
-if [ "$final" == " $all_switches" ] ; then
- echo "findmisopt: All optimizations pass. Perhaps this isn't a misopt?"
- exit 0
-fi
-echo "Smallest Optimization list=$final"
-
-bpcmd="$bugpoint -run-llc -disable-loop-extraction --output "$out" --input /dev/null $bcfile $final --args $args"
-
-echo "Running: $bpcmd"
-$bpcmd
-echo "findmisopt finished."
Modified: trunk/contrib/llvm/utils/findoptdiff
===================================================================
--- trunk/contrib/llvm/utils/findoptdiff 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/findoptdiff 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,101 +0,0 @@
-#!/bin/bash
-#
-# findoptdiff
-#
-# This script helps find the optimization difference between two llvm
-# builds. It is useful when you have a build that is known to work and
-# one that exhibits an optimization problem. Identifying the difference
-# between the two builds can lead to discovery of the source of a
-# mis-optimization.
-#
-# The script takes two llvm build paths as arguments. These specify the
-# the two llvm builds to compare. It is generally expected that they
-# are "close cousins". That is, they are the same except that the
-# second build contains some experimental optimization features that
-# are suspected of producing a misoptimization.
-#
-# The script takes two bitcode files, one from each build. They are
-# presumed to be a compilation of the same program or program fragment
-# with the only difference being the builds.
-#
-# The script operates by iteratively applying the optimizations that gccas
-# and gccld run until there is a difference in the assembly resulting
-# from the optimization. The difference is then reported with the set of
-# optimization passes that produce the difference. The processing
-# continues until all optimization passes have been tried. The differences
-# for each pass, if they do differ, are placed in a diffs.# file.
-#
-# To work around differences in the assembly language format, the script
-# can also take two filter arguments that post-process the assembly
-# so they can be differenced without making false positives for known
-# differences in the two builds. These filters are optional.
-#
-# Usage:
-# findoptdiff llvm1 llvm2 bc1 bc2 filter1 filter2
-#
-# Where:
-# llvm1
-# is the path to the first llvm build dir
-# llvm2
-# is the path to the second llvm build dir
-# bc1
-# is the bitcode file for the first llvm environment
-# bc2
-# is the bitcode file for the second llvm environment
-# filter1
-# is an optional filter for filtering the llvm1 generated assembly
-# filter2
-# is an optional filter for filtering the llvm2 generated assembly
-#
-llvm1=$1
-llvm2=$2
-bc1=$3
-bc2=$4
-filt1=$5
-filt2=$6
-if [ -z "$filt1" ] ; then
- filt1="cat"
-fi
-if [ -z "$filt2" ] ; then
- filt2="cat"
-fi
-opt1="${bc1}.opt"
-opt2="${bc2}.opt"
-ll1="${bc1}.ll"
-ll2="${bc2}.ll"
-opt1ll="${bc1}.opt.ll"
-opt2ll="${bc2}.opt.ll"
-dis1="$llvm1/Debug/bin/llvm-dis"
-dis2="$llvm2/Debug/bin/llvm-dis"
-opt1="$llvm1/Debug/bin/opt"
-opt2="$llvm2/Debug/bin/opt"
-
-all_switches="-verify -lowersetjmp -simplifycfg -mem2reg -globalopt -globaldce -ipconstprop -deadargelim -instcombine -simplifycfg -prune-eh -inline -simplify-libcalls -argpromotion -tailduplicate -simplifycfg -scalarrepl -instcombine -predsimplify -condprop -tailcallelim -simplifycfg -reassociate -licm -loop-unswitch -instcombine -indvars -loop-unroll -instcombine -load-vn -gcse -sccp -instcombine -condprop -dse -dce -simplifycfg -deadtypeelim -constmerge -internalize -ipsccp -globalopt -constmerge -deadargelim -inline -prune-eh -globalopt -globaldce -argpromotion -instcombine -predsimplify -scalarrepl -globalsmodref-aa -licm -load-vn -gcse -dse -instcombine -simplifycfg -verify"
-
-#counter=0
-function tryit {
- switches_to_use="$1"
- $opt1 $switches_to_use "$bc1" -o - | $dis1 | $filt1 > "$opt1ll"
- $opt2 $switches_to_use "$bc2" -o - | $dis2 | $filt2 > "$opt2ll"
- diffs="diffs."$((counter++))
- diff "$opt1ll" "$opt2ll" > $diffs
- if [ $? -ne 0 ] ; then
- echo
- echo "Diff fails with these switches:"
- echo $switches
- echo "Differences:"
- head $diffs
- echo 'Switches:' $switches_to_use >> $diffs
- else
- rm $diffs
- fi
- return 1
-}
-
-for sw in $all_switches ; do
- echo -n " $sw"
- switches="$switches $sw"
- if tryit "$switches" ; then
- break;
- fi
-done
Modified: trunk/contrib/llvm/utils/findsym.pl
===================================================================
--- trunk/contrib/llvm/utils/findsym.pl 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/findsym.pl 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,33 +0,0 @@
-#!/usr/bin/perl -w
-#
-# Program: findsym.pl
-#
-# Synopsis: Generate a list of the libraries in which a symbol is defined or
-# referenced.
-#
-# Syntax: findsym.pl <directory_with_libraries_in_it> <symbol>
-#
-
-# Give first option a name.
-my $Directory = $ARGV[0];
-my $Symbol = $ARGV[1];
-
-# Open the directory and read its contents, sorting by name and differentiating
-# by whether its a library (.a) or an object file (.o)
-opendir DIR,$Directory;
-my @files = readdir DIR;
-closedir DIR;
- at objects = grep(/l?i?b?LLVM.*\.[oa]$/,sort(@files));
-
-# Gather definitions from the libraries
-foreach $lib (@objects) {
- my $head = 0;
- open SYMS,
- "nm $Directory/$lib | grep '$Symbol' | sort --key=3 | uniq |";
- while (<SYMS>) {
- if (!$head) { print "$lib:\n"; $head = 1; }
- chomp($_);
- print " $_\n";
- }
- close SYMS;
-}
Modified: trunk/contrib/llvm/utils/fpcmp/fpcmp.cpp
===================================================================
--- trunk/contrib/llvm/utils/fpcmp/fpcmp.cpp 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/fpcmp/fpcmp.cpp 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,43 +0,0 @@
-//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-//
-// fpcmp is a tool that basically works like the 'cmp' tool, except that it can
-// tolerate errors due to floating point noise, with the -r and -a options.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/FileUtilities.h"
-#include "llvm/Support/raw_ostream.h"
-using namespace llvm;
-
-namespace {
- cl::opt<std::string>
- File1(cl::Positional, cl::desc("<input file #1>"), cl::Required);
- cl::opt<std::string>
- File2(cl::Positional, cl::desc("<input file #2>"), cl::Required);
-
- cl::opt<double>
- RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0));
- cl::opt<double>
- AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0));
-}
-
-int main(int argc, char **argv) {
- cl::ParseCommandLineOptions(argc, argv);
-
- std::string ErrorMsg;
- int DF = DiffFilesWithTolerance(sys::PathWithStatus(File1),
- sys::PathWithStatus(File2),
- AbsTolerance, RelTolerance, &ErrorMsg);
- if (!ErrorMsg.empty())
- errs() << argv[0] << ": " << ErrorMsg << "\n";
- return DF;
-}
-
Modified: trunk/contrib/llvm/utils/getsrcs.sh
===================================================================
--- trunk/contrib/llvm/utils/getsrcs.sh 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/getsrcs.sh 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,34 +0,0 @@
-#!/bin/sh
-##===- utils/getsrcs.sh - Counts Lines Of Code ---------------*- Script -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-# details.
-#
-##===----------------------------------------------------------------------===##
-#
-# This script just prints out the path names for all the source files in LLVM.
-# The optional -topdir option can be used to specify the top LLVM source
-# directory. Without it, the llvm-config command is consulted to find the
-# top source directory.
-#
-# Note that the implementation is based on llvmdo. See that script for more
-# details.
-##===----------------------------------------------------------------------===##
-
-if test "$1" = "-topdir" ; then
- TOPDIR="$2"
- shift; shift;
-else
- TOPDIR=`llvm-config --src-root`
-fi
-
-if test -d "$TOPDIR" ; then
- cd $TOPDIR
- ./utils/llvmdo -topdir "$TOPDIR" \
- -dirs "include lib tools utils examples projects" echo
-else
- echo "Can't find LLVM top directory"
-fi
Modified: trunk/contrib/llvm/utils/git/find-rev
===================================================================
--- trunk/contrib/llvm/utils/git/find-rev 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/git/find-rev 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,50 +0,0 @@
-#!/usr/bin/python
-
-import os, sys, subprocess
-
-def main():
- from optparse import OptionParser, OptionGroup
- parser = OptionParser("usage: %prog [options] <repo> <revision>")
- parser.add_option("", "--branch", dest="branch",
- help="Ref for the branch to search [%default]",
- action="store", default="git-svn")
- (opts, args) = parser.parse_args()
-
- if len(args) != 2:
- parser.error("invalid number of arguments")
-
- repo,rev = args
-
- try:
- rev = int(rev)
- except:
- parser.error("invalid revision argument (not an integer)")
-
- os.chdir(repo)
- p = subprocess.Popen(['git', 'rev-list', opts.branch, '--pretty'],
- stdout=subprocess.PIPE)
-
- bestRev = bestCommit = None
- lastCommit = None
- for ln in p.stdout:
- if ln.startswith('commit '):
- lastCommit = ln.split(' ',2)[1]
- elif ln.startswith(' git-svn-id: '):
- _,repo,_ = ln.strip().split(' ')
- _,lrev = repo.rsplit('@',1)
- lrev = int(lrev)
- if lrev<=rev:
- if bestRev is None or lrev>bestRev:
- assert lastCommit
- bestCommit = lastCommit
- bestRev = lrev
- if lrev == rev:
- break
-
- if bestCommit is not None:
- print bestCommit
- sys.exit(0)
- sys.exit(1)
-
-if __name__=='__main__':
- main()
Modified: trunk/contrib/llvm/utils/git-svn/git-svnrevert
===================================================================
--- trunk/contrib/llvm/utils/git-svn/git-svnrevert 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/git-svn/git-svnrevert 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,52 +0,0 @@
-#!/bin/bash
-
-if [ $# -ne 1 ]; then
- echo "Invalid arguments!"
- echo "$0 <commit to revert>"
- exit 1
-fi
-
-if [ -n "$(git status -uno -s --porcelain)" ]; then
- echo "You have unstashed changes. Please stash and then revert."
- git status -uno
- exit 1
-fi
-
-COMMIT=$1
-
-SVN_REVISION=$(git svn find-rev "$COMMIT")
-if [ $? -ne 0 ]; then
- echo "Error! Could not find an svn revision for commit $COMMIT!"
- exit 1
-fi
-
-# Grab the one line message for our revert commit message.
-ONE_LINE_MSG=$(git log --oneline $COMMIT -1 | cut -f2- -d " ")
-
-# Revert the commit.
-git revert --no-commit $COMMIT 2>/dev/null
-if [ $? -ne 0 ]; then
- echo "Error! Failed to revert commit $COMMIT. Resetting to head."
- git reset --hard HEAD
- exit 1
-fi
-
-# Create a template in our .git directory.
-TEMPLATE="`git rev-parse --git-dir`/git-svn-revert-template"
-cat > $TEMPLATE <<EOF
-Revert "$ONE_LINE_MSG"
-
-This reverts commit r$SVN_REVISION.
-EOF
-
-# Begin the commit but give our user an opportunity to edit it.
-git commit --file="$TEMPLATE" --edit
-if [ $? -ne 0 ]; then
- echo "Error! Failed to commit reverting commit for commit $COMMIT. Reverting to head."
- git reset --hard HEAD
- rm -rf $TEMPLATE
- exit 1
-fi
-
-rm -rf $TEMPLATE
-
Modified: trunk/contrib/llvm/utils/git-svn/git-svnup
===================================================================
--- trunk/contrib/llvm/utils/git-svn/git-svnup 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/git-svn/git-svnup 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,15 +0,0 @@
-#!/bin/bash
-
-if [ -n "`git status -uno -s --porcelain`" ]; then
- echo "You have unstashed changes. Can not update repository..."
- git status -uno
- exit 1
-fi
-
-git fetch
-OLD_BRANCH=$(git rev-parse --abbrev-ref HEAD)
-git checkout master 2> /dev/null
-git svn rebase -l
-git checkout $OLD_BRANCH 2> /dev/null
-
-exit 0
Modified: trunk/contrib/llvm/utils/jedit/README
===================================================================
--- trunk/contrib/llvm/utils/jedit/README 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/jedit/README 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,14 +0,0 @@
--*- llvm/utils/jedit/README -*-
-
-These are syntax highlighting files for the jEdit editor. Included are:
-
-* tablegen.xml
-
- Syntax highlighting mode for TableGen description files. To use, copy this
- file to ~/.jedit/modes/ and add this code to your ~/.jedit/modes/catalog:
-
- <MODE NAME="tablegen" FILE="tablegen.xml" FILE_NAME_GLOB="*.td" />
-
-Note: If you notice missing or incorrect syntax highlighting, please contact
-<llvmbugs [at] cs.uiuc.edu>; if you wish to provide a patch to improve the
-functionality, it will be most appreciated. Thank you.
Modified: trunk/contrib/llvm/utils/jedit/tablegen.xml
===================================================================
(Binary files differ)
Modified: trunk/contrib/llvm/utils/kate/README
===================================================================
--- trunk/contrib/llvm/utils/kate/README 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/kate/README 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,12 +0,0 @@
--*- llvm/utils/kate/README -*-
-
-These are syntax highlighting files for the Kate editor. Included are:
-
-* llvm.xml
-
- Syntax Highlighting Mode for the KDE Kate editor. To install just copy
- this file to ~/.kde/share/apps/katepart/syntax (or better yet, symlink it).
-
-Note: If you notice missing or incorrect syntax highlighting, please contact
-<llvmbugs [at] cs.uiuc.edu>; if you wish to provide a patch to improve the
-functionality, it will be most appreciated. Thank you.
Modified: trunk/contrib/llvm/utils/kate/llvm.xml
===================================================================
(Binary files differ)
Modified: trunk/contrib/llvm/utils/lint/common_lint.py
===================================================================
--- trunk/contrib/llvm/utils/lint/common_lint.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/lint/common_lint.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,97 +0,0 @@
-#!/usr/bin/python
-#
-# Common lint functions applicable to multiple types of files.
-
-import re
-
-def VerifyLineLength(filename, lines, max_length):
- """Checks to make sure the file has no lines with lines exceeding the length
- limit.
-
- Args:
- filename: the file under consideration as string
- lines: contents of the file as string array
- max_length: maximum acceptable line length as number
-
- Returns:
- A list of tuples with format [(filename, line number, msg), ...] with any
- violations found.
- """
- lint = []
- line_num = 1
- for line in lines:
- length = len(line.rstrip('\n'))
- if length > max_length:
- lint.append((filename, line_num,
- 'Line exceeds %d chars (%d)' % (max_length, length)))
- line_num += 1
- return lint
-
-def VerifyTabs(filename, lines):
- """Checks to make sure the file has no tab characters.
-
- Args:
- filename: the file under consideration as string
- lines: contents of the file as string array
-
- Returns:
- A list of tuples with format [(line_number, msg), ...] with any violations
- found.
- """
- lint = []
- tab_re = re.compile(r'\t')
- line_num = 1
- for line in lines:
- if tab_re.match(line.rstrip('\n')):
- lint.append((filename, line_num, 'Tab found instead of whitespace'))
- line_num += 1
- return lint
-
-
-def VerifyTrailingWhitespace(filename, lines):
- """Checks to make sure the file has no lines with trailing whitespace.
-
- Args:
- filename: the file under consideration as string
- lines: contents of the file as string array
-
- Returns:
- A list of tuples with format [(filename, line number, msg), ...] with any
- violations found.
- """
- lint = []
- trailing_whitespace_re = re.compile(r'\s+$')
- line_num = 1
- for line in lines:
- if trailing_whitespace_re.match(line.rstrip('\n')):
- lint.append((filename, line_num, 'Trailing whitespace'))
- line_num += 1
- return lint
-
-
-class BaseLint:
- def RunOnFile(filename, lines):
- raise Exception('RunOnFile() unimplemented')
-
-
-def RunLintOverAllFiles(linter, filenames):
- """Runs linter over the contents of all files.
-
- Args:
- lint: subclass of BaseLint, implementing RunOnFile()
- filenames: list of all files whose contents will be linted
-
- Returns:
- A list of tuples with format [(filename, line number, msg), ...] with any
- violations found.
- """
- lint = []
- for filename in filenames:
- file = open(filename, 'r')
- if not file:
- print 'Cound not open %s' % filename
- continue
- lines = file.readlines()
- lint.extend(linter.RunOnFile(filename, lines))
-
- return lint
Modified: trunk/contrib/llvm/utils/lint/cpp_lint.py
===================================================================
--- trunk/contrib/llvm/utils/lint/cpp_lint.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/lint/cpp_lint.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,94 +0,0 @@
-#!/usr/bin/python
-#
-# Checks C++ files to make sure they conform to LLVM standards, as specified in
-# http://llvm.org/docs/CodingStandards.html .
-#
-# TODO: add unittests for the verifier functions:
-# http://docs.python.org/library/unittest.html .
-
-import common_lint
-import re
-import sys
-
-def VerifyIncludes(filename, lines):
- """Makes sure the #includes are in proper order and no disallows files are
- #included.
-
- Args:
- filename: the file under consideration as string
- lines: contents of the file as string array
- """
- lint = []
-
- include_gtest_re = re.compile(r'^#include "gtest/(.*)"')
- include_llvm_re = re.compile(r'^#include "llvm/(.*)"')
- include_support_re = re.compile(r'^#include "(Support/.*)"')
- include_config_re = re.compile(r'^#include "(Config/.*)"')
- include_system_re = re.compile(r'^#include <(.*)>')
-
- DISALLOWED_SYSTEM_HEADERS = ['iostream']
-
- line_num = 1
- prev_config_header = None
- prev_system_header = None
- for line in lines:
- # TODO: implement private headers
- # TODO: implement gtest headers
- # TODO: implement top-level llvm/* headers
- # TODO: implement llvm/Support/* headers
-
- # Process Config/* headers
- config_header = include_config_re.match(line)
- if config_header:
- curr_config_header = config_header.group(1)
- if prev_config_header:
- if prev_config_header > curr_config_header:
- lint.append((filename, line_num,
- 'Config headers not in order: "%s" before "%s"' % (
- prev_config_header, curr_config_header)))
-
- # Process system headers
- system_header = include_system_re.match(line)
- if system_header:
- curr_system_header = system_header.group(1)
-
- # Is it blacklisted?
- if curr_system_header in DISALLOWED_SYSTEM_HEADERS:
- lint.append((filename, line_num,
- 'Disallowed system header: <%s>' % curr_system_header))
- elif prev_system_header:
- # Make sure system headers are alphabetized amongst themselves
- if prev_system_header > curr_system_header:
- lint.append((filename, line_num,
- 'System headers not in order: <%s> before <%s>' % (
- prev_system_header, curr_system_header)))
-
- prev_system_header = curr_system_header
-
- line_num += 1
-
- return lint
-
-
-class CppLint(common_lint.BaseLint):
- MAX_LINE_LENGTH = 80
-
- def RunOnFile(self, filename, lines):
- lint = []
- lint.extend(VerifyIncludes(filename, lines))
- lint.extend(common_lint.VerifyLineLength(filename, lines,
- CppLint.MAX_LINE_LENGTH))
- lint.extend(common_lint.VerifyTabs(filename, lines))
- lint.extend(common_lint.VerifyTrailingWhitespace(filename, lines))
- return lint
-
-
-def CppLintMain(filenames):
- all_lint = common_lint.RunLintOverAllFiles(CppLint(), filenames)
- for lint in all_lint:
- print '%s:%d:%s' % (lint[0], lint[1], lint[2])
- return 0
-
-
-if __name__ == '__main__':
- sys.exit(CppLintMain(sys.argv[1:]))
Modified: trunk/contrib/llvm/utils/lint/generic_lint.py
===================================================================
--- trunk/contrib/llvm/utils/lint/generic_lint.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/lint/generic_lint.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,24 +0,0 @@
-#!/usr/bin/python
-#
-# Checks files to make sure they conform to LLVM standards which can be applied
-# to any programming language: at present, line length and trailing whitespace.
-
-import common_lint
-import sys
-
-class GenericCodeLint(common_lint.BaseLint):
- MAX_LINE_LENGTH = 80
-
- def RunOnFile(self, filename, lines):
- common_lint.VerifyLineLength(filename, lines,
- GenericCodeLint.MAX_LINE_LENGTH)
- common_lint.VerifyTrailingWhitespace(filename, lines)
-
-
-def GenericCodeLintMain(filenames):
- common_lint.RunLintOverAllFiles(GenericCodeLint(), filenames)
- return 0
-
-
-if __name__ == '__main__':
- sys.exit(GenericCodeLintMain(sys.argv[1:]))
Modified: trunk/contrib/llvm/utils/lint/remove_trailing_whitespace.sh
===================================================================
--- trunk/contrib/llvm/utils/lint/remove_trailing_whitespace.sh 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/lint/remove_trailing_whitespace.sh 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,6 +0,0 @@
-#!/bin/sh
-# Deletes trailing whitespace in-place in the passed-in files.
-# Sample syntax:
-# $0 *.cpp
-
-perl -pi -e 's/\s+$/\n/' $*
Modified: trunk/contrib/llvm/utils/lldbDataFormatters.py
===================================================================
--- trunk/contrib/llvm/utils/lldbDataFormatters.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/lldbDataFormatters.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,47 +0,0 @@
-"""
-Load into LLDB with:
-script import lldbDataFormatters
-type synthetic add -x "^llvm::SmallVectorImpl<.+>$" -l lldbDataFormatters.SmallVectorSynthProvider
-type synthetic add -x "^llvm::SmallVector<.+,.+>$" -l lldbDataFormatters.SmallVectorSynthProvider
-"""
-
-# Pretty printer for llvm::SmallVector/llvm::SmallVectorImpl
-class SmallVectorSynthProvider:
- def __init__(self, valobj, dict):
- self.valobj = valobj;
- self.update() # initialize this provider
-
- def num_children(self):
- begin = self.begin.GetValueAsUnsigned(0)
- end = self.end.GetValueAsUnsigned(0)
- return (end - begin)/self.type_size
-
- def get_child_index(self, name):
- try:
- return int(name.lstrip('[').rstrip(']'))
- except:
- return -1;
-
- def get_child_at_index(self, index):
- # Do bounds checking.
- if index < 0:
- return None
- if index >= self.num_children():
- return None;
-
- offset = index * self.type_size
- return self.begin.CreateChildAtOffset('['+str(index)+']',
- offset, self.data_type)
-
- def update(self):
- self.begin = self.valobj.GetChildMemberWithName('BeginX')
- self.end = self.valobj.GetChildMemberWithName('EndX')
- the_type = self.valobj.GetType()
- # If this is a reference type we have to dereference it to get to the
- # template parameter.
- if the_type.IsReferenceType():
- the_type = the_type.GetDereferencedType()
-
- self.data_type = the_type.GetTemplateArgumentType(0)
- self.type_size = self.data_type.GetByteSize()
- assert self.type_size != 0
Modified: trunk/contrib/llvm/utils/llvm-build/llvm-build
===================================================================
--- trunk/contrib/llvm/utils/llvm-build/llvm-build 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-build/llvm-build 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,6 +0,0 @@
-#!/usr/bin/env python
-
-import llvmbuild
-
-if __name__ == '__main__':
- llvmbuild.main()
Modified: trunk/contrib/llvm/utils/llvm-build/llvmbuild/__init__.py
===================================================================
--- trunk/contrib/llvm/utils/llvm-build/llvmbuild/__init__.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-build/llvmbuild/__init__.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1 +0,0 @@
-from main import main
Modified: trunk/contrib/llvm/utils/llvm-build/llvmbuild/componentinfo.py
===================================================================
--- trunk/contrib/llvm/utils/llvm-build/llvmbuild/componentinfo.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-build/llvmbuild/componentinfo.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,468 +0,0 @@
-"""
-Descriptor objects for entities that are part of the LLVM project.
-"""
-
-import ConfigParser
-import StringIO
-import sys
-
-from util import *
-
-class ParseError(Exception):
- pass
-
-class ComponentInfo(object):
- """
- Base class for component descriptions.
- """
-
- type_name = None
-
- @staticmethod
- def parse_items(items, has_dependencies = True):
- kwargs = {}
- kwargs['name'] = items.get_string('name')
- kwargs['parent'] = items.get_optional_string('parent')
- if has_dependencies:
- kwargs['dependencies'] = items.get_list('dependencies')
- return kwargs
-
- def __init__(self, subpath, name, dependencies, parent):
- if not subpath.startswith('/'):
- raise ValueError,"invalid subpath: %r" % subpath
- self.subpath = subpath
- self.name = name
- self.dependencies = list(dependencies)
-
- # The name of the parent component to logically group this component
- # under.
- self.parent = parent
-
- # The parent instance, once loaded.
- self.parent_instance = None
- self.children = []
-
- # The original source path.
- self._source_path = None
-
- # A flag to mark "special" components which have some amount of magic
- # handling (generally based on command line options).
- self._is_special_group = False
-
- def set_parent_instance(self, parent):
- assert parent.name == self.parent, "Unexpected parent!"
- self.parent_instance = parent
- self.parent_instance.children.append(self)
-
- def get_component_references(self):
- """get_component_references() -> iter
-
- Return an iterator over the named references to other components from
- this object. Items are of the form (reference-type, component-name).
- """
-
- # Parent references are handled specially.
- for r in self.dependencies:
- yield ('dependency', r)
-
- def get_llvmbuild_fragment(self):
- abstract
-
- def get_parent_target_group(self):
- """get_parent_target_group() -> ComponentInfo or None
-
- Return the nearest parent target group (if any), or None if the
- component is not part of any target group.
- """
-
- # If this is a target group, return it.
- if self.type_name == 'TargetGroup':
- return self
-
- # Otherwise recurse on the parent, if any.
- if self.parent_instance:
- return self.parent_instance.get_parent_target_group()
-
-class GroupComponentInfo(ComponentInfo):
- """
- Group components have no semantics as far as the build system are concerned,
- but exist to help organize other components into a logical tree structure.
- """
-
- type_name = 'Group'
-
- @staticmethod
- def parse(subpath, items):
- kwargs = ComponentInfo.parse_items(items, has_dependencies = False)
- return GroupComponentInfo(subpath, **kwargs)
-
- def __init__(self, subpath, name, parent):
- ComponentInfo.__init__(self, subpath, name, [], parent)
-
- def get_llvmbuild_fragment(self):
- result = StringIO.StringIO()
- print >>result, 'type = %s' % self.type_name
- print >>result, 'name = %s' % self.name
- print >>result, 'parent = %s' % self.parent
- return result.getvalue()
-
-class LibraryComponentInfo(ComponentInfo):
- type_name = 'Library'
-
- @staticmethod
- def parse_items(items):
- kwargs = ComponentInfo.parse_items(items)
- kwargs['library_name'] = items.get_optional_string('library_name')
- kwargs['required_libraries'] = items.get_list('required_libraries')
- kwargs['add_to_library_groups'] = items.get_list(
- 'add_to_library_groups')
- kwargs['installed'] = items.get_optional_bool('installed', True)
- return kwargs
-
- @staticmethod
- def parse(subpath, items):
- kwargs = LibraryComponentInfo.parse_items(items)
- return LibraryComponentInfo(subpath, **kwargs)
-
- def __init__(self, subpath, name, dependencies, parent, library_name,
- required_libraries, add_to_library_groups, installed):
- ComponentInfo.__init__(self, subpath, name, dependencies, parent)
-
- # If given, the name to use for the library instead of deriving it from
- # the component name.
- self.library_name = library_name
-
- # The names of the library components which are required when linking
- # with this component.
- self.required_libraries = list(required_libraries)
-
- # The names of the library group components this component should be
- # considered part of.
- self.add_to_library_groups = list(add_to_library_groups)
-
- # Whether or not this library is installed.
- self.installed = installed
-
- def get_component_references(self):
- for r in ComponentInfo.get_component_references(self):
- yield r
- for r in self.required_libraries:
- yield ('required library', r)
- for r in self.add_to_library_groups:
- yield ('library group', r)
-
- def get_llvmbuild_fragment(self):
- result = StringIO.StringIO()
- print >>result, 'type = %s' % self.type_name
- print >>result, 'name = %s' % self.name
- print >>result, 'parent = %s' % self.parent
- if self.library_name is not None:
- print >>result, 'library_name = %s' % self.library_name
- if self.required_libraries:
- print >>result, 'required_libraries = %s' % ' '.join(
- self.required_libraries)
- if self.add_to_library_groups:
- print >>result, 'add_to_library_groups = %s' % ' '.join(
- self.add_to_library_groups)
- if not self.installed:
- print >>result, 'installed = 0'
- return result.getvalue()
-
- def get_library_name(self):
- return self.library_name or self.name
-
- def get_prefixed_library_name(self):
- """
- get_prefixed_library_name() -> str
-
- Return the library name prefixed by the project name. This is generally
- what the library name will be on disk.
- """
-
- basename = self.get_library_name()
-
- # FIXME: We need to get the prefix information from an explicit project
- # object, or something.
- if basename in ('gtest', 'gtest_main'):
- return basename
-
- return 'LLVM%s' % basename
-
- def get_llvmconfig_component_name(self):
- return self.get_library_name().lower()
-
-class OptionalLibraryComponentInfo(LibraryComponentInfo):
- type_name = "OptionalLibrary"
-
- @staticmethod
- def parse(subpath, items):
- kwargs = LibraryComponentInfo.parse_items(items)
- return OptionalLibraryComponentInfo(subpath, **kwargs)
-
- def __init__(self, subpath, name, dependencies, parent, library_name,
- required_libraries, add_to_library_groups, installed):
- LibraryComponentInfo.__init__(self, subpath, name, dependencies, parent,
- library_name, required_libraries,
- add_to_library_groups, installed)
-
-class LibraryGroupComponentInfo(ComponentInfo):
- type_name = 'LibraryGroup'
-
- @staticmethod
- def parse(subpath, items):
- kwargs = ComponentInfo.parse_items(items, has_dependencies = False)
- kwargs['required_libraries'] = items.get_list('required_libraries')
- kwargs['add_to_library_groups'] = items.get_list(
- 'add_to_library_groups')
- return LibraryGroupComponentInfo(subpath, **kwargs)
-
- def __init__(self, subpath, name, parent, required_libraries = [],
- add_to_library_groups = []):
- ComponentInfo.__init__(self, subpath, name, [], parent)
-
- # The names of the library components which are required when linking
- # with this component.
- self.required_libraries = list(required_libraries)
-
- # The names of the library group components this component should be
- # considered part of.
- self.add_to_library_groups = list(add_to_library_groups)
-
- def get_component_references(self):
- for r in ComponentInfo.get_component_references(self):
- yield r
- for r in self.required_libraries:
- yield ('required library', r)
- for r in self.add_to_library_groups:
- yield ('library group', r)
-
- def get_llvmbuild_fragment(self):
- result = StringIO.StringIO()
- print >>result, 'type = %s' % self.type_name
- print >>result, 'name = %s' % self.name
- print >>result, 'parent = %s' % self.parent
- if self.required_libraries and not self._is_special_group:
- print >>result, 'required_libraries = %s' % ' '.join(
- self.required_libraries)
- if self.add_to_library_groups:
- print >>result, 'add_to_library_groups = %s' % ' '.join(
- self.add_to_library_groups)
- return result.getvalue()
-
- def get_llvmconfig_component_name(self):
- return self.name.lower()
-
-class TargetGroupComponentInfo(ComponentInfo):
- type_name = 'TargetGroup'
-
- @staticmethod
- def parse(subpath, items):
- kwargs = ComponentInfo.parse_items(items, has_dependencies = False)
- kwargs['required_libraries'] = items.get_list('required_libraries')
- kwargs['add_to_library_groups'] = items.get_list(
- 'add_to_library_groups')
- kwargs['has_jit'] = items.get_optional_bool('has_jit', False)
- kwargs['has_asmprinter'] = items.get_optional_bool('has_asmprinter',
- False)
- kwargs['has_asmparser'] = items.get_optional_bool('has_asmparser',
- False)
- kwargs['has_disassembler'] = items.get_optional_bool('has_disassembler',
- False)
- return TargetGroupComponentInfo(subpath, **kwargs)
-
- def __init__(self, subpath, name, parent, required_libraries = [],
- add_to_library_groups = [], has_jit = False,
- has_asmprinter = False, has_asmparser = False,
- has_disassembler = False):
- ComponentInfo.__init__(self, subpath, name, [], parent)
-
- # The names of the library components which are required when linking
- # with this component.
- self.required_libraries = list(required_libraries)
-
- # The names of the library group components this component should be
- # considered part of.
- self.add_to_library_groups = list(add_to_library_groups)
-
- # Whether or not this target supports the JIT.
- self.has_jit = bool(has_jit)
-
- # Whether or not this target defines an assembly printer.
- self.has_asmprinter = bool(has_asmprinter)
-
- # Whether or not this target defines an assembly parser.
- self.has_asmparser = bool(has_asmparser)
-
- # Whether or not this target defines an disassembler.
- self.has_disassembler = bool(has_disassembler)
-
- # Whether or not this target is enabled. This is set in response to
- # configuration parameters.
- self.enabled = False
-
- def get_component_references(self):
- for r in ComponentInfo.get_component_references(self):
- yield r
- for r in self.required_libraries:
- yield ('required library', r)
- for r in self.add_to_library_groups:
- yield ('library group', r)
-
- def get_llvmbuild_fragment(self):
- result = StringIO.StringIO()
- print >>result, 'type = %s' % self.type_name
- print >>result, 'name = %s' % self.name
- print >>result, 'parent = %s' % self.parent
- if self.required_libraries:
- print >>result, 'required_libraries = %s' % ' '.join(
- self.required_libraries)
- if self.add_to_library_groups:
- print >>result, 'add_to_library_groups = %s' % ' '.join(
- self.add_to_library_groups)
- for bool_key in ('has_asmparser', 'has_asmprinter', 'has_disassembler',
- 'has_jit'):
- if getattr(self, bool_key):
- print >>result, '%s = 1' % (bool_key,)
- return result.getvalue()
-
- def get_llvmconfig_component_name(self):
- return self.name.lower()
-
-class ToolComponentInfo(ComponentInfo):
- type_name = 'Tool'
-
- @staticmethod
- def parse(subpath, items):
- kwargs = ComponentInfo.parse_items(items)
- kwargs['required_libraries'] = items.get_list('required_libraries')
- return ToolComponentInfo(subpath, **kwargs)
-
- def __init__(self, subpath, name, dependencies, parent,
- required_libraries):
- ComponentInfo.__init__(self, subpath, name, dependencies, parent)
-
- # The names of the library components which are required to link this
- # tool.
- self.required_libraries = list(required_libraries)
-
- def get_component_references(self):
- for r in ComponentInfo.get_component_references(self):
- yield r
- for r in self.required_libraries:
- yield ('required library', r)
-
- def get_llvmbuild_fragment(self):
- result = StringIO.StringIO()
- print >>result, 'type = %s' % self.type_name
- print >>result, 'name = %s' % self.name
- print >>result, 'parent = %s' % self.parent
- print >>result, 'required_libraries = %s' % ' '.join(
- self.required_libraries)
- return result.getvalue()
-
-class BuildToolComponentInfo(ToolComponentInfo):
- type_name = 'BuildTool'
-
- @staticmethod
- def parse(subpath, items):
- kwargs = ComponentInfo.parse_items(items)
- kwargs['required_libraries'] = items.get_list('required_libraries')
- return BuildToolComponentInfo(subpath, **kwargs)
-
-###
-
-class IniFormatParser(dict):
- def get_list(self, key):
- # Check if the value is defined.
- value = self.get(key)
- if value is None:
- return []
-
- # Lists are just whitespace separated strings.
- return value.split()
-
- def get_optional_string(self, key):
- value = self.get_list(key)
- if not value:
- return None
- if len(value) > 1:
- raise ParseError("multiple values for scalar key: %r" % key)
- return value[0]
-
- def get_string(self, key):
- value = self.get_optional_string(key)
- if not value:
- raise ParseError("missing value for required string: %r" % key)
- return value
-
- def get_optional_bool(self, key, default = None):
- value = self.get_optional_string(key)
- if not value:
- return default
- if value not in ('0', '1'):
- raise ParseError("invalid value(%r) for boolean property: %r" % (
- value, key))
- return bool(int(value))
-
- def get_bool(self, key):
- value = self.get_optional_bool(key)
- if value is None:
- raise ParseError("missing value for required boolean: %r" % key)
- return value
-
-_component_type_map = dict(
- (t.type_name, t)
- for t in (GroupComponentInfo,
- LibraryComponentInfo, LibraryGroupComponentInfo,
- ToolComponentInfo, BuildToolComponentInfo,
- TargetGroupComponentInfo, OptionalLibraryComponentInfo))
-def load_from_path(path, subpath):
- # Load the LLVMBuild.txt file as an .ini format file.
- parser = ConfigParser.RawConfigParser()
- parser.read(path)
-
- # Extract the common section.
- if parser.has_section("common"):
- common = IniFormatParser(parser.items("common"))
- parser.remove_section("common")
- else:
- common = IniFormatParser({})
-
- return common, _read_components_from_parser(parser, path, subpath)
-
-def _read_components_from_parser(parser, path, subpath):
- # We load each section which starts with 'component' as a distinct component
- # description (so multiple components can be described in one file).
- for section in parser.sections():
- if not section.startswith('component'):
- # We don't expect arbitrary sections currently, warn the user.
- warning("ignoring unknown section %r in %r" % (section, path))
- continue
-
- # Determine the type of the component to instantiate.
- if not parser.has_option(section, 'type'):
- fatal("invalid component %r in %r: %s" % (
- section, path, "no component type"))
-
- type_name = parser.get(section, 'type')
- type_class = _component_type_map.get(type_name)
- if type_class is None:
- fatal("invalid component %r in %r: %s" % (
- section, path, "invalid component type: %r" % type_name))
-
- # Instantiate the component based on the remaining values.
- try:
- info = type_class.parse(subpath,
- IniFormatParser(parser.items(section)))
- except TypeError:
- print >>sys.stderr, "error: invalid component %r in %r: %s" % (
- section, path, "unable to instantiate: %r" % type_name)
- import traceback
- traceback.print_exc()
- raise SystemExit, 1
- except ParseError,e:
- fatal("unable to load component %r in %r: %s" % (
- section, path, e.message))
-
- info._source_path = path
- yield info
Modified: trunk/contrib/llvm/utils/llvm-build/llvmbuild/configutil.py
===================================================================
--- trunk/contrib/llvm/utils/llvm-build/llvmbuild/configutil.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-build/llvmbuild/configutil.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,66 +0,0 @@
-"""
-Defines utilities useful for performing standard "configuration" style tasks.
-"""
-
-import re
-import os
-
-def configure_file(input_path, output_path, substitutions):
- """configure_file(input_path, output_path, substitutions) -> bool
-
- Given an input and output path, "configure" the file at the given input path
- by replacing variables in the file with those given in the substitutions
- list. Returns true if the output file was written.
-
- The substitutions list should be given as a list of tuples (regex string,
- replacement), where the regex and replacement will be used as in 're.sub' to
- execute the variable replacement.
-
- The output path's parent directory need not exist (it will be created).
-
- If the output path does exist and the configured data is not different than
- it's current contents, the output file will not be modified. This is
- designed to limit the impact of configured files on build dependencies.
- """
-
- # Read in the input data.
- f = open(input_path, "rb")
- try:
- data = f.read()
- finally:
- f.close()
-
- # Perform the substitutions.
- for regex_string,replacement in substitutions:
- regex = re.compile(regex_string)
- data = regex.sub(replacement, data)
-
- # Ensure the output parent directory exists.
- output_parent_path = os.path.dirname(os.path.abspath(output_path))
- if not os.path.exists(output_parent_path):
- os.makedirs(output_parent_path)
-
- # If the output path exists, load it and compare to the configured contents.
- if os.path.exists(output_path):
- current_data = None
- try:
- f = open(output_path, "rb")
- try:
- current_data = f.read()
- except:
- current_data = None
- f.close()
- except:
- current_data = None
-
- if current_data is not None and current_data == data:
- return False
-
- # Write the output contents.
- f = open(output_path, "wb")
- try:
- f.write(data)
- finally:
- f.close()
-
- return True
Modified: trunk/contrib/llvm/utils/llvm-build/llvmbuild/main.py
===================================================================
--- trunk/contrib/llvm/utils/llvm-build/llvmbuild/main.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-build/llvmbuild/main.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,893 +0,0 @@
-import StringIO
-import os
-import sys
-
-import componentinfo
-import configutil
-
-from util import *
-
-###
-
-def cmake_quote_string(value):
- """
- cmake_quote_string(value) -> str
-
- Return a quoted form of the given value that is suitable for use in CMake
- language files.
- """
-
- # Currently, we only handle escaping backslashes.
- value = value.replace("\\", "\\\\")
-
- return value
-
-def cmake_quote_path(value):
- """
- cmake_quote_path(value) -> str
-
- Return a quoted form of the given value that is suitable for use in CMake
- language files.
- """
-
- # CMake has a bug in it's Makefile generator that doesn't properly quote
- # strings it generates. So instead of using proper quoting, we just use "/"
- # style paths. Currently, we only handle escaping backslashes.
- value = value.replace("\\", "/")
-
- return value
-
-def mk_quote_string_for_target(value):
- """
- mk_quote_string_for_target(target_name) -> str
-
- Return a quoted form of the given target_name suitable for including in a
- Makefile as a target name.
- """
-
- # The only quoting we currently perform is for ':', to support msys users.
- return value.replace(":", "\\:")
-
-def make_install_dir(path):
- """
- make_install_dir(path) -> None
-
- Create the given directory path for installation, including any parents.
- """
-
- # os.makedirs considers it an error to be called with an existent path.
- if not os.path.exists(path):
- os.makedirs(path)
-
-###
-
-class LLVMProjectInfo(object):
- @staticmethod
- def load_infos_from_path(llvmbuild_source_root):
- def recurse(subpath):
- # Load the LLVMBuild file.
- llvmbuild_path = os.path.join(llvmbuild_source_root + subpath,
- 'LLVMBuild.txt')
- if not os.path.exists(llvmbuild_path):
- fatal("missing LLVMBuild.txt file at: %r" % (llvmbuild_path,))
-
- # Parse the components from it.
- common,info_iter = componentinfo.load_from_path(llvmbuild_path,
- subpath)
- for info in info_iter:
- yield info
-
- # Recurse into the specified subdirectories.
- for subdir in common.get_list("subdirectories"):
- for item in recurse(os.path.join(subpath, subdir)):
- yield item
-
- return recurse("/")
-
- @staticmethod
- def load_from_path(source_root, llvmbuild_source_root):
- infos = list(
- LLVMProjectInfo.load_infos_from_path(llvmbuild_source_root))
-
- return LLVMProjectInfo(source_root, infos)
-
- def __init__(self, source_root, component_infos):
- # Store our simple ivars.
- self.source_root = source_root
- self.component_infos = list(component_infos)
- self.component_info_map = None
- self.ordered_component_infos = None
-
- def validate_components(self):
- """validate_components() -> None
-
- Validate that the project components are well-defined. Among other
- things, this checks that:
- - Components have valid references.
- - Components references do not form cycles.
-
- We also construct the map from component names to info, and the
- topological ordering of components.
- """
-
- # Create the component info map and validate that component names are
- # unique.
- self.component_info_map = {}
- for ci in self.component_infos:
- existing = self.component_info_map.get(ci.name)
- if existing is not None:
- # We found a duplicate component name, report it and error out.
- fatal("found duplicate component %r (at %r and %r)" % (
- ci.name, ci.subpath, existing.subpath))
- self.component_info_map[ci.name] = ci
-
- # Disallow 'all' as a component name, which is a special case.
- if 'all' in self.component_info_map:
- fatal("project is not allowed to define 'all' component")
-
- # Add the root component.
- if '$ROOT' in self.component_info_map:
- fatal("project is not allowed to define $ROOT component")
- self.component_info_map['$ROOT'] = componentinfo.GroupComponentInfo(
- '/', '$ROOT', None)
- self.component_infos.append(self.component_info_map['$ROOT'])
-
- # Topologically order the component information according to their
- # component references.
- def visit_component_info(ci, current_stack, current_set):
- # Check for a cycles.
- if ci in current_set:
- # We found a cycle, report it and error out.
- cycle_description = ' -> '.join(
- '%r (%s)' % (ci.name, relation)
- for relation,ci in current_stack)
- fatal("found cycle to %r after following: %s -> %s" % (
- ci.name, cycle_description, ci.name))
-
- # If we have already visited this item, we are done.
- if ci not in components_to_visit:
- return
-
- # Otherwise, mark the component info as visited and traverse.
- components_to_visit.remove(ci)
-
- # Validate the parent reference, which we treat specially.
- if ci.parent is not None:
- parent = self.component_info_map.get(ci.parent)
- if parent is None:
- fatal("component %r has invalid reference %r (via %r)" % (
- ci.name, ci.parent, 'parent'))
- ci.set_parent_instance(parent)
-
- for relation,referent_name in ci.get_component_references():
- # Validate that the reference is ok.
- referent = self.component_info_map.get(referent_name)
- if referent is None:
- fatal("component %r has invalid reference %r (via %r)" % (
- ci.name, referent_name, relation))
-
- # Visit the reference.
- current_stack.append((relation,ci))
- current_set.add(ci)
- visit_component_info(referent, current_stack, current_set)
- current_set.remove(ci)
- current_stack.pop()
-
- # Finally, add the component info to the ordered list.
- self.ordered_component_infos.append(ci)
-
- # FIXME: We aren't actually correctly checking for cycles along the
- # parent edges. Haven't decided how I want to handle this -- I thought
- # about only checking cycles by relation type. If we do that, it falls
- # out easily. If we don't, we should special case the check.
-
- self.ordered_component_infos = []
- components_to_visit = sorted(
- set(self.component_infos),
- key = lambda c: c.name)
- while components_to_visit:
- visit_component_info(iter(components_to_visit).next(), [], set())
-
- # Canonicalize children lists.
- for c in self.ordered_component_infos:
- c.children.sort(key = lambda c: c.name)
-
- def print_tree(self):
- def visit(node, depth = 0):
- print '%s%-40s (%s)' % (' '*depth, node.name, node.type_name)
- for c in node.children:
- visit(c, depth + 1)
- visit(self.component_info_map['$ROOT'])
-
- def write_components(self, output_path):
- # Organize all the components by the directory their LLVMBuild file
- # should go in.
- info_basedir = {}
- for ci in self.component_infos:
- # Ignore the $ROOT component.
- if ci.parent is None:
- continue
-
- info_basedir[ci.subpath] = info_basedir.get(ci.subpath, []) + [ci]
-
- # Compute the list of subdirectories to scan.
- subpath_subdirs = {}
- for ci in self.component_infos:
- # Ignore root components.
- if ci.subpath == '/':
- continue
-
- # Otherwise, append this subpath to the parent list.
- parent_path = os.path.dirname(ci.subpath)
- subpath_subdirs[parent_path] = parent_list = subpath_subdirs.get(
- parent_path, set())
- parent_list.add(os.path.basename(ci.subpath))
-
- # Generate the build files.
- for subpath, infos in info_basedir.items():
- # Order the components by name to have a canonical ordering.
- infos.sort(key = lambda ci: ci.name)
-
- # Format the components into llvmbuild fragments.
- fragments = []
-
- # Add the common fragments.
- subdirectories = subpath_subdirs.get(subpath)
- if subdirectories:
- fragment = """\
-subdirectories = %s
-""" % (" ".join(sorted(subdirectories)),)
- fragments.append(("common", fragment))
-
- # Add the component fragments.
- num_common_fragments = len(fragments)
- for ci in infos:
- fragment = ci.get_llvmbuild_fragment()
- if fragment is None:
- continue
-
- name = "component_%d" % (len(fragments) - num_common_fragments)
- fragments.append((name, fragment))
-
- if not fragments:
- continue
-
- assert subpath.startswith('/')
- directory_path = os.path.join(output_path, subpath[1:])
-
- # Create the directory if it does not already exist.
- if not os.path.exists(directory_path):
- os.makedirs(directory_path)
-
- # In an effort to preserve comments (which aren't parsed), read in
- # the original file and extract the comments. We only know how to
- # associate comments that prefix a section name.
- f = open(infos[0]._source_path)
- comments_map = {}
- comment_block = ""
- for ln in f:
- if ln.startswith(';'):
- comment_block += ln
- elif ln.startswith('[') and ln.endswith(']\n'):
- comments_map[ln[1:-2]] = comment_block
- else:
- comment_block = ""
- f.close()
-
- # Create the LLVMBuild fil[e.
- file_path = os.path.join(directory_path, 'LLVMBuild.txt')
- f = open(file_path, "w")
-
- # Write the header.
- header_fmt = ';===- %s %s-*- Conf -*--===;'
- header_name = '.' + os.path.join(subpath, 'LLVMBuild.txt')
- header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
- header_string = header_fmt % (header_name, header_pad)
- print >>f, """\
-%s
-;
-; The LLVM Compiler Infrastructure
-;
-; This file is distributed under the University of Illinois Open Source
-; License. See LICENSE.TXT for details.
-;
-;===------------------------------------------------------------------------===;
-;
-; This is an LLVMBuild description file for the components in this subdirectory.
-;
-; For more information on the LLVMBuild system, please see:
-;
-; http://llvm.org/docs/LLVMBuild.html
-;
-;===------------------------------------------------------------------------===;
-""" % header_string
-
- # Write out each fragment.each component fragment.
- for name,fragment in fragments:
- comment = comments_map.get(name)
- if comment is not None:
- f.write(comment)
- print >>f, "[%s]" % name
- f.write(fragment)
- if fragment is not fragments[-1][1]:
- print >>f
-
- f.close()
-
- def write_library_table(self, output_path, enabled_optional_components):
- # Write out the mapping from component names to required libraries.
- #
- # We do this in topological order so that we know we can append the
- # dependencies for added library groups.
- entries = {}
- for c in self.ordered_component_infos:
- # Skip optional components which are not enabled.
- if c.type_name == 'OptionalLibrary' \
- and c.name not in enabled_optional_components:
- continue
-
- # Skip target groups which are not enabled.
- tg = c.get_parent_target_group()
- if tg and not tg.enabled:
- continue
-
- # Only certain components are in the table.
- if c.type_name not in ('Library', 'OptionalLibrary', \
- 'LibraryGroup', 'TargetGroup'):
- continue
-
- # Compute the llvm-config "component name". For historical reasons,
- # this is lowercased based on the library name.
- llvmconfig_component_name = c.get_llvmconfig_component_name()
-
- # Get the library name, or None for LibraryGroups.
- if c.type_name == 'Library' or c.type_name == 'OptionalLibrary':
- library_name = c.get_prefixed_library_name()
- is_installed = c.installed
- else:
- library_name = None
- is_installed = True
-
- # Get the component names of all the required libraries.
- required_llvmconfig_component_names = [
- self.component_info_map[dep].get_llvmconfig_component_name()
- for dep in c.required_libraries]
-
- # Insert the entries for library groups we should add to.
- for dep in c.add_to_library_groups:
- entries[dep][2].append(llvmconfig_component_name)
-
- # Add the entry.
- entries[c.name] = (llvmconfig_component_name, library_name,
- required_llvmconfig_component_names,
- is_installed)
-
- # Convert to a list of entries and sort by name.
- entries = entries.values()
-
- # Create an 'all' pseudo component. We keep the dependency list small by
- # only listing entries that have no other dependents.
- root_entries = set(e[0] for e in entries)
- for _,_,deps,_ in entries:
- root_entries -= set(deps)
- entries.append(('all', None, root_entries, True))
-
- entries.sort()
-
- # Compute the maximum number of required libraries, plus one so there is
- # always a sentinel.
- max_required_libraries = max(len(deps)
- for _,_,deps,_ in entries) + 1
-
- # Write out the library table.
- make_install_dir(os.path.dirname(output_path))
- f = open(output_path, 'w')
- print >>f, """\
-//===- llvm-build generated file --------------------------------*- C++ -*-===//
-//
-// Component Library Depenedency Table
-//
-// Automatically generated file, do not edit!
-//
-//===----------------------------------------------------------------------===//
-"""
- print >>f, 'struct AvailableComponent {'
- print >>f, ' /// The name of the component.'
- print >>f, ' const char *Name;'
- print >>f, ''
- print >>f, ' /// The name of the library for this component (or NULL).'
- print >>f, ' const char *Library;'
- print >>f, ''
- print >>f, ' /// Whether the component is installed.'
- print >>f, ' bool IsInstalled;'
- print >>f, ''
- print >>f, '\
- /// The list of libraries required when linking this component.'
- print >>f, ' const char *RequiredLibraries[%d];' % (
- max_required_libraries)
- print >>f, '} AvailableComponents[%d] = {' % len(entries)
- for name,library_name,required_names,is_installed in entries:
- if library_name is None:
- library_name_as_cstr = '0'
- else:
- library_name_as_cstr = '"lib%s.a"' % library_name
- print >>f, ' { "%s", %s, %d, { %s } },' % (
- name, library_name_as_cstr, is_installed,
- ', '.join('"%s"' % dep
- for dep in required_names))
- print >>f, '};'
- f.close()
-
- def get_required_libraries_for_component(self, ci, traverse_groups = False):
- """
- get_required_libraries_for_component(component_info) -> iter
-
- Given a Library component info descriptor, return an iterator over all
- of the directly required libraries for linking with this component. If
- traverse_groups is True, then library and target groups will be
- traversed to include their required libraries.
- """
-
- assert ci.type_name in ('Library', 'LibraryGroup', 'TargetGroup')
-
- for name in ci.required_libraries:
- # Get the dependency info.
- dep = self.component_info_map[name]
-
- # If it is a library, yield it.
- if dep.type_name == 'Library':
- yield dep
- continue
-
- # Otherwise if it is a group, yield or traverse depending on what
- # was requested.
- if dep.type_name in ('LibraryGroup', 'TargetGroup'):
- if not traverse_groups:
- yield dep
- continue
-
- for res in self.get_required_libraries_for_component(dep, True):
- yield res
-
- def get_fragment_dependencies(self):
- """
- get_fragment_dependencies() -> iter
-
- Compute the list of files (as absolute paths) on which the output
- fragments depend (i.e., files for which a modification should trigger a
- rebuild of the fragment).
- """
-
- # Construct a list of all the dependencies of the Makefile fragment
- # itself. These include all the LLVMBuild files themselves, as well as
- # all of our own sources.
- #
- # Many components may come from the same file, so we make sure to unique
- # these.
- build_paths = set()
- for ci in self.component_infos:
- p = os.path.join(self.source_root, ci.subpath[1:], 'LLVMBuild.txt')
- if p not in build_paths:
- yield p
- build_paths.add(p)
-
- # Gather the list of necessary sources by just finding all loaded
- # modules that are inside the LLVM source tree.
- for module in sys.modules.values():
- # Find the module path.
- if not hasattr(module, '__file__'):
- continue
- path = getattr(module, '__file__')
- if not path:
- continue
-
- # Strip off any compiled suffix.
- if os.path.splitext(path)[1] in ['.pyc', '.pyo', '.pyd']:
- path = path[:-1]
-
- # If the path exists and is in the source tree, consider it a
- # dependency.
- if (path.startswith(self.source_root) and os.path.exists(path)):
- yield path
-
- def write_cmake_fragment(self, output_path):
- """
- write_cmake_fragment(output_path) -> None
-
- Generate a CMake fragment which includes all of the collated LLVMBuild
- information in a format that is easily digestible by a CMake. The exact
- contents of this are closely tied to how the CMake configuration
- integrates LLVMBuild, see CMakeLists.txt in the top-level.
- """
-
- dependencies = list(self.get_fragment_dependencies())
-
- # Write out the CMake fragment.
- make_install_dir(os.path.dirname(output_path))
- f = open(output_path, 'w')
-
- # Write the header.
- header_fmt = '\
-#===-- %s - LLVMBuild Configuration for LLVM %s-*- CMake -*--===#'
- header_name = os.path.basename(output_path)
- header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
- header_string = header_fmt % (header_name, header_pad)
- print >>f, """\
-%s
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-#===------------------------------------------------------------------------===#
-#
-# This file contains the LLVMBuild project information in a format easily
-# consumed by the CMake based build system.
-#
-# This file is autogenerated by llvm-build, do not edit!
-#
-#===------------------------------------------------------------------------===#
-""" % header_string
-
- # Write the dependency information in the best way we can.
- print >>f, """
-# LLVMBuild CMake fragment dependencies.
-#
-# CMake has no builtin way to declare that the configuration depends on
-# a particular file. However, a side effect of configure_file is to add
-# said input file to CMake's internal dependency list. So, we use that
-# and a dummy output file to communicate the dependency information to
-# CMake.
-#
-# FIXME: File a CMake RFE to get a properly supported version of this
-# feature."""
- for dep in dependencies:
- print >>f, """\
-configure_file(\"%s\"
- ${CMAKE_CURRENT_BINARY_DIR}/DummyConfigureOutput)""" % (
- cmake_quote_path(dep),)
-
- # Write the properties we use to encode the required library dependency
- # information in a form CMake can easily use directly.
- print >>f, """
-# Explicit library dependency information.
-#
-# The following property assignments effectively create a map from component
-# names to required libraries, in a way that is easily accessed from CMake."""
- for ci in self.ordered_component_infos:
- # We only write the information for libraries currently.
- if ci.type_name != 'Library':
- continue
-
- print >>f, """\
-set_property(GLOBAL PROPERTY LLVMBUILD_LIB_DEPS_%s %s)""" % (
- ci.get_prefixed_library_name(), " ".join(sorted(
- dep.get_prefixed_library_name()
- for dep in self.get_required_libraries_for_component(ci))))
-
- f.close()
-
- def write_make_fragment(self, output_path):
- """
- write_make_fragment(output_path) -> None
-
- Generate a Makefile fragment which includes all of the collated
- LLVMBuild information in a format that is easily digestible by a
- Makefile. The exact contents of this are closely tied to how the LLVM
- Makefiles integrate LLVMBuild, see Makefile.rules in the top-level.
- """
-
- dependencies = list(self.get_fragment_dependencies())
-
- # Write out the Makefile fragment.
- make_install_dir(os.path.dirname(output_path))
- f = open(output_path, 'w')
-
- # Write the header.
- header_fmt = '\
-#===-- %s - LLVMBuild Configuration for LLVM %s-*- Makefile -*--===#'
- header_name = os.path.basename(output_path)
- header_pad = '-' * (80 - len(header_fmt % (header_name, '')))
- header_string = header_fmt % (header_name, header_pad)
- print >>f, """\
-%s
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-#===------------------------------------------------------------------------===#
-#
-# This file contains the LLVMBuild project information in a format easily
-# consumed by the Makefile based build system.
-#
-# This file is autogenerated by llvm-build, do not edit!
-#
-#===------------------------------------------------------------------------===#
-""" % header_string
-
- # Write the dependencies for the fragment.
- #
- # FIXME: Technically, we need to properly quote for Make here.
- print >>f, """\
-# Clients must explicitly enable LLVMBUILD_INCLUDE_DEPENDENCIES to get
-# these dependencies. This is a compromise to help improve the
-# performance of recursive Make systems."""
- print >>f, 'ifeq ($(LLVMBUILD_INCLUDE_DEPENDENCIES),1)'
- print >>f, "# The dependencies for this Makefile fragment itself."
- print >>f, "%s: \\" % (mk_quote_string_for_target(output_path),)
- for dep in dependencies:
- print >>f, "\t%s \\" % (dep,)
- print >>f
-
- # Generate dummy rules for each of the dependencies, so that things
- # continue to work correctly if any of those files are moved or removed.
- print >>f, """\
-# The dummy targets to allow proper regeneration even when files are moved or
-# removed."""
- for dep in dependencies:
- print >>f, "%s:" % (mk_quote_string_for_target(dep),)
- print >>f, 'endif'
-
- f.close()
-
-def add_magic_target_components(parser, project, opts):
- """add_magic_target_components(project, opts) -> None
-
- Add the "magic" target based components to the project, which can only be
- determined based on the target configuration options.
-
- This currently is responsible for populating the required_libraries list of
- the "all-targets", "Native", "NativeCodeGen", and "Engine" components.
- """
-
- # Determine the available targets.
- available_targets = dict((ci.name,ci)
- for ci in project.component_infos
- if ci.type_name == 'TargetGroup')
-
- # Find the configured native target.
-
- # We handle a few special cases of target names here for historical
- # reasons, as these are the names configure currently comes up with.
- native_target_name = { 'x86' : 'X86',
- 'x86_64' : 'X86',
- 'Unknown' : None }.get(opts.native_target,
- opts.native_target)
- if native_target_name is None:
- native_target = None
- else:
- native_target = available_targets.get(native_target_name)
- if native_target is None:
- parser.error("invalid native target: %r (not in project)" % (
- opts.native_target,))
- if native_target.type_name != 'TargetGroup':
- parser.error("invalid native target: %r (not a target)" % (
- opts.native_target,))
-
- # Find the list of targets to enable.
- if opts.enable_targets is None:
- enable_targets = available_targets.values()
- else:
- # We support both space separated and semi-colon separated lists.
- if ' ' in opts.enable_targets:
- enable_target_names = opts.enable_targets.split()
- else:
- enable_target_names = opts.enable_targets.split(';')
-
- enable_targets = []
- for name in enable_target_names:
- target = available_targets.get(name)
- if target is None:
- parser.error("invalid target to enable: %r (not in project)" % (
- name,))
- if target.type_name != 'TargetGroup':
- parser.error("invalid target to enable: %r (not a target)" % (
- name,))
- enable_targets.append(target)
-
- # Find the special library groups we are going to populate. We enforce that
- # these appear in the project (instead of just adding them) so that they at
- # least have an explicit representation in the project LLVMBuild files (and
- # comments explaining how they are populated).
- def find_special_group(name):
- info = info_map.get(name)
- if info is None:
- fatal("expected project to contain special %r component" % (
- name,))
-
- if info.type_name != 'LibraryGroup':
- fatal("special component %r should be a LibraryGroup" % (
- name,))
-
- if info.required_libraries:
- fatal("special component %r must have empty %r list" % (
- name, 'required_libraries'))
- if info.add_to_library_groups:
- fatal("special component %r must have empty %r list" % (
- name, 'add_to_library_groups'))
-
- info._is_special_group = True
- return info
-
- info_map = dict((ci.name, ci) for ci in project.component_infos)
- all_targets = find_special_group('all-targets')
- native_group = find_special_group('Native')
- native_codegen_group = find_special_group('NativeCodeGen')
- engine_group = find_special_group('Engine')
-
- # Set the enabled bit in all the target groups, and append to the
- # all-targets list.
- for ci in enable_targets:
- all_targets.required_libraries.append(ci.name)
- ci.enabled = True
-
- # If we have a native target, then that defines the native and
- # native_codegen libraries.
- if native_target and native_target.enabled:
- native_group.required_libraries.append(native_target.name)
- native_codegen_group.required_libraries.append(
- '%sCodeGen' % native_target.name)
-
- # If we have a native target with a JIT, use that for the engine. Otherwise,
- # use the interpreter.
- if native_target and native_target.enabled and native_target.has_jit:
- engine_group.required_libraries.append('JIT')
- engine_group.required_libraries.append(native_group.name)
- else:
- engine_group.required_libraries.append('Interpreter')
-
-def main():
- from optparse import OptionParser, OptionGroup
- parser = OptionParser("usage: %prog [options]")
-
- group = OptionGroup(parser, "Input Options")
- group.add_option("", "--source-root", dest="source_root", metavar="PATH",
- help="Path to the LLVM source (inferred if not given)",
- action="store", default=None)
- group.add_option("", "--llvmbuild-source-root",
- dest="llvmbuild_source_root",
- help=(
- "If given, an alternate path to search for LLVMBuild.txt files"),
- action="store", default=None, metavar="PATH")
- group.add_option("", "--build-root", dest="build_root", metavar="PATH",
- help="Path to the build directory (if needed) [%default]",
- action="store", default=None)
- parser.add_option_group(group)
-
- group = OptionGroup(parser, "Output Options")
- group.add_option("", "--print-tree", dest="print_tree",
- help="Print out the project component tree [%default]",
- action="store_true", default=False)
- group.add_option("", "--write-llvmbuild", dest="write_llvmbuild",
- help="Write out the LLVMBuild.txt files to PATH",
- action="store", default=None, metavar="PATH")
- group.add_option("", "--write-library-table",
- dest="write_library_table", metavar="PATH",
- help="Write the C++ library dependency table to PATH",
- action="store", default=None)
- group.add_option("", "--write-cmake-fragment",
- dest="write_cmake_fragment", metavar="PATH",
- help="Write the CMake project information to PATH",
- action="store", default=None)
- group.add_option("", "--write-make-fragment",
- dest="write_make_fragment", metavar="PATH",
- help="Write the Makefile project information to PATH",
- action="store", default=None)
- group.add_option("", "--configure-target-def-file",
- dest="configure_target_def_files",
- help="""Configure the given file at SUBPATH (relative to
-the inferred or given source root, and with a '.in' suffix) by replacing certain
-substitution variables with lists of targets that support certain features (for
-example, targets with AsmPrinters) and write the result to the build root (as
-given by --build-root) at the same SUBPATH""",
- metavar="SUBPATH", action="append", default=None)
- parser.add_option_group(group)
-
- group = OptionGroup(parser, "Configuration Options")
- group.add_option("", "--native-target",
- dest="native_target", metavar="NAME",
- help=("Treat the named target as the 'native' one, if "
- "given [%default]"),
- action="store", default=None)
- group.add_option("", "--enable-targets",
- dest="enable_targets", metavar="NAMES",
- help=("Enable the given space or semi-colon separated "
- "list of targets, or all targets if not present"),
- action="store", default=None)
- group.add_option("", "--enable-optional-components",
- dest="optional_components", metavar="NAMES",
- help=("Enable the given space or semi-colon separated "
- "list of optional components"),
- action="store", default=None)
- parser.add_option_group(group)
-
- (opts, args) = parser.parse_args()
-
- # Determine the LLVM source path, if not given.
- source_root = opts.source_root
- if source_root:
- if not os.path.exists(os.path.join(source_root, 'lib', 'IR',
- 'Function.cpp')):
- parser.error('invalid LLVM source root: %r' % source_root)
- else:
- llvmbuild_path = os.path.dirname(__file__)
- llvm_build_path = os.path.dirname(llvmbuild_path)
- utils_path = os.path.dirname(llvm_build_path)
- source_root = os.path.dirname(utils_path)
- if not os.path.exists(os.path.join(source_root, 'lib', 'IR',
- 'Function.cpp')):
- parser.error('unable to infer LLVM source root, please specify')
-
- # Construct the LLVM project information.
- llvmbuild_source_root = opts.llvmbuild_source_root or source_root
- project_info = LLVMProjectInfo.load_from_path(
- source_root, llvmbuild_source_root)
-
- # Add the magic target based components.
- add_magic_target_components(parser, project_info, opts)
-
- # Validate the project component info.
- project_info.validate_components()
-
- # Print the component tree, if requested.
- if opts.print_tree:
- project_info.print_tree()
-
- # Write out the components, if requested. This is useful for auto-upgrading
- # the schema.
- if opts.write_llvmbuild:
- project_info.write_components(opts.write_llvmbuild)
-
- # Write out the required library table, if requested.
- if opts.write_library_table:
- project_info.write_library_table(opts.write_library_table,
- opts.optional_components)
-
- # Write out the make fragment, if requested.
- if opts.write_make_fragment:
- project_info.write_make_fragment(opts.write_make_fragment)
-
- # Write out the cmake fragment, if requested.
- if opts.write_cmake_fragment:
- project_info.write_cmake_fragment(opts.write_cmake_fragment)
-
- # Configure target definition files, if requested.
- if opts.configure_target_def_files:
- # Verify we were given a build root.
- if not opts.build_root:
- parser.error("must specify --build-root when using "
- "--configure-target-def-file")
-
- # Create the substitution list.
- available_targets = [ci for ci in project_info.component_infos
- if ci.type_name == 'TargetGroup']
- substitutions = [
- ("@LLVM_ENUM_TARGETS@",
- ' '.join('LLVM_TARGET(%s)' % ci.name
- for ci in available_targets)),
- ("@LLVM_ENUM_ASM_PRINTERS@",
- ' '.join('LLVM_ASM_PRINTER(%s)' % ci.name
- for ci in available_targets
- if ci.has_asmprinter)),
- ("@LLVM_ENUM_ASM_PARSERS@",
- ' '.join('LLVM_ASM_PARSER(%s)' % ci.name
- for ci in available_targets
- if ci.has_asmparser)),
- ("@LLVM_ENUM_DISASSEMBLERS@",
- ' '.join('LLVM_DISASSEMBLER(%s)' % ci.name
- for ci in available_targets
- if ci.has_disassembler))]
-
- # Configure the given files.
- for subpath in opts.configure_target_def_files:
- inpath = os.path.join(source_root, subpath + '.in')
- outpath = os.path.join(opts.build_root, subpath)
- result = configutil.configure_file(inpath, outpath, substitutions)
- if not result:
- note("configured file %r hasn't changed" % outpath)
-
-if __name__=='__main__':
- main()
Modified: trunk/contrib/llvm/utils/llvm-build/llvmbuild/util.py
===================================================================
--- trunk/contrib/llvm/utils/llvm-build/llvmbuild/util.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-build/llvmbuild/util.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,13 +0,0 @@
-import os
-import sys
-
-def _write_message(kind, message):
- program = os.path.basename(sys.argv[0])
- print >>sys.stderr, '%s: %s: %s' % (program, kind, message)
-
-note = lambda message: _write_message('note', message)
-warning = lambda message: _write_message('warning', message)
-error = lambda message: _write_message('error', message)
-fatal = lambda message: (_write_message('fatal error', message), sys.exit(1))
-
-__all__ = ['note', 'warning', 'error', 'fatal']
Modified: trunk/contrib/llvm/utils/llvm-compilers-check
===================================================================
--- trunk/contrib/llvm/utils/llvm-compilers-check 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-compilers-check 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,617 +0,0 @@
-#!/usr/bin/python3
-##===- utils/llvmbuild - Build the LLVM project ----------------*-python-*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-#
-# This script builds many different flavors of the LLVM ecosystem. It
-# will build LLVM, Clang and dragonegg as well as run tests on them.
-# This script is convenient to use to check builds and tests before
-# committing changes to the upstream repository
-#
-# A typical source setup uses three trees and looks like this:
-#
-# official
-# dragonegg
-# llvm
-# tools
-# clang
-# staging
-# dragonegg
-# llvm
-# tools
-# clang
-# commit
-# dragonegg
-# llvm
-# tools
-# clang
-#
-# In a typical workflow, the "official" tree always contains unchanged
-# sources from the main LLVM project repositories. The "staging" tree
-# is where local work is done. A set of changes resides there waiting
-# to be moved upstream. The "commit" tree is where changes from
-# "staging" make their way upstream. Individual incremental changes
-# from "staging" are applied to "commit" and committed upstream after
-# a successful build and test run. A successful build is one in which
-# testing results in no more failures than seen in the testing of the
-# "official" tree.
-#
-# A build may be invoked as such:
-#
-# llvmbuild --src=~/llvm/commit --src=~/llvm/staging --src=~/llvm/official
-# --build=debug --build=release --build=paranoid
-# --prefix=/home/greened/install --builddir=/home/greened/build
-#
-# This will build the LLVM ecosystem, including LLVM, Clangand
-# dragonegg, putting build results in ~/build and installing tools in
-# ~/install. llvm-compilers-check creates separate build and install
-# directories for each source/build flavor. In the above example,
-# llvmbuild will build debug, release and paranoid (debug+checks)
-# flavors from each source tree (official, staging and commit) for a
-# total of nine builds. All builds will be run in parallel.
-#
-# The user may control parallelism via the --jobs and --threads
-# switches. --jobs tells llvm-compilers-checl the maximum total
-# number of builds to activate in parallel. The user may think of it
-# as equivalent to the GNU make -j switch. --threads tells
-# llvm-compilers-check how many worker threads to use to accomplish
-# those builds. If --threads is less than --jobs, --threads workers
-# will be launched and each one will pick a source/flavor combination
-# to build. Then llvm-compilers-check will invoke GNU make with -j
-# (--jobs / --threads) to use up the remaining job capacity. Once a
-# worker is finished with a build, it will pick another combination
-# off the list and start building it.
-#
-##===----------------------------------------------------------------------===##
-
-import optparse
-import os
-import sys
-import threading
-import queue
-import logging
-import traceback
-import subprocess
-import re
-
-# TODO: Use shutil.which when it is available (3.2 or later)
-def find_executable(executable, path=None):
- """Try to find 'executable' in the directories listed in 'path' (a
- string listing directories separated by 'os.pathsep'; defaults to
- os.environ['PATH']). Returns the complete filename or None if not
- found
- """
- if path is None:
- path = os.environ['PATH']
- paths = path.split(os.pathsep)
- extlist = ['']
- if os.name == 'os2':
- (base, ext) = os.path.splitext(executable)
- # executable files on OS/2 can have an arbitrary extension, but
- # .exe is automatically appended if no dot is present in the name
- if not ext:
- executable = executable + ".exe"
- elif sys.platform == 'win32':
- pathext = os.environ['PATHEXT'].lower().split(os.pathsep)
- (base, ext) = os.path.splitext(executable)
- if ext.lower() not in pathext:
- extlist = pathext
- for ext in extlist:
- execname = executable + ext
- if os.path.isfile(execname):
- return execname
- else:
- for p in paths:
- f = os.path.join(p, execname)
- if os.path.isfile(f):
- return f
- else:
- return None
-
-def is_executable(fpath):
- return os.path.exists(fpath) and os.access(fpath, os.X_OK)
-
-def add_options(parser):
- parser.add_option("-v", "--verbose", action="store_true",
- default=False,
- help=("Output informational messages"
- " [default: %default]"))
- parser.add_option("--src", action="append",
- help=("Top-level source directory [default: %default]"))
- parser.add_option("--build", action="append",
- help=("Build types to run [default: %default]"))
- parser.add_option("--cc", default=find_executable("cc"),
- help=("The C compiler to use [default: %default]"))
- parser.add_option("--cxx", default=find_executable("c++"),
- help=("The C++ compiler to use [default: %default]"))
- parser.add_option("--threads", default=4, type="int",
- help=("The number of worker threads to use "
- "[default: %default]"))
- parser.add_option("--jobs", "-j", default=8, type="int",
- help=("The number of simultaneous build jobs "
- "[default: %default]"))
- parser.add_option("--prefix",
- help=("Root install directory [default: %default]"))
- parser.add_option("--builddir",
- help=("Root build directory [default: %default]"))
- parser.add_option("--extra-llvm-config-flags", default="",
- help=("Extra flags to pass to llvm configure [default: %default]"))
- parser.add_option("--force-configure", default=False, action="store_true",
- help=("Force reconfigure of all components"))
- parser.add_option("--no-dragonegg", default=False, action="store_true",
- help=("Do not build dragonegg"))
- parser.add_option("--no-install", default=False, action="store_true",
- help=("Do not do installs"))
- parser.add_option("--keep-going", default=False, action="store_true",
- help=("Keep going after failures"))
- return
-
-def check_options(parser, options, valid_builds):
- # See if we're building valid flavors.
- for build in options.build:
- if (build not in valid_builds):
- parser.error("'" + build + "' is not a valid build flavor "
- + str(valid_builds))
-
- # See if we can find source directories.
- for src in options.src:
- for component in components:
- component = component.rstrip("2")
- compsrc = src + "/" + component
- if (not os.path.isdir(compsrc)):
- parser.error("'" + compsrc + "' does not exist")
-
- # See if we can find the compilers
- options.cc = find_executable(options.cc)
- options.cxx = find_executable(options.cxx)
-
- return
-
-# Find a unique short name for the given set of paths. This searches
-# back through path components until it finds unique component names
-# among all given paths.
-def get_path_abbrevs(paths):
- # Find the number of common starting characters in the last component
- # of the paths.
- unique_paths = list(paths)
-
- class NotFoundException(Exception): pass
-
- # Find a unique component of each path.
- unique_bases = unique_paths[:]
- found = 0
- while len(unique_paths) > 0:
- bases = [os.path.basename(src) for src in unique_paths]
- components = { c for c in bases }
- # Account for single entry in paths.
- if len(components) > 1 or len(components) == len(bases):
- # We found something unique.
- for c in components:
- if bases.count(c) == 1:
- index = bases.index(c)
- unique_bases[index] = c
- # Remove the corresponding path from the set under
- # consideration.
- unique_paths[index] = None
- unique_paths = [ p for p in unique_paths if p is not None ]
- unique_paths = [os.path.dirname(src) for src in unique_paths]
-
- if len(unique_paths) > 0:
- raise NotFoundException()
-
- abbrevs = dict(zip(paths, [base for base in unique_bases]))
-
- return abbrevs
-
-# Given a set of unique names, find a short character sequence that
-# uniquely identifies them.
-def get_short_abbrevs(unique_bases):
- # Find a unique start character for each path base.
- my_unique_bases = unique_bases[:]
- unique_char_starts = unique_bases[:]
- while len(my_unique_bases) > 0:
- for start, char_tuple in enumerate(zip(*[base
- for base in my_unique_bases])):
- chars = { c for c in char_tuple }
- # Account for single path.
- if len(chars) > 1 or len(chars) == len(char_tuple):
- # We found something unique.
- for c in chars:
- if char_tuple.count(c) == 1:
- index = char_tuple.index(c)
- unique_char_starts[index] = start
- # Remove the corresponding path from the set under
- # consideration.
- my_unique_bases[index] = None
- my_unique_bases = [ b for b in my_unique_bases
- if b is not None ]
- break
-
- if len(my_unique_bases) > 0:
- raise NotFoundException()
-
- abbrevs = [abbrev[start_index:start_index+3]
- for abbrev, start_index
- in zip([base for base in unique_bases],
- [index for index in unique_char_starts])]
-
- abbrevs = dict(zip(unique_bases, abbrevs))
-
- return abbrevs
-
-class Builder(threading.Thread):
- class ExecutableNotFound(Exception): pass
- class FileNotExecutable(Exception): pass
-
- def __init__(self, work_queue, jobs,
- build_abbrev, source_abbrev,
- options):
- super().__init__()
- self.work_queue = work_queue
- self.jobs = jobs
- self.cc = options.cc
- self.cxx = options.cxx
- self.build_abbrev = build_abbrev
- self.source_abbrev = source_abbrev
- self.build_prefix = options.builddir
- self.install_prefix = options.prefix
- self.options = options
- self.component_abbrev = dict(
- llvm="llvm",
- dragonegg="degg")
- def run(self):
- while True:
- try:
- source, build = self.work_queue.get()
- self.dobuild(source, build)
- except:
- traceback.print_exc()
- finally:
- self.work_queue.task_done()
-
- def execute(self, command, execdir, env, component):
- prefix = self.component_abbrev[component.replace("-", "_")]
- pwd = os.getcwd()
- if not os.path.exists(execdir):
- os.makedirs(execdir)
-
- execenv = os.environ.copy()
-
- for key, value in env.items():
- execenv[key] = value
-
- self.logger.debug("[" + prefix + "] " + "env " + str(env) + " "
- + " ".join(command));
-
- try:
- proc = subprocess.Popen(command,
- cwd=execdir,
- env=execenv,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
-
- line = proc.stdout.readline()
- while line:
- self.logger.info("[" + prefix + "] "
- + str(line, "utf-8").rstrip())
- line = proc.stdout.readline()
-
- (stdoutdata, stderrdata) = proc.communicate()
- retcode = proc.wait()
-
- return retcode
-
- except:
- traceback.print_exc()
-
- # Get a list of C++ include directories to pass to clang.
- def get_includes(self):
- # Assume we're building with g++ for now.
- command = [self.cxx]
- command += ["-v", "-x", "c++", "/dev/null", "-fsyntax-only"]
- includes = []
- self.logger.debug(command)
- try:
- proc = subprocess.Popen(command,
- stdout=subprocess.PIPE,
- stderr=subprocess.STDOUT)
-
- gather = False
- line = proc.stdout.readline()
- while line:
- self.logger.debug(line)
- if re.search("End of search list", str(line)) is not None:
- self.logger.debug("Stop Gather")
- gather = False
- if gather:
- includes.append(str(line, "utf-8").strip())
- if re.search("#include <...> search starts", str(line)) is not None:
- self.logger.debug("Start Gather")
- gather = True
- line = proc.stdout.readline()
-
- except:
- traceback.print_exc()
- self.logger.debug(includes)
- return includes
-
- def dobuild(self, source, build):
- build_suffix = ""
-
- ssabbrev = get_short_abbrevs([ab for ab in self.source_abbrev.values()])
-
- prefix = "[" + ssabbrev[self.source_abbrev[source]] + "-" + self.build_abbrev[build] + "]"
- self.install_prefix += "/" + self.source_abbrev[source] + "/" + build
- build_suffix += "/" + self.source_abbrev[source] + "/" + build
-
- self.logger = logging.getLogger(prefix)
-
- self.logger.debug(self.install_prefix)
-
- # Assume we're building with gcc for now.
- cxxincludes = self.get_includes()
- cxxroot = os.path.dirname(cxxincludes[0]) # Remove the version
- cxxroot = os.path.dirname(cxxroot) # Remove the c++
- cxxroot = os.path.dirname(cxxroot) # Remove the include
-
- configure_flags = dict(
- llvm=dict(debug=["--prefix=" + self.install_prefix,
- "--enable-werror",
- "--enable-assertions",
- "--disable-optimized",
- "--with-gcc-toolchain=" + cxxroot],
- release=["--prefix=" + self.install_prefix,
- "--enable-werror",
- "--enable-optimized",
- "--with-gcc-toolchain=" + cxxroot],
- paranoid=["--prefix=" + self.install_prefix,
- "--enable-werror",
- "--enable-assertions",
- "--enable-expensive-checks",
- "--disable-optimized",
- "--with-gcc-toolchain=" + cxxroot]),
- dragonegg=dict(debug=[],
- release=[],
- paranoid=[]))
-
- configure_env = dict(
- llvm=dict(debug=dict(CC=self.cc,
- CXX=self.cxx),
- release=dict(CC=self.cc,
- CXX=self.cxx),
- paranoid=dict(CC=self.cc,
- CXX=self.cxx)),
- dragonegg=dict(debug=dict(CC=self.cc,
- CXX=self.cxx),
- release=dict(CC=self.cc,
- CXX=self.cxx),
- paranoid=dict(CC=self.cc,
- CXX=self.cxx)))
-
- make_flags = dict(
- llvm=dict(debug=["-j" + str(self.jobs)],
- release=["-j" + str(self.jobs)],
- paranoid=["-j" + str(self.jobs)]),
- dragonegg=dict(debug=["-j" + str(self.jobs)],
- release=["-j" + str(self.jobs)],
- paranoid=["-j" + str(self.jobs)]))
-
- make_env = dict(
- llvm=dict(debug=dict(),
- release=dict(),
- paranoid=dict()),
- dragonegg=dict(debug=dict(GCC=self.cc,
- LLVM_CONFIG=self.install_prefix + "/bin/llvm-config"),
- release=dict(GCC=self.cc,
- LLVM_CONFIG=self.install_prefix + "/bin/llvm-config"),
- paranoid=dict(GCC=self.cc,
- LLVM_CONFIG=self.install_prefix + "/bin/llvm-config")))
-
- make_install_flags = dict(
- llvm=dict(debug=["install"],
- release=["install"],
- paranoid=["install"]),
- dragonegg=dict(debug=["install"],
- release=["install"],
- paranoid=["install"]))
-
- make_install_env = dict(
- llvm=dict(debug=dict(),
- release=dict(),
- paranoid=dict()),
- dragonegg=dict(debug=dict(),
- release=dict(),
- paranoid=dict()))
-
- make_check_flags = dict(
- llvm=dict(debug=["check"],
- release=["check"],
- paranoid=["check"]),
- dragonegg=dict(debug=["check"],
- release=["check"],
- paranoid=["check"]))
-
- make_check_env = dict(
- llvm=dict(debug=dict(),
- release=dict(),
- paranoid=dict()),
- dragonegg=dict(debug=dict(),
- release=dict(),
- paranoid=dict()))
-
- for component in components:
- comp = component[:]
-
- if (self.options.no_dragonegg):
- if (comp == 'dragonegg'):
- self.logger.info("Skipping " + component + " in "
- + builddir)
- continue
-
- srcdir = source + "/" + comp.rstrip("2")
- builddir = self.build_prefix + "/" + comp + "/" + build_suffix
- installdir = self.install_prefix
-
- comp_key = comp.replace("-", "_")
-
- config_args = configure_flags[comp_key][build][:]
- config_args.extend(getattr(self.options,
- "extra_" + comp_key.rstrip("2")
- + "_config_flags",
- "").split())
-
- self.logger.info("Configuring " + component + " in " + builddir)
- configrc = self.configure(component, srcdir, builddir,
- config_args,
- configure_env[comp_key][build])
-
- if (configrc == None) :
- self.logger.info("[None] Failed to configure " + component + " in " + installdir)
-
- if (configrc == 0 or self.options.keep_going) :
- self.logger.info("Building " + component + " in " + builddir)
- self.logger.info("Build: make " + str(make_flags[comp_key][build]))
- buildrc = self.make(component, srcdir, builddir,
- make_flags[comp_key][build],
- make_env[comp_key][build])
-
- if (buildrc == None) :
- self.logger.info("[None] Failed to build " + component + " in " + installdir)
-
- if (buildrc == 0 or self.options.keep_going) :
- self.logger.info("Testing " + component + " in " + builddir)
- self.logger.info("Test: make "
- + str(make_check_flags[comp_key][build]))
- testrc = self.make(component, srcdir, builddir,
- make_check_flags[comp_key][build],
- make_check_env[comp_key][build])
-
- if (testrc == None) :
- self.logger.info("[None] Failed to test " + component + " in " + installdir)
-
- if ((testrc == 0 or self.options.keep_going)
- and not self.options.no_install):
- self.logger.info("Installing " + component + " in " + installdir)
- self.make(component, srcdir, builddir,
- make_install_flags[comp_key][build],
- make_install_env[comp_key][build])
- else :
- self.logger.info("Failed testing " + component + " in " + installdir)
-
- else :
- self.logger.info("Failed to build " + component + " in " + installdir)
-
- else :
- self.logger.info("Failed to configure " + component + " in " + installdir)
-
- def configure(self, component, srcdir, builddir, flags, env):
- prefix = self.component_abbrev[component.replace("-", "_")]
-
- self.logger.debug("Configure " + str(flags) + " " + str(srcdir) + " -> "
- + str(builddir))
-
- configure_files = dict(
- llvm=[(srcdir + "/configure", builddir + "/Makefile")],
- dragonegg=[(None,None)])
-
-
- doconfig = False
- for conf, mf in configure_files[component.replace("-", "_")]:
- if conf is None:
- # No configure necessary
- return 0
-
- if not os.path.exists(conf):
- self.logger.info("[" + prefix + "] Configure failed, no configure script " + conf)
- return -1
-
- if not os.path.exists(mf):
- self.logger.info("[" + prefix + "] Configure failed, no makefile " + mf)
- return -1
-
- if os.path.exists(conf) and os.path.exists(mf):
- confstat = os.stat(conf)
- makestat = os.stat(mf)
- if confstat.st_mtime > makestat.st_mtime:
- doconfig = True
- break
- else:
- doconfig = True
- break
-
- if not doconfig and not self.options.force_configure:
- return 0
-
- program = srcdir + "/configure"
- if not is_executable(program):
- self.logger.info("[" + prefix + "] Configure failed, cannot execute " + program)
- return -1
-
- args = [program]
- args += ["--verbose"]
- args += flags
- return self.execute(args, builddir, env, component)
-
- def make(self, component, srcdir, builddir, flags, env):
- program = find_executable("make")
- if program is None:
- raise ExecutableNotFound
-
- if not is_executable(program):
- raise FileNotExecutable
-
- args = [program]
- args += flags
- return self.execute(args, builddir, env, component)
-
-# Global constants
-build_abbrev = dict(debug="dbg", release="opt", paranoid="par")
-components = ["llvm", "dragonegg"]
-
-# Parse options
-parser = optparse.OptionParser(version="%prog 1.0")
-add_options(parser)
-(options, args) = parser.parse_args()
-check_options(parser, options, build_abbrev.keys());
-
-if options.verbose:
- logging.basicConfig(level=logging.DEBUG,
- format='%(name)-13s: %(message)s')
-else:
- logging.basicConfig(level=logging.INFO,
- format='%(name)-13s: %(message)s')
-
-source_abbrev = get_path_abbrevs(set(options.src))
-
-work_queue = queue.Queue()
-
-jobs = options.jobs // options.threads
-if jobs == 0:
- jobs = 1
-
-numthreads = options.threads
-
-logging.getLogger().info("Building with " + str(options.jobs) + " jobs and "
- + str(numthreads) + " threads using " + str(jobs)
- + " make jobs")
-
-logging.getLogger().info("CC = " + str(options.cc))
-logging.getLogger().info("CXX = " + str(options.cxx))
-
-for t in range(numthreads):
- builder = Builder(work_queue, jobs,
- build_abbrev, source_abbrev,
- options)
- builder.daemon = True
- builder.start()
-
-for build in set(options.build):
- for source in set(options.src):
- work_queue.put((source, build))
-
-work_queue.join()
Modified: trunk/contrib/llvm/utils/llvm-lit/llvm-lit.in
===================================================================
--- trunk/contrib/llvm/utils/llvm-lit/llvm-lit.in 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-lit/llvm-lit.in 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,32 +0,0 @@
-#!/usr/bin/env python
-
-import os
-import sys
-
-# Variables configured at build time.
-llvm_source_root = "@LLVM_SOURCE_DIR@"
-llvm_obj_root = "@LLVM_BINARY_DIR@"
-
-# Make sure we can find the lit package.
-sys.path.insert(0, os.path.join(llvm_source_root, 'utils', 'lit'))
-
-# Set up some builtin parameters, so that by default the LLVM test suite
-# configuration file knows how to find the object tree.
-builtin_parameters = {
- 'build_mode' : "@CMAKE_CFG_INTDIR@",
- 'llvm_site_config' : os.path.join(llvm_obj_root, 'test', 'lit.site.cfg')
- }
-
-clang_obj_root = os.path.join(llvm_obj_root, 'tools', 'clang')
-
-if os.path.exists(clang_obj_root):
- builtin_parameters['clang_site_config'] = \
- os.path.join(clang_obj_root, 'test', 'lit.site.cfg')
- clang_tools_extra_obj_root = os.path.join(clang_obj_root, 'tools', 'extra')
- if os.path.exists(clang_tools_extra_obj_root):
- builtin_parameters['clang_tools_extra_site_config'] = \
- os.path.join(clang_tools_extra_obj_root, 'test', 'lit.site.cfg')
-
-if __name__=='__main__':
- import lit
- lit.main(builtin_parameters)
Modified: trunk/contrib/llvm/utils/llvm-native-gcc
===================================================================
--- trunk/contrib/llvm/utils/llvm-native-gcc 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-native-gcc 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,249 +0,0 @@
-#!/usr/bin/perl
-# Wrapper around LLVM tools to generate a native .o from llvm-gcc using an
-# LLVM back-end (CBE by default).
-
-# set up defaults.
-$Verbose = 0;
-$SaveTemps = 1;
-$PreprocessOnly = 0;
-$CompileDontLink = 0;
-$Backend = 'cbe';
-chomp ($ProgramName = `basename $0`);
-
-sub boldprint {
- print "[1m", @_, "[0m";
-}
-
-# process command-line options.
-# most of these are passed on to llvm-gcc.
-$GCCOptions = "";
-for ($i = 0; $i <= $#ARGV; ++$i) {
- if ($ARGV[$i] =~ /-mllvm-backend=([a-z0-9]*)/) {
- $Backend = $1;
- if ($ProgramName =~ /llvm-native-gcc/) {
- splice (@ARGV, $i, 1);
- --$i;
- }
- } elsif ($ARGV[$i] eq "-E") {
- $PreprocessOnly = 1;
- } elsif ($ARGV[$i] eq "-c") {
- $GCCOptions .= " " . $ARGV[$i];
- $CompileDontLink = 1;
- } elsif ($ARGV[$i] eq "-v") {
- $GCCOptions .= " " . $ARGV[$i];
- $Verbose = 1;
- } elsif ($ARGV[$i] eq "-o") {
- $OutputFile = $ARGV[$i + 1];
- } elsif ($ARGV[$i] eq "-save-temps") {
- $GCCOptions .= " " . $ARGV[$i];
- $SaveTemps = 1;
- } elsif ($ARGV[$i] =~ /\.bc$/) {
- push (@BytecodeFiles, $ARGV[$i]);
- } elsif ($ARGV[$i] =~ /^-L/) {
- $GCCOptions .= " " . $ARGV[$i];
- push (@LibDirs, $ARGV[$i]);
- } elsif ($ARGV[$i] =~ /^-l/) {
- $GCCOptions .= " " . $ARGV[$i];
- push (@Libs, $ARGV[$i]);
- } elsif ($ARGV[$i] =~ /\.(c|cpp|cc|i|ii|C)$/) {
- $LastCFile = $ARGV[$i];
- }
-}
-
-sub GetDefaultOutputFileName {
- my $DefaultOutputFileBase;
-
- if ($ProgramName =~ /llvm-native-gcc/) {
- $DefaultOutputFileBase = $LastCFile;
- } elsif ($ProgramName =~ /native-build/) {
- $DefaultOutputFileBase = $BytecodeFiles[0];
- }
-
- my $def = $DefaultOutputFileBase;
-
- die "Can't figure out name of output file.\n"
- unless $DefaultOutputFileBase
- && (($ProgramName !~ /native-build/)
- || $#BytecodeFiles == 0);
-
- print "Warning: defaulting output file name ",
- "based on '$DefaultOutputFileBase'\n" if $Verbose;
-
- if ($ProgramName =~ /llvm-native-gcc/) {
- $def =~ s/\.(c|cpp|cc|i|ii|C)$/.o/;
- } elsif ($ProgramName =~ /native-build/) {
- $def =~ s/\.bc$/.$Backend/;
- if ($CompileDontLink) {
- $def .= ".o";
- }
- }
-
- return $def;
-}
-
-# run a command, optionally echoing, and quitting if it fails:
-sub run {
- my $command = join(" ", @_);
- print "$command\n" if $Verbose;
- $command =~ s/\"/\\\"/g;
- system $command and die "$0: $command failed";
-}
-
-sub LinkBytecodeFilesIntoTemporary {
- my $FinalOutputFileName = shift @_;
- my @BytecodeFiles = @_;
-
- my $BCFiles = join (" ", @BytecodeFiles);
- my $LinkedBCFile;
- if ($SaveTemps) {
- $LinkedBCFile = "${FinalOutputFileName}.llvm.bc";
- } else {
- $LinkedBCFile = "/tmp/nativebuild-$$.llvm.bc";
- }
- run "llvm-link -o $LinkedBCFile $BCFiles";
- return $LinkedBCFile;
-}
-
-sub CompileBytecodeToNative {
- my ($BCFile, $Backend, $OutputFile) = @_;
-
- my $GeneratedCode;
- if ($Backend eq 'cbe') {
- if ($SaveTemps) {
- $GeneratedCode = "${OutputFile}.c";
- } else {
- $GeneratedCode = "/tmp/nativebuild-$$.c";
- }
- run "llc -enable-correct-eh-support -march=c -f -o $GeneratedCode $BCFile";
- } elsif ($Backend eq 'llc') {
- if ($SaveTemps) {
- $GeneratedCode = "${OutputFile}.s";
- } else {
- $GeneratedCode = "/tmp/nativebuild-$$.s";
- }
- run "llc -enable-correct-eh-support -f -o $GeneratedCode $BCFile";
- }
- my $LibDirs = join (" ", @LibDirs);
- my $Libs = join (" ", @Libs);
- run "gcc $GCCOptions $GeneratedCode -o $OutputFile $LibDirs $Libs";
- run "rm $BCFile $GeneratedCode"
- unless $SaveTemps;
-}
-
-sub CompileCToNative {
- my ($LLVMGCCCommand, $Backend, $OutputFile) = @_;
- run $LLVMGCCCommand;
- if ($PreprocessOnly) {
- return;
- }
- my $BCFile = "${OutputFile}.llvm.bc";
- if ($CompileDontLink) {
- run "mv ${OutputFile} $BCFile";
- } else { # gccld messes with the output file name
- run "mv ${OutputFile}.bc $BCFile";
- }
- my $GeneratedCode;
- if ($Backend eq 'cbe') {
- $GeneratedCode = "${OutputFile}.cbe.c";
- run "llc -enable-correct-eh-support -march=c -f -o $GeneratedCode $BCFile";
- } elsif ($Backend eq 'llc') {
- $GeneratedCode = "${OutputFile}.llc.s";
- run "llc -enable-correct-eh-support -f -o $GeneratedCode $BCFile";
- }
- my $NativeGCCOptions = "";
- if ($CompileDontLink) {
- $NativeGCCOptions = "-c";
- }
- run "gcc $NativeGCCOptions $GeneratedCode -o $OutputFile";
- run "rm ${OutputFile}.llvm.bc $GeneratedCode"
- unless $SaveTemps;
-}
-
-# guess the name of the output file, if -o was not specified.
-$OutputFile = GetDefaultOutputFileName () unless $OutputFile;
-print "Output file is $OutputFile\n" if $Verbose;
-# do all the dirty work:
-if ($ProgramName eq /native-build/) {
- my $LinkedBCFile = LinkBytecodeFilesIntoTemporary (@BytecodeFiles);
- CompileBytecodeToNative ($LinkedBCFile, $Backend, $OutputFile);
-} elsif ($ProgramName =~ /llvm-native-gcc/) {
- # build the llvm-gcc command line.
- $LLVMGCCCommand = join (" ", ("llvm-gcc", @ARGV));
- CompileCToNative ($LLVMGCCCommand, $Backend, $OutputFile);
-}
-
-# we're done.
-exit 0;
-
-__END__
-
-=pod
-
-=head1 NAME
-
-llvm-native-gcc
-
-=head1 SYNOPSIS
-
-llvm-native-gcc [OPTIONS...] FILE
-
-native-build [OPTIONS...] FILE
-
-=head1 DESCRIPTION
-
-llvm-native-gcc is a wrapper around the LLVM command-line tools which generates
-a native object (.o) file by compiling FILE with llvm-gcc, and then running
-an LLVM back-end (CBE by default) over the resulting bitcode, and then
-compiling the resulting code to a native object file.
-
-If called as "native-build", it compiles bitcode to native code, and takes
-different options.
-
-=head1 OPTIONS
-
-llvm-native-gcc takes the same options as llvm-gcc. All options
-except -mllvm-backend=... are passed on to llvm-gcc.
-
-=over 4
-
-=item -mllvm-backend=BACKEND
-
-Use BACKEND for native code generation.
-
-=item -v
-
-Print command lines that llvm-native-gcc runs.
-
-=item -o FILE
-
-llvm-native-gcc tries to guess the name of the llvm-gcc output file by looking
-for this option in the command line. If it can't find it, it finds the last C
-or C++ source file named on the command line, and turns its suffix into .o. See
-BUGS.
-
-=item -save-temps
-
-Save temporary files used by llvm-native-gcc (and llvm-gcc, and gcc).
-
-=back
-
-=head1 BUGS
-
-llvm-native-gcc only handles the case where llvm-gcc compiles a single
-file per invocation. llvm-native-gcc has weak command-line argument
-parsing and is a poor substitute for making gcc/gcc.c do this stuff.
-
-This manual page does not adequately document native-build mode.
-
-llvm-native-gcc is pretty gross because it represents the blind merging of two
-other scripts that predated it. It could use some code clean-up.
-
-=head1 SEE ALSO
-
-gcc(1)
-
-=head1 AUTHOR
-
-Brian R. Gaeke
-
-=cut
Modified: trunk/contrib/llvm/utils/llvm-native-gxx
===================================================================
--- trunk/contrib/llvm/utils/llvm-native-gxx 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm-native-gxx 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,249 +0,0 @@
-#!/usr/bin/perl
-# Wrapper around LLVM tools to generate a native .o from llvm-gxx using an
-# LLVM back-end (CBE by default).
-
-# set up defaults.
-$Verbose = 0;
-$SaveTemps = 1;
-$PreprocessOnly = 0;
-$CompileDontLink = 0;
-$Backend = 'cbe';
-chomp ($ProgramName = `basename $0`);
-
-sub boldprint {
- print "[1m", @_, "[0m";
-}
-
-# process command-line options.
-# most of these are passed on to llvm-gxx.
-$GCCOptions = "";
-for ($i = 0; $i <= $#ARGV; ++$i) {
- if ($ARGV[$i] =~ /-mllvm-backend=([a-z0-9]*)/) {
- $Backend = $1;
- if ($ProgramName =~ /llvm-native-gxx/) {
- splice (@ARGV, $i, 1);
- --$i;
- }
- } elsif ($ARGV[$i] eq "-E") {
- $PreprocessOnly = 1;
- } elsif ($ARGV[$i] eq "-c") {
- $GCCOptions .= " " . $ARGV[$i];
- $CompileDontLink = 1;
- } elsif ($ARGV[$i] eq "-v") {
- $GCCOptions .= " " . $ARGV[$i];
- $Verbose = 1;
- } elsif ($ARGV[$i] eq "-o") {
- $OutputFile = $ARGV[$i + 1];
- } elsif ($ARGV[$i] eq "-save-temps") {
- $GCCOptions .= " " . $ARGV[$i];
- $SaveTemps = 1;
- } elsif ($ARGV[$i] =~ /\.bc$/) {
- push (@BytecodeFiles, $ARGV[$i]);
- } elsif ($ARGV[$i] =~ /^-L/) {
- $GCCOptions .= " " . $ARGV[$i];
- push (@LibDirs, $ARGV[$i]);
- } elsif ($ARGV[$i] =~ /^-l/) {
- $GCCOptions .= " " . $ARGV[$i];
- push (@Libs, $ARGV[$i]);
- } elsif ($ARGV[$i] =~ /\.(c|cpp|cc|i|ii|C)$/) {
- $LastCFile = $ARGV[$i];
- }
-}
-
-sub GetDefaultOutputFileName {
- my $DefaultOutputFileBase;
-
- if ($ProgramName =~ /llvm-native-gxx/) {
- $DefaultOutputFileBase = $LastCFile;
- } elsif ($ProgramName =~ /native-build/) {
- $DefaultOutputFileBase = $BytecodeFiles[0];
- }
-
- my $def = $DefaultOutputFileBase;
-
- die "Can't figure out name of output file.\n"
- unless $DefaultOutputFileBase
- && (($ProgramName !~ /native-build/)
- || $#BytecodeFiles == 0);
-
- print "Warning: defaulting output file name ",
- "based on '$DefaultOutputFileBase'\n" if $Verbose;
-
- if ($ProgramName =~ /llvm-native-gxx/) {
- $def =~ s/\.(c|cpp|cc|i|ii|C)$/.o/;
- } elsif ($ProgramName =~ /native-build/) {
- $def =~ s/\.bc$/.$Backend/;
- if ($CompileDontLink) {
- $def .= ".o";
- }
- }
-
- return $def;
-}
-
-# run a command, optionally echoing, and quitting if it fails:
-sub run {
- my $command = join(" ", @_);
- print "$command\n" if $Verbose;
- $command =~ s/\"/\\\"/g;
- system $command and die "$0: $command failed";
-}
-
-sub LinkBytecodeFilesIntoTemporary {
- my $FinalOutputFileName = shift @_;
- my @BytecodeFiles = @_;
-
- my $BCFiles = join (" ", @BytecodeFiles);
- my $LinkedBCFile;
- if ($SaveTemps) {
- $LinkedBCFile = "${FinalOutputFileName}.llvm.bc";
- } else {
- $LinkedBCFile = "/tmp/nativebuild-$$.llvm.bc";
- }
- run "llvm-link -o $LinkedBCFile $BCFiles";
- return $LinkedBCFile;
-}
-
-sub CompileBytecodeToNative {
- my ($BCFile, $Backend, $OutputFile) = @_;
-
- my $GeneratedCode;
- if ($Backend eq 'cbe') {
- if ($SaveTemps) {
- $GeneratedCode = "${OutputFile}.c";
- } else {
- $GeneratedCode = "/tmp/nativebuild-$$.c";
- }
- run "llc -march=c -f -o $GeneratedCode $BCFile";
- } elsif ($Backend eq 'llc') {
- if ($SaveTemps) {
- $GeneratedCode = "${OutputFile}.s";
- } else {
- $GeneratedCode = "/tmp/nativebuild-$$.s";
- }
- run "llc -f -o $GeneratedCode $BCFile";
- }
- my $LibDirs = join (" ", @LibDirs);
- my $Libs = join (" ", @Libs);
- run "gcc $GCCOptions $GeneratedCode -o $OutputFile $LibDirs $Libs";
- run "rm $BCFile $GeneratedCode"
- unless $SaveTemps;
-}
-
-sub CompileCToNative {
- my ($LLVMGCCCommand, $Backend, $OutputFile) = @_;
- run $LLVMGCCCommand;
- if ($PreprocessOnly) {
- return;
- }
- my $BCFile = "${OutputFile}.llvm.bc";
- if ($CompileDontLink) {
- run "mv ${OutputFile} $BCFile";
- } else { # gccld messes with the output file name
- run "mv ${OutputFile}.bc $BCFile";
- }
- my $GeneratedCode;
- if ($Backend eq 'cbe') {
- $GeneratedCode = "${OutputFile}.cbe.c";
- run "llc -march=c -f -o $GeneratedCode $BCFile";
- } elsif ($Backend eq 'llc') {
- $GeneratedCode = "${OutputFile}.llc.s";
- run "llc -f -o $GeneratedCode $BCFile";
- }
- my $NativeGCCOptions = "";
- if ($CompileDontLink) {
- $NativeGCCOptions = "-c";
- }
- run "gcc $NativeGCCOptions $GeneratedCode -o $OutputFile";
- run "rm ${OutputFile}.llvm.bc $GeneratedCode"
- unless $SaveTemps;
-}
-
-# guess the name of the output file, if -o was not specified.
-$OutputFile = GetDefaultOutputFileName () unless $OutputFile;
-print "Output file is $OutputFile\n" if $Verbose;
-# do all the dirty work:
-if ($ProgramName eq /native-build/) {
- my $LinkedBCFile = LinkBytecodeFilesIntoTemporary (@BytecodeFiles);
- CompileBytecodeToNative ($LinkedBCFile, $Backend, $OutputFile);
-} elsif ($ProgramName =~ /llvm-native-gxx/) {
- # build the llvm-gxx command line.
- $LLVMGCCCommand = join (" ", ("llvm-g++", @ARGV));
- CompileCToNative ($LLVMGCCCommand, $Backend, $OutputFile);
-}
-
-# we're done.
-exit 0;
-
-__END__
-
-=pod
-
-=head1 NAME
-
-llvm-native-gxx
-
-=head1 SYNOPSIS
-
-llvm-native-g++ [OPTIONS...] FILE
-
-native-build [OPTIONS...] FILE
-
-=head1 DESCRIPTION
-
-llvm-native-g++ is a wrapper around the LLVM command-line tools which generates
-a native object (.o) file by compiling FILE with llvm-g++, and then running
-an LLVM back-end (CBE by default) over the resulting bitcode, and then
-compiling the resulting code to a native object file.
-
-If called as "native-build", it compiles bitcode to native code, and takes
-different options.
-
-=head1 OPTIONS
-
-llvm-native-g++ takes the same options as llvm-gcc. All options
-except -mllvm-backend=... are passed on to llvm-g++.
-
-=over 4
-
-=item -mllvm-backend=BACKEND
-
-Use BACKEND for native code generation.
-
-=item -v
-
-Print command lines that llvm-native-g++ runs.
-
-=item -o FILE
-
-llvm-native-g++ tries to guess the name of the llvm-g++ output file by looking
-for this option in the command line. If it can't find it, it finds the last C
-or C++ source file named on the command line, and turns its suffix into .o. See
-BUGS.
-
-=item -save-temps
-
-Save temporary files used by llvm-native-g++ (and llvm-g++, and g++).
-
-=back
-
-=head1 BUGS
-
-llvm-native-g++ only handles the case where llvm-g++ compiles a single
-file per invocation. llvm-native-g++ has weak command-line argument
-parsing and is a poor substitute for making g++/g++.c do this stuff.
-
-This manual page does not adequately document native-build mode.
-
-llvm-native-g++ is pretty gross because it represents the blind merging of two
-other scripts that predated it. It could use some code clean-up.
-
-=head1 SEE ALSO
-
-g++(1)
-
-=head1 AUTHOR
-
-Brian R. Gaeke
-
-=cut
Modified: trunk/contrib/llvm/utils/llvm.grm
===================================================================
--- trunk/contrib/llvm/utils/llvm.grm 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvm.grm 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,423 +0,0 @@
-(*
-
-polygen grammar for LLVM assembly language.
-
-This file defines an LLVM assembly language grammar for polygen,
-which is a tool for generating random text based on a grammar.
-It is strictly syntax-based, and makes no attempt to generate
-IR that is semantically valid. Most of the IR produced doesn't
-pass the Verifier.
-
-TODO: Metadata, in all its forms
-
-*)
-
-I ::= "title: LLVM assembly language\n"
- ^ "status: experimental\n"
- ^ "audience: LLVM developers\n"
-;
-
-S ::= Module ;
-
-(*
-Define rules for non-keyword tokens. This is currently just a bunch
-of hacks. They don't cover many valid forms of tokens, and they also
-generate some invalid forms of tokens. The LLVM parser has custom
-C++ code to lex these; custom C++ code for emitting them would be
-convenient, but polygen doesn't support that.
-*)
-NonZeroDecimalDigit ::= 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ;
-DecimalDigit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 ;
-DecimalDigitSeq ::= DecimalDigit [^ DecimalDigitSeq ];
-HexDigit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
- | a | b | c | d | e | f ;
-HexDigitSeq ::= HexDigit [^ HexDigitSeq ];
-StringChar ::= a | b | c | d | e | f | g | h | i | j | k | l | m
- | n | o | p | q | r | s | t | u | v | w | x | y | z ;
-StringConstantSeq ::= StringChar [^ StringConstantSeq ];
-StringConstant ::= StringChar [^ StringConstantSeq ];
-EUINT64VAL ::= NonZeroDecimalDigit [^ DecimalDigitSeq ];
-ESINT64VAL ::= [ "-" ] ^ EUINT64VAL ;
-EUAPINTVAL ::= EUINT64VAL ;
-ESAPINTVAL ::= ESINT64VAL ;
-LOCALVALID ::= "%" ^ DecimalDigitSeq ;
-GLOBALVALID ::= "@" ^ DecimalDigitSeq ;
-INTTYPE ::= "i" ^ EUINT64VAL ;
-GLOBALVAR ::= "@" ^ StringConstant ;
-LOCALVAR ::= "%" ^ StringConstant ;
-STRINGCONSTANT ::= "\"" ^ StringConstant ^ "\"" ;
-ATSTRINGCONSTANT ::= "@" ^ STRINGCONSTANT ;
-PCTSTRINGCONSTANT ::= "%" ^ STRINGCONSTANT ;
-LABELSTR ::= StringConstant ;
-FPVAL ::= ESAPINTVAL ^ "." ^ EUAPINTVAL | "0x" ^ HexDigitSeq ;
-
-(*
-The rest of this file is derived directly from llvmAsmParser.y.
-*)
-
-ArithmeticOps ::= + OptNW add | fadd | OptNW sub | fsub | OptNW mul | fmul |
- udiv | OptExact sdiv | fdiv | urem | srem | frem ;
-LogicalOps ::= shl | lshr | ashr | and | or | xor;
-CastOps ::= trunc | zext | sext | fptrunc | fpext | bitcast |
- uitofp | sitofp | fptoui | fptosi | inttoptr | ptrtoint ;
-
-IPredicates ::= eq | ne | slt | sgt | sle | sge | ult | ugt | ule | uge ;
-
-FPredicates ::= oeq | one | olt | ogt | ole | oge | ord | uno | ueq | une
- | ult | ugt | ule | uge | true | false ;
-
-IntType ::= INTTYPE;
-FPType ::= float | double | "ppc_fp128" | fp128 | "x86_fp80";
-
-LocalName ::= LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
-OptLocalName ::= LocalName | _ ;
-
-OptAddrSpace ::= - addrspace ^ "(" ^ EUINT64VAL ^ ")" | _ ;
-
-OptLocalAssign ::= LocalName "=" | _ ;
-
-GlobalName ::= GLOBALVAR | ATSTRINGCONSTANT ;
-
-OptGlobalAssign ::= GlobalAssign | _ ;
-
-GlobalAssign ::= GlobalName "=" ;
-
-GVInternalLinkage
- ::= + internal
- | weak
- | "weak_odr"
- | linkonce
- | "linkonce_odr"
- | appending
- | dllexport
- | common
- | private
- | "linker_private"
- | "linker_private_weak"
- ;
-
-GVExternalLinkage
- ::= dllimport
- | "extern_weak"
- | + external
- ;
-
-GVVisibilityStyle
- ::= + _
- | default
- | hidden
- | protected
- ;
-
-FunctionDeclareLinkage
- ::= + _
- | dllimport
- | "extern_weak"
- ;
-
-FunctionDefineLinkage
- ::= + _
- | internal
- | linkonce
- | "linkonce_odr"
- | weak
- | "weak_odr"
- | dllexport
- ;
-
-AliasLinkage ::= + _ | weak | "weak_odr" | internal ;
-
-OptCallingConv ::= + _ |
- ccc |
- fastcc |
- coldcc |
- "x86_stdcallcc" |
- "x86_fastcallcc" |
- cc EUINT64VAL ;
-
-ParamAttr ::= zeroext
- | signext
- | inreg
- | sret
- | noalias
- | nocapture
- | byval
- | nest
- | align EUINT64VAL
- ;
-
-OptParamAttrs ::= + _ | OptParamAttrs ParamAttr ;
-
-RetAttr ::= inreg
- | zeroext
- | signext
- | noalias
- ;
-
-OptRetAttrs ::= _
- | OptRetAttrs RetAttr
- ;
-
-FuncAttr ::= noreturn
- | nounwind
- | inreg
- | zeroext
- | signext
- | readnone
- | readonly
- | inlinehint
- | alignstack
- | noinline
- | alwaysinline
- | optsize
- | ssp
- | sspreq
- | returns_twice
- | nonlazybind
- | sanitize_address
- | sanitize_thread
- | sanitize_memory
- ;
-
-OptFuncAttrs ::= + _ | OptFuncAttrs FuncAttr ;
-
-OptGC ::= + _ | gc STRINGCONSTANT ;
-
-OptAlign ::= + _ | align EUINT64VAL ;
-OptCAlign ::= + _ | ^ "," align EUINT64VAL ;
-
-SectionString ::= section STRINGCONSTANT ;
-
-OptSection ::= + _ | SectionString ;
-
-GlobalVarAttributes ::= + _ | ^ "," GlobalVarAttribute GlobalVarAttributes ;
-GlobalVarAttribute ::= SectionString | align EUINT64VAL ;
-
-PrimType ::= INTTYPE | float | double | "ppc_fp128" | fp128 | "x86_fp80"
- | - label ;
-
-Types
- ::= opaque
- | PrimType
- | Types OptAddrSpace ^ "*"
- | SymbolicValueRef
- | "\\" ^ EUINT64VAL
- | Types "(" ^ ArgTypeListI ^ ")" OptFuncAttrs
- | void "(" ^ ArgTypeListI ^ ")" OptFuncAttrs
- | "[" ^ EUINT64VAL "x" Types ^ "]"
- | "<" ^ EUINT64VAL "x" Types ^ ">"
- | "{" TypeListI "}"
- | "{" ^ "}"
- | "<" ^ "{" TypeListI "}" ^ ">"
- | "<" ^ "{" ^ "}" ^ ">"
- ;
-
-ArgType ::= Types OptParamAttrs ;
-
-ResultTypes ::= Types | void ;
-
-ArgTypeList ::= ArgType | ArgTypeList ^ "," ArgType ;
-
-ArgTypeListI ::= ArgTypeList | ArgTypeList ^ "," "..." | "..." | _ ;
-
-TypeListI ::= Types | TypeListI ^ "," Types ;
-
-ConstVal::= Types "[" ^ ConstVector ^ "]"
- | Types "[" ^ "]"
- | Types "c" ^ STRINGCONSTANT
- | Types "<" ^ ConstVector ^ ">"
- | Types "{" ConstVector "}"
- | Types "{" ^ "}"
- | Types "<" ^ "{" ConstVector "}" ^ ">"
- | Types "<" ^ "{" ^ "}" ^ ">"
- | Types null
- | Types undef
- | Types SymbolicValueRef
- | Types ConstExpr
- | Types zeroinitializer
- | Types ESINT64VAL
- | Types ESAPINTVAL
- | Types EUINT64VAL
- | Types EUAPINTVAL
- | Types true
- | Types false
- | Types FPVAL ;
-
-ConstExpr::= CastOps "(" ^ ConstVal to Types ^ ")"
- | getelementptr OptInBounds "(" ^ ConstVal IndexList ^ ")"
- | select "(" ^ ConstVal ^ "," ConstVal ^ "," ConstVal ^ ")"
- | ArithmeticOps "(" ^ ConstVal ^ "," ConstVal ^ ")"
- | LogicalOps "(" ^ ConstVal ^ "," ConstVal ^ ")"
- | icmp IPredicates "(" ^ ConstVal ^ "," ConstVal ^ ")"
- | fcmp FPredicates "(" ^ ConstVal ^ "," ConstVal ^ ")"
- | extractelement "(" ^ ConstVal ^ "," ConstVal ^ ")"
- | insertelement "(" ^ ConstVal ^ "," ConstVal ^ "," ConstVal ^ ")"
- | shufflevector "(" ^ ConstVal ^ "," ConstVal ^ "," ConstVal ^ ")"
- | extractvalue "(" ^ ConstVal ^ ConstantIndexList ^ ")"
- | insertvalue "(" ^ ConstVal ^ "," ConstVal ^ ConstantIndexList ^ ")" ;
-
-ConstVector ::= ConstVector ^ "," ConstVal | ConstVal ;
-
-GlobalType ::= global | constant ;
-
-ThreadLocal ::= - "thread_local" | _ ;
-
-AliaseeRef ::= ResultTypes SymbolicValueRef
- | bitcast "(" ^ AliaseeRef to Types ^ ")" ;
-
-Module ::= +++ DefinitionList | --- _ ;
-
-DefinitionList ::= - Definition | + DefinitionList Definition ;
-
-Definition
- ::= ^ ( +++++ define Function
- | declare FunctionProto
- | - module asm AsmBlock
- | OptLocalAssign type Types
- | OptGlobalAssign GVVisibilityStyle ThreadLocal OptAddrSpace GlobalType
- ConstVal GlobalVarAttributes
- | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal OptAddrSpace
- GlobalType ConstVal GlobalVarAttributes
- | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal OptAddrSpace
- GlobalType Types GlobalVarAttributes
- | OptGlobalAssign GVVisibilityStyle alias AliasLinkage AliaseeRef
- | target TargetDefinition
- | deplibs "=" LibrariesDefinition
- ) ^ "\n";
-
-AsmBlock ::= STRINGCONSTANT ;
-
-TargetDefinition ::= triple "=" STRINGCONSTANT
- | datalayout "=" STRINGCONSTANT ;
-
-LibrariesDefinition ::= "[" ( LibList | _ ) "]";
-
-LibList ::= LibList ^ "," STRINGCONSTANT | STRINGCONSTANT ;
-
-ArgListH ::= ArgListH ^ "," Types OptParamAttrs OptLocalName
- | Types OptParamAttrs OptLocalName ;
-
-ArgList ::= ArgListH | ArgListH ^ "," "..." | "..." | _ ;
-
-FunctionHeaderH ::= OptCallingConv OptRetAttrs ResultTypes
- GlobalName ^ "(" ^ ArgList ^ ")"
- OptFuncAttrs OptSection OptAlign OptGC ;
-
-BEGIN ::= ( begin | "{" ) ^ "\n";
-
-FunctionHeader ::=
- FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN ;
-
-END ::= ^ ( end | "}" ) ^ "\n";
-
-Function ::= BasicBlockList END ;
-
-FunctionProto ::= FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH ;
-
-OptSideEffect ::= _ | sideeffect ;
-
-ConstValueRef ::= ESINT64VAL
- | EUINT64VAL
- | FPVAL
- | true
- | false
- | null
- | undef
- | zeroinitializer
- | "<" ConstVector ">"
- | "[" ConstVector "]"
- | "[" ^ "]"
- | "c" ^ STRINGCONSTANT
- | "{" ConstVector "}"
- | "{" ^ "}"
- | "<" ^ "{" ConstVector "}" ^ ">"
- | "<" ^ "{" ^ "}" ^ ">"
- | ConstExpr
- | asm OptSideEffect STRINGCONSTANT ^ "," STRINGCONSTANT ;
-
-SymbolicValueRef ::= LOCALVALID
- | GLOBALVALID
- | LocalName
- | GlobalName ;
-
-ValueRef ::= SymbolicValueRef | ConstValueRef;
-
-ResolvedVal ::= Types ValueRef ;
-
-ReturnedVal ::= ResolvedVal | ReturnedVal ^ "," ResolvedVal ;
-
-BasicBlockList ::= BasicBlockList BasicBlock | FunctionHeader BasicBlock ;
-
-BasicBlock ::= InstructionList OptLocalAssign BBTerminatorInst ;
-
-InstructionList ::= +++ InstructionList Inst
- | - _
- | ^ LABELSTR ^ ":\n" ;
-
-BBTerminatorInst ::= ^ " " ^
- ( ret ReturnedVal
- | ret void
- | br label ValueRef
- | br INTTYPE ValueRef ^ "," label ValueRef ^ "," label ValueRef
- | switch IntType ValueRef ^ "," label ValueRef "[" JumpTable "]"
- | switch IntType ValueRef ^ "," label ValueRef "[" ^ "]"
- | invoke OptCallingConv ResultTypes ValueRef ^ "(" ^ ParamList ^ ")"
- OptFuncAttrs
- to label ValueRef unwind label ValueRef
- | unwind
- | unreachable ) ^ "\n";
-
-JumpTable ::= JumpTable IntType ConstValueRef ^ "," label ValueRef
- | IntType ConstValueRef ^ "," label ValueRef ;
-
-Inst ::= ^ " " ^ OptLocalAssign InstVal ^ "\n";
-
-PHIList ::= Types "[" ValueRef ^ "," ValueRef "]"
- | PHIList ^ "," "[" ValueRef ^ "," ValueRef "]" ;
-
-ParamList ::= Types OptParamAttrs ValueRef OptParamAttrs
- | label OptParamAttrs ValueRef OptParamAttrs
- | ParamList ^ "," Types OptParamAttrs ValueRef OptParamAttrs
- | ParamList ^ "," label OptParamAttrs ValueRef OptParamAttrs
- | - _ ;
-
-IndexList ::= _ | IndexList ^ "," ResolvedVal ;
-
-ConstantIndexList ::= "," EUINT64VAL | ConstantIndexList ^ "," EUINT64VAL ;
-
-OptTailCall ::= tail call | call ;
-
-InstVal ::=
- ArithmeticOps Types ValueRef ^ "," ValueRef
- | LogicalOps Types ValueRef ^ "," ValueRef
- | icmp IPredicates Types ValueRef ^ "," ValueRef
- | fcmp FPredicates Types ValueRef ^ "," ValueRef
- | CastOps ResolvedVal to Types
- | select ResolvedVal ^ "," ResolvedVal ^ "," ResolvedVal
- | "va_arg" ResolvedVal ^ "," Types
- | extractelement ResolvedVal ^ "," ResolvedVal
- | insertelement ResolvedVal ^ "," ResolvedVal ^ "," ResolvedVal
- | shufflevector ResolvedVal ^ "," ResolvedVal ^ "," ResolvedVal
- | phi PHIList
- | OptTailCall OptCallingConv ResultTypes ValueRef ^ "(" ^ ParamList ^ ")"
- OptFuncAttrs
- | MemoryInst ;
-
-OptVolatile ::= - volatile | _ ;
-OptExact ::= - exact | _ ;
-OptNSW ::= - nsw | _ ;
-OptNUW ::= - nuw | _ ;
-OptNW ::= OptNUW OptNSW | OptNSW OptNUW ;
-OptInBounds ::= - inbounds | _ ;
-
-MemoryInst ::= malloc Types OptCAlign
- | malloc Types ^ "," INTTYPE ValueRef OptCAlign
- | alloca Types OptCAlign
- | alloca Types ^ "," INTTYPE ValueRef OptCAlign
- | free ResolvedVal
- | OptVolatile load Types ValueRef OptCAlign
- | OptVolatile store ResolvedVal ^ "," Types ValueRef OptCAlign
- | getresult Types ValueRef ^ "," EUINT64VAL
- | getelementptr OptInBounds Types ValueRef IndexList
- | extractvalue Types ValueRef ^ ConstantIndexList
- | insertvalue Types ValueRef ^ "," Types ValueRef ^ ConstantIndexList ;
Modified: trunk/contrib/llvm/utils/llvm.natvis
===================================================================
(Binary files differ)
Modified: trunk/contrib/llvm/utils/llvmdo
===================================================================
--- trunk/contrib/llvm/utils/llvmdo 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvmdo 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,184 +0,0 @@
-#!/bin/sh
-##===- utils/llvmdo - Counts Lines Of Code -------------------*- Script -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-#
-# This script is a general purpose "apply" function for the source files in LLVM
-# It uses "find" to locate all the source files and then applies the user's
-# command to them. As such, this command is often not used by itself much but
-# the other find related tools (countloc.sh,llvmgrep,getsrcs.sh,userloc.sh) are
-# all based on this script. This script defines "what is a source file" in
-# LLVM and so should be maintained if new directories, new file extensions,
-# etc. are used in LLVM as it progresses.
-#
-# Usage:
-# llvmdo [-topdir DIR] [-dirs "DIRNAMES..."] [-code-only] PROGRAM ARGS...
-#
-# The -topdir option allows you to specify the llvm source root directly. If it
-# is not specified then it will be obtained with llvm-config which must be built
-# and in your path.
-#
-# The -dirs argument allows you to specify the set of directories that are
-# searched. The default list of directories searched is:
-# include lib tools utils runtime autoconf docs test examples projects
-# Note that you must use quotes around the list of directory names.
-#
-# The -code-only option specifies that only those files that are considered
-# "code" should be visited. HTML documentation is considered code, but things
-# like README files, etc. are not.
-#
-# Finally, you simply specify whatever program you want to run against each
-# file and the arguments to give it. The PROGRAM will be given the file name
-# as its last argument.
-##===----------------------------------------------------------------------===##
-
-if test $# -lt 1 ; then
- echo "Usage: llvmdo [-topdir DIR] [-dirs "DIRNAMES..."] [-code-only] PROGRAM ARGS..."
- exit 1
-fi
-
-if test "$1" = "-topdir" ; then
- TOPDIR="$2"
- shift; shift;
-else
- TOPDIR=`llvm-config --src-root`
-fi
-
-if test "$1" = "-dirs" ; then
- LLVMDO_DIRS="$2"
- shift ; shift
-elif test -z "$LLVMDO_DIRS" ; then
- LLVMDO_DIRS="include lib tools utils runtime autoconf docs test examples projects cmake"
-fi
-
-if test "$1" = "-code-only" ; then
- CODE_ONLY="set"
- shift
-else
- CODE_ONLY=""
-fi
-
-if test "$1" = "" ; then
- echo "Missing program name to run"
- exit 1
-fi
-
-PROGRAM=`which $1`
-if test ! -x "$PROGRAM" ; then
- echo "Can't execute $1"
- exit 1
-fi
-shift;
-
-paths_to_ignore="\
- -path */.svn/ -o \
- -path */.svn/* -o \
- -path docs/doxygen/* -o \
- -path docs/CommandGuide/html/* -o \
- -path docs/CommandGuide/man/* -o \
- -path docs/CommandGuide/ps/* -o \
- -path docs/CommandGuide/man/* -o \
- -path docs/HistoricalNotes/* -o \
- -path docs/img/* -o \
- -path */.libs/* -o \
- -path lib/Support/bzip2/* -o \
- -path projects/llvm-test/* \
-"
-files_to_match="\
- -name *.ac \
- -o -name *.b \
- -o -name *.c \
- -o -name *.cc \
- -o -name *.cfg \
- -o -name *.cpp \
- -o -name *.css \
- -o -name *.def \
- -o -name *.el \
- -o -name *.exp \
- -o -name *.footer \
- -o -name *.gnuplot' \
- -o -name *.h \
- -o -name *.header \
- -o -name *.html \
- -o -name *.in \
- -o -name *.inc \
- -o -name *.intro \
- -o -name *.l \
- -o -name *.ll \
- -o -name *.lst \
- -o -name *.m4 \
- -o -name *.pod \
- -o -name *.pl \
- -o -name *.py \
- -o -name *.sh \
- -o -name *.schema \
- -o -name *.st \
- -o -name *.tcl \
- -o -name *.td \
- -o -name *.tr \
- -o -name *.y \
- -o -name Make* \
- -o -name *.cmake \
- -o -name llvmdo \
- -o -name llvmgrep \
- -o -name check-each-file \
- -o -name codgen-diff \
- -o -name llvm-native-gcc \
- -o -name llvm-native-gxx \
- -o -name makellvm \
- -o -path include/llvm/ADT/ilist \
- -o -path test/\*.ll \
- -o -path test/Scripts/not \
- -o -path runtime/\*.ll \
-"
-if test -z "$CODE_ONLY" ; then
- files_to_match="$files_to_match \
- -o -name *.txt \
- -o -name *.TXT \
- -o -name *.vim \
- -o -name vimrc \
- -o -name README \
- -o -name COPYING.LIB \
- -o -name LICENSE* "
-fi
-files_to_ignore="\
- -name \.* \
- -o -name *~ \
- -o -name #* \
- -o -name configure \
- -o -name slow.ll \
- -o -name *libtool* \
- -o -name ltdl* \
- -o -name ltdl.m4 \
- -o -name ltmain.m4 \
- -o -name ltmain.sh \
- -o -name aclocal.m4 \
- -o -name acinclude.m4 \
- -o -name *LoopSimplifyCrash.ll \
- -o -name *AST-Remove.ll \
- -o -name PPCPerfectShuffle.h \
-"
-
-if test -d "$TOPDIR" ; then
- cd $TOPDIR
- # Have to use the right "find" on a per-platform basis. Most platforms have
- # Gnu find as "find", but Solaris does not.
- case `uname -s` in
- SunOS) find_prog=gfind ;;
- *) find_prog=find ;;
- esac
- # Turn off file name generation (globbing) so that substitution of the
- # variables doesn't cause the shell to create lists of file names
- set -f
- $find_prog $LLVMDO_DIRS -type f \
- \( $paths_to_ignore \) -prune \
- -o \( \( $files_to_match \) \! \( $files_to_ignore \) \
- -exec $PROGRAM "$@" {} \; \)
-else
- echo "Can't find LLVM top directory in $TOPDIR"
-fi
Modified: trunk/contrib/llvm/utils/llvmgrep
===================================================================
--- trunk/contrib/llvm/utils/llvmgrep 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/llvmgrep 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,39 +0,0 @@
-#!/bin/sh
-##===- utils/llvmgrep - Counts Lines Of Code -----------------*- Script -*-===##
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License. See LICENSE.TXT for details.
-#
-##===----------------------------------------------------------------------===##
-#
-# This script searches your srcdir for an egrep style pattern. This can quickly
-# help you build a list of the places you need to modify when changing a header
-# or other "global" name. The only argument is the pattern you want to search
-# for. It should be quoted to escape shell interpretation of the pattern's
-# special characters.
-#
-# Note that the implementation is based on llvmdo. See that script for more
-# details.
-##===----------------------------------------------------------------------===##
-
-if test "$1" = "-topdir" ; then
- TOPDIR="$2"
- shift; shift;
-else
- TOPDIR=`llvm-config --src-root`
-fi
-
-if test -d "$TOPDIR" ; then
- cd $TOPDIR
- case `uname -s` in
- SunOS) grep_cmd="ggrep -H -n" ;;
- Linux|Darwin) grep_cmd="egrep -H -n" ;;
- *) grep_cmd="egrep -l -n" ;;
- esac
- ./utils/llvmdo -topdir "$TOPDIR" \
- -dirs "include lib tools utils docs examples test unittests projects cmake" $grep_cmd "$*"
-else
- echo "Can't find LLVM top directory"
-fi
Modified: trunk/contrib/llvm/utils/makellvm
===================================================================
--- trunk/contrib/llvm/utils/makellvm 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/makellvm 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,145 +0,0 @@
-#!/bin/csh -f
-
-set pstatus = 0
-onintr cleanup
-alias usage 'echo "USAGE: $0:t [-h] [-n] [-obj obj-root] [gmake-flags] [VAR=...] [toolname (default: opt)]"; set pstatus = 1; goto cleanup'
-
-set EXEC = opt
-set GMAKE_OPTS = ""
-set DEBUG = 0
-
-## Search path for automatically finding the obj-root to use.
-## Note: The src root directory ${LLVMDIR} will be prepended to this path later.
-##
-set OBJROOTDIRLIST = ( )
-
-set doit = 1
-unset options_done
-while ( !( $?options_done ) && ($#argv > 0))
- switch ($argv[1])
- case -h :
- usage
- case -f :
- if ($#argv < 2) usage
- shift argv; set MFILE = $argv[1]; shift argv; breaksw
- case -n :
- set doit = 0; shift argv; breaksw
- case -obj :
- set OBJROOT = $argv[2]; shift argv; shift argv
- if (! -d "$OBJROOT") then
- echo "FATAL: Illegal obj-root directory ${OBJROOT}"
- exit 1
- endif
- breaksw
- case -d :
- set doit = 0; set DEBUG = 1; shift argv; breaksw
- case -* :
- set GMAKE_OPTS = ( $GMAKE_OPTS $argv[1] ); shift argv; breaksw
- default :
- set optarg = `echo -n $argv[1] | sed 's/^[^=]*$//'`
- if ($#optarg) then
- set GMAKE_OPTS = ( $GMAKE_OPTS $optarg )
- shift argv
- else
- set options_done
- endif
- breaksw
- endsw
-end
-
-if ($#argv > 1) then
- echo 'ERROR: More than one tool is not supported by "makellvm"'
- usage
-endif
-if ($#argv > 0) then
- set EXEC = $argv[1]
-endif
-if ($DEBUG) then
- echo "DEBUG: EXEC = $EXEC"
-endif
-
-## Compute LLVMDIR: the root of the current LLVM tree.
-## It is recorded in the variable LEVEL in Makefile, to compute it
-##
-if (! $?MFILE) then
- if (-f GNUmakefile) then
- set MFILE = GNUmakefile
- else if (-f makefile) then
- set MFILE = makefile
- else
- set MFILE = Makefile
- endif
-endif
-if ($DEBUG) then
- echo "DEBUG: MFILE = $MFILE"
-endif
-if (! -f $MFILE) then
- echo "Missing or invalid makefile: $MFILE"
- exit 1
-endif
-
-set LLVMDIR = `awk '/LEVEL[ ]*=/ {print $NF}' $MFILE`
-if ($DEBUG) then
- echo "DEBUG: LLVMDIR = $LLVMDIR"
-endif
-
-if ($#LLVMDIR == 0 || ! -d "$LLVMDIR") then
- echo "Unable to find LLVM src-root directory or directory is invalid."
- echo "Are you within a valid LLVM directory for running gmake?"
- exit 1
-endif
-
-## Try to determine the obj-root directory automatically if not specified
-##
-set OBJROOTDIRLIST = ( ${LLVMDIR} $OBJROOTDIRLIST ) ## add src dir
-if ($?OBJROOT == 0) then
- ## Try to determine object root directory by looking for Makefile.config
- foreach objdir ( $OBJROOTDIRLIST )
- if (-f "${objdir}/Makefile.config") then
- set OBJROOT = ${objdir}
- break
- endif
- end
- if ($?OBJROOT == 0) then
- echo "FATAL: Could not choose an obj-root directory from these choices:"
- echo " ${OBJROOTDIRLIST}."
- echo " You can specify it explicitly using '-obj obj-root'."
- exit 1
- endif
- echo "Using OBJ-ROOT = ${OBJROOT} (specify '-obj obj-root' to override)."
-endif
-if (${OBJROOT} == ${LLVMDIR}) then
- # run make in the source directory itself
- set BUILDROOT = .
-else
- # run make in the in the obj-root tree, in the directory for $cwd
- set SRCROOT = `sh -c "cd $LLVMDIR; pwd | sed 's/\//\\\//g'"`
- set CURSRCDIR = `echo $cwd | sed -e "s/${SRCROOT}//"`
- set BUILDROOT = ${OBJROOT}/${CURSRCDIR}
- unset SRCROOT CURSRCDIR
-endif
-if ($DEBUG) then
- echo "DEBUG: BUILDROOT = $BUILDROOT"
-endif
-if (! -d $BUILDROOT) then
- echo "FATAL: Invalid build directory: ${BUILDROOT}"
- exit 1
-endif
-cd $BUILDROOT
-
-set CMD = "make $GMAKE_OPTS && (cd $LLVMDIR/tools/$EXEC && make $GMAKE_OPTS)"
-
-if ($doit == 1) then
- csh -f -c "$CMD"
- set pstatus = $?
-else
- echo '(NOT EXECUTING) COMMAND:'
- echo " $CMD"
-endif
-
-
-#=========================================================
-# CODE TO BE EXECUTED IF INTERRUPT IS RECEIVED
-#=========================================================
-cleanup:
- exit($pstatus)
Modified: trunk/contrib/llvm/utils/not/not.cpp
===================================================================
--- trunk/contrib/llvm/utils/not/not.cpp 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/not/not.cpp 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,27 +0,0 @@
-//===- not.cpp - The 'not' testing tool -----------------------------------===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Support/Path.h"
-#include "llvm/Support/Program.h"
-#include "llvm/Support/raw_ostream.h"
-using namespace llvm;
-
-int main(int argc, const char **argv) {
- sys::Path Program = sys::Program::FindProgramByName(argv[1]);
-
- std::string ErrMsg;
- int Result = sys::Program::ExecuteAndWait(Program, argv + 1, 0, 0, 0, 0,
- &ErrMsg);
- if (Result < 0) {
- errs() << "Error: " << ErrMsg << "\n";
- return 1;
- }
-
- return Result == 0;
-}
Modified: trunk/contrib/llvm/utils/profile.pl
===================================================================
--- trunk/contrib/llvm/utils/profile.pl 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/profile.pl 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,74 +0,0 @@
-#!/usr/bin/perl -w
-#
-# Program: profile.pl
-#
-# Synopsis: Insert instrumentation code into a program, run it with the JIT,
-# then print out a profile report.
-#
-# Syntax: profile.pl [OPTIONS] bitcodefile <arguments>
-#
-# OPTIONS may include one or more of the following:
-# -block - Enable basicblock profiling
-# -edge - Enable edge profiling
-# -function - Enable function profiling
-# -o <filename> - Emit profiling information to the specified file, instead
-# of llvmprof.out
-#
-# Any unrecognized options are passed into the invocation of llvm-prof
-#
-
-my $ProfilePass = "-insert-edge-profiling";
-
-my $LLVMProfOpts = "";
-my $ProgramOpts = "";
-my $ProfileFile = "";
-
-# Parse arguments...
-while (scalar(@ARGV) and ($_ = $ARGV[0], /^[-+]/)) {
- shift;
- last if /^--$/; # Stop processing arguments on --
-
- # List command line options here...
- if (/^-?-block$/) { $ProfilePass = "-insert-block-profiling"; next; }
- if (/^-?-edge$/) { $ProfilePass = "-insert-edge-profiling"; next; }
- if (/^-?-function$/) { $ProfilePass = "-insert-function-profiling"; next; }
- if (/^-?-o$/) { # Read -o filename...
- die "-o option requires a filename argument!" if (!scalar(@ARGV));
- $ProgramOpts .= " -llvmprof-output $ARGV[0]";
- $ProfileFile = $ARGV[0];
- shift;
- next;
- }
- if (/^-?-help$/) {
- print "OVERVIEW: profile.pl - Instrumentation and profile printer.\n\n";
- print "USAGE: profile.pl [options] program.bc <program args>\n\n";
- print "OPTIONS:\n";
- print " -block - Enable basicblock profiling\n";
- print " -edge - Enable edge profiling\n";
- print " -function - Enable function profiling\n";
- print " -o <file> - Specify an output file other than llvm-prof.out.\n";
- print " -help - Print this usage information\n";
- print "\nAll other options are passed into llvm-prof.\n";
- exit 1;
- }
-
- # Otherwise, pass the option on to llvm-prof
- $LLVMProfOpts .= " " . $_;
-}
-
-die "Must specify LLVM bitcode file as first argument!" if (@ARGV == 0);
-
-my $BytecodeFile = $ARGV[0];
-
-shift @ARGV;
-
-my $libdir = `llvm-config --libdir`;
-chomp $libdir;
-
-my $LibProfPath = $libdir . "/libprofile_rt.so";
-
-system "opt -q -f $ProfilePass $BytecodeFile -o $BytecodeFile.inst";
-system "lli -fake-argv0 '$BytecodeFile' -load $LibProfPath " .
- "$BytecodeFile.inst $ProgramOpts " . (join ' ', @ARGV);
-system "rm $BytecodeFile.inst";
-system "llvm-prof $LLVMProfOpts $BytecodeFile $ProfileFile";
Modified: trunk/contrib/llvm/utils/release/findRegressions-nightly.py
===================================================================
--- trunk/contrib/llvm/utils/release/findRegressions-nightly.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/release/findRegressions-nightly.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,130 +0,0 @@
-#!/usr/bin/env python
-import re, string, sys, os, time
-
-DEBUG = 0
-testDirName = 'llvm-test'
-test = ['compile', 'llc', 'jit', 'cbe']
-exectime = ['llc-time', 'jit-time', 'cbe-time',]
-comptime = ['llc', 'jit-comptime', 'compile']
-
-(tp, exp) = ('compileTime_', 'executeTime_')
-
-def parse(file):
- f=open(file, 'r')
- d = f.read()
-
- #Cleanup weird stuff
- d = re.sub(r',\d+:\d','', d)
-
- r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d)
-
- test = {}
- fname = ''
- for t in r:
- if DEBUG:
- print t
- if t[0] == 'PASS' or t[0] == 'FAIL' :
- tmp = t[2].split(testDirName)
-
- if DEBUG:
- print tmp
-
- if len(tmp) == 2:
- fname = tmp[1].strip('\r\n')
- else:
- fname = tmp[0].strip('\r\n')
-
- if not test.has_key(fname) :
- test[fname] = {}
-
- for k in test:
- test[fname][k] = 'NA'
- test[fname][t[1]] = t[0]
- if DEBUG:
- print test[fname][t[1]]
- else :
- try:
- n = t[0].split('RESULT-')[1]
-
- if DEBUG:
- print n;
-
- if n == 'llc' or n == 'jit-comptime' or n == 'compile':
- test[fname][tp + n] = float(t[2].split(' ')[2])
- if DEBUG:
- print test[fname][tp + n]
-
- elif n.endswith('-time') :
- test[fname][exp + n] = float(t[2].strip('\r\n'))
- if DEBUG:
- print test[fname][exp + n]
-
- else :
- print "ERROR!"
- sys.exit(1)
-
- except:
- continue
-
- return test
-
-# Diff results and look for regressions.
-def diffResults(d_old, d_new):
-
- for t in sorted(d_old.keys()) :
- if DEBUG:
- print t
-
- if d_new.has_key(t) :
-
- # Check if the test passed or failed.
- for x in test:
- if d_old[t].has_key(x):
- if d_new[t].has_key(x):
- if d_old[t][x] == 'PASS':
- if d_new[t][x] != 'PASS':
- print t + " *** REGRESSION (" + x + ")\n"
- else:
- if d_new[t][x] == 'PASS':
- print t + " * NEW PASS (" + x + ")\n"
-
- else :
- print t + "*** REGRESSION (" + x + ")\n"
-
- # For execution time, if there is no result, its a fail.
- for x in exectime:
- if d_old[t].has_key(tp + x):
- if not d_new[t].has_key(tp + x):
- print t + " *** REGRESSION (" + tp + x + ")\n"
-
- else :
- if d_new[t].has_key(tp + x):
- print t + " * NEW PASS (" + tp + x + ")\n"
-
-
- for x in comptime:
- if d_old[t].has_key(exp + x):
- if not d_new[t].has_key(exp + x):
- print t + " *** REGRESSION (" + exp + x + ")\n"
-
- else :
- if d_new[t].has_key(exp + x):
- print t + " * NEW PASS (" + exp + x + ")\n"
-
- else :
- print t + ": Removed from test-suite.\n"
-
-
-#Main
-if len(sys.argv) < 3 :
- print 'Usage:', sys.argv[0], \
- '<old log> <new log>'
- sys.exit(-1)
-
-d_old = parse(sys.argv[1])
-d_new = parse(sys.argv[2])
-
-
-diffResults(d_old, d_new)
-
-
Modified: trunk/contrib/llvm/utils/release/findRegressions-simple.py
===================================================================
--- trunk/contrib/llvm/utils/release/findRegressions-simple.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/release/findRegressions-simple.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,158 +0,0 @@
-#!/usr/bin/env python
-import re, string, sys, os, time, math
-
-DEBUG = 0
-
-(tp, exp) = ('compile', 'exec')
-
-def parse(file):
- f = open(file, 'r')
- d = f.read()
-
- # Cleanup weird stuff
- d = re.sub(r',\d+:\d', '', d)
-
- r = re.findall(r'TEST-(PASS|FAIL|RESULT.*?):\s+(.*?)\s+(.*?)\r*\n', d)
-
- test = {}
- fname = ''
- for t in r:
- if DEBUG:
- print t
-
- if t[0] == 'PASS' or t[0] == 'FAIL' :
- tmp = t[2].split('llvm-test/')
-
- if DEBUG:
- print tmp
-
- if len(tmp) == 2:
- fname = tmp[1].strip('\r\n')
- else:
- fname = tmp[0].strip('\r\n')
-
- if not test.has_key(fname):
- test[fname] = {}
-
- test[fname][t[1] + ' state'] = t[0]
- test[fname][t[1] + ' time'] = float('nan')
- else :
- try:
- n = t[0].split('RESULT-')[1]
-
- if DEBUG:
- print "n == ", n;
-
- if n == 'compile-success':
- test[fname]['compile time'] = float(t[2].split('program')[1].strip('\r\n'))
-
- elif n == 'exec-success':
- test[fname]['exec time'] = float(t[2].split('program')[1].strip('\r\n'))
- if DEBUG:
- print test[fname][string.replace(n, '-success', '')]
-
- else :
- # print "ERROR!"
- sys.exit(1)
-
- except:
- continue
-
- return test
-
-# Diff results and look for regressions.
-def diffResults(d_old, d_new):
- regressions = {}
- passes = {}
- removed = ''
-
- for x in ['compile state', 'compile time', 'exec state', 'exec time']:
- regressions[x] = ''
- passes[x] = ''
-
- for t in sorted(d_old.keys()) :
- if d_new.has_key(t):
-
- # Check if the test passed or failed.
- for x in ['compile state', 'compile time', 'exec state', 'exec time']:
-
- if not d_old[t].has_key(x) and not d_new[t].has_key(x):
- continue
-
- if d_old[t].has_key(x):
- if d_new[t].has_key(x):
-
- if d_old[t][x] == 'PASS':
- if d_new[t][x] != 'PASS':
- regressions[x] += t + "\n"
- else:
- if d_new[t][x] == 'PASS':
- passes[x] += t + "\n"
-
- else :
- regressions[x] += t + "\n"
-
- if x == 'compile state' or x == 'exec state':
- continue
-
- # For execution time, if there is no result it's a fail.
- if not d_old[t].has_key(x) and not d_new[t].has_key(x):
- continue
- elif not d_new[t].has_key(x):
- regressions[x] += t + "\n"
- elif not d_old[t].has_key(x):
- passes[x] += t + "\n"
-
- if math.isnan(d_old[t][x]) and math.isnan(d_new[t][x]):
- continue
-
- elif math.isnan(d_old[t][x]) and not math.isnan(d_new[t][x]):
- passes[x] += t + "\n"
-
- elif not math.isnan(d_old[t][x]) and math.isnan(d_new[t][x]):
- regressions[x] += t + ": NaN%\n"
-
- if d_new[t][x] > d_old[t][x] and d_old[t][x] > 0.0 and \
- (d_new[t][x] - d_old[t][x]) / d_old[t][x] > .05:
- regressions[x] += t + ": " + "{0:.1f}".format(100 * (d_new[t][x] - d_old[t][x]) / d_old[t][x]) + "%\n"
-
- else :
- removed += t + "\n"
-
- if len(regressions['compile state']) != 0:
- print 'REGRESSION: Compilation Failed'
- print regressions['compile state']
-
- if len(regressions['exec state']) != 0:
- print 'REGRESSION: Execution Failed'
- print regressions['exec state']
-
- if len(regressions['compile time']) != 0:
- print 'REGRESSION: Compilation Time'
- print regressions['compile time']
-
- if len(regressions['exec time']) != 0:
- print 'REGRESSION: Execution Time'
- print regressions['exec time']
-
- if len(passes['compile state']) != 0:
- print 'NEW PASSES: Compilation'
- print passes['compile state']
-
- if len(passes['exec state']) != 0:
- print 'NEW PASSES: Execution'
- print passes['exec state']
-
- if len(removed) != 0:
- print 'REMOVED TESTS'
- print removed
-
-# Main
-if len(sys.argv) < 3 :
- print 'Usage:', sys.argv[0], '<old log> <new log>'
- sys.exit(-1)
-
-d_old = parse(sys.argv[1])
-d_new = parse(sys.argv[2])
-
-diffResults(d_old, d_new)
Modified: trunk/contrib/llvm/utils/release/merge.sh
===================================================================
--- trunk/contrib/llvm/utils/release/merge.sh 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/release/merge.sh 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,74 +0,0 @@
-#!/bin/sh
-#===-- merge.sh - Test the LLVM release candidates -------------------------===#
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License.
-#
-#===------------------------------------------------------------------------===#
-#
-# Merge a revision into a project.
-#
-#===------------------------------------------------------------------------===#
-
-set -e
-
-rev=""
-proj=""
-
-function usage() {
- echo "usage: `basename $0` [OPTIONS]"
- echo " -proj PROJECT The project to merge the result into"
- echo " -rev NUM The revision to merge into the project"
-}
-
-while [ $# -gt 0 ]; do
- case $1 in
- -rev | --rev | -r )
- shift
- rev=$1
- ;;
- -proj | --proj | -project | --project | -p )
- shift
- proj=$1
- ;;
- -h | -help | --help )
- usage
- ;;
- * )
- echo "unknown option: $1"
- echo ""
- usage
- exit 1
- ;;
- esac
- shift
-done
-
-if [ "x$rev" = "x" -o "x$proj" = "x" ]; then
- echo "error: need to specify project and revision"
- echo
- usage
- exit 1
-fi
-
-if ! svn ls http://llvm.org/svn/llvm-project/$proj/trunk > /dev/null 2>&1 ; then
- echo "error: invalid project: $proj"
- exit 1
-fi
-
-tempfile=`mktemp /tmp/merge.XXXXXX` || exit 1
-
-echo "Merging r$rev:" > $tempfile
-svn log -c $rev http://llvm.org/svn/llvm-project/$proj/trunk >> $tempfile 2>&1
-
-cd $proj.src
-echo "# Updating tree"
-svn up
-echo "# Merging r$rev into $proj"
-svn merge -c $rev https://llvm.org/svn/llvm-project/$proj/trunk . || exit 1
-echo "# Committing changes"
-svn commit -F $tempfile || exit 1
-rm -f $tempfile
-exit 0
Modified: trunk/contrib/llvm/utils/release/tag.sh
===================================================================
--- trunk/contrib/llvm/utils/release/tag.sh 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/release/tag.sh 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,109 +0,0 @@
-#!/bin/sh
-#===-- tag.sh - Tag the LLVM release candidates ----------------------------===#
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License.
-#
-#===------------------------------------------------------------------------===#
-#
-# Create branches and release candidates for the LLVM release.
-#
-#===------------------------------------------------------------------------===#
-
-set -e
-
-release=""
-rc=""
-rebranch="no"
-
-base_url="https://llvm.org/svn/llvm-project"
-
-function usage() {
- echo "usage: `basename $0` -release <num> [-rebranch]"
- echo "usage: `basename $0` -release <num> -rc <num>"
- echo " "
- echo " -release <num> The version number of the release"
- echo " -rc <num> The release candidate number"
- echo " -rebranch Remove existing branch, if present, before branching"
- echo " -final Tag final release candidate"
-}
-
-function tag_version() {
- set -x
- for proj in llvm cfe dragonegg test-suite compiler-rt libcxx clang-tools-extra ; do
- if svn ls $base_url/$proj/branches/release_$release > /dev/null 2>&1 ; then
- if [ $rebranch = "no" ]; then
- continue
- fi
- svn remove -m "Removing old release_$release branch for rebranching." \
- $base_url/$proj/branches/release_$release
- fi
- svn copy -m "Creating release_$release branch" \
- $base_url/$proj/trunk \
- $base_url/$proj/branches/release_$release
- done
- set +x
-}
-
-function tag_release_candidate() {
- set -x
- for proj in llvm cfe dragonegg test-suite compiler-rt libcxx clang-tools-extra ; do
- if ! svn ls $base_url/$proj/tags/RELEASE_$release > /dev/null 2>&1 ; then
- svn mkdir -m "Creating release directory for release_$release." $base_url/$proj/tags/RELEASE_$release
- fi
- if ! svn ls $base_url/$proj/tags/RELEASE_$release/$rc > /dev/null 2>&1 ; then
- svn copy -m "Creating release candidate $rc from release_$release branch" \
- $base_url/$proj/branches/release_$release \
- $base_url/$proj/tags/RELEASE_$release/$rc
- fi
- done
- set +x
-}
-
-while [ $# -gt 0 ]; do
- case $1 in
- -release | --release )
- shift
- release=$1
- ;;
- -rc | --rc )
- shift
- rc="rc$1"
- ;;
- -rebranch | --rebranch )
- rebranch="yes"
- ;;
- -final | --final )
- rc="final"
- ;;
- -h | --help | -help )
- usage
- exit 0
- ;;
- * )
- echo "unknown option: $1"
- usage
- exit 1
- ;;
- esac
- shift
-done
-
-if [ "x$release" = "x" ]; then
- echo "error: need to specify a release version"
- echo
- usage
- exit 1
-fi
-
-release=`echo $release | sed -e 's,\.,,g'`
-
-if [ "x$rc" = "x" ]; then
- tag_version
-else
- tag_release_candidate
-fi
-
-exit 1
Modified: trunk/contrib/llvm/utils/release/test-release.sh
===================================================================
--- trunk/contrib/llvm/utils/release/test-release.sh 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/release/test-release.sh 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,519 +0,0 @@
-#!/usr/bin/env bash
-#===-- test-release.sh - Test the LLVM release candidates ------------------===#
-#
-# The LLVM Compiler Infrastructure
-#
-# This file is distributed under the University of Illinois Open Source
-# License.
-#
-#===------------------------------------------------------------------------===#
-#
-# Download, build, and test the release candidate for an LLVM release.
-#
-#===------------------------------------------------------------------------===#
-
-if [ `uname -s` = "FreeBSD" ]; then
- MAKE=gmake
-else
- MAKE=make
-fi
-
-projects="llvm cfe dragonegg compiler-rt test-suite"
-
-# Base SVN URL for the sources.
-Base_url="http://llvm.org/svn/llvm-project"
-
-Release=""
-Release_no_dot=""
-RC=""
-do_checkout="yes"
-do_ada="no"
-do_clang="yes"
-do_dragonegg="no"
-do_fortran="no"
-do_objc="yes"
-do_64bit="yes"
-do_debug="no"
-do_asserts="no"
-do_compare="no"
-BuildDir="`pwd`"
-
-function usage() {
- echo "usage: `basename $0` -release X.Y -rc NUM [OPTIONS]"
- echo ""
- echo " -release X.Y The release number to test."
- echo " -rc NUM The pre-release candidate number."
- echo " -final The final release candidate."
- echo " -j NUM Number of compile jobs to run. [default: 3]"
- echo " -build-dir DIR Directory to perform testing in. [default: pwd]"
- echo " -no-checkout Don't checkout the sources from SVN."
- echo " -no-64bit Don't test the 64-bit version. [default: yes]"
- echo " -enable-ada Build Ada. [default: disable]"
- echo " -disable-clang Do not test clang. [default: enable]"
- echo " -enable-dragonegg Test dragonegg. [default: disable]"
- echo " -enable-fortran Enable Fortran build. [default: disable]"
- echo " -disable-objc Disable ObjC build. [default: enable]"
- echo " -test-debug Test the debug build. [default: no]"
- echo " -test-asserts Test with asserts on. [default: no]"
- echo " -no-compare-files Don't test that phase 2 and 3 files are identical."
-}
-
-while [ $# -gt 0 ]; do
- case $1 in
- -release | --release )
- shift
- Release="$1"
- Release_no_dot="`echo $1 | sed -e 's,\.,,'`"
- ;;
- -rc | --rc | -RC | --RC )
- shift
- RC="rc$1"
- ;;
- -final | --final )
- RC=final
- ;;
- -j* )
- NumJobs="`echo $1 | sed -e 's,-j\([0-9]*\),\1,g'`"
- if [ -z "$NumJobs" ]; then
- shift
- NumJobs="$1"
- fi
- ;;
- -build-dir | --build-dir | -builddir | --builddir )
- shift
- BuildDir="$1"
- ;;
- -no-checkout | --no-checkout )
- do_checkout="no"
- ;;
- -no-64bit | --no-64bit )
- do_64bit="no"
- ;;
- -enable-ada | --enable-ada )
- do_ada="yes"
- ;;
- -disable-clang | --disable-clang )
- do_clang="no"
- ;;
- -enable-dragonegg | --enable-dragonegg )
- do_dragonegg="yes"
- ;;
- -enable-fortran | --enable-fortran )
- do_fortran="yes"
- ;;
- -disable-objc | --disable-objc )
- do_objc="no"
- ;;
- -test-debug | --test-debug )
- do_debug="yes"
- ;;
- -test-asserts | --test-asserts )
- do_asserts="yes"
- ;;
- -no-compare-files | --no-compare-files )
- do_compare="no"
- ;;
- -help | --help | -h | --h | -\? )
- usage
- exit 0
- ;;
- * )
- echo "unknown option: $1"
- usage
- exit 1
- ;;
- esac
- shift
-done
-
-# Check required arguments.
-if [ -z "$Release" ]; then
- echo "error: no release number specified"
- exit 1
-fi
-if [ -z "$RC" ]; then
- echo "error: no release candidate number specified"
- exit 1
-fi
-
-# Figure out how many make processes to run.
-if [ -z "$NumJobs" ]; then
- NumJobs=`sysctl -n hw.activecpu 2> /dev/null || true`
-fi
-if [ -z "$NumJobs" ]; then
- NumJobs=`sysctl -n hw.ncpu 2> /dev/null || true`
-fi
-if [ -z "$NumJobs" ]; then
- NumJobs=`grep -c processor /proc/cpuinfo 2> /dev/null || true`
-fi
-if [ -z "$NumJobs" ]; then
- NumJobs=3
-fi
-
-# Go to the build directory (may be different from CWD)
-BuildDir=$BuildDir/$RC
-mkdir -p $BuildDir
-cd $BuildDir
-
-# Location of log files.
-LogDir=$BuildDir/logs
-mkdir -p $LogDir
-
-# Find compilers.
-if [ "$do_dragonegg" = "yes" ]; then
- gcc_compiler="$GCC"
- if [ -z "$gcc_compiler" ]; then
- gcc_compiler="`which gcc`"
- if [ -z "$gcc_compiler" ]; then
- echo "error: cannot find gcc to use with dragonegg"
- exit 1
- fi
- fi
-
- gxx_compiler="$GXX"
- if [ -z "$gxx_compiler" ]; then
- gxx_compiler="`which g++`"
- if [ -z "$gxx_compiler" ]; then
- echo "error: cannot find g++ to use with dragonegg"
- exit 1
- fi
- fi
-fi
-
-
-# Make sure that the URLs are valid.
-function check_valid_urls() {
- for proj in $projects ; do
- echo "# Validating $proj SVN URL"
-
- if ! svn ls $Base_url/$proj/tags/RELEASE_$Release_no_dot/$RC > /dev/null 2>&1 ; then
- echo "llvm $Release release candidate $RC doesn't exist!"
- exit 1
- fi
- done
-}
-
-# Export sources to the build directory.
-function export_sources() {
- check_valid_urls
-
- for proj in $projects ; do
- echo "# Exporting $proj $Release-RC$RC sources"
- if ! svn export -q $Base_url/$proj/tags/RELEASE_$Release_no_dot/$RC $proj.src ; then
- echo "error: failed to export $proj project"
- exit 1
- fi
- done
-
- echo "# Creating symlinks"
- cd $BuildDir/llvm.src/tools
- if [ ! -h clang ]; then
- ln -s ../../cfe.src clang
- fi
- cd $BuildDir/llvm.src/projects
- if [ ! -h llvm-test ]; then
- ln -s ../../test-suite.src llvm-test
- fi
- if [ ! -h compiler-rt ]; then
- ln -s ../../compiler-rt.src compiler-rt
- fi
- cd $BuildDir
-}
-
-function configure_llvmCore() {
- Phase="$1"
- Flavor="$2"
- ObjDir="$3"
- InstallDir="$4"
-
- case $Flavor in
- Release | Release-64 )
- Optimized="yes"
- Assertions="no"
- ;;
- Release+Asserts )
- Optimized="yes"
- Assertions="yes"
- ;;
- Debug )
- Optimized="no"
- Assertions="yes"
- ;;
- * )
- echo "# Invalid flavor '$Flavor'"
- echo ""
- return
- ;;
- esac
-
- echo "# Using C compiler: $c_compiler"
- echo "# Using C++ compiler: $cxx_compiler"
-
- cd $ObjDir
- echo "# Configuring llvm $Release-$RC $Flavor"
- echo "# $BuildDir/llvm.src/configure --prefix=$InstallDir \
- --enable-optimized=$Optimized \
- --enable-assertions=$Assertions"
- env CC="$c_compiler" CXX="$cxx_compiler" \
- $BuildDir/llvm.src/configure --prefix=$InstallDir \
- --enable-optimized=$Optimized \
- --enable-assertions=$Assertions \
- --disable-timestamps \
- 2>&1 | tee $LogDir/llvm.configure-Phase$Phase-$Flavor.log
- cd $BuildDir
-}
-
-function build_llvmCore() {
- Phase="$1"
- Flavor="$2"
- ObjDir="$3"
- ExtraOpts=""
-
- if [ "$Flavor" = "Release-64" ]; then
- ExtraOpts="EXTRA_OPTIONS=-m64"
- fi
-
- cd $ObjDir
- echo "# Compiling llvm $Release-$RC $Flavor"
- echo "# ${MAKE} -j $NumJobs VERBOSE=1 $ExtraOpts"
- ${MAKE} -j $NumJobs VERBOSE=1 $ExtraOpts \
- 2>&1 | tee $LogDir/llvm.make-Phase$Phase-$Flavor.log
-
- echo "# Installing llvm $Release-$RC $Flavor"
- echo "# ${MAKE} install"
- ${MAKE} install \
- 2>&1 | tee $LogDir/llvm.install-Phase$Phase-$Flavor.log
- cd $BuildDir
-}
-
-function build_dragonegg() {
- Phase="$1"
- Flavor="$2"
- LLVMInstallDir="$3"
- DragonEggObjDir="$4"
- LLVM_CONFIG=$LLVMInstallDir/bin/llvm-config
- TOP_DIR=$BuildDir/dragonegg.src
-
- echo "# Targeted compiler: $gcc_compiler"
-
- cd $DragonEggObjDir
- echo "# Compiling phase $Phase dragonegg $Release-$RC $Flavor"
- echo -n "# CXX=$cxx_compiler TOP_DIR=$TOP_DIR GCC=$gcc_compiler "
- echo -n "LLVM_CONFIG=$LLVM_CONFIG ${MAKE} -f $TOP_DIR/Makefile "
- echo "-j $NumJobs VERBOSE=1"
- CXX="$cxx_compiler" TOP_DIR="$TOP_DIR" GCC="$gcc_compiler" \
- LLVM_CONFIG="$LLVM_CONFIG" ${MAKE} -f $TOP_DIR/Makefile \
- -j $NumJobs VERBOSE=1 \
- 2>&1 | tee $LogDir/dragonegg-Phase$Phase-$Flavor.log
- cd $BuildDir
-}
-
-function test_llvmCore() {
- Phase="$1"
- Flavor="$2"
- ObjDir="$3"
-
- cd $ObjDir
- ${MAKE} -k check-all \
- 2>&1 | tee $LogDir/llvm.check-Phase$Phase-$Flavor.log
- ${MAKE} -k unittests \
- 2>&1 | tee $LogDir/llvm.unittests-Phase$Phase-$Flavor.log
- cd $BuildDir
-}
-
-set -e # Exit if any command fails
-
-if [ "$do_checkout" = "yes" ]; then
- export_sources
-fi
-
-(
-Flavors="Release"
-if [ "$do_debug" = "yes" ]; then
- Flavors="Debug $Flavors"
-fi
-if [ "$do_asserts" = "yes" ]; then
- Flavors="$Flavors Release+Asserts"
-fi
-if [ "$do_64bit" = "yes" ]; then
- Flavors="$Flavors Release-64"
-fi
-
-for Flavor in $Flavors ; do
- echo ""
- echo ""
- echo "********************************************************************************"
- echo " Release: $Release-$RC"
- echo " Build: $Flavor"
- echo " System Info: "
- echo " `uname -a`"
- echo "********************************************************************************"
- echo ""
-
- c_compiler="$CC"
- cxx_compiler="$CXX"
-
- llvmCore_phase1_objdir=$BuildDir/Phase1/$Flavor/llvmCore-$Release-$RC.obj
- llvmCore_phase1_installdir=$BuildDir/Phase1/$Flavor/llvmCore-$Release-$RC.install
- dragonegg_phase1_objdir=$BuildDir/Phase1/$Flavor/DragonEgg-$Release-$RC.obj
-
- llvmCore_phase2_objdir=$BuildDir/Phase2/$Flavor/llvmCore-$Release-$RC.obj
- llvmCore_phase2_installdir=$BuildDir/Phase2/$Flavor/llvmCore-$Release-$RC.install
- llvmCore_de_phase2_objdir=$BuildDir/Phase2/$Flavor/llvmCore-DragonEgg-$Release-$RC.obj
- llvmCore_de_phase2_installdir=$BuildDir/Phase2/$Flavor/llvmCore-DragonEgg-$Release-$RC.install
- dragonegg_phase2_objdir=$BuildDir/Phase2/$Flavor/DragonEgg-$Release-$RC.obj
-
- llvmCore_phase3_objdir=$BuildDir/Phase3/$Flavor/llvmCore-$Release-$RC.obj
- llvmCore_phase3_installdir=$BuildDir/Phase3/$Flavor/llvmCore-$Release-$RC.install
- llvmCore_de_phase3_objdir=$BuildDir/Phase3/$Flavor/llvmCore-DragonEgg-$Release-$RC.obj
- llvmCore_de_phase3_installdir=$BuildDir/Phase3/$Flavor/llvmCore-DragonEgg-$Release-$RC.install
- dragonegg_phase3_objdir=$BuildDir/Phase3/$Flavor/DragonEgg-$Release-$RC.obj
-
- rm -rf $llvmCore_phase1_objdir
- rm -rf $llvmCore_phase1_installdir
- rm -rf $dragonegg_phase1_objdir
-
- rm -rf $llvmCore_phase2_objdir
- rm -rf $llvmCore_phase2_installdir
- rm -rf $llvmCore_de_phase2_objdir
- rm -rf $llvmCore_de_phase2_installdir
- rm -rf $dragonegg_phase2_objdir
-
- rm -rf $llvmCore_phase3_objdir
- rm -rf $llvmCore_phase3_installdir
- rm -rf $llvmCore_de_phase3_objdir
- rm -rf $llvmCore_de_phase3_installdir
- rm -rf $dragonegg_phase3_objdir
-
- mkdir -p $llvmCore_phase1_objdir
- mkdir -p $llvmCore_phase1_installdir
- mkdir -p $dragonegg_phase1_objdir
-
- mkdir -p $llvmCore_phase2_objdir
- mkdir -p $llvmCore_phase2_installdir
- mkdir -p $llvmCore_de_phase2_objdir
- mkdir -p $llvmCore_de_phase2_installdir
- mkdir -p $dragonegg_phase2_objdir
-
- mkdir -p $llvmCore_phase3_objdir
- mkdir -p $llvmCore_phase3_installdir
- mkdir -p $llvmCore_de_phase3_objdir
- mkdir -p $llvmCore_de_phase3_installdir
- mkdir -p $dragonegg_phase3_objdir
-
- ############################################################################
- # Phase 1: Build llvmCore and clang
- echo "# Phase 1: Building llvmCore"
- configure_llvmCore 1 $Flavor \
- $llvmCore_phase1_objdir $llvmCore_phase1_installdir
- build_llvmCore 1 $Flavor \
- $llvmCore_phase1_objdir
-
- # Test clang
- if [ "$do_clang" = "yes" ]; then
- ########################################################################
- # Phase 2: Build llvmCore with newly built clang from phase 1.
- c_compiler=$llvmCore_phase1_installdir/bin/clang
- cxx_compiler=$llvmCore_phase1_installdir/bin/clang++
- echo "# Phase 2: Building llvmCore"
- configure_llvmCore 2 $Flavor \
- $llvmCore_phase2_objdir $llvmCore_phase2_installdir
- build_llvmCore 2 $Flavor \
- $llvmCore_phase2_objdir
-
- ########################################################################
- # Phase 3: Build llvmCore with newly built clang from phase 2.
- c_compiler=$llvmCore_phase2_installdir/bin/clang
- cxx_compiler=$llvmCore_phase2_installdir/bin/clang++
- echo "# Phase 3: Building llvmCore"
- configure_llvmCore 3 $Flavor \
- $llvmCore_phase3_objdir $llvmCore_phase3_installdir
- build_llvmCore 3 $Flavor \
- $llvmCore_phase3_objdir
-
- ########################################################################
- # Testing: Test phase 3
- echo "# Testing - built with clang"
- test_llvmCore 3 $Flavor $llvmCore_phase3_objdir
-
- ########################################################################
- # Compare .o files between Phase2 and Phase3 and report which ones
- # differ.
- if [ "$do_compare" = "yes" ]; then
- echo
- echo "# Comparing Phase 2 and Phase 3 files"
- for o in `find $llvmCore_phase2_objdir -name '*.o'` ; do
- p3=`echo $o | sed -e 's,Phase2,Phase3,'`
- if ! cmp --ignore-initial=16 $o $p3 > /dev/null 2>&1 ; then
- echo "file `basename $o` differs between phase 2 and phase 3"
- fi
- done
- fi
- fi
-
- # Test dragonegg
- if [ "$do_dragonegg" = "yes" ]; then
- # Build dragonegg using the targeted gcc. This isn't necessary, but
- # helps avoid using broken versions of gcc (which are legion), tests
- # that the targeted gcc is basically sane and is consistent with the
- # later phases in which the targeted gcc + dragonegg are used.
- c_compiler="$gcc_compiler"
- cxx_compiler="$gxx_compiler"
- build_dragonegg 1 $Flavor $llvmCore_phase1_installdir $dragonegg_phase1_objdir
-
- ########################################################################
- # Phase 2: Build llvmCore with newly built dragonegg from phase 1.
- c_compiler="$gcc_compiler -fplugin=$dragonegg_phase1_objdir/dragonegg.so"
- cxx_compiler="$gxx_compiler -fplugin=$dragonegg_phase1_objdir/dragonegg.so"
- echo "# Phase 2: Building llvmCore with dragonegg"
- configure_llvmCore 2 $Flavor \
- $llvmCore_de_phase2_objdir $llvmCore_de_phase2_installdir
- build_llvmCore 2 $Flavor \
- $llvmCore_de_phase2_objdir
- build_dragonegg 2 $Flavor $llvmCore_de_phase2_installdir $dragonegg_phase2_objdir
-
- ########################################################################
- # Phase 3: Build llvmCore with newly built clang from phase 2.
- c_compiler="$gcc_compiler -fplugin=$dragonegg_phase2_objdir/dragonegg.so"
- cxx_compiler="$gxx_compiler -fplugin=$dragonegg_phase2_objdir/dragonegg.so"
- echo "# Phase 3: Building llvmCore with dragonegg"
- configure_llvmCore 3 $Flavor \
- $llvmCore_de_phase3_objdir $llvmCore_de_phase3_installdir
- build_llvmCore 3 $Flavor \
- $llvmCore_de_phase3_objdir
- build_dragonegg 3 $Flavor $llvmCore_de_phase3_installdir $dragonegg_phase3_objdir
-
- ########################################################################
- # Testing: Test phase 3
- c_compiler="$gcc_compiler -fplugin=$dragonegg_phase3_objdir/dragonegg.so"
- cxx_compiler="$gxx_compiler -fplugin=$dragonegg_phase3_objdir/dragonegg.so"
- echo "# Testing - built with dragonegg"
- test_llvmCore 3 $Flavor $llvmCore_de_phase3_objdir
-
- ########################################################################
- # Compare .o files between Phase2 and Phase3 and report which ones differ.
- echo
- echo "# Comparing Phase 2 and Phase 3 files"
- for o in `find $llvmCore_de_phase2_objdir -name '*.o'` \
- `find $dragonegg_phase2_objdir -name '*.o'` ; do
- p3=`echo $o | sed -e 's,Phase2,Phase3,'`
- if ! cmp --ignore-initial=16 $o $p3 > /dev/null 2>&1 ; then
- echo "file `basename $o` differs between dragonegg phase 2 and phase 3"
- fi
- done
- fi
-
- # Otherwise just test the core.
- if [ "$do_clang" != "yes" -a "$do_dragonegg" != "yes" ]; then
- echo "# Testing - built with system compiler"
- test_llvmCore 1 $Flavor $llvmCore_phase1_objdir
- fi
-done
-) 2>&1 | tee $LogDir/testing.$Release-$RC.log
-
-set +e
-
-# Woo hoo!
-echo "### Testing Finished ###"
-echo "### Logs: $LogDir"
-exit 0
Modified: trunk/contrib/llvm/utils/sort_includes.py
===================================================================
--- trunk/contrib/llvm/utils/sort_includes.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/sort_includes.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,87 +0,0 @@
-#!/usr/bin/env python
-
-"""Script to sort the top-most block of #include lines.
-
-Assumes the LLVM coding conventions.
-
-Currently, this script only bothers sorting the llvm/... headers. Patches
-welcome for more functionality, and sorting other header groups.
-"""
-
-import argparse
-import os
-
-def sort_includes(f):
- """Sort the #include lines of a specific file."""
-
- # Skip files which are under INPUTS trees or test trees.
- if 'INPUTS/' in f.name or 'test/' in f.name:
- return
-
- ext = os.path.splitext(f.name)[1]
- if ext not in ['.cpp', '.c', '.h', '.inc', '.def']:
- return
-
- lines = f.readlines()
- look_for_api_header = ext in ['.cpp', '.c']
- found_headers = False
- headers_begin = 0
- headers_end = 0
- api_headers = []
- local_headers = []
- project_headers = []
- system_headers = []
- for (i, l) in enumerate(lines):
- if l.strip() == '':
- continue
- if l.startswith('#include'):
- if not found_headers:
- headers_begin = i
- found_headers = True
- headers_end = i
- header = l[len('#include'):].lstrip()
- if look_for_api_header and header.startswith('"'):
- api_headers.append(header)
- look_for_api_header = False
- continue
- if header.startswith('<') or header.startswith('"gtest/'):
- system_headers.append(header)
- continue
- if (header.startswith('"llvm/') or header.startswith('"llvm-c/') or
- header.startswith('"clang/') or header.startswith('"clang-c/')):
- project_headers.append(header)
- continue
- local_headers.append(header)
- continue
-
- # Only allow comments and #defines prior to any includes. If either are
- # mixed with includes, the order might be sensitive.
- if found_headers:
- break
- if l.startswith('//') or l.startswith('#define') or l.startswith('#ifndef'):
- continue
- break
- if not found_headers:
- return
-
- local_headers = sorted(set(local_headers))
- project_headers = sorted(set(project_headers))
- system_headers = sorted(set(system_headers))
- headers = api_headers + local_headers + project_headers + system_headers
- header_lines = ['#include ' + h for h in headers]
- lines = lines[:headers_begin] + header_lines + lines[headers_end + 1:]
-
- f.seek(0)
- f.truncate()
- f.writelines(lines)
-
-def main():
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument('files', nargs='+', type=argparse.FileType('r+'),
- help='the source files to sort includes within')
- args = parser.parse_args()
- for f in args.files:
- sort_includes(f)
-
-if __name__ == '__main__':
- main()
Modified: trunk/contrib/llvm/utils/test_debuginfo.pl
===================================================================
--- trunk/contrib/llvm/utils/test_debuginfo.pl 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/test_debuginfo.pl 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,61 +0,0 @@
-#!/usr/bin/perl
-#
-# This script tests debugging information generated by a compiler.
-# Input arguments
-# - Input source program. Usually this source file is decorated using
-# special comments to communicate debugger commands.
-# - Executable file. This file is generated by the compiler.
-#
-# This perl script extracts debugger commands from input source program
-# comments in a script. A debugger is used to load the executable file
-# and run the script generated from source program comments. Finally,
-# the debugger output is checked, using FileCheck, to validate
-# debugging information.
-
-use File::Basename;
-
-my $testcase_file = $ARGV[0];
-my $executable_file = $ARGV[1];
-
-my $input_filename = basename $testcase_file;
-my $output_dir = dirname $executable_file;
-
-my $debugger_script_file = "$output_dir/$input_filename.debugger.script";
-my $output_file = "$output_dir/$input_filename.gdb.output";
-
-# Extract debugger commands from testcase. They are marked with DEBUGGER:
-# at the beginning of a comment line.
-open(INPUT, $testcase_file);
-open(OUTPUT, ">$debugger_script_file");
-while(<INPUT>) {
- my($line) = $_;
- $i = index($line, "DEBUGGER:");
- if ( $i >= 0) {
- $l = length("DEBUGGER:");
- $s = substr($line, $i + $l);
- print OUTPUT "$s";
- }
-}
-print OUTPUT "\n";
-print OUTPUT "quit\n";
-close(INPUT);
-close(OUTPUT);
-
-# setup debugger and debugger options to run a script.
-my $my_debugger = $ENV{'DEBUGGER'};
-if (!$my_debugger) {
- $my_debugger = "gdb";
-}
-my $debugger_options = "-q -batch -n -x";
-
-# run debugger and capture output.
-system("$my_debugger $debugger_options $debugger_script_file $executable_file > $output_file 2>&1");
-
-# validate output.
-system("FileCheck", "-input-file", "$output_file", "$testcase_file");
-if ($?>>8 == 1) {
- exit 1;
-}
-else {
- exit 0;
-}
Modified: trunk/contrib/llvm/utils/testgen/mc-bundling-x86-gen.py
===================================================================
--- trunk/contrib/llvm/utils/testgen/mc-bundling-x86-gen.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/testgen/mc-bundling-x86-gen.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,103 +0,0 @@
-
-#!/usr/bin/python
-
-# Auto-generates an exhaustive and repetitive test for correct bundle-locked
-# alignment on x86.
-# For every possible offset in an aligned bundle, a bundle-locked group of every
-# size in the inclusive range [1, bundle_size] is inserted. An appropriate CHECK
-# is added to verify that NOP padding occurred (or did not occur) as expected.
-# Run with --align-to-end to generate a similar test with align_to_end for each
-# .bundle_lock directive.
-
-# This script runs with Python 2.7 and 3.2+
-
-from __future__ import print_function
-import argparse
-
-BUNDLE_SIZE_POW2 = 4
-BUNDLE_SIZE = 2 ** BUNDLE_SIZE_POW2
-
-PREAMBLE = '''
-# RUN: llvm-mc -filetype=obj -triple i386-pc-linux-gnu %s -o - \\
-# RUN: | llvm-objdump -triple i386 -disassemble -no-show-raw-insn - | FileCheck %s
-
-# !!! This test is auto-generated from utils/testgen/mc-bundling-x86-gen.py !!!
-# It tests that bundle-aligned grouping works correctly in MC. Read the
-# source of the script for more details.
-
- .text
- .bundle_align_mode {0}
-'''.format(BUNDLE_SIZE_POW2).lstrip()
-
-ALIGNTO = ' .align {0}, 0x90'
-NOPFILL = ' .fill {0}, 1, 0x90'
-
-def print_bundle_locked_sequence(len, align_to_end=False):
- print(' .bundle_lock{0}'.format(' align_to_end' if align_to_end else ''))
- print(' .rept {0}'.format(len))
- print(' inc %eax')
- print(' .endr')
- print(' .bundle_unlock')
-
-def generate(align_to_end=False):
- print(PREAMBLE)
-
- ntest = 0
- for instlen in range(1, BUNDLE_SIZE + 1):
- for offset in range(0, BUNDLE_SIZE):
- # Spread out all the instructions to not worry about cross-bundle
- # interference.
- print(ALIGNTO.format(2 * BUNDLE_SIZE))
- print('INSTRLEN_{0}_OFFSET_{1}:'.format(instlen, offset))
- if offset > 0:
- print(NOPFILL.format(offset))
- print_bundle_locked_sequence(instlen, align_to_end)
-
- # Now generate an appropriate CHECK line
- base_offset = ntest * 2 * BUNDLE_SIZE
- inst_orig_offset = base_offset + offset # had it not been padded...
-
- def print_check(adjusted_offset=None, nop_split_offset=None):
- if adjusted_offset is not None:
- print('# CHECK: {0:x}: nop'.format(inst_orig_offset))
- if nop_split_offset is not None:
- print('# CHECK: {0:x}: nop'.format(nop_split_offset))
- print('# CHECK: {0:x}: incl'.format(adjusted_offset))
- else:
- print('# CHECK: {0:x}: incl'.format(inst_orig_offset))
-
- if align_to_end:
- if offset + instlen == BUNDLE_SIZE:
- # No padding needed
- print_check()
- elif offset + instlen < BUNDLE_SIZE:
- # Pad to end at nearest bundle boundary
- offset_to_end = base_offset + (BUNDLE_SIZE - instlen)
- print_check(offset_to_end)
- else: # offset + instlen > BUNDLE_SIZE
- # Pad to end at next bundle boundary, splitting the nop sequence
- # at the nearest bundle boundary
- offset_to_nearest_bundle = base_offset + BUNDLE_SIZE
- offset_to_end = base_offset + (BUNDLE_SIZE * 2 - instlen)
- if offset_to_nearest_bundle == offset_to_end:
- offset_to_nearest_bundle = None
- print_check(offset_to_end, offset_to_nearest_bundle)
- else:
- if offset + instlen > BUNDLE_SIZE:
- # Padding needed
- aligned_offset = (inst_orig_offset + instlen) & ~(BUNDLE_SIZE - 1)
- print_check(aligned_offset)
- else:
- # No padding needed
- print_check()
-
- print()
- ntest += 1
-
-if __name__ == '__main__':
- argparser = argparse.ArgumentParser()
- argparser.add_argument('--align-to-end',
- action='store_true',
- help='generate .bundle_lock with align_to_end option')
- args = argparser.parse_args()
- generate(align_to_end=args.align_to_end)
Modified: trunk/contrib/llvm/utils/textmate/README
===================================================================
--- trunk/contrib/llvm/utils/textmate/README 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/textmate/README 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,8 +0,0 @@
-This directory contains a "bundle" for doing syntax highlighting of TableGen
-files for the TextMate editor for OS X. The highlighting follows that done
-by the TextMate "C" bundle. Currently, keywords, comments, and strings are
-highlighted.
-
-To install this bundle, copy it to the per user area:
- cp -R utils/textmate/TableGen.tmbundle \
- ~/Library/Application\ Support/TextMate/Bundles/TableGen.tmbundle
Modified: trunk/contrib/llvm/utils/textmate/TableGen.tmbundle/Syntaxes/TableGen.tmLanguage
===================================================================
(Binary files differ)
Modified: trunk/contrib/llvm/utils/textmate/TableGen.tmbundle/info.plist
===================================================================
(Binary files differ)
Modified: trunk/contrib/llvm/utils/unittest/UnitTestMain/TestMain.cpp
===================================================================
--- trunk/contrib/llvm/utils/unittest/UnitTestMain/TestMain.cpp 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/unittest/UnitTestMain/TestMain.cpp 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,49 +0,0 @@
-//===--- utils/unittest/UnitTestMain/TestMain.cpp - unittest driver -------===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===----------------------------------------------------------------------===//
-
-#include "llvm/Config/config.h"
-#include "llvm/Support/CommandLine.h"
-#include "llvm/Support/Signals.h"
-#include "gtest/gtest.h"
-
-
-#if defined(LLVM_ON_WIN32)
-# include <windows.h>
-# if defined(_MSC_VER)
-# include <crtdbg.h>
-# endif
-#endif
-
-const char *TestMainArgv0;
-
-int main(int argc, char **argv) {
- llvm::sys::PrintStackTraceOnErrorSignal();
- testing::InitGoogleTest(&argc, argv);
- llvm::cl::ParseCommandLineOptions(argc, argv);
-
- // Make it easy for a test to re-execute itself by saving argv[0].
- TestMainArgv0 = argv[0];
-
-# if defined(LLVM_ON_WIN32)
- // Disable all of the possible ways Windows conspires to make automated
- // testing impossible.
- ::SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
-# if defined(_MSC_VER)
- ::_set_error_mode(_OUT_TO_STDERR);
- _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
- _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
- _CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
- _CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR);
- _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
- _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
-# endif
-# endif
-
- return RUN_ALL_TESTS();
-}
Modified: trunk/contrib/llvm/utils/wciia.py
===================================================================
--- trunk/contrib/llvm/utils/wciia.py 2015-06-20 23:09:57 UTC (rev 7057)
+++ trunk/contrib/llvm/utils/wciia.py 2015-06-20 23:10:46 UTC (rev 7058)
@@ -1,125 +0,0 @@
-#!/usr/bin/env python
-
-"""
-wciia - Whose Code Is It Anyway
-
-Determines code owner of the file/folder relative to the llvm source root.
-Code owner is determined from the content of the CODE_OWNERS.TXT
-by parsing the D: field
-
-usage:
-
-utils/wciia.py path
-
-limitations:
-- must be run from llvm source root
-- very simplistic algorithm
-- only handles * as a wildcard
-- not very user friendly
-- does not handle the proposed F: field
-
-"""
-
-import os
-
-code_owners = {}
-
-def process_files_and_folders(owner):
- filesfolders = owner['filesfolders']
- # paths must be in ( ... ) so strip them
- lpar = filesfolders.find('(')
- rpar = filesfolders.rfind(')')
- if rpar <= lpar:
- # give up
- return
- paths = filesfolders[lpar+1:rpar]
- # split paths
- owner['paths'] = []
- for path in paths.split():
- owner['paths'].append(path)
-
-def process_code_owner(owner):
- if 'filesfolders' in owner:
- filesfolders = owner['filesfolders']
- else:
-# print "F: field missing, using D: field"
- owner['filesfolders'] = owner['description']
- process_files_and_folders(owner)
- code_owners[owner['name']] = owner
-
-# process CODE_OWNERS.TXT first
-code_owners_file = open("CODE_OWNERS.TXT", "r").readlines()
-code_owner = {}
-for line in code_owners_file:
- for word in line.split():
- if word == "N:":
- name = line[2:].strip()
- if code_owner:
- process_code_owner(code_owner)
- code_owner = {}
- # reset the values
- code_owner['name'] = name
- if word == "E:":
- email = line[2:].strip()
- code_owner['email'] = email
- if word == "D:":
- description = line[2:].strip()
- code_owner['description'] = description
- if word == "F:":
- filesfolders = line[2:].strip()
- code_owner['filesfolders'].append(filesfolders)
-
-def find_owners(fpath):
- onames = []
- lmatch = -1
- # very simplistic way of findning the best match
- for name in code_owners:
- owner = code_owners[name]
- if 'paths' in owner:
- for path in owner['paths']:
-# print "searching (" + path + ")"
- # try exact match
- if fpath == path:
- return name
- # see if path ends with a *
- rstar = path.rfind('*')
- if rstar>0:
- # try the longest match,
- rpos = -1
- if len(fpath) < len(path):
- rpos = path.find(fpath)
- if rpos == 0:
- onames.append(name)
- onames.append('Chris Lattner')
- return onames
-
-# now lest try to find the owner of the file or folder
-import sys
-
-if len(sys.argv) < 2:
- print "usage " + sys.argv[0] + " file_or_folder"
- exit(-1)
-
-# the path we are checking
-path = str(sys.argv[1])
-
-# check if this is real path
-if not os.path.exists(path):
- print "path (" + path + ") does not exist"
- exit(-1)
-
-owners_name = find_owners(path)
-
-# be gramatically correct
-print "The owner(s) of the (" + path + ") is(are) : " + str(owners_name)
-
-exit(0)
-
-# bottom up walk of the current .
-# not yet used
-root = "."
-for dir,subdirList,fileList in os.walk( root , topdown=False ) :
- print "dir :" , dir
- for fname in fileList :
- print "-" , fname
- print
More information about the Midnightbsd-cvs
mailing list