36fe8fb9f6915500189c8bcd9e28ef8635d707aa
[oota-llvm.git] / utils / lit / lit / util.py
1 import errno
2 import itertools
3 import math
4 import os
5 import platform
6 import signal
7 import subprocess
8 import sys
9
10 def to_bytes(str):
11     # Encode to UTF-8 to get binary data.
12     return str.encode('utf-8')
13
14 def to_string(bytes):
15     if isinstance(bytes, str):
16         return bytes
17     return to_bytes(bytes)
18
19 def convert_string(bytes):
20     try:
21         return to_string(bytes.decode('utf-8'))
22     except UnicodeError:
23         return str(bytes)
24
25 def detectCPUs():
26     """
27     Detects the number of CPUs on a system. Cribbed from pp.
28     """
29     # Linux, Unix and MacOS:
30     if hasattr(os, "sysconf"):
31         if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
32             # Linux & Unix:
33             ncpus = os.sysconf("SC_NPROCESSORS_ONLN")
34             if isinstance(ncpus, int) and ncpus > 0:
35                 return ncpus
36         else: # OSX:
37             return int(capture(['sysctl', '-n', 'hw.ncpu']))
38     # Windows:
39     if "NUMBER_OF_PROCESSORS" in os.environ:
40         ncpus = int(os.environ["NUMBER_OF_PROCESSORS"])
41         if ncpus > 0:
42             # With more than 32 processes, process creation often fails with
43             # "Too many open files".  FIXME: Check if there's a better fix.
44             return min(ncpus, 32)
45     return 1 # Default
46
47 def mkdir_p(path):
48     """mkdir_p(path) - Make the "path" directory, if it does not exist; this
49     will also make directories for any missing parent directories."""
50     if not path or os.path.exists(path):
51         return
52
53     parent = os.path.dirname(path)
54     if parent != path:
55         mkdir_p(parent)
56
57     try:
58         os.mkdir(path)
59     except OSError:
60         e = sys.exc_info()[1]
61         # Ignore EEXIST, which may occur during a race condition.
62         if e.errno != errno.EEXIST:
63             raise
64
65 def capture(args, env=None):
66     """capture(command) - Run the given command (or argv list) in a shell and
67     return the standard output."""
68     p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
69                          env=env)
70     out,_ = p.communicate()
71     return convert_string(out)
72
73 def which(command, paths = None):
74     """which(command, [paths]) - Look up the given command in the paths string
75     (or the PATH environment variable, if unspecified)."""
76
77     if paths is None:
78         paths = os.environ.get('PATH','')
79
80     # Check for absolute match first.
81     if os.path.isfile(command):
82         return command
83
84     # Would be nice if Python had a lib function for this.
85     if not paths:
86         paths = os.defpath
87
88     # Get suffixes to search.
89     # On Cygwin, 'PATHEXT' may exist but it should not be used.
90     if os.pathsep == ';':
91         pathext = os.environ.get('PATHEXT', '').split(';')
92     else:
93         pathext = ['']
94
95     # Search the paths...
96     for path in paths.split(os.pathsep):
97         for ext in pathext:
98             p = os.path.join(path, command + ext)
99             if os.path.exists(p) and not os.path.isdir(p):
100                 return p
101
102     return None
103
104 def checkToolsPath(dir, tools):
105     for tool in tools:
106         if not os.path.exists(os.path.join(dir, tool)):
107             return False;
108     return True;
109
110 def whichTools(tools, paths):
111     for path in paths.split(os.pathsep):
112         if checkToolsPath(path, tools):
113             return path
114     return None
115
116 def printHistogram(items, title = 'Items'):
117     items.sort(key = lambda item: item[1])
118
119     maxValue = max([v for _,v in items])
120
121     # Select first "nice" bar height that produces more than 10 bars.
122     power = int(math.ceil(math.log(maxValue, 10)))
123     for inc in itertools.cycle((5, 2, 2.5, 1)):
124         barH = inc * 10**power
125         N = int(math.ceil(maxValue / barH))
126         if N > 10:
127             break
128         elif inc == 1:
129             power -= 1
130
131     histo = [set() for i in range(N)]
132     for name,v in items:
133         bin = min(int(N * v/maxValue), N-1)
134         histo[bin].add(name)
135
136     barW = 40
137     hr = '-' * (barW + 34)
138     print('\nSlowest %s:' % title)
139     print(hr)
140     for name,value in items[-20:]:
141         print('%.2fs: %s' % (value, name))
142     print('\n%s Times:' % title)
143     print(hr)
144     pDigits = int(math.ceil(math.log(maxValue, 10)))
145     pfDigits = max(0, 3-pDigits)
146     if pfDigits:
147         pDigits += pfDigits + 1
148     cDigits = int(math.ceil(math.log(len(items), 10)))
149     print("[%s] :: [%s] :: [%s]" % ('Range'.center((pDigits+1)*2 + 3),
150                                     'Percentage'.center(barW),
151                                     'Count'.center(cDigits*2 + 1)))
152     print(hr)
153     for i,row in enumerate(histo):
154         pct = float(len(row)) / len(items)
155         w = int(barW * pct)
156         print("[%*.*fs,%*.*fs) :: [%s%s] :: [%*d/%*d]" % (
157             pDigits, pfDigits, i*barH, pDigits, pfDigits, (i+1)*barH,
158             '*'*w, ' '*(barW-w), cDigits, len(row), cDigits, len(items)))
159
160 # Close extra file handles on UNIX (on Windows this cannot be done while
161 # also redirecting input).
162 kUseCloseFDs = not (platform.system() == 'Windows')
163 def executeCommand(command, cwd=None, env=None, input=None):
164     p = subprocess.Popen(command, cwd=cwd,
165                          stdin=subprocess.PIPE,
166                          stdout=subprocess.PIPE,
167                          stderr=subprocess.PIPE,
168                          env=env, close_fds=kUseCloseFDs)
169     out,err = p.communicate(input=input)
170     exitCode = p.wait()
171
172     # Detect Ctrl-C in subprocess.
173     if exitCode == -signal.SIGINT:
174         raise KeyboardInterrupt
175
176     # Ensure the resulting output is always of string type.
177     out = convert_string(out)
178     err = convert_string(err)
179
180     return out, err, exitCode
181
182 def usePlatformSdkOnDarwin(config, lit_config):
183     # On Darwin, support relocatable SDKs by providing Clang with a
184     # default system root path.
185     if 'darwin' in config.target_triple:
186         try:
187             cmd = subprocess.Popen(['xcrun', '--show-sdk-path'],
188                                    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
189             out, err = cmd.communicate()
190             out = out.strip()
191             res = cmd.wait()
192         except OSError:
193             res = -1
194         if res == 0 and out:
195             sdk_path = out
196             lit_config.note('using SDKROOT: %r' % sdk_path)
197             config.environment['SDKROOT'] = sdk_path