blob: 4472ddcc37f073c4a9b205a0c9e9ec5e44128670 [file] [log] [blame]
Daniel Dunbar378530c2009-01-05 19:53:30 +00001import os
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +00002import platform
Daniel Dunbara95c6392009-02-19 22:59:57 +00003import subprocess
Daniel Dunbar378530c2009-01-05 19:53:30 +00004import sys
5import tempfile
6from pprint import pprint
7
8###
9
10import Arguments
11import Jobs
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +000012import HostInfo
Daniel Dunbar378530c2009-01-05 19:53:30 +000013import Phases
14import Tools
15import Types
16import Util
17
18# FIXME: Clean up naming of options and arguments. Decide whether to
19# rename Option and be consistent about use of Option/Arg.
20
21####
22
Daniel Dunbar378530c2009-01-05 19:53:30 +000023class Driver(object):
Daniel Dunbara0026f22009-01-16 23:12:12 +000024 def __init__(self, driverName, driverDir):
25 self.driverName = driverName
26 self.driverDir = driverDir
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +000027 self.hostInfo = None
Daniel Dunbare9f1a692009-01-06 06:12:13 +000028 self.parser = Arguments.OptionParser()
Daniel Dunbar7c2f91b2009-01-14 01:03:36 +000029 self.cccHostBits = self.cccHostMachine = None
30 self.cccHostSystem = self.cccHostRelease = None
31 self.cccCXX = False
Daniel Dunbar4c751dc2009-01-14 01:32:05 +000032 self.cccEcho = False
Daniel Dunbar7c2f91b2009-01-14 01:03:36 +000033 self.cccFallback = False
Daniel Dunbar72999172009-01-29 23:54:06 +000034 self.cccNoClang = self.cccNoClangCXX = self.cccNoClangPreprocessor = False
35 self.cccClangArchs = None
Daniel Dunbar378530c2009-01-05 19:53:30 +000036
Daniel Dunbar8fd28cd2009-01-28 19:26:20 +000037 # Certain options suppress the 'no input files' warning.
38 self.suppressMissingInputWarning = False
39
Daniel Dunbar61320532009-02-22 01:23:52 +000040 # Temporary files used in compilation, removed on exit.
41 self.tempFiles = []
42 # Result files produced by compilation, removed on error.
43 self.resultFiles = []
44
Daniel Dunbardbc9ee92009-01-09 22:21:24 +000045 # Host queries which can be forcibly over-riden by the user for
46 # testing purposes.
47 #
48 # FIXME: We should make sure these are drawn from a fixed set so
49 # that nothing downstream ever plays a guessing game.
50
51 def getHostBits(self):
52 if self.cccHostBits:
53 return self.cccHostBits
54
55 return platform.architecture()[0].replace('bit','')
56
57 def getHostMachine(self):
58 if self.cccHostMachine:
59 return self.cccHostMachine
60
61 machine = platform.machine()
62 # Normalize names.
63 if machine == 'Power Macintosh':
64 return 'ppc'
Daniel Dunbar405327e2009-01-27 19:29:51 +000065 if machine == 'x86_64':
66 return 'i386'
Daniel Dunbardbc9ee92009-01-09 22:21:24 +000067 return machine
68
69 def getHostSystemName(self):
70 if self.cccHostSystem:
71 return self.cccHostSystem
72
73 return platform.system().lower()
74
Daniel Dunbarc2148562009-01-12 04:21:12 +000075 def getHostReleaseName(self):
76 if self.cccHostRelease:
77 return self.cccHostRelease
78
79 return platform.release()
80
Daniel Dunbar4c751dc2009-01-14 01:32:05 +000081 def getenvBool(self, name):
82 var = os.getenv(name)
83 if not var:
84 return False
85
86 try:
87 return bool(int(var))
88 except:
89 return False
90
Daniel Dunbardbc9ee92009-01-09 22:21:24 +000091 ###
92
Daniel Dunbarf677a602009-01-21 02:03:52 +000093 def getFilePath(self, name, toolChain=None):
94 tc = toolChain or self.toolChain
95 for p in tc.filePathPrefixes:
96 path = os.path.join(p, name)
97 if os.path.exists(path):
98 return path
99 return name
100
101 def getProgramPath(self, name, toolChain=None):
102 tc = toolChain or self.toolChain
103 for p in tc.programPathPrefixes:
104 path = os.path.join(p, name)
105 if os.path.exists(path):
106 return path
107 return name
108
109 ###
110
Daniel Dunbar74727872009-01-06 01:35:44 +0000111 def run(self, argv):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000112 # FIXME: Things to support from environment: GCC_EXEC_PREFIX,
113 # COMPILER_PATH, LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS,
114 # QA_OVERRIDE_GCC3_OPTIONS, ...?
115
116 # FIXME: -V and -b processing
117
118 # Handle some special -ccc- options used for testing which are
119 # only allowed at the beginning of the command line.
120 cccPrintOptions = False
121 cccPrintPhases = False
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000122
123 # FIXME: How to handle override of host? ccc specific options?
124 # Abuse -b?
Daniel Dunbar72999172009-01-29 23:54:06 +0000125 arg = os.getenv('CCC_ADD_ARGS')
126 if arg:
127 args = filter(None, map(str.strip, arg.split(',')))
128 argv = args + argv
Daniel Dunbar4c751dc2009-01-14 01:32:05 +0000129
Daniel Dunbar74727872009-01-06 01:35:44 +0000130 while argv and argv[0].startswith('-ccc-'):
Daniel Dunbara0026f22009-01-16 23:12:12 +0000131 fullOpt,argv = argv[0],argv[1:]
132 opt = fullOpt[5:]
Daniel Dunbar378530c2009-01-05 19:53:30 +0000133
134 if opt == 'print-options':
135 cccPrintOptions = True
136 elif opt == 'print-phases':
137 cccPrintPhases = True
Daniel Dunbar7c2f91b2009-01-14 01:03:36 +0000138 elif opt == 'cxx':
139 self.cccCXX = True
Daniel Dunbar4c751dc2009-01-14 01:32:05 +0000140 elif opt == 'echo':
141 self.cccEcho = True
Daniel Dunbar7c2f91b2009-01-14 01:03:36 +0000142 elif opt == 'fallback':
143 self.cccFallback = True
Daniel Dunbar72999172009-01-29 23:54:06 +0000144
145 elif opt == 'no-clang':
146 self.cccNoClang = True
147 elif opt == 'no-clang-cxx':
148 self.cccNoClangCXX = True
149 elif opt == 'no-clang-cpp':
150 self.cccNoClangPreprocessor = True
151 elif opt == 'clang-archs':
152 self.cccClangArchs,argv = argv[0].split(','),argv[1:]
153
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000154 elif opt == 'host-bits':
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000155 self.cccHostBits,argv = argv[0],argv[1:]
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000156 elif opt == 'host-machine':
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000157 self.cccHostMachine,argv = argv[0],argv[1:]
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000158 elif opt == 'host-system':
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000159 self.cccHostSystem,argv = argv[0],argv[1:]
Daniel Dunbarc2148562009-01-12 04:21:12 +0000160 elif opt == 'host-release':
161 self.cccHostRelease,argv = argv[0],argv[1:]
Daniel Dunbar378530c2009-01-05 19:53:30 +0000162 else:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000163 raise Arguments.InvalidArgumentsError("invalid option: %r" % fullOpt)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000164
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000165 self.hostInfo = HostInfo.getHostInfo(self)
Daniel Dunbar08dea462009-01-10 02:07:54 +0000166 self.toolChain = self.hostInfo.getToolChain()
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000167
Daniel Dunbar74727872009-01-06 01:35:44 +0000168 args = self.parser.parseArgs(argv)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000169
170 # FIXME: Ho hum I have just realized -Xarch_ is broken. We really
171 # need to reparse the Arguments after they have been expanded by
172 # -Xarch. How is this going to work?
173 #
174 # Scratch that, we aren't going to do that; it really disrupts the
175 # organization, doesn't consistently work with gcc-dd, and is
176 # confusing. Instead we are going to enforce that -Xarch_ is only
177 # used with options which do not alter the driver behavior. Let's
178 # hope this is ok, because the current architecture is a little
179 # tied to it.
180
181 if cccPrintOptions:
Daniel Dunbar74727872009-01-06 01:35:44 +0000182 self.printOptions(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000183 sys.exit(0)
184
Daniel Dunbar74727872009-01-06 01:35:44 +0000185 self.handleImmediateOptions(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000186
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000187 if self.hostInfo.useDriverDriver():
Daniel Dunbar74727872009-01-06 01:35:44 +0000188 phases = self.buildPipeline(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000189 else:
Daniel Dunbar74727872009-01-06 01:35:44 +0000190 phases = self.buildNormalPipeline(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000191
192 if cccPrintPhases:
Daniel Dunbar74727872009-01-06 01:35:44 +0000193 self.printPhases(phases, args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000194 sys.exit(0)
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000195
Daniel Dunbar378530c2009-01-05 19:53:30 +0000196 if 0:
197 print Util.pprint(phases)
198
Daniel Dunbar74727872009-01-06 01:35:44 +0000199 jobs = self.bindPhases(phases, args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000200
201 # FIXME: We should provide some basic sanity checking of the
202 # pipeline as a "verification" sort of stage. For example, the
203 # pipeline should never end up writing to an output file in two
204 # places (I think). The pipeline should also never end up writing
205 # to an output file that is an input.
206 #
207 # This is intended to just be a "verify" step, not a functionality
208 # step. It should catch things like the driver driver not
209 # preventing -save-temps, but it shouldn't change behavior (so we
210 # can turn it off in Release-Asserts builds).
211
212 # Print in -### syntax.
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000213 hasHashHashHash = args.getLastArg(self.parser.hashHashHashOption)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000214 if hasHashHashHash:
215 self.claim(hasHashHashHash)
216 for j in jobs.iterjobs():
217 if isinstance(j, Jobs.Command):
Daniel Dunbard87b6ec2009-01-12 19:36:35 +0000218 print >>sys.stderr, ' "%s"' % '" "'.join(j.getArgv())
Daniel Dunbar378530c2009-01-05 19:53:30 +0000219 elif isinstance(j, Jobs.PipedJob):
220 for c in j.commands:
Daniel Dunbard87b6ec2009-01-12 19:36:35 +0000221 print >>sys.stderr, ' "%s" %c' % ('" "'.join(c.getArgv()),
222 "| "[c is j.commands[-1]])
Daniel Dunbar378530c2009-01-05 19:53:30 +0000223 elif not isinstance(j, JobList):
224 raise ValueError,'Encountered unknown job.'
225 sys.exit(0)
226
Daniel Dunbar61320532009-02-22 01:23:52 +0000227 try:
228 try:
229 self.executeJobs(args, jobs)
230 except:
231 for f in self.resultFiles:
232 # Fail if removing a result fails:
233 if os.path.exists(f):
234 os.remove(f)
235 raise
236 finally:
237 for f in self.tempFiles:
238 # Ignore failures in removing temporary files
239 try:
240 os.remove(f)
241 except:
242 pass
243
244 def executeJobs(self, args, jobs):
Daniel Dunbar8fd28cd2009-01-28 19:26:20 +0000245 vArg = args.getLastArg(self.parser.vOption)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000246 for j in jobs.iterjobs():
247 if isinstance(j, Jobs.Command):
Daniel Dunbar8fd28cd2009-01-28 19:26:20 +0000248 if vArg or self.cccEcho:
249 print >>sys.stderr, ' '.join(map(str,j.getArgv()))
Anders Carlsson76613bf2009-01-18 02:54:17 +0000250 sys.stderr.flush()
Daniel Dunbara95c6392009-02-19 22:59:57 +0000251 p = self.startSubprocess(j.getArgv(), j.executable)
252 res = p.wait()
Daniel Dunbar378530c2009-01-05 19:53:30 +0000253 if res:
254 sys.exit(res)
Daniel Dunbara95c6392009-02-19 22:59:57 +0000255
Daniel Dunbar378530c2009-01-05 19:53:30 +0000256 elif isinstance(j, Jobs.PipedJob):
Daniel Dunbare19ed8e2009-01-17 02:02:35 +0000257 procs = []
258 for sj in j.commands:
Daniel Dunbar8fd28cd2009-01-28 19:26:20 +0000259 if vArg or self.cccEcho:
260 print >> sys.stderr, ' '.join(map(str,sj.getArgv()))
Daniel Dunbare19ed8e2009-01-17 02:02:35 +0000261 sys.stdout.flush()
262
263 if not procs:
264 stdin = None
265 else:
266 stdin = procs[-1].stdout
267 if sj is j.commands[-1]:
268 stdout = None
269 else:
270 stdout = subprocess.PIPE
Daniel Dunbara95c6392009-02-19 22:59:57 +0000271
272 procs.append(self.startSubprocess(sj.getArgv(), sj.executable,
273 stdin=stdin,
274 stdout=stdout))
275
Daniel Dunbare19ed8e2009-01-17 02:02:35 +0000276 for proc in procs:
277 res = proc.wait()
278 if res:
279 sys.exit(res)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000280 else:
281 raise ValueError,'Encountered unknown job.'
282
Daniel Dunbara95c6392009-02-19 22:59:57 +0000283 def startSubprocess(self, argv, executable, **kwargs):
284 try:
285 return subprocess.Popen(argv, executable=executable, **kwargs)
286 except OSError, e:
287 self.warning("error trying to exec '%s': %s" %
288 (executable, e.args[1]))
289 sys.exit(1)
290
Daniel Dunbar378530c2009-01-05 19:53:30 +0000291 def claim(self, option):
292 # FIXME: Move to OptionList once introduced and implement.
293 pass
294
295 def warning(self, message):
Daniel Dunbara0026f22009-01-16 23:12:12 +0000296 print >>sys.stderr,'%s: %s' % (self.driverName, message)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000297
Daniel Dunbar74727872009-01-06 01:35:44 +0000298 def printOptions(self, args):
299 for i,arg in enumerate(args):
Daniel Dunbar74727872009-01-06 01:35:44 +0000300 if isinstance(arg, Arguments.MultipleValuesArg):
301 values = list(args.getValues(arg))
302 elif isinstance(arg, Arguments.ValueArg):
303 values = [args.getValue(arg)]
304 elif isinstance(arg, Arguments.JoinedAndSeparateValuesArg):
305 values = [args.getJoinedValue(arg), args.getSeparateValue(arg)]
Daniel Dunbar378530c2009-01-05 19:53:30 +0000306 else:
307 values = []
Daniel Dunbar927a5092009-01-06 02:30:10 +0000308 print 'Option %d - Name: "%s", Values: {%s}' % (i, arg.opt.name,
Daniel Dunbar378530c2009-01-05 19:53:30 +0000309 ', '.join(['"%s"' % v
310 for v in values]))
311
Daniel Dunbar74727872009-01-06 01:35:44 +0000312 def printPhases(self, phases, args):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000313 def printPhase(p, f, steps, arch=None):
314 if p in steps:
315 return steps[p]
316 elif isinstance(p, Phases.BindArchAction):
317 for kid in p.inputs:
318 printPhase(kid, f, steps, p.arch)
319 steps[p] = len(steps)
320 return
321
322 if isinstance(p, Phases.InputAction):
323 phaseName = 'input'
Daniel Dunbar74727872009-01-06 01:35:44 +0000324 inputStr = '"%s"' % args.getValue(p.filename)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000325 else:
326 phaseName = p.phase.name
327 inputs = [printPhase(i, f, steps, arch)
328 for i in p.inputs]
329 inputStr = '{%s}' % ', '.join(map(str, inputs))
330 if arch is not None:
Daniel Dunbar74727872009-01-06 01:35:44 +0000331 phaseName += '-' + args.getValue(arch)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000332 steps[p] = index = len(steps)
333 print "%d: %s, %s, %s" % (index,phaseName,inputStr,p.type.name)
334 return index
335 steps = {}
336 for phase in phases:
337 printPhase(phase, sys.stdout, steps)
Daniel Dunbar8fd28cd2009-01-28 19:26:20 +0000338
339 def printVersion(self):
340 # FIXME: Print default target triple.
Mike Stump406abf62009-02-11 01:01:17 +0000341 vers = '$HeadURL$'
342 vers = vers.split('/tools/ccc')[0]
Mike Stump6bf3bd42009-02-11 01:11:36 +0000343 vers = vers.split('/clang/tools/clang')[0]
Mike Stump406abf62009-02-11 01:01:17 +0000344 vers = ' (' + vers[10:] + ')'
345 print >>sys.stderr,'ccc version 1.0' + vers
Daniel Dunbar378530c2009-01-05 19:53:30 +0000346
Daniel Dunbar74727872009-01-06 01:35:44 +0000347 def handleImmediateOptions(self, args):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000348 # FIXME: Some driver Arguments are consumed right off the bat,
349 # like -dumpversion. Currently the gcc-dd handles these
350 # poorly, so we should be ok handling them upfront instead of
351 # after driver-driver level dispatching.
352 #
353 # FIXME: The actual order of these options in gcc is all over the
354 # place. The -dump ones seem to be first and in specification
355 # order, but there are other levels of precedence. For example,
356 # -print-search-dirs is evaluated before -print-prog-name=,
357 # regardless of order (and the last instance of -print-prog-name=
358 # wins verse itself).
359 #
360 # FIXME: Do we want to report "argument unused" type errors in the
361 # presence of things like -dumpmachine and -print-search-dirs?
362 # Probably not.
Daniel Dunbar8fd28cd2009-01-28 19:26:20 +0000363 if (args.getLastArg(self.parser.vOption) or
364 args.getLastArg(self.parser.hashHashHashOption)):
365 self.printVersion()
366 self.suppressMissingInputWarning = True
367
Daniel Dunbarf677a602009-01-21 02:03:52 +0000368 arg = (args.getLastArg(self.parser.dumpmachineOption) or
369 args.getLastArg(self.parser.dumpversionOption) or
370 args.getLastArg(self.parser.printSearchDirsOption))
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000371 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000372 raise NotImplementedError('%s unsupported' % arg.opt.name)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000373
Daniel Dunbarf677a602009-01-21 02:03:52 +0000374 arg = (args.getLastArg(self.parser.dumpspecsOption) or
375 args.getLastArg(self.parser.printMultiDirectoryOption) or
Daniel Dunbar73fb9072009-01-23 02:00:46 +0000376 args.getLastArg(self.parser.printMultiOsDirectoryOption) or
Daniel Dunbarf677a602009-01-21 02:03:52 +0000377 args.getLastArg(self.parser.printMultiLibOption))
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000378 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000379 raise Arguments.InvalidArgumentsError('%s unsupported by this driver' % arg.opt.name)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000380
381 arg = args.getLastArg(self.parser.printFileNameOption)
382 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000383 print self.getFilePath(args.getValue(arg))
384 sys.exit(0)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000385
386 arg = args.getLastArg(self.parser.printProgNameOption)
387 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000388 print self.getProgramPath(args.getValue(arg))
389 sys.exit(0)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000390
Daniel Dunbarf677a602009-01-21 02:03:52 +0000391 arg = args.getLastArg(self.parser.printLibgccFileNameOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000392 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000393 print self.getFilePath('libgcc.a')
394 sys.exit(0)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000395
Daniel Dunbar74727872009-01-06 01:35:44 +0000396 def buildNormalPipeline(self, args):
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000397 hasAnalyze = args.getLastArg(self.parser.analyzeOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000398 hasCombine = args.getLastArg(self.parser.combineOption)
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000399 hasEmitLLVM = args.getLastArg(self.parser.emitLLVMOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000400 hasSyntaxOnly = args.getLastArg(self.parser.syntaxOnlyOption)
401 hasDashC = args.getLastArg(self.parser.cOption)
402 hasDashE = args.getLastArg(self.parser.EOption)
403 hasDashS = args.getLastArg(self.parser.SOption)
Daniel Dunbar445c46d2009-01-20 01:53:54 +0000404 hasDashM = args.getLastArg(self.parser.MOption)
405 hasDashMM = args.getLastArg(self.parser.MMOption)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000406
407 inputType = None
408 inputTypeOpt = None
409 inputs = []
410 for a in args:
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000411 if a.opt is self.parser.inputOption:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000412 inputValue = args.getValue(a)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000413 if inputType is None:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000414 base,ext = os.path.splitext(inputValue)
Daniel Dunbar6dbfa662009-02-05 23:44:44 +0000415 # stdin is handled specially.
416 if inputValue == '-':
417 if args.getLastArg(self.parser.EOption):
418 # Treat as a C input needing preprocessing
419 # (or Obj-C if over-ridden below).
420 klass = Types.CType
421 else:
422 raise Arguments.InvalidArgumentsError("-E or -x required when input is from standard input")
423 elif ext and ext in Types.kTypeSuffixMap:
Daniel Dunbar378530c2009-01-05 19:53:30 +0000424 klass = Types.kTypeSuffixMap[ext]
425 else:
426 # FIXME: Its not clear why we shouldn't just
427 # revert to unknown. I think this is more likely a
428 # bug / unintended behavior in gcc. Not very
429 # important though.
430 klass = Types.ObjectType
Daniel Dunbar6dbfa662009-02-05 23:44:44 +0000431
432 # -ObjC and -ObjC++ over-ride the default
433 # language, but only for "source files". We
434 # just treat everything that isn't a linker
435 # input as a source file.
436 #
437 # FIXME: Clean this up if we move the phase
438 # sequence into the type.
439 if klass is not Types.ObjectType:
440 if args.getLastArg(self.parser.ObjCOption):
441 klass = Types.ObjCType
442 elif args.getLastArg(self.parser.ObjCXXOption):
443 klass = Types.ObjCType
Daniel Dunbar378530c2009-01-05 19:53:30 +0000444 else:
445 assert inputTypeOpt is not None
446 self.claim(inputTypeOpt)
447 klass = inputType
Daniel Dunbara0026f22009-01-16 23:12:12 +0000448
449 # Check that the file exists. It isn't clear this is
450 # worth doing, since the tool presumably does this
451 # anyway, and this just adds an extra stat to the
452 # equation, but this is gcc compatible.
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000453 if inputValue != '-' and not os.path.exists(inputValue):
Daniel Dunbara0026f22009-01-16 23:12:12 +0000454 self.warning("%s: No such file or directory" % inputValue)
455 else:
456 inputs.append((klass, a))
Daniel Dunbarfc2ad022009-01-12 03:33:58 +0000457 elif a.opt.isLinkerInput:
458 # Treat as a linker input.
Daniel Dunbar927a5092009-01-06 02:30:10 +0000459 #
460 # FIXME: This might not be good enough. We may
461 # need to introduce another type for this case, so
462 # that other code which needs to know the inputs
463 # handles this properly. Best not to try and lipo
464 # this, for example.
465 inputs.append((Types.ObjectType, a))
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000466 elif a.opt is self.parser.xOption:
Daniel Dunbar927a5092009-01-06 02:30:10 +0000467 inputTypeOpt = a
468 value = args.getValue(a)
469 if value in Types.kTypeSpecifierMap:
470 inputType = Types.kTypeSpecifierMap[value]
471 else:
472 # FIXME: How are we going to handle diagnostics.
473 self.warning("language %s not recognized" % value)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000474
Daniel Dunbar927a5092009-01-06 02:30:10 +0000475 # FIXME: Its not clear why we shouldn't just
476 # revert to unknown. I think this is more likely a
477 # bug / unintended behavior in gcc. Not very
478 # important though.
Daniel Dunbar6cb42052009-01-13 21:07:43 +0000479 inputType = Types.ObjectType
Daniel Dunbar378530c2009-01-05 19:53:30 +0000480
481 # We claim things here so that options for which we silently allow
482 # override only ever claim the used option.
483 if hasCombine:
484 self.claim(hasCombine)
485
486 finalPhase = Phases.Phase.eOrderPostAssemble
487 finalPhaseOpt = None
488
489 # Determine what compilation mode we are in.
Daniel Dunbar445c46d2009-01-20 01:53:54 +0000490 if hasDashE or hasDashM or hasDashMM:
Daniel Dunbar378530c2009-01-05 19:53:30 +0000491 finalPhase = Phases.Phase.eOrderPreprocess
492 finalPhaseOpt = hasDashE
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000493 elif (hasAnalyze or hasSyntaxOnly or
494 hasEmitLLVM or hasDashS):
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000495 finalPhase = Phases.Phase.eOrderCompile
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000496 finalPhaseOpt = (hasAnalyze or hasSyntaxOnly or
497 hasEmitLLVM or hasDashS)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000498 elif hasDashC:
499 finalPhase = Phases.Phase.eOrderAssemble
500 finalPhaseOpt = hasDashC
501
502 if finalPhaseOpt:
503 self.claim(finalPhaseOpt)
504
Daniel Dunbar80e48b72009-01-17 00:53:19 +0000505 # Reject -Z* at the top level for now.
506 arg = args.getLastArg(self.parser.ZOption)
507 if arg:
508 raise Arguments.InvalidArgumentsError("%s: unsupported use of internal gcc option" % ' '.join(args.render(arg)))
509
Daniel Dunbar8fd28cd2009-01-28 19:26:20 +0000510 if not inputs and not self.suppressMissingInputWarning:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000511 raise Arguments.InvalidArgumentsError("no input files")
Daniel Dunbar378530c2009-01-05 19:53:30 +0000512
513 actions = []
514 linkerInputs = []
515 # FIXME: This is gross.
516 linkPhase = Phases.LinkPhase()
517 for klass,input in inputs:
518 # Figure out what step to start at.
519
520 # FIXME: This should be part of the input class probably?
521 # Altough it doesn't quite fit there either, things like
522 # asm-with-preprocess don't easily fit into a linear scheme.
523
524 # FIXME: I think we are going to end up wanting to just build
525 # a simple FSA which we run the inputs down.
526 sequence = []
527 if klass.preprocess:
528 sequence.append(Phases.PreprocessPhase())
529 if klass == Types.ObjectType:
530 sequence.append(linkPhase)
531 elif klass.onlyAssemble:
532 sequence.extend([Phases.AssemblePhase(),
533 linkPhase])
534 elif klass.onlyPrecompile:
535 sequence.append(Phases.PrecompilePhase())
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000536 elif hasAnalyze:
537 sequence.append(Phases.AnalyzePhase())
538 elif hasSyntaxOnly:
539 sequence.append(Phases.SyntaxOnlyPhase())
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000540 elif hasEmitLLVM:
541 sequence.append(Phases.EmitLLVMPhase())
Daniel Dunbar378530c2009-01-05 19:53:30 +0000542 else:
543 sequence.extend([Phases.CompilePhase(),
544 Phases.AssemblePhase(),
545 linkPhase])
546
547 if sequence[0].order > finalPhase:
548 assert finalPhaseOpt and finalPhaseOpt.opt
549 # FIXME: Explain what type of input file is. Or just match
550 # gcc warning.
Daniel Dunbar74727872009-01-06 01:35:44 +0000551 self.warning("%s: %s input file unused when %s is present" % (args.getValue(input),
Daniel Dunbar378530c2009-01-05 19:53:30 +0000552 sequence[0].name,
553 finalPhaseOpt.opt.name))
554 else:
555 # Build the pipeline for this file.
556
557 current = Phases.InputAction(input, klass)
558 for transition in sequence:
559 # If the current action produces no output, or we are
560 # past what the user requested, we are done.
561 if (current.type is Types.NothingType or
562 transition.order > finalPhase):
563 break
564 else:
565 if isinstance(transition, Phases.PreprocessPhase):
566 assert isinstance(klass.preprocess, Types.InputType)
567 current = Phases.JobAction(transition,
568 [current],
569 klass.preprocess)
570 elif isinstance(transition, Phases.PrecompilePhase):
571 current = Phases.JobAction(transition,
572 [current],
573 Types.PCHType)
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000574 elif isinstance(transition, Phases.AnalyzePhase):
575 output = Types.PlistType
576 current = Phases.JobAction(transition,
577 [current],
578 output)
579 elif isinstance(transition, Phases.SyntaxOnlyPhase):
580 output = Types.NothingType
581 current = Phases.JobAction(transition,
582 [current],
583 output)
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000584 elif isinstance(transition, Phases.EmitLLVMPhase):
585 if hasDashS:
586 output = Types.LLVMAsmType
587 else:
588 output = Types.LLVMBCType
589 current = Phases.JobAction(transition,
590 [current],
591 output)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000592 elif isinstance(transition, Phases.CompilePhase):
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000593 output = Types.AsmTypeNoPP
Daniel Dunbar378530c2009-01-05 19:53:30 +0000594 current = Phases.JobAction(transition,
595 [current],
596 output)
597 elif isinstance(transition, Phases.AssemblePhase):
598 current = Phases.JobAction(transition,
599 [current],
600 Types.ObjectType)
601 elif transition is linkPhase:
602 linkerInputs.append(current)
603 current = None
604 break
605 else:
606 raise RuntimeError,'Unrecognized transition: %s.' % transition
607 pass
608
609 if current is not None:
610 assert not isinstance(current, Phases.InputAction)
611 actions.append(current)
612
613 if linkerInputs:
614 actions.append(Phases.JobAction(linkPhase,
615 linkerInputs,
616 Types.ImageType))
617
618 return actions
619
Daniel Dunbar74727872009-01-06 01:35:44 +0000620 def buildPipeline(self, args):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000621 # FIXME: We need to handle canonicalization of the specified arch.
622
Daniel Dunbar31c80812009-01-20 21:29:14 +0000623 archs = {}
Daniel Dunbar445c46d2009-01-20 01:53:54 +0000624 hasDashM = args.getLastArg(self.parser.MGroup)
Daniel Dunbara33176f2009-01-21 18:49:34 +0000625 hasSaveTemps = args.getLastArg(self.parser.saveTempsOption)
Daniel Dunbar74727872009-01-06 01:35:44 +0000626 for arg in args:
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000627 if arg.opt is self.parser.archOption:
Daniel Dunbar31c80812009-01-20 21:29:14 +0000628 # FIXME: Canonicalize this.
629 archName = args.getValue(arg)
630 archs[archName] = arg
631
632 archs = archs.values()
Daniel Dunbar378530c2009-01-05 19:53:30 +0000633 if not archs:
Daniel Dunbarf3d5ca02009-01-13 04:05:40 +0000634 archs.append(args.makeSeparateArg(self.hostInfo.getArchName(args),
Daniel Dunbar1ba90982009-01-07 18:54:26 +0000635 self.parser.archOption))
Daniel Dunbar378530c2009-01-05 19:53:30 +0000636
Daniel Dunbar74727872009-01-06 01:35:44 +0000637 actions = self.buildNormalPipeline(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000638
639 # FIXME: Use custom exception for this.
640 #
641 # FIXME: We killed off some others but these aren't yet detected in
642 # a functional manner. If we added information to jobs about which
643 # "auxiliary" files they wrote then we could detect the conflict
644 # these cause downstream.
645 if len(archs) > 1:
646 if hasDashM:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000647 raise Arguments.InvalidArgumentsError("Cannot use -M options with multiple arch flags.")
Daniel Dunbar378530c2009-01-05 19:53:30 +0000648 elif hasSaveTemps:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000649 raise Arguments.InvalidArgumentsError("Cannot use -save-temps with multiple arch flags.")
Daniel Dunbar378530c2009-01-05 19:53:30 +0000650
651 # Execute once per arch.
652 finalActions = []
653 for p in actions:
654 # Make sure we can lipo this kind of output. If not (and it
655 # is an actual output) then we disallow, since we can't
656 # create an output file with the right name without
657 # overwriting it. We could remove this oddity by just
658 # changing the output names to include the arch, which would
659 # also fix -save-temps. Compatibility wins for now.
660 #
661 # FIXME: Is this error substantially less useful than
662 # gcc-dd's? The main problem is that "Cannot use compiler
663 # output with multiple arch flags" won't make sense to most
664 # developers.
665 if (len(archs) > 1 and
666 p.type not in (Types.NothingType,Types.ObjectType,Types.ImageType)):
Daniel Dunbara0026f22009-01-16 23:12:12 +0000667 raise Arguments.InvalidArgumentsError('Cannot use %s output with multiple arch flags.' % p.type.name)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000668
669 inputs = []
670 for arch in archs:
671 inputs.append(Phases.BindArchAction(p, arch))
672
673 # Lipo if necessary. We do it this way because we need to set
674 # the arch flag so that -Xarch_ gets rewritten.
675 if len(inputs) == 1 or p.type == Types.NothingType:
676 finalActions.extend(inputs)
677 else:
678 finalActions.append(Phases.JobAction(Phases.LipoPhase(),
679 inputs,
680 p.type))
681
Daniel Dunbar378530c2009-01-05 19:53:30 +0000682 return finalActions
683
Daniel Dunbar74727872009-01-06 01:35:44 +0000684 def bindPhases(self, phases, args):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000685 jobs = Jobs.JobList()
686
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000687 finalOutput = args.getLastArg(self.parser.oOption)
Daniel Dunbara33176f2009-01-21 18:49:34 +0000688 hasSaveTemps = args.getLastArg(self.parser.saveTempsOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000689 hasNoIntegratedCPP = args.getLastArg(self.parser.noIntegratedCPPOption)
Daniel Dunbarf86e98a2009-01-12 09:23:15 +0000690 hasTraditionalCPP = args.getLastArg(self.parser.traditionalCPPOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000691 hasPipe = args.getLastArg(self.parser.pipeOption)
Daniel Dunbarfc2ad022009-01-12 03:33:58 +0000692
Daniel Dunbar378530c2009-01-05 19:53:30 +0000693 # We claim things here so that options for which we silently allow
694 # override only ever claim the used option.
695 if hasPipe:
696 self.claim(hasPipe)
697 # FIXME: Hack, override -pipe till we support it.
Daniel Dunbare19ed8e2009-01-17 02:02:35 +0000698 if hasSaveTemps:
699 self.warning('-pipe ignored because -save-temps specified')
700 hasPipe = None
Daniel Dunbar378530c2009-01-05 19:53:30 +0000701 # Claim these here. Its not completely accurate but any warnings
702 # about these being unused are likely to be noise anyway.
703 if hasSaveTemps:
704 self.claim(hasSaveTemps)
Daniel Dunbarf86e98a2009-01-12 09:23:15 +0000705
706 if hasTraditionalCPP:
707 self.claim(hasTraditionalCPP)
708 elif hasNoIntegratedCPP:
Daniel Dunbar378530c2009-01-05 19:53:30 +0000709 self.claim(hasNoIntegratedCPP)
Daniel Dunbarf86e98a2009-01-12 09:23:15 +0000710
Daniel Dunbare5fb6792009-01-13 06:25:31 +0000711 # FIXME: Move to... somewhere else.
Daniel Dunbar378530c2009-01-05 19:53:30 +0000712 class InputInfo:
713 def __init__(self, source, type, baseInput):
714 self.source = source
715 self.type = type
716 self.baseInput = baseInput
717
718 def __repr__(self):
719 return '%s(%r, %r, %r)' % (self.__class__.__name__,
720 self.source, self.type, self.baseInput)
Daniel Dunbare5fb6792009-01-13 06:25:31 +0000721
722 def isOriginalInput(self):
723 return self.source is self.baseInput
Daniel Dunbar378530c2009-01-05 19:53:30 +0000724
Daniel Dunbarb3492762009-01-13 18:51:26 +0000725 def createJobs(tc, phase,
726 canAcceptPipe=False, atTopLevel=False, arch=None,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000727 tcArgs=None, linkingOutput=None):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000728 if isinstance(phase, Phases.InputAction):
729 return InputInfo(phase.filename, phase.type, phase.filename)
730 elif isinstance(phase, Phases.BindArchAction):
Daniel Dunbar74727872009-01-06 01:35:44 +0000731 archName = args.getValue(phase.arch)
Daniel Dunbar758cf642009-01-11 22:06:22 +0000732 tc = self.hostInfo.getToolChainForArch(archName)
Daniel Dunbarb3492762009-01-13 18:51:26 +0000733 return createJobs(tc, phase.inputs[0],
734 canAcceptPipe, atTopLevel, phase.arch,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000735 None, linkingOutput)
Daniel Dunbarb3492762009-01-13 18:51:26 +0000736
737 if tcArgs is None:
738 tcArgs = tc.translateArgs(args, arch)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000739
740 assert isinstance(phase, Phases.JobAction)
Daniel Dunbar758cf642009-01-11 22:06:22 +0000741 tool = tc.selectTool(phase)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000742
743 # See if we should use an integrated CPP. We only use an
744 # integrated cpp when we have exactly one input, since this is
745 # the only use case we care about.
746 useIntegratedCPP = False
747 inputList = phase.inputs
748 if (not hasNoIntegratedCPP and
Daniel Dunbarf86e98a2009-01-12 09:23:15 +0000749 not hasTraditionalCPP and
Daniel Dunbar378530c2009-01-05 19:53:30 +0000750 not hasSaveTemps and
751 tool.hasIntegratedCPP()):
752 if (len(phase.inputs) == 1 and
Daniel Dunbar7d494092009-01-20 00:47:24 +0000753 isinstance(phase.inputs[0], Phases.JobAction) and
Daniel Dunbar378530c2009-01-05 19:53:30 +0000754 isinstance(phase.inputs[0].phase, Phases.PreprocessPhase)):
755 useIntegratedCPP = True
756 inputList = phase.inputs[0].inputs
757
758 # Only try to use pipes when exactly one input.
Daniel Dunbar1e46f552009-01-22 23:19:32 +0000759 attemptToPipeInput = len(inputList) == 1 and tool.acceptsPipedInput()
760 inputs = [createJobs(tc, p, attemptToPipeInput, False,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000761 arch, tcArgs, linkingOutput)
Daniel Dunbar758cf642009-01-11 22:06:22 +0000762 for p in inputList]
Daniel Dunbar378530c2009-01-05 19:53:30 +0000763
764 # Determine if we should output to a pipe.
765 canOutputToPipe = canAcceptPipe and tool.canPipeOutput()
766 outputToPipe = False
767 if canOutputToPipe:
768 # Some things default to writing to a pipe if the final
769 # phase and there was no user override.
770 #
771 # FIXME: What is the best way to handle this?
Daniel Dunbar1b391272009-01-18 21:35:24 +0000772 if atTopLevel:
773 if (isinstance(phase.phase, Phases.PreprocessPhase) and
774 not finalOutput):
775 outputToPipe = True
Daniel Dunbar378530c2009-01-05 19:53:30 +0000776 elif hasPipe:
777 outputToPipe = True
778
779 # Figure out where to put the job (pipes).
780 jobList = jobs
Daniel Dunbar1e46f552009-01-22 23:19:32 +0000781 if isinstance(inputs[0].source, Jobs.PipedJob):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000782 jobList = inputs[0].source
Daniel Dunbar31c80812009-01-20 21:29:14 +0000783
Daniel Dunbar378530c2009-01-05 19:53:30 +0000784 baseInput = inputs[0].baseInput
Daniel Dunbard9b7a742009-01-21 00:05:15 +0000785 output,jobList = self.getOutputName(phase, outputToPipe, jobs, jobList, baseInput,
786 args, atTopLevel, hasSaveTemps, finalOutput)
Daniel Dunbarb421dba2009-01-07 18:40:45 +0000787 tool.constructJob(phase, arch, jobList, inputs, output, phase.type,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000788 tcArgs, linkingOutput)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000789
790 return InputInfo(output, phase.type, baseInput)
791
792 # It is an error to provide a -o option if we are making multiple
793 # output files.
794 if finalOutput and len([a for a in phases if a.type is not Types.NothingType]) > 1:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000795 raise Arguments.InvalidArgumentsError("cannot specify -o when generating multiple files")
Daniel Dunbar378530c2009-01-05 19:53:30 +0000796
797 for phase in phases:
Daniel Dunbar31c80812009-01-20 21:29:14 +0000798 # If we are linking an image for multiple archs then the
799 # linker wants -arch_multiple and -final_output <final image
800 # name>. Unfortunately this requires some gross contortions.
801 #
802 # FIXME: This is a hack; find a cleaner way to integrate this
803 # into the process.
804 linkingOutput = None
805 if (isinstance(phase, Phases.JobAction) and
806 isinstance(phase.phase, Phases.LipoPhase)):
807 finalOutput = args.getLastArg(self.parser.oOption)
808 if finalOutput:
809 linkingOutput = finalOutput
810 else:
811 linkingOutput = args.makeSeparateArg('a.out',
812 self.parser.oOption)
813
Daniel Dunbarb3492762009-01-13 18:51:26 +0000814 createJobs(self.toolChain, phase,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000815 canAcceptPipe=True, atTopLevel=True,
816 linkingOutput=linkingOutput)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000817
818 return jobs
Daniel Dunbar31c80812009-01-20 21:29:14 +0000819
820 def getOutputName(self, phase, outputToPipe, jobs, jobList, baseInput,
821 args, atTopLevel, hasSaveTemps, finalOutput):
822 # Figure out where to put the output.
823 if phase.type == Types.NothingType:
824 output = None
825 elif outputToPipe:
826 if isinstance(jobList, Jobs.PipedJob):
827 output = jobList
828 else:
829 jobList = output = Jobs.PipedJob([])
830 jobs.addJob(output)
831 else:
832 # Figure out what the derived output location would be.
Daniel Dunbar31c80812009-01-20 21:29:14 +0000833 if phase.type is Types.ImageType:
834 namedOutput = "a.out"
835 else:
Daniel Dunbar31c80812009-01-20 21:29:14 +0000836 assert phase.type.tempSuffix is not None
Daniel Dunbar0e8c48c2009-02-13 17:42:34 +0000837 inputName = args.getValue(baseInput)
838 if phase.type.appendSuffix:
839 namedOutput = inputName + '.' + phase.type.tempSuffix
840 else:
841 base,_ = os.path.splitext(inputName)
842 namedOutput = base + '.' + phase.type.tempSuffix
Daniel Dunbar31c80812009-01-20 21:29:14 +0000843
Daniel Dunbar61320532009-02-22 01:23:52 +0000844 isTemp = False
Daniel Dunbar31c80812009-01-20 21:29:14 +0000845 # Output to user requested destination?
846 if atTopLevel and finalOutput:
847 output = finalOutput
Daniel Dunbar61320532009-02-22 01:23:52 +0000848 self.resultFiles.append(args.getValue(finalOutput))
849
Daniel Dunbar31c80812009-01-20 21:29:14 +0000850 # Contruct a named destination?
851 elif atTopLevel or hasSaveTemps:
852 # As an annoying special case, pch generation
853 # doesn't strip the pathname.
854 if phase.type is Types.PCHType:
855 outputName = namedOutput
856 else:
857 outputName = os.path.basename(namedOutput)
858 output = args.makeSeparateArg(outputName,
859 self.parser.oOption)
Daniel Dunbar61320532009-02-22 01:23:52 +0000860 self.resultFiles.append(outputName)
861
Daniel Dunbar31c80812009-01-20 21:29:14 +0000862 else:
863 # Output to temp file...
864 fd,filename = tempfile.mkstemp(suffix='.'+phase.type.tempSuffix)
865 output = args.makeSeparateArg(filename,
866 self.parser.oOption)
Daniel Dunbar61320532009-02-22 01:23:52 +0000867 self.tempFiles.append(filename)
Daniel Dunbard9b7a742009-01-21 00:05:15 +0000868 return output,jobList