blob: 0fe58068ae403f74868aab2106bcee72c3fb9872 [file] [log] [blame]
Daniel Dunbar378530c2009-01-05 19:53:30 +00001import os
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +00002import platform
Daniel Dunbar378530c2009-01-05 19:53:30 +00003import sys
4import tempfile
5from pprint import pprint
6
7###
8
9import Arguments
10import Jobs
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +000011import HostInfo
Daniel Dunbar378530c2009-01-05 19:53:30 +000012import Phases
13import Tools
14import Types
15import Util
16
17# FIXME: Clean up naming of options and arguments. Decide whether to
18# rename Option and be consistent about use of Option/Arg.
19
20####
21
Daniel Dunbar378530c2009-01-05 19:53:30 +000022class Driver(object):
Daniel Dunbara0026f22009-01-16 23:12:12 +000023 def __init__(self, driverName, driverDir):
24 self.driverName = driverName
25 self.driverDir = driverDir
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +000026 self.hostInfo = None
Daniel Dunbare9f1a692009-01-06 06:12:13 +000027 self.parser = Arguments.OptionParser()
Daniel Dunbar7c2f91b2009-01-14 01:03:36 +000028 self.cccHostBits = self.cccHostMachine = None
29 self.cccHostSystem = self.cccHostRelease = None
30 self.cccCXX = False
31 self.cccClang = False
Daniel Dunbar4c751dc2009-01-14 01:32:05 +000032 self.cccEcho = False
Daniel Dunbar7c2f91b2009-01-14 01:03:36 +000033 self.cccFallback = False
Daniel Dunbar378530c2009-01-05 19:53:30 +000034
Daniel Dunbardbc9ee92009-01-09 22:21:24 +000035 # Host queries which can be forcibly over-riden by the user for
36 # testing purposes.
37 #
38 # FIXME: We should make sure these are drawn from a fixed set so
39 # that nothing downstream ever plays a guessing game.
40
41 def getHostBits(self):
42 if self.cccHostBits:
43 return self.cccHostBits
44
45 return platform.architecture()[0].replace('bit','')
46
47 def getHostMachine(self):
48 if self.cccHostMachine:
49 return self.cccHostMachine
50
51 machine = platform.machine()
52 # Normalize names.
53 if machine == 'Power Macintosh':
54 return 'ppc'
55 return machine
56
57 def getHostSystemName(self):
58 if self.cccHostSystem:
59 return self.cccHostSystem
60
61 return platform.system().lower()
62
Daniel Dunbarc2148562009-01-12 04:21:12 +000063 def getHostReleaseName(self):
64 if self.cccHostRelease:
65 return self.cccHostRelease
66
67 return platform.release()
68
Daniel Dunbar4c751dc2009-01-14 01:32:05 +000069 def getenvBool(self, name):
70 var = os.getenv(name)
71 if not var:
72 return False
73
74 try:
75 return bool(int(var))
76 except:
77 return False
78
Daniel Dunbardbc9ee92009-01-09 22:21:24 +000079 ###
80
Daniel Dunbarf677a602009-01-21 02:03:52 +000081 def getFilePath(self, name, toolChain=None):
82 tc = toolChain or self.toolChain
83 for p in tc.filePathPrefixes:
84 path = os.path.join(p, name)
85 if os.path.exists(path):
86 return path
87 return name
88
89 def getProgramPath(self, name, toolChain=None):
90 tc = toolChain or self.toolChain
91 for p in tc.programPathPrefixes:
92 path = os.path.join(p, name)
93 if os.path.exists(path):
94 return path
95 return name
96
97 ###
98
Daniel Dunbar74727872009-01-06 01:35:44 +000099 def run(self, argv):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000100 # FIXME: Things to support from environment: GCC_EXEC_PREFIX,
101 # COMPILER_PATH, LIBRARY_PATH, LPATH, CC_PRINT_OPTIONS,
102 # QA_OVERRIDE_GCC3_OPTIONS, ...?
103
104 # FIXME: -V and -b processing
105
106 # Handle some special -ccc- options used for testing which are
107 # only allowed at the beginning of the command line.
108 cccPrintOptions = False
109 cccPrintPhases = False
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000110
111 # FIXME: How to handle override of host? ccc specific options?
112 # Abuse -b?
Daniel Dunbar4c751dc2009-01-14 01:32:05 +0000113 if self.getenvBool('CCC_CLANG'):
114 self.cccClang = True
115 if self.getenvBool('CCC_ECHO'):
116 self.cccEcho = True
117 if self.getenvBool('CCC_FALLBACK'):
118 self.cccFallback = True
119
Daniel Dunbar74727872009-01-06 01:35:44 +0000120 while argv and argv[0].startswith('-ccc-'):
Daniel Dunbara0026f22009-01-16 23:12:12 +0000121 fullOpt,argv = argv[0],argv[1:]
122 opt = fullOpt[5:]
Daniel Dunbar378530c2009-01-05 19:53:30 +0000123
124 if opt == 'print-options':
125 cccPrintOptions = True
126 elif opt == 'print-phases':
127 cccPrintPhases = True
Daniel Dunbar7c2f91b2009-01-14 01:03:36 +0000128 elif opt == 'cxx':
129 self.cccCXX = True
130 elif opt == 'clang':
131 self.cccClang = True
Daniel Dunbar4c751dc2009-01-14 01:32:05 +0000132 elif opt == 'echo':
133 self.cccEcho = True
Daniel Dunbar7c2f91b2009-01-14 01:03:36 +0000134 elif opt == 'fallback':
135 self.cccFallback = True
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000136 elif opt == 'host-bits':
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000137 self.cccHostBits,argv = argv[0],argv[1:]
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000138 elif opt == 'host-machine':
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000139 self.cccHostMachine,argv = argv[0],argv[1:]
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000140 elif opt == 'host-system':
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000141 self.cccHostSystem,argv = argv[0],argv[1:]
Daniel Dunbarc2148562009-01-12 04:21:12 +0000142 elif opt == 'host-release':
143 self.cccHostRelease,argv = argv[0],argv[1:]
Daniel Dunbar378530c2009-01-05 19:53:30 +0000144 else:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000145 raise Arguments.InvalidArgumentsError("invalid option: %r" % fullOpt)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000146
Daniel Dunbardbc9ee92009-01-09 22:21:24 +0000147 self.hostInfo = HostInfo.getHostInfo(self)
Daniel Dunbar08dea462009-01-10 02:07:54 +0000148 self.toolChain = self.hostInfo.getToolChain()
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000149
Daniel Dunbar74727872009-01-06 01:35:44 +0000150 args = self.parser.parseArgs(argv)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000151
152 # FIXME: Ho hum I have just realized -Xarch_ is broken. We really
153 # need to reparse the Arguments after they have been expanded by
154 # -Xarch. How is this going to work?
155 #
156 # Scratch that, we aren't going to do that; it really disrupts the
157 # organization, doesn't consistently work with gcc-dd, and is
158 # confusing. Instead we are going to enforce that -Xarch_ is only
159 # used with options which do not alter the driver behavior. Let's
160 # hope this is ok, because the current architecture is a little
161 # tied to it.
162
163 if cccPrintOptions:
Daniel Dunbar74727872009-01-06 01:35:44 +0000164 self.printOptions(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000165 sys.exit(0)
166
Daniel Dunbar74727872009-01-06 01:35:44 +0000167 self.handleImmediateOptions(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000168
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000169 if self.hostInfo.useDriverDriver():
Daniel Dunbar74727872009-01-06 01:35:44 +0000170 phases = self.buildPipeline(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000171 else:
Daniel Dunbar74727872009-01-06 01:35:44 +0000172 phases = self.buildNormalPipeline(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000173
174 if cccPrintPhases:
Daniel Dunbar74727872009-01-06 01:35:44 +0000175 self.printPhases(phases, args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000176 sys.exit(0)
Daniel Dunbar4ed45ea2009-01-09 01:00:40 +0000177
Daniel Dunbar378530c2009-01-05 19:53:30 +0000178 if 0:
179 print Util.pprint(phases)
180
Daniel Dunbar74727872009-01-06 01:35:44 +0000181 jobs = self.bindPhases(phases, args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000182
183 # FIXME: We should provide some basic sanity checking of the
184 # pipeline as a "verification" sort of stage. For example, the
185 # pipeline should never end up writing to an output file in two
186 # places (I think). The pipeline should also never end up writing
187 # to an output file that is an input.
188 #
189 # This is intended to just be a "verify" step, not a functionality
190 # step. It should catch things like the driver driver not
191 # preventing -save-temps, but it shouldn't change behavior (so we
192 # can turn it off in Release-Asserts builds).
193
194 # Print in -### syntax.
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000195 hasHashHashHash = args.getLastArg(self.parser.hashHashHashOption)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000196 if hasHashHashHash:
197 self.claim(hasHashHashHash)
198 for j in jobs.iterjobs():
199 if isinstance(j, Jobs.Command):
Daniel Dunbard87b6ec2009-01-12 19:36:35 +0000200 print >>sys.stderr, ' "%s"' % '" "'.join(j.getArgv())
Daniel Dunbar378530c2009-01-05 19:53:30 +0000201 elif isinstance(j, Jobs.PipedJob):
202 for c in j.commands:
Daniel Dunbard87b6ec2009-01-12 19:36:35 +0000203 print >>sys.stderr, ' "%s" %c' % ('" "'.join(c.getArgv()),
204 "| "[c is j.commands[-1]])
Daniel Dunbar378530c2009-01-05 19:53:30 +0000205 elif not isinstance(j, JobList):
206 raise ValueError,'Encountered unknown job.'
207 sys.exit(0)
208
209 for j in jobs.iterjobs():
210 if isinstance(j, Jobs.Command):
Daniel Dunbar4c751dc2009-01-14 01:32:05 +0000211 if self.cccEcho:
Anders Carlsson76613bf2009-01-18 02:54:17 +0000212 print >>sys.stderr, ' '.join(map(repr,j.getArgv()))
213 sys.stderr.flush()
Daniel Dunbarb421dba2009-01-07 18:40:45 +0000214 res = os.spawnvp(os.P_WAIT, j.executable, j.getArgv())
Daniel Dunbar378530c2009-01-05 19:53:30 +0000215 if res:
216 sys.exit(res)
217 elif isinstance(j, Jobs.PipedJob):
Daniel Dunbare19ed8e2009-01-17 02:02:35 +0000218 import subprocess
219 procs = []
220 for sj in j.commands:
221 if self.cccEcho:
Anders Carlsson76613bf2009-01-18 02:54:17 +0000222 print >> sys.stderr, ' '.join(map(repr,sj.getArgv()))
Daniel Dunbare19ed8e2009-01-17 02:02:35 +0000223 sys.stdout.flush()
224
225 if not procs:
226 stdin = None
227 else:
228 stdin = procs[-1].stdout
229 if sj is j.commands[-1]:
230 stdout = None
231 else:
232 stdout = subprocess.PIPE
233 procs.append(subprocess.Popen(sj.getArgv(),
234 executable=sj.executable,
235 stdin=stdin,
236 stdout=stdout))
237 for proc in procs:
238 res = proc.wait()
239 if res:
240 sys.exit(res)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000241 else:
242 raise ValueError,'Encountered unknown job.'
243
244 def claim(self, option):
245 # FIXME: Move to OptionList once introduced and implement.
246 pass
247
248 def warning(self, message):
Daniel Dunbara0026f22009-01-16 23:12:12 +0000249 print >>sys.stderr,'%s: %s' % (self.driverName, message)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000250
Daniel Dunbar74727872009-01-06 01:35:44 +0000251 def printOptions(self, args):
252 for i,arg in enumerate(args):
Daniel Dunbar74727872009-01-06 01:35:44 +0000253 if isinstance(arg, Arguments.MultipleValuesArg):
254 values = list(args.getValues(arg))
255 elif isinstance(arg, Arguments.ValueArg):
256 values = [args.getValue(arg)]
257 elif isinstance(arg, Arguments.JoinedAndSeparateValuesArg):
258 values = [args.getJoinedValue(arg), args.getSeparateValue(arg)]
Daniel Dunbar378530c2009-01-05 19:53:30 +0000259 else:
260 values = []
Daniel Dunbar927a5092009-01-06 02:30:10 +0000261 print 'Option %d - Name: "%s", Values: {%s}' % (i, arg.opt.name,
Daniel Dunbar378530c2009-01-05 19:53:30 +0000262 ', '.join(['"%s"' % v
263 for v in values]))
264
Daniel Dunbar74727872009-01-06 01:35:44 +0000265 def printPhases(self, phases, args):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000266 def printPhase(p, f, steps, arch=None):
267 if p in steps:
268 return steps[p]
269 elif isinstance(p, Phases.BindArchAction):
270 for kid in p.inputs:
271 printPhase(kid, f, steps, p.arch)
272 steps[p] = len(steps)
273 return
274
275 if isinstance(p, Phases.InputAction):
276 phaseName = 'input'
Daniel Dunbar74727872009-01-06 01:35:44 +0000277 inputStr = '"%s"' % args.getValue(p.filename)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000278 else:
279 phaseName = p.phase.name
280 inputs = [printPhase(i, f, steps, arch)
281 for i in p.inputs]
282 inputStr = '{%s}' % ', '.join(map(str, inputs))
283 if arch is not None:
Daniel Dunbar74727872009-01-06 01:35:44 +0000284 phaseName += '-' + args.getValue(arch)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000285 steps[p] = index = len(steps)
286 print "%d: %s, %s, %s" % (index,phaseName,inputStr,p.type.name)
287 return index
288 steps = {}
289 for phase in phases:
290 printPhase(phase, sys.stdout, steps)
291
Daniel Dunbar74727872009-01-06 01:35:44 +0000292 def handleImmediateOptions(self, args):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000293 # FIXME: Some driver Arguments are consumed right off the bat,
294 # like -dumpversion. Currently the gcc-dd handles these
295 # poorly, so we should be ok handling them upfront instead of
296 # after driver-driver level dispatching.
297 #
298 # FIXME: The actual order of these options in gcc is all over the
299 # place. The -dump ones seem to be first and in specification
300 # order, but there are other levels of precedence. For example,
301 # -print-search-dirs is evaluated before -print-prog-name=,
302 # regardless of order (and the last instance of -print-prog-name=
303 # wins verse itself).
304 #
305 # FIXME: Do we want to report "argument unused" type errors in the
306 # presence of things like -dumpmachine and -print-search-dirs?
307 # Probably not.
Daniel Dunbarf677a602009-01-21 02:03:52 +0000308 arg = (args.getLastArg(self.parser.dumpmachineOption) or
309 args.getLastArg(self.parser.dumpversionOption) or
310 args.getLastArg(self.parser.printSearchDirsOption))
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000311 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000312 raise NotImplementedError('%s unsupported' % arg.opt.name)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000313
Daniel Dunbarf677a602009-01-21 02:03:52 +0000314 arg = (args.getLastArg(self.parser.dumpspecsOption) or
315 args.getLastArg(self.parser.printMultiDirectoryOption) or
Daniel Dunbar73fb9072009-01-23 02:00:46 +0000316 args.getLastArg(self.parser.printMultiOsDirectoryOption) or
Daniel Dunbarf677a602009-01-21 02:03:52 +0000317 args.getLastArg(self.parser.printMultiLibOption))
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000318 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000319 raise Arguments.InvalidArgumentsError('%s unsupported by this driver' % arg.opt.name)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000320
321 arg = args.getLastArg(self.parser.printFileNameOption)
322 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000323 print self.getFilePath(args.getValue(arg))
324 sys.exit(0)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000325
326 arg = args.getLastArg(self.parser.printProgNameOption)
327 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000328 print self.getProgramPath(args.getValue(arg))
329 sys.exit(0)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000330
Daniel Dunbarf677a602009-01-21 02:03:52 +0000331 arg = args.getLastArg(self.parser.printLibgccFileNameOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000332 if arg:
Daniel Dunbarf677a602009-01-21 02:03:52 +0000333 print self.getFilePath('libgcc.a')
334 sys.exit(0)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000335
Daniel Dunbar74727872009-01-06 01:35:44 +0000336 def buildNormalPipeline(self, args):
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000337 hasAnalyze = args.getLastArg(self.parser.analyzeOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000338 hasCombine = args.getLastArg(self.parser.combineOption)
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000339 hasEmitLLVM = args.getLastArg(self.parser.emitLLVMOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000340 hasSyntaxOnly = args.getLastArg(self.parser.syntaxOnlyOption)
341 hasDashC = args.getLastArg(self.parser.cOption)
342 hasDashE = args.getLastArg(self.parser.EOption)
343 hasDashS = args.getLastArg(self.parser.SOption)
Daniel Dunbar445c46d2009-01-20 01:53:54 +0000344 hasDashM = args.getLastArg(self.parser.MOption)
345 hasDashMM = args.getLastArg(self.parser.MMOption)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000346
347 inputType = None
348 inputTypeOpt = None
349 inputs = []
350 for a in args:
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000351 if a.opt is self.parser.inputOption:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000352 inputValue = args.getValue(a)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000353 if inputType is None:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000354 base,ext = os.path.splitext(inputValue)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000355 if ext and ext in Types.kTypeSuffixMap:
356 klass = Types.kTypeSuffixMap[ext]
357 else:
358 # FIXME: Its not clear why we shouldn't just
359 # revert to unknown. I think this is more likely a
360 # bug / unintended behavior in gcc. Not very
361 # important though.
362 klass = Types.ObjectType
363 else:
364 assert inputTypeOpt is not None
365 self.claim(inputTypeOpt)
366 klass = inputType
Daniel Dunbara0026f22009-01-16 23:12:12 +0000367
368 # Check that the file exists. It isn't clear this is
369 # worth doing, since the tool presumably does this
370 # anyway, and this just adds an extra stat to the
371 # equation, but this is gcc compatible.
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000372 if inputValue != '-' and not os.path.exists(inputValue):
Daniel Dunbara0026f22009-01-16 23:12:12 +0000373 self.warning("%s: No such file or directory" % inputValue)
374 else:
375 inputs.append((klass, a))
Daniel Dunbarfc2ad022009-01-12 03:33:58 +0000376 elif a.opt.isLinkerInput:
377 # Treat as a linker input.
Daniel Dunbar927a5092009-01-06 02:30:10 +0000378 #
379 # FIXME: This might not be good enough. We may
380 # need to introduce another type for this case, so
381 # that other code which needs to know the inputs
382 # handles this properly. Best not to try and lipo
383 # this, for example.
384 inputs.append((Types.ObjectType, a))
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000385 elif a.opt is self.parser.xOption:
Daniel Dunbar927a5092009-01-06 02:30:10 +0000386 inputTypeOpt = a
387 value = args.getValue(a)
388 if value in Types.kTypeSpecifierMap:
389 inputType = Types.kTypeSpecifierMap[value]
390 else:
391 # FIXME: How are we going to handle diagnostics.
392 self.warning("language %s not recognized" % value)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000393
Daniel Dunbar927a5092009-01-06 02:30:10 +0000394 # FIXME: Its not clear why we shouldn't just
395 # revert to unknown. I think this is more likely a
396 # bug / unintended behavior in gcc. Not very
397 # important though.
Daniel Dunbar6cb42052009-01-13 21:07:43 +0000398 inputType = Types.ObjectType
Daniel Dunbar378530c2009-01-05 19:53:30 +0000399
400 # We claim things here so that options for which we silently allow
401 # override only ever claim the used option.
402 if hasCombine:
403 self.claim(hasCombine)
404
405 finalPhase = Phases.Phase.eOrderPostAssemble
406 finalPhaseOpt = None
407
408 # Determine what compilation mode we are in.
Daniel Dunbar445c46d2009-01-20 01:53:54 +0000409 if hasDashE or hasDashM or hasDashMM:
Daniel Dunbar378530c2009-01-05 19:53:30 +0000410 finalPhase = Phases.Phase.eOrderPreprocess
411 finalPhaseOpt = hasDashE
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000412 elif (hasAnalyze or hasSyntaxOnly or
413 hasEmitLLVM or hasDashS):
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000414 finalPhase = Phases.Phase.eOrderCompile
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000415 finalPhaseOpt = (hasAnalyze or hasSyntaxOnly or
416 hasEmitLLVM or hasDashS)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000417 elif hasDashC:
418 finalPhase = Phases.Phase.eOrderAssemble
419 finalPhaseOpt = hasDashC
420
421 if finalPhaseOpt:
422 self.claim(finalPhaseOpt)
423
424 # FIXME: Support -combine.
425 if hasCombine:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000426 raise NotImplementedError,"-combine is not yet supported"
427
Daniel Dunbar80e48b72009-01-17 00:53:19 +0000428 # Reject -Z* at the top level for now.
429 arg = args.getLastArg(self.parser.ZOption)
430 if arg:
431 raise Arguments.InvalidArgumentsError("%s: unsupported use of internal gcc option" % ' '.join(args.render(arg)))
432
Daniel Dunbara0026f22009-01-16 23:12:12 +0000433 if (not inputs and
434 not args.getLastArg(self.parser.hashHashHashOption)):
435 raise Arguments.InvalidArgumentsError("no input files")
Daniel Dunbar378530c2009-01-05 19:53:30 +0000436
437 actions = []
438 linkerInputs = []
439 # FIXME: This is gross.
440 linkPhase = Phases.LinkPhase()
441 for klass,input in inputs:
442 # Figure out what step to start at.
443
444 # FIXME: This should be part of the input class probably?
445 # Altough it doesn't quite fit there either, things like
446 # asm-with-preprocess don't easily fit into a linear scheme.
447
448 # FIXME: I think we are going to end up wanting to just build
449 # a simple FSA which we run the inputs down.
450 sequence = []
451 if klass.preprocess:
452 sequence.append(Phases.PreprocessPhase())
453 if klass == Types.ObjectType:
454 sequence.append(linkPhase)
455 elif klass.onlyAssemble:
456 sequence.extend([Phases.AssemblePhase(),
457 linkPhase])
458 elif klass.onlyPrecompile:
459 sequence.append(Phases.PrecompilePhase())
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000460 elif hasAnalyze:
461 sequence.append(Phases.AnalyzePhase())
462 elif hasSyntaxOnly:
463 sequence.append(Phases.SyntaxOnlyPhase())
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000464 elif hasEmitLLVM:
465 sequence.append(Phases.EmitLLVMPhase())
Daniel Dunbar378530c2009-01-05 19:53:30 +0000466 else:
467 sequence.extend([Phases.CompilePhase(),
468 Phases.AssemblePhase(),
469 linkPhase])
470
471 if sequence[0].order > finalPhase:
472 assert finalPhaseOpt and finalPhaseOpt.opt
473 # FIXME: Explain what type of input file is. Or just match
474 # gcc warning.
Daniel Dunbar74727872009-01-06 01:35:44 +0000475 self.warning("%s: %s input file unused when %s is present" % (args.getValue(input),
Daniel Dunbar378530c2009-01-05 19:53:30 +0000476 sequence[0].name,
477 finalPhaseOpt.opt.name))
478 else:
479 # Build the pipeline for this file.
480
481 current = Phases.InputAction(input, klass)
482 for transition in sequence:
483 # If the current action produces no output, or we are
484 # past what the user requested, we are done.
485 if (current.type is Types.NothingType or
486 transition.order > finalPhase):
487 break
488 else:
489 if isinstance(transition, Phases.PreprocessPhase):
490 assert isinstance(klass.preprocess, Types.InputType)
491 current = Phases.JobAction(transition,
492 [current],
493 klass.preprocess)
494 elif isinstance(transition, Phases.PrecompilePhase):
495 current = Phases.JobAction(transition,
496 [current],
497 Types.PCHType)
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000498 elif isinstance(transition, Phases.AnalyzePhase):
499 output = Types.PlistType
500 current = Phases.JobAction(transition,
501 [current],
502 output)
503 elif isinstance(transition, Phases.SyntaxOnlyPhase):
504 output = Types.NothingType
505 current = Phases.JobAction(transition,
506 [current],
507 output)
Daniel Dunbar34f60f62009-01-26 17:09:15 +0000508 elif isinstance(transition, Phases.EmitLLVMPhase):
509 if hasDashS:
510 output = Types.LLVMAsmType
511 else:
512 output = Types.LLVMBCType
513 current = Phases.JobAction(transition,
514 [current],
515 output)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000516 elif isinstance(transition, Phases.CompilePhase):
Daniel Dunbar90c72cd2009-01-21 01:07:49 +0000517 output = Types.AsmTypeNoPP
Daniel Dunbar378530c2009-01-05 19:53:30 +0000518 current = Phases.JobAction(transition,
519 [current],
520 output)
521 elif isinstance(transition, Phases.AssemblePhase):
522 current = Phases.JobAction(transition,
523 [current],
524 Types.ObjectType)
525 elif transition is linkPhase:
526 linkerInputs.append(current)
527 current = None
528 break
529 else:
530 raise RuntimeError,'Unrecognized transition: %s.' % transition
531 pass
532
533 if current is not None:
534 assert not isinstance(current, Phases.InputAction)
535 actions.append(current)
536
537 if linkerInputs:
538 actions.append(Phases.JobAction(linkPhase,
539 linkerInputs,
540 Types.ImageType))
541
542 return actions
543
Daniel Dunbar74727872009-01-06 01:35:44 +0000544 def buildPipeline(self, args):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000545 # FIXME: We need to handle canonicalization of the specified arch.
546
Daniel Dunbar31c80812009-01-20 21:29:14 +0000547 archs = {}
Daniel Dunbar445c46d2009-01-20 01:53:54 +0000548 hasDashM = args.getLastArg(self.parser.MGroup)
Daniel Dunbara33176f2009-01-21 18:49:34 +0000549 hasSaveTemps = args.getLastArg(self.parser.saveTempsOption)
Daniel Dunbar74727872009-01-06 01:35:44 +0000550 for arg in args:
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000551 if arg.opt is self.parser.archOption:
Daniel Dunbar31c80812009-01-20 21:29:14 +0000552 # FIXME: Canonicalize this.
553 archName = args.getValue(arg)
554 archs[archName] = arg
555
556 archs = archs.values()
Daniel Dunbar378530c2009-01-05 19:53:30 +0000557 if not archs:
Daniel Dunbarf3d5ca02009-01-13 04:05:40 +0000558 archs.append(args.makeSeparateArg(self.hostInfo.getArchName(args),
Daniel Dunbar1ba90982009-01-07 18:54:26 +0000559 self.parser.archOption))
Daniel Dunbar378530c2009-01-05 19:53:30 +0000560
Daniel Dunbar74727872009-01-06 01:35:44 +0000561 actions = self.buildNormalPipeline(args)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000562
563 # FIXME: Use custom exception for this.
564 #
565 # FIXME: We killed off some others but these aren't yet detected in
566 # a functional manner. If we added information to jobs about which
567 # "auxiliary" files they wrote then we could detect the conflict
568 # these cause downstream.
569 if len(archs) > 1:
570 if hasDashM:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000571 raise Arguments.InvalidArgumentsError("Cannot use -M options with multiple arch flags.")
Daniel Dunbar378530c2009-01-05 19:53:30 +0000572 elif hasSaveTemps:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000573 raise Arguments.InvalidArgumentsError("Cannot use -save-temps with multiple arch flags.")
Daniel Dunbar378530c2009-01-05 19:53:30 +0000574
575 # Execute once per arch.
576 finalActions = []
577 for p in actions:
578 # Make sure we can lipo this kind of output. If not (and it
579 # is an actual output) then we disallow, since we can't
580 # create an output file with the right name without
581 # overwriting it. We could remove this oddity by just
582 # changing the output names to include the arch, which would
583 # also fix -save-temps. Compatibility wins for now.
584 #
585 # FIXME: Is this error substantially less useful than
586 # gcc-dd's? The main problem is that "Cannot use compiler
587 # output with multiple arch flags" won't make sense to most
588 # developers.
589 if (len(archs) > 1 and
590 p.type not in (Types.NothingType,Types.ObjectType,Types.ImageType)):
Daniel Dunbara0026f22009-01-16 23:12:12 +0000591 raise Arguments.InvalidArgumentsError('Cannot use %s output with multiple arch flags.' % p.type.name)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000592
593 inputs = []
594 for arch in archs:
595 inputs.append(Phases.BindArchAction(p, arch))
596
597 # Lipo if necessary. We do it this way because we need to set
598 # the arch flag so that -Xarch_ gets rewritten.
599 if len(inputs) == 1 or p.type == Types.NothingType:
600 finalActions.extend(inputs)
601 else:
602 finalActions.append(Phases.JobAction(Phases.LipoPhase(),
603 inputs,
604 p.type))
605
Daniel Dunbar378530c2009-01-05 19:53:30 +0000606 return finalActions
607
Daniel Dunbar74727872009-01-06 01:35:44 +0000608 def bindPhases(self, phases, args):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000609 jobs = Jobs.JobList()
610
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000611 finalOutput = args.getLastArg(self.parser.oOption)
Daniel Dunbara33176f2009-01-21 18:49:34 +0000612 hasSaveTemps = args.getLastArg(self.parser.saveTempsOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000613 hasNoIntegratedCPP = args.getLastArg(self.parser.noIntegratedCPPOption)
Daniel Dunbarf86e98a2009-01-12 09:23:15 +0000614 hasTraditionalCPP = args.getLastArg(self.parser.traditionalCPPOption)
Daniel Dunbare9f1a692009-01-06 06:12:13 +0000615 hasPipe = args.getLastArg(self.parser.pipeOption)
Daniel Dunbarfc2ad022009-01-12 03:33:58 +0000616
Daniel Dunbar378530c2009-01-05 19:53:30 +0000617 # We claim things here so that options for which we silently allow
618 # override only ever claim the used option.
619 if hasPipe:
620 self.claim(hasPipe)
621 # FIXME: Hack, override -pipe till we support it.
Daniel Dunbare19ed8e2009-01-17 02:02:35 +0000622 if hasSaveTemps:
623 self.warning('-pipe ignored because -save-temps specified')
624 hasPipe = None
Daniel Dunbar378530c2009-01-05 19:53:30 +0000625 # Claim these here. Its not completely accurate but any warnings
626 # about these being unused are likely to be noise anyway.
627 if hasSaveTemps:
628 self.claim(hasSaveTemps)
Daniel Dunbarf86e98a2009-01-12 09:23:15 +0000629
630 if hasTraditionalCPP:
631 self.claim(hasTraditionalCPP)
632 elif hasNoIntegratedCPP:
Daniel Dunbar378530c2009-01-05 19:53:30 +0000633 self.claim(hasNoIntegratedCPP)
Daniel Dunbarf86e98a2009-01-12 09:23:15 +0000634
Daniel Dunbare5fb6792009-01-13 06:25:31 +0000635 # FIXME: Move to... somewhere else.
Daniel Dunbar378530c2009-01-05 19:53:30 +0000636 class InputInfo:
637 def __init__(self, source, type, baseInput):
638 self.source = source
639 self.type = type
640 self.baseInput = baseInput
641
642 def __repr__(self):
643 return '%s(%r, %r, %r)' % (self.__class__.__name__,
644 self.source, self.type, self.baseInput)
Daniel Dunbare5fb6792009-01-13 06:25:31 +0000645
646 def isOriginalInput(self):
647 return self.source is self.baseInput
Daniel Dunbar378530c2009-01-05 19:53:30 +0000648
Daniel Dunbarb3492762009-01-13 18:51:26 +0000649 def createJobs(tc, phase,
650 canAcceptPipe=False, atTopLevel=False, arch=None,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000651 tcArgs=None, linkingOutput=None):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000652 if isinstance(phase, Phases.InputAction):
653 return InputInfo(phase.filename, phase.type, phase.filename)
654 elif isinstance(phase, Phases.BindArchAction):
Daniel Dunbar74727872009-01-06 01:35:44 +0000655 archName = args.getValue(phase.arch)
Daniel Dunbar758cf642009-01-11 22:06:22 +0000656 tc = self.hostInfo.getToolChainForArch(archName)
Daniel Dunbarb3492762009-01-13 18:51:26 +0000657 return createJobs(tc, phase.inputs[0],
658 canAcceptPipe, atTopLevel, phase.arch,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000659 None, linkingOutput)
Daniel Dunbarb3492762009-01-13 18:51:26 +0000660
661 if tcArgs is None:
662 tcArgs = tc.translateArgs(args, arch)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000663
664 assert isinstance(phase, Phases.JobAction)
Daniel Dunbar758cf642009-01-11 22:06:22 +0000665 tool = tc.selectTool(phase)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000666
667 # See if we should use an integrated CPP. We only use an
668 # integrated cpp when we have exactly one input, since this is
669 # the only use case we care about.
670 useIntegratedCPP = False
671 inputList = phase.inputs
672 if (not hasNoIntegratedCPP and
Daniel Dunbarf86e98a2009-01-12 09:23:15 +0000673 not hasTraditionalCPP and
Daniel Dunbar378530c2009-01-05 19:53:30 +0000674 not hasSaveTemps and
675 tool.hasIntegratedCPP()):
676 if (len(phase.inputs) == 1 and
Daniel Dunbar7d494092009-01-20 00:47:24 +0000677 isinstance(phase.inputs[0], Phases.JobAction) and
Daniel Dunbar378530c2009-01-05 19:53:30 +0000678 isinstance(phase.inputs[0].phase, Phases.PreprocessPhase)):
679 useIntegratedCPP = True
680 inputList = phase.inputs[0].inputs
681
682 # Only try to use pipes when exactly one input.
Daniel Dunbar1e46f552009-01-22 23:19:32 +0000683 attemptToPipeInput = len(inputList) == 1 and tool.acceptsPipedInput()
684 inputs = [createJobs(tc, p, attemptToPipeInput, False,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000685 arch, tcArgs, linkingOutput)
Daniel Dunbar758cf642009-01-11 22:06:22 +0000686 for p in inputList]
Daniel Dunbar378530c2009-01-05 19:53:30 +0000687
688 # Determine if we should output to a pipe.
689 canOutputToPipe = canAcceptPipe and tool.canPipeOutput()
690 outputToPipe = False
691 if canOutputToPipe:
692 # Some things default to writing to a pipe if the final
693 # phase and there was no user override.
694 #
695 # FIXME: What is the best way to handle this?
Daniel Dunbar1b391272009-01-18 21:35:24 +0000696 if atTopLevel:
697 if (isinstance(phase.phase, Phases.PreprocessPhase) and
698 not finalOutput):
699 outputToPipe = True
Daniel Dunbar378530c2009-01-05 19:53:30 +0000700 elif hasPipe:
701 outputToPipe = True
702
703 # Figure out where to put the job (pipes).
704 jobList = jobs
Daniel Dunbar1e46f552009-01-22 23:19:32 +0000705 if isinstance(inputs[0].source, Jobs.PipedJob):
Daniel Dunbar378530c2009-01-05 19:53:30 +0000706 jobList = inputs[0].source
Daniel Dunbar31c80812009-01-20 21:29:14 +0000707
Daniel Dunbar378530c2009-01-05 19:53:30 +0000708 baseInput = inputs[0].baseInput
Daniel Dunbard9b7a742009-01-21 00:05:15 +0000709 output,jobList = self.getOutputName(phase, outputToPipe, jobs, jobList, baseInput,
710 args, atTopLevel, hasSaveTemps, finalOutput)
Daniel Dunbarb421dba2009-01-07 18:40:45 +0000711 tool.constructJob(phase, arch, jobList, inputs, output, phase.type,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000712 tcArgs, linkingOutput)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000713
714 return InputInfo(output, phase.type, baseInput)
715
716 # It is an error to provide a -o option if we are making multiple
717 # output files.
718 if finalOutput and len([a for a in phases if a.type is not Types.NothingType]) > 1:
Daniel Dunbara0026f22009-01-16 23:12:12 +0000719 raise Arguments.InvalidArgumentsError("cannot specify -o when generating multiple files")
Daniel Dunbar378530c2009-01-05 19:53:30 +0000720
721 for phase in phases:
Daniel Dunbar31c80812009-01-20 21:29:14 +0000722 # If we are linking an image for multiple archs then the
723 # linker wants -arch_multiple and -final_output <final image
724 # name>. Unfortunately this requires some gross contortions.
725 #
726 # FIXME: This is a hack; find a cleaner way to integrate this
727 # into the process.
728 linkingOutput = None
729 if (isinstance(phase, Phases.JobAction) and
730 isinstance(phase.phase, Phases.LipoPhase)):
731 finalOutput = args.getLastArg(self.parser.oOption)
732 if finalOutput:
733 linkingOutput = finalOutput
734 else:
735 linkingOutput = args.makeSeparateArg('a.out',
736 self.parser.oOption)
737
Daniel Dunbarb3492762009-01-13 18:51:26 +0000738 createJobs(self.toolChain, phase,
Daniel Dunbar31c80812009-01-20 21:29:14 +0000739 canAcceptPipe=True, atTopLevel=True,
740 linkingOutput=linkingOutput)
Daniel Dunbar378530c2009-01-05 19:53:30 +0000741
742 return jobs
Daniel Dunbar31c80812009-01-20 21:29:14 +0000743
744 def getOutputName(self, phase, outputToPipe, jobs, jobList, baseInput,
745 args, atTopLevel, hasSaveTemps, finalOutput):
746 # Figure out where to put the output.
747 if phase.type == Types.NothingType:
748 output = None
749 elif outputToPipe:
750 if isinstance(jobList, Jobs.PipedJob):
751 output = jobList
752 else:
753 jobList = output = Jobs.PipedJob([])
754 jobs.addJob(output)
755 else:
756 # Figure out what the derived output location would be.
757 #
758 # FIXME: gcc has some special case in here so that it doesn't
759 # create output files if they would conflict with an input.
760 if phase.type is Types.ImageType:
761 namedOutput = "a.out"
762 else:
763 inputName = args.getValue(baseInput)
764 base,_ = os.path.splitext(inputName)
765 assert phase.type.tempSuffix is not None
766 namedOutput = base + '.' + phase.type.tempSuffix
767
768 # Output to user requested destination?
769 if atTopLevel and finalOutput:
770 output = finalOutput
771 # Contruct a named destination?
772 elif atTopLevel or hasSaveTemps:
773 # As an annoying special case, pch generation
774 # doesn't strip the pathname.
775 if phase.type is Types.PCHType:
776 outputName = namedOutput
777 else:
778 outputName = os.path.basename(namedOutput)
779 output = args.makeSeparateArg(outputName,
780 self.parser.oOption)
781 else:
782 # Output to temp file...
783 fd,filename = tempfile.mkstemp(suffix='.'+phase.type.tempSuffix)
784 output = args.makeSeparateArg(filename,
785 self.parser.oOption)
Daniel Dunbard9b7a742009-01-21 00:05:15 +0000786 return output,jobList