PageRenderTime 25ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/couchjs/scons/scons-local-2.0.1/SCons/Tool/intelc.py

http://github.com/cloudant/bigcouch
Python | 482 lines | 443 code | 8 blank | 31 comment | 25 complexity | 310de8bdc3cac33a4371faa285013c64 MD5 | raw file
Possible License(s): Apache-2.0
  1. """SCons.Tool.icl
  2. Tool-specific initialization for the Intel C/C++ compiler.
  3. Supports Linux and Windows compilers, v7 and up.
  4. There normally shouldn't be any need to import this module directly.
  5. It will usually be imported through the generic SCons.Tool.Tool()
  6. selection method.
  7. """
  8. #
  9. # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation
  10. #
  11. # Permission is hereby granted, free of charge, to any person obtaining
  12. # a copy of this software and associated documentation files (the
  13. # "Software"), to deal in the Software without restriction, including
  14. # without limitation the rights to use, copy, modify, merge, publish,
  15. # distribute, sublicense, and/or sell copies of the Software, and to
  16. # permit persons to whom the Software is furnished to do so, subject to
  17. # the following conditions:
  18. #
  19. # The above copyright notice and this permission notice shall be included
  20. # in all copies or substantial portions of the Software.
  21. #
  22. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  23. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  24. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. from __future__ import division
  30. __revision__ = "src/engine/SCons/Tool/intelc.py 5134 2010/08/16 23:02:40 bdeegan"
  31. import math, sys, os.path, glob, string, re
  32. is_windows = sys.platform == 'win32'
  33. is_win64 = is_windows and (os.environ['PROCESSOR_ARCHITECTURE'] == 'AMD64' or
  34. ('PROCESSOR_ARCHITEW6432' in os.environ and
  35. os.environ['PROCESSOR_ARCHITEW6432'] == 'AMD64'))
  36. is_linux = sys.platform == 'linux2'
  37. is_mac = sys.platform == 'darwin'
  38. if is_windows:
  39. import SCons.Tool.msvc
  40. elif is_linux:
  41. import SCons.Tool.gcc
  42. elif is_mac:
  43. import SCons.Tool.gcc
  44. import SCons.Util
  45. import SCons.Warnings
  46. # Exceptions for this tool
  47. class IntelCError(SCons.Errors.InternalError):
  48. pass
  49. class MissingRegistryError(IntelCError): # missing registry entry
  50. pass
  51. class MissingDirError(IntelCError): # dir not found
  52. pass
  53. class NoRegistryModuleError(IntelCError): # can't read registry at all
  54. pass
  55. def uniquify(s):
  56. """Return a sequence containing only one copy of each unique element from input sequence s.
  57. Does not preserve order.
  58. Input sequence must be hashable (i.e. must be usable as a dictionary key)."""
  59. u = {}
  60. for x in s:
  61. u[x] = 1
  62. return list(u.keys())
  63. def linux_ver_normalize(vstr):
  64. """Normalize a Linux compiler version number.
  65. Intel changed from "80" to "9.0" in 2005, so we assume if the number
  66. is greater than 60 it's an old-style number and otherwise new-style.
  67. Always returns an old-style float like 80 or 90 for compatibility with Windows.
  68. Shades of Y2K!"""
  69. # Check for version number like 9.1.026: return 91.026
  70. m = re.match(r'([0-9]+)\.([0-9]+)\.([0-9]+)', vstr)
  71. if m:
  72. vmaj,vmin,build = m.groups()
  73. return float(vmaj) * 10. + float(vmin) + float(build) / 1000.;
  74. else:
  75. f = float(vstr)
  76. if is_windows:
  77. return f
  78. else:
  79. if f < 60: return f * 10.0
  80. else: return f
  81. def check_abi(abi):
  82. """Check for valid ABI (application binary interface) name,
  83. and map into canonical one"""
  84. if not abi:
  85. return None
  86. abi = abi.lower()
  87. # valid_abis maps input name to canonical name
  88. if is_windows:
  89. valid_abis = {'ia32' : 'ia32',
  90. 'x86' : 'ia32',
  91. 'ia64' : 'ia64',
  92. 'em64t' : 'em64t',
  93. 'amd64' : 'em64t'}
  94. if is_linux:
  95. valid_abis = {'ia32' : 'ia32',
  96. 'x86' : 'ia32',
  97. 'x86_64' : 'x86_64',
  98. 'em64t' : 'x86_64',
  99. 'amd64' : 'x86_64'}
  100. if is_mac:
  101. valid_abis = {'ia32' : 'ia32',
  102. 'x86' : 'ia32',
  103. 'x86_64' : 'x86_64',
  104. 'em64t' : 'x86_64'}
  105. try:
  106. abi = valid_abis[abi]
  107. except KeyError:
  108. raise SCons.Errors.UserError("Intel compiler: Invalid ABI %s, valid values are %s"% \
  109. (abi, list(valid_abis.keys())))
  110. return abi
  111. def vercmp(a, b):
  112. """Compare strings as floats,
  113. but Intel changed Linux naming convention at 9.0"""
  114. return cmp(linux_ver_normalize(b), linux_ver_normalize(a))
  115. def get_version_from_list(v, vlist):
  116. """See if we can match v (string) in vlist (list of strings)
  117. Linux has to match in a fuzzy way."""
  118. if is_windows:
  119. # Simple case, just find it in the list
  120. if v in vlist: return v
  121. else: return None
  122. else:
  123. # Fuzzy match: normalize version number first, but still return
  124. # original non-normalized form.
  125. fuzz = 0.001
  126. for vi in vlist:
  127. if math.fabs(linux_ver_normalize(vi) - linux_ver_normalize(v)) < fuzz:
  128. return vi
  129. # Not found
  130. return None
  131. def get_intel_registry_value(valuename, version=None, abi=None):
  132. """
  133. Return a value from the Intel compiler registry tree. (Windows only)
  134. """
  135. # Open the key:
  136. if is_win64:
  137. K = 'Software\\Wow6432Node\\Intel\\Compilers\\C++\\' + version + '\\'+abi.upper()
  138. else:
  139. K = 'Software\\Intel\\Compilers\\C++\\' + version + '\\'+abi.upper()
  140. try:
  141. k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, K)
  142. except SCons.Util.RegError:
  143. raise MissingRegistryError("%s was not found in the registry, for Intel compiler version %s, abi='%s'"%(K, version,abi))
  144. # Get the value:
  145. try:
  146. v = SCons.Util.RegQueryValueEx(k, valuename)[0]
  147. return v # or v.encode('iso-8859-1', 'replace') to remove unicode?
  148. except SCons.Util.RegError:
  149. raise MissingRegistryError("%s\\%s was not found in the registry."%(K, valuename))
  150. def get_all_compiler_versions():
  151. """Returns a sorted list of strings, like "70" or "80" or "9.0"
  152. with most recent compiler version first.
  153. """
  154. versions=[]
  155. if is_windows:
  156. if is_win64:
  157. keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++'
  158. else:
  159. keyname = 'Software\\Intel\\Compilers\\C++'
  160. try:
  161. k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE,
  162. keyname)
  163. except WindowsError:
  164. return []
  165. i = 0
  166. versions = []
  167. try:
  168. while i < 100:
  169. subkey = SCons.Util.RegEnumKey(k, i) # raises EnvironmentError
  170. # Check that this refers to an existing dir.
  171. # This is not 100% perfect but should catch common
  172. # installation issues like when the compiler was installed
  173. # and then the install directory deleted or moved (rather
  174. # than uninstalling properly), so the registry values
  175. # are still there.
  176. ok = False
  177. for try_abi in ('IA32', 'IA32e', 'IA64', 'EM64T'):
  178. try:
  179. d = get_intel_registry_value('ProductDir', subkey, try_abi)
  180. except MissingRegistryError:
  181. continue # not found in reg, keep going
  182. if os.path.exists(d): ok = True
  183. if ok:
  184. versions.append(subkey)
  185. else:
  186. try:
  187. # Registry points to nonexistent dir. Ignore this
  188. # version.
  189. value = get_intel_registry_value('ProductDir', subkey, 'IA32')
  190. except MissingRegistryError, e:
  191. # Registry key is left dangling (potentially
  192. # after uninstalling).
  193. print \
  194. "scons: *** Ignoring the registry key for the Intel compiler version %s.\n" \
  195. "scons: *** It seems that the compiler was uninstalled and that the registry\n" \
  196. "scons: *** was not cleaned up properly.\n" % subkey
  197. else:
  198. print "scons: *** Ignoring "+str(value)
  199. i = i + 1
  200. except EnvironmentError:
  201. # no more subkeys
  202. pass
  203. elif is_linux:
  204. for d in glob.glob('/opt/intel_cc_*'):
  205. # Typical dir here is /opt/intel_cc_80.
  206. m = re.search(r'cc_(.*)$', d)
  207. if m:
  208. versions.append(m.group(1))
  209. for d in glob.glob('/opt/intel/cc*/*'):
  210. # Typical dir here is /opt/intel/cc/9.0 for IA32,
  211. # /opt/intel/cce/9.0 for EMT64 (AMD64)
  212. m = re.search(r'([0-9.]+)$', d)
  213. if m:
  214. versions.append(m.group(1))
  215. elif is_mac:
  216. for d in glob.glob('/opt/intel/cc*/*'):
  217. # Typical dir here is /opt/intel/cc/9.0 for IA32,
  218. # /opt/intel/cce/9.0 for EMT64 (AMD64)
  219. m = re.search(r'([0-9.]+)$', d)
  220. if m:
  221. versions.append(m.group(1))
  222. return sorted(uniquify(versions)) # remove dups
  223. def get_intel_compiler_top(version, abi):
  224. """
  225. Return the main path to the top-level dir of the Intel compiler,
  226. using the given version.
  227. The compiler will be in <top>/bin/icl.exe (icc on linux),
  228. the include dir is <top>/include, etc.
  229. """
  230. if is_windows:
  231. if not SCons.Util.can_read_reg:
  232. raise NoRegistryModuleError("No Windows registry module was found")
  233. top = get_intel_registry_value('ProductDir', version, abi)
  234. # pre-11, icl was in Bin. 11 and later, it's in Bin/<abi> apparently.
  235. if not os.path.exists(os.path.join(top, "Bin", "icl.exe")) \
  236. and not os.path.exists(os.path.join(top, "Bin", abi, "icl.exe")):
  237. raise MissingDirError("Can't find Intel compiler in %s"%(top))
  238. elif is_mac or is_linux:
  239. # first dir is new (>=9.0) style, second is old (8.0) style.
  240. dirs=('/opt/intel/cc/%s', '/opt/intel_cc_%s')
  241. if abi == 'x86_64':
  242. dirs=('/opt/intel/cce/%s',) # 'e' stands for 'em64t', aka x86_64 aka amd64
  243. top=None
  244. for d in dirs:
  245. if os.path.exists(os.path.join(d%version, "bin", "icc")):
  246. top = d%version
  247. break
  248. if not top:
  249. raise MissingDirError("Can't find version %s Intel compiler in %s (abi='%s')"%(version,top, abi))
  250. return top
  251. def generate(env, version=None, abi=None, topdir=None, verbose=0):
  252. """Add Builders and construction variables for Intel C/C++ compiler
  253. to an Environment.
  254. args:
  255. version: (string) compiler version to use, like "80"
  256. abi: (string) 'win32' or whatever Itanium version wants
  257. topdir: (string) compiler top dir, like
  258. "c:\Program Files\Intel\Compiler70"
  259. If topdir is used, version and abi are ignored.
  260. verbose: (int) if >0, prints compiler version used.
  261. """
  262. if not (is_mac or is_linux or is_windows):
  263. # can't handle this platform
  264. return
  265. if is_windows:
  266. SCons.Tool.msvc.generate(env)
  267. elif is_linux:
  268. SCons.Tool.gcc.generate(env)
  269. elif is_mac:
  270. SCons.Tool.gcc.generate(env)
  271. # if version is unspecified, use latest
  272. vlist = get_all_compiler_versions()
  273. if not version:
  274. if vlist:
  275. version = vlist[0]
  276. else:
  277. # User may have specified '90' but we need to get actual dirname '9.0'.
  278. # get_version_from_list does that mapping.
  279. v = get_version_from_list(version, vlist)
  280. if not v:
  281. raise SCons.Errors.UserError("Invalid Intel compiler version %s: "%version + \
  282. "installed versions are %s"%(', '.join(vlist)))
  283. version = v
  284. # if abi is unspecified, use ia32
  285. # alternatives are ia64 for Itanium, or amd64 or em64t or x86_64 (all synonyms here)
  286. abi = check_abi(abi)
  287. if abi is None:
  288. if is_mac or is_linux:
  289. # Check if we are on 64-bit linux, default to 64 then.
  290. uname_m = os.uname()[4]
  291. if uname_m == 'x86_64':
  292. abi = 'x86_64'
  293. else:
  294. abi = 'ia32'
  295. else:
  296. if is_win64:
  297. abi = 'em64t'
  298. else:
  299. abi = 'ia32'
  300. if version and not topdir:
  301. try:
  302. topdir = get_intel_compiler_top(version, abi)
  303. except (SCons.Util.RegError, IntelCError):
  304. topdir = None
  305. if not topdir:
  306. # Normally this is an error, but it might not be if the compiler is
  307. # on $PATH and the user is importing their env.
  308. class ICLTopDirWarning(SCons.Warnings.Warning):
  309. pass
  310. if (is_mac or is_linux) and not env.Detect('icc') or \
  311. is_windows and not env.Detect('icl'):
  312. SCons.Warnings.enableWarningClass(ICLTopDirWarning)
  313. SCons.Warnings.warn(ICLTopDirWarning,
  314. "Failed to find Intel compiler for version='%s', abi='%s'"%
  315. (str(version), str(abi)))
  316. else:
  317. # should be cleaned up to say what this other version is
  318. # since in this case we have some other Intel compiler installed
  319. SCons.Warnings.enableWarningClass(ICLTopDirWarning)
  320. SCons.Warnings.warn(ICLTopDirWarning,
  321. "Can't find Intel compiler top dir for version='%s', abi='%s'"%
  322. (str(version), str(abi)))
  323. if topdir:
  324. if verbose:
  325. print "Intel C compiler: using version %s (%g), abi %s, in '%s'"%\
  326. (repr(version), linux_ver_normalize(version),abi,topdir)
  327. if is_linux:
  328. # Show the actual compiler version by running the compiler.
  329. os.system('%s/bin/icc --version'%topdir)
  330. if is_mac:
  331. # Show the actual compiler version by running the compiler.
  332. os.system('%s/bin/icc --version'%topdir)
  333. env['INTEL_C_COMPILER_TOP'] = topdir
  334. if is_linux:
  335. paths={'INCLUDE' : 'include',
  336. 'LIB' : 'lib',
  337. 'PATH' : 'bin',
  338. 'LD_LIBRARY_PATH' : 'lib'}
  339. for p in paths.keys():
  340. env.PrependENVPath(p, os.path.join(topdir, paths[p]))
  341. if is_mac:
  342. paths={'INCLUDE' : 'include',
  343. 'LIB' : 'lib',
  344. 'PATH' : 'bin',
  345. 'LD_LIBRARY_PATH' : 'lib'}
  346. for p in paths.keys():
  347. env.PrependENVPath(p, os.path.join(topdir, paths[p]))
  348. if is_windows:
  349. # env key reg valname default subdir of top
  350. paths=(('INCLUDE', 'IncludeDir', 'Include'),
  351. ('LIB' , 'LibDir', 'Lib'),
  352. ('PATH' , 'BinDir', 'Bin'))
  353. # We are supposed to ignore version if topdir is set, so set
  354. # it to the emptry string if it's not already set.
  355. if version is None:
  356. version = ''
  357. # Each path has a registry entry, use that or default to subdir
  358. for p in paths:
  359. try:
  360. path=get_intel_registry_value(p[1], version, abi)
  361. # These paths may have $(ICInstallDir)
  362. # which needs to be substituted with the topdir.
  363. path=path.replace('$(ICInstallDir)', topdir + os.sep)
  364. except IntelCError:
  365. # Couldn't get it from registry: use default subdir of topdir
  366. env.PrependENVPath(p[0], os.path.join(topdir, p[2]))
  367. else:
  368. env.PrependENVPath(p[0], path.split(os.pathsep))
  369. # print "ICL %s: %s, final=%s"%(p[0], path, str(env['ENV'][p[0]]))
  370. if is_windows:
  371. env['CC'] = 'icl'
  372. env['CXX'] = 'icl'
  373. env['LINK'] = 'xilink'
  374. else:
  375. env['CC'] = 'icc'
  376. env['CXX'] = 'icpc'
  377. # Don't reset LINK here;
  378. # use smart_link which should already be here from link.py.
  379. #env['LINK'] = '$CC'
  380. env['AR'] = 'xiar'
  381. env['LD'] = 'xild' # not used by default
  382. # This is not the exact (detailed) compiler version,
  383. # just the major version as determined above or specified
  384. # by the user. It is a float like 80 or 90, in normalized form for Linux
  385. # (i.e. even for Linux 9.0 compiler, still returns 90 rather than 9.0)
  386. if version:
  387. env['INTEL_C_COMPILER_VERSION']=linux_ver_normalize(version)
  388. if is_windows:
  389. # Look for license file dir
  390. # in system environment, registry, and default location.
  391. envlicdir = os.environ.get("INTEL_LICENSE_FILE", '')
  392. K = ('SOFTWARE\Intel\Licenses')
  393. try:
  394. k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, K)
  395. reglicdir = SCons.Util.RegQueryValueEx(k, "w_cpp")[0]
  396. except (AttributeError, SCons.Util.RegError):
  397. reglicdir = ""
  398. defaultlicdir = r'C:\Program Files\Common Files\Intel\Licenses'
  399. licdir = None
  400. for ld in [envlicdir, reglicdir]:
  401. # If the string contains an '@', then assume it's a network
  402. # license (port@system) and good by definition.
  403. if ld and (ld.find('@') != -1 or os.path.exists(ld)):
  404. licdir = ld
  405. break
  406. if not licdir:
  407. licdir = defaultlicdir
  408. if not os.path.exists(licdir):
  409. class ICLLicenseDirWarning(SCons.Warnings.Warning):
  410. pass
  411. SCons.Warnings.enableWarningClass(ICLLicenseDirWarning)
  412. SCons.Warnings.warn(ICLLicenseDirWarning,
  413. "Intel license dir was not found."
  414. " Tried using the INTEL_LICENSE_FILE environment variable (%s), the registry (%s) and the default path (%s)."
  415. " Using the default path as a last resort."
  416. % (envlicdir, reglicdir, defaultlicdir))
  417. env['ENV']['INTEL_LICENSE_FILE'] = licdir
  418. def exists(env):
  419. if not (is_mac or is_linux or is_windows):
  420. # can't handle this platform
  421. return 0
  422. try:
  423. versions = get_all_compiler_versions()
  424. except (SCons.Util.RegError, IntelCError):
  425. versions = None
  426. detected = versions is not None and len(versions) > 0
  427. if not detected:
  428. # try env.Detect, maybe that will work
  429. if is_windows:
  430. return env.Detect('icl')
  431. elif is_linux:
  432. return env.Detect('icc')
  433. elif is_mac:
  434. return env.Detect('icc')
  435. return detected
  436. # end of file
  437. # Local Variables:
  438. # tab-width:4
  439. # indent-tabs-mode:nil
  440. # End:
  441. # vim: set expandtab tabstop=4 shiftwidth=4: