[PATCH] D59118: creduce script for clang crashes

2019-03-07 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
akhuang added reviewers: rnk, george.burgess.iv.
Herald added a reviewer: serge-sans-paille.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Add a script that calls C-Reduce on an input file and given the clang crash 
script, which is used to generate an interestingness test for C-Reduce.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D59118

Files:
  .arcconfig
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- /dev/null
+++ clang/utils/creduce-clang-crash.py
@@ -0,0 +1,123 @@
+#!/usr/bin/env python
+# A tool that calls C-Reduce to create a minimal reproducer for clang crashes
+# Requires C-Reduce and not (part of LLVM utils) to be installed
+
+from argparse import ArgumentParser
+import os
+import re
+import stat
+import sys
+import subprocess
+
+def is_exe(fpath):
+  return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
+
+def which(program):
+  """
+  Return the full path to a program or return None.
+  """
+  fpath, fname = os.path.split(program)
+  if fpath:
+if is_exe(program):
+  return program
+  else:
+for path in os.environ["PATH"].split(os.pathsep):
+  exe_file = os.path.join(path, program)
+  if is_exe(exe_file):
+return exe_file
+  return None
+
+def create_test(build_script, llvm_not):
+  """
+  Create an interestingness test from the crash output.
+  Return as a string.
+  """
+  # Get clang call from build script
+  cmd = None
+  with open(build_script, 'r') as f:
+cmd = f.read()
+cmd = re.sub("#!.*\n", "", cmd)
+cmd = cmd.rstrip('\n\r')
+
+  # Get crash output
+  p = subprocess.Popen(build_script,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
+
+  output = ['#!/bin/bash']
+  output.append('%s --crash %s >& t.log || exit 1' % (llvm_not, cmd))
+
+  # Add messages from crash output to the test
+  # If there is an Assertion failure, use that; otherwise use the
+  # last five stack trace functions
+  assertion_re = "Assertion \`([^\']+)\' failed"
+  assertion_match = re.search(assertion_re, crash_output)
+  if assertion_match:
+msg = assertion_match.group(1).replace('"', '\\"')
+output.append('grep "%s" t.log || exit 1' % msg)
+  else:
+stacktrace_re = "#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\("
+matches = re.findall(stacktrace_re, crash_output)
+del matches[:len(matches)-5]
+output += ['grep "%s" t.log || exit 1' % msg for msg in matches]
+
+  return output
+
+def main():
+  parser = ArgumentParser(description='Runs C-Reduce on the input file')
+  parser.add_argument('build_script', type=str, nargs=1,
+  help='Name of the script that generates the crash.')
+  parser.add_argument('file_to_reduce', type=str, nargs=1,
+  help='Name of the file to be reduced.')
+  parser.add_argument('-o', '--output', dest='output', type=str,
+  help='Name of the output file for the reduction. Optional.')
+  parser.add_argument('--llvm-not', dest='llvm_not', type=str,
+  help="""The path to the llvm-not executable.
+  Required if 'not' is not in PATH environment.""");
+  parser.add_argument('--creduce', dest='creduce', type=str,
+  help="""The path to the C-Reduce executable.
+  Required if 'creduce' is not in PATH environment.""");
+  args = parser.parse_args()
+
+  build_script = os.path.abspath(args.build_script[0])
+  file_to_reduce = os.path.abspath(args.file_to_reduce[0])
+  llvm_not = which(args.llvm_not) if args.llvm_not else which('not')
+  creduce = which(args.creduce) if args.creduce else which('creduce')
+
+  if not os.path.isfile(build_script):
+print(("ERROR: input file '%s' does not exist") % build_script)
+sys.exit(1)
+
+  if not os.path.isfile(file_to_reduce):
+print(("ERROR: input file '%s' does not exist") % file_to_reduce)
+sys.exit(1)
+
+  if not llvm_not:
+parser.print_help()
+sys.exit(1)
+
+  if not creduce:
+parser.print_help()
+sys.exit(1)
+
+  # Write interestingness test to file
+  test_contents = create_test(build_script, llvm_not)
+  testname, _ = os.path.splitext(file_to_reduce)
+  testfile = testname + '.test.sh'
+  open(testfile, 'w').write('\n'.join(test_contents))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+  # Call C-Reduce
+  try:
+p = subprocess.Popen([creduce, testfile, file_to_reduce])
+p.communicate()
+
+  except KeyboardInterrupt:
+print('\n\nctrl-c detected, killed creduce')
+p.kill()
+
+  sys.exit(0)
+
+if __name__ == '__main__':
+  main()
Index: .arcconfig
===
--- .arcconfig
+++ .arcconfig
@@ -1,4 +1,4 @@
 {
-  "repository.callsign" : "G",
-  "conduit_uri" : "https://reviews.

[PATCH] D59118: creduce script for clang crashes

2019-03-11 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 190126.
akhuang marked 15 inline comments as done.
akhuang added a comment.

Addressed readability comments


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59118/new/

https://reviews.llvm.org/D59118

Files:
  clang/utils/creduce-clang-crash.py


Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -8,6 +8,7 @@
 import stat
 import sys
 import subprocess
+import pipes
 
 def is_exe(fpath):
   return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
@@ -33,11 +34,9 @@
   Return as a string.
   """
   # Get clang call from build script
-  cmd = None
-  with open(build_script, 'r') as f:
-cmd = f.read()
-cmd = re.sub("#!.*\n", "", cmd)
-cmd = cmd.rstrip('\n\r')
+  # Assumes the call is the last line of the script
+  with open(build_script) as f:
+cmd = f.readlines()[-1].rstrip('\n\r')
 
   # Get crash output
   p = subprocess.Popen(build_script,
@@ -46,21 +45,22 @@
   crash_output, _ = p.communicate()
 
   output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (llvm_not, cmd))
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
+  cmd))
 
   # Add messages from crash output to the test
   # If there is an Assertion failure, use that; otherwise use the
   # last five stack trace functions
-  assertion_re = "Assertion \`([^\']+)\' failed"
+  assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1).replace('"', '\\"')
-output.append('grep "%s" t.log || exit 1' % msg)
+msg = assertion_match.group(1)
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
   else:
-stacktrace_re = "#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\("
+stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:len(matches)-5]
-output += ['grep "%s" t.log || exit 1' % msg for msg in matches]
+del matches[:-5]
+output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
 
   return output
 
@@ -73,11 +73,11 @@
   parser.add_argument('-o', '--output', dest='output', type=str,
   help='Name of the output file for the reduction. 
Optional.')
   parser.add_argument('--llvm-not', dest='llvm_not', type=str,
-  help="""The path to the llvm-not executable.
-  Required if 'not' is not in PATH environment.""");
+  help="The path to the llvm-not executable. "
+  "Required if 'not' is not in PATH environment.");
   parser.add_argument('--creduce', dest='creduce', type=str,
-  help="""The path to the C-Reduce executable.
-  Required if 'creduce' is not in PATH environment.""");
+  help="The path to the C-Reduce executable. "
+  "Required if 'creduce' is not in PATH environment.");
   args = parser.parse_args()
 
   build_script = os.path.abspath(args.build_script[0])
@@ -105,19 +105,11 @@
   test_contents = create_test(build_script, llvm_not)
   testname, _ = os.path.splitext(file_to_reduce)
   testfile = testname + '.test.sh'
-  open(testfile, 'w').write('\n'.join(test_contents))
+  with open(testfile, 'w') as f:
+f.write('\n'.join(test_contents))
   os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
 
-  # Call C-Reduce
-  try:
-p = subprocess.Popen([creduce, testfile, file_to_reduce])
-p.communicate()
-
-  except KeyboardInterrupt:
-print('\n\nctrl-c detected, killed creduce')
-p.kill()
-
-  sys.exit(0)
+  sys.exit(subprocess.call([creduce, testfile, file_to_reduce]))
 
 if __name__ == '__main__':
   main()


Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -8,6 +8,7 @@
 import stat
 import sys
 import subprocess
+import pipes
 
 def is_exe(fpath):
   return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
@@ -33,11 +34,9 @@
   Return as a string.
   """
   # Get clang call from build script
-  cmd = None
-  with open(build_script, 'r') as f:
-cmd = f.read()
-cmd = re.sub("#!.*\n", "", cmd)
-cmd = cmd.rstrip('\n\r')
+  # Assumes the call is the last line of the script
+  with open(build_script) as f:
+cmd = f.readlines()[-1].rstrip('\n\r')
 
   # Get crash output
   p = subprocess.Popen(build_script,
@@ -46,21 +45,22 @@
   crash_output, _ = p.communicate()
 
   output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (llvm_not, cmd))
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
+   

[PATCH] D59118: creduce script for clang crashes

2019-03-11 Thread Amy Huang via Phabricator via cfe-commits
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:43
+  # Get crash output
+  p = subprocess.Popen(build_script,
+   stdout=subprocess.PIPE,

george.burgess.iv wrote:
> nit: can replace with `subprocess.check_output` unless we explicitly want to 
> ignore the return value (in which case, we should probably still call 
> `wait()` anyway?)
`check_output()` raises an error when the return code is nonzero, which it is 
in this case. I think `communicate()` calls `wait()`, though.



Comment at: clang/utils/creduce-clang-crash.py:49
+  output = ['#!/bin/bash']
+  output.append('%s --crash %s >& t.log || exit 1' % (llvm_not, cmd))
+

george.burgess.iv wrote:
> please `pipes.quote(llvm_not)` and `pipes.quote(cmd)`
`cmd` is already quoted, since it's read out of another file


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59118/new/

https://reviews.llvm.org/D59118



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59118: creduce script for clang crashes

2019-03-11 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 190164.
akhuang added a comment.

fixed diff with style edits


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59118/new/

https://reviews.llvm.org/D59118

Files:
  .arcconfig
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- /dev/null
+++ clang/utils/creduce-clang-crash.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python
+# A tool that calls C-Reduce to create a minimal reproducer for clang crashes
+# Requires C-Reduce and not (part of LLVM utils) to be installed
+
+from argparse import ArgumentParser
+import os
+import re
+import stat
+import sys
+import subprocess
+import pipes
+
+def is_exe(fpath):
+  return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
+
+def which(program):
+  """
+  Return the full path to a program or return None.
+  """
+  fpath, fname = os.path.split(program)
+  if fpath:
+if is_exe(program):
+  return program
+  else:
+for path in os.environ["PATH"].split(os.pathsep):
+  exe_file = os.path.join(path, program)
+  if is_exe(exe_file):
+return exe_file
+  return None
+
+def create_test(build_script, llvm_not):
+  """
+  Create an interestingness test from the crash output.
+  Return as a string.
+  """
+  # Get clang call from build script
+  # Assumes the call is the last line of the script
+  with open(build_script) as f:
+cmd = f.readlines()[-1].rstrip('\n\r')
+
+  # Get crash output
+  p = subprocess.Popen(build_script,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
+
+  output = ['#!/bin/bash']
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
+  cmd))
+
+  # Add messages from crash output to the test
+  # If there is an Assertion failure, use that; otherwise use the
+  # last five stack trace functions
+  assertion_re = r'Assertion `([^\']+)\' failed'
+  assertion_match = re.search(assertion_re, crash_output)
+  if assertion_match:
+msg = assertion_match.group(1)
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+  else:
+stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
+matches = re.findall(stacktrace_re, crash_output)
+del matches[:-5]
+output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+
+  return output
+
+def main():
+  parser = ArgumentParser(description='Runs C-Reduce on the input file')
+  parser.add_argument('build_script', type=str, nargs=1,
+  help='Name of the script that generates the crash.')
+  parser.add_argument('file_to_reduce', type=str, nargs=1,
+  help='Name of the file to be reduced.')
+  parser.add_argument('-o', '--output', dest='output', type=str,
+  help='Name of the output file for the reduction. Optional.')
+  parser.add_argument('--llvm-not', dest='llvm_not', type=str,
+  help="The path to the llvm-not executable. "
+  "Required if 'not' is not in PATH environment.");
+  parser.add_argument('--creduce', dest='creduce', type=str,
+  help="The path to the C-Reduce executable. "
+  "Required if 'creduce' is not in PATH environment.");
+  args = parser.parse_args()
+
+  build_script = os.path.abspath(args.build_script[0])
+  file_to_reduce = os.path.abspath(args.file_to_reduce[0])
+  llvm_not = which(args.llvm_not) if args.llvm_not else which('not')
+  creduce = which(args.creduce) if args.creduce else which('creduce')
+
+  if not os.path.isfile(build_script):
+print(("ERROR: input file '%s' does not exist") % build_script)
+sys.exit(1)
+
+  if not os.path.isfile(file_to_reduce):
+print(("ERROR: input file '%s' does not exist") % file_to_reduce)
+sys.exit(1)
+
+  if not llvm_not:
+parser.print_help()
+sys.exit(1)
+
+  if not creduce:
+parser.print_help()
+sys.exit(1)
+
+  # Write interestingness test to file
+  test_contents = create_test(build_script, llvm_not)
+  testname, _ = os.path.splitext(file_to_reduce)
+  testfile = testname + '.test.sh'
+  with open(testfile, 'w') as f:
+f.write('\n'.join(test_contents))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+  sys.exit(subprocess.call([creduce, testfile, file_to_reduce]))
+
+if __name__ == '__main__':
+  main()
Index: .arcconfig
===
--- .arcconfig
+++ .arcconfig
@@ -1,4 +1,4 @@
 {
-  "repository.callsign" : "G",
-  "conduit_uri" : "https://reviews.llvm.org/";
+"repository.callsign" : "G",
+"conduit_uri" : "https://reviews.llvm.org/";
 }
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59118: creduce script for clang crashes

2019-03-11 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 190189.
akhuang added a comment.

add interestingness test sanity check;
revive ctrl-c hack


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59118/new/

https://reviews.llvm.org/D59118

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- /dev/null
+++ clang/utils/creduce-clang-crash.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python
+# A tool that calls C-Reduce to create a minimal reproducer for clang crashes
+# Requires C-Reduce and not (part of LLVM utils) to be installed
+
+from argparse import ArgumentParser
+import os
+import re
+import stat
+import sys
+import subprocess
+import pipes
+
+def is_exe(fpath):
+  return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
+
+def which(program):
+  """
+  Return the full path to a program or return None.
+  """
+  fpath, fname = os.path.split(program)
+  if fpath:
+if is_exe(program):
+  return program
+  else:
+for path in os.environ["PATH"].split(os.pathsep):
+  exe_file = os.path.join(path, program)
+  if is_exe(exe_file):
+return exe_file
+  return None
+
+def create_test(build_script, llvm_not):
+  """
+  Create an interestingness test from the crash output.
+  Return as a string.
+  """
+  # Get clang call from build script
+  # Assumes the call is the last line of the script
+  with open(build_script) as f:
+cmd = f.readlines()[-1].rstrip('\n\r')
+
+  # Get crash output
+  p = subprocess.Popen(build_script,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
+
+  output = ['#!/bin/bash']
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
+  cmd))
+
+  # Add messages from crash output to the test
+  # If there is an Assertion failure, use that; otherwise use the
+  # last five stack trace functions
+  assertion_re = r'Assertion `([^\']+)\' failed'
+  assertion_match = re.search(assertion_re, crash_output)
+  if assertion_match:
+msg = assertion_match.group(1)
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+  else:
+stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
+matches = re.findall(stacktrace_re, crash_output)
+del matches[:-5]
+output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+
+  return output
+
+def main():
+  parser = ArgumentParser(description='Runs C-Reduce on the input file')
+  parser.add_argument('build_script', type=str, nargs=1,
+  help='Name of the script that generates the crash.')
+  parser.add_argument('file_to_reduce', type=str, nargs=1,
+  help='Name of the file to be reduced.')
+  parser.add_argument('-o', '--output', dest='output', type=str,
+  help='Name of the output file for the reduction. Optional.')
+  parser.add_argument('--llvm-not', dest='llvm_not', type=str,
+  help="The path to the llvm-not executable. "
+  "Required if 'not' is not in PATH environment.");
+  parser.add_argument('--creduce', dest='creduce', type=str,
+  help="The path to the C-Reduce executable. "
+  "Required if 'creduce' is not in PATH environment.");
+  args = parser.parse_args()
+
+  build_script = os.path.abspath(args.build_script[0])
+  file_to_reduce = os.path.abspath(args.file_to_reduce[0])
+  llvm_not = which(args.llvm_not) if args.llvm_not else which('not')
+  creduce = which(args.creduce) if args.creduce else which('creduce')
+
+  if not os.path.isfile(build_script):
+print(("ERROR: input file '%s' does not exist") % build_script)
+sys.exit(1)
+
+  if not os.path.isfile(file_to_reduce):
+print(("ERROR: input file '%s' does not exist") % file_to_reduce)
+sys.exit(1)
+
+  if not llvm_not:
+parser.print_help()
+sys.exit(1)
+
+  if not creduce:
+parser.print_help()
+sys.exit(1)
+
+  # Write interestingness test to file
+  test_contents = create_test(build_script, llvm_not)
+  testname, _ = os.path.splitext(file_to_reduce)
+  testfile = testname + '.test.sh'
+  with open(testfile, 'w') as f:
+f.write('\n'.join(test_contents))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+  # Confirm that the interestingness test passes
+  try:
+with open(os.devnull, 'w') as devnull:
+  subprocess.check_call(testfile, stdout=devnull)
+  except subprocess.CalledProcessError:
+print("For some reason the interestingness test does not return zero")
+sys.exit(1)
+
+  # FIXME: try running clang preprocessor first
+
+  try:
+p = subprocess.Popen([creduce, testfile, file_to_reduce])
+p.communicate()
+  except KeyboardInterrupt:
+# Hack to kill C-Reduce because it jumps into its own pgid
+print('\n\nctrl-c detected, killed creduce')
+p.k

[PATCH] D59118: creduce script for clang crashes

2019-03-12 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 190285.
akhuang marked 6 inline comments as done.
akhuang added a comment.

style edits


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59118/new/

https://reviews.llvm.org/D59118

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- /dev/null
+++ clang/utils/creduce-clang-crash.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python
+"""Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Requires C-Reduce and not (part of LLVM utils) to be installed.
+"""
+
+from argparse import ArgumentParser
+import os
+import re
+import stat
+import sys
+import subprocess
+import pipes
+from distutils.spawn import find_executable
+
+def create_test(build_script, llvm_not):
+  """
+  Create an interestingness test from the crash output.
+  Return as a string.
+  """
+  # Get clang call from build script
+  # Assumes the call is the last line of the script
+  with open(build_script) as f:
+cmd = f.readlines()[-1].rstrip('\n\r')
+
+  # Get crash output
+  p = subprocess.Popen(build_script,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
+
+  output = ['#!/bin/bash']
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
+  cmd))
+
+  # Add messages from crash output to the test
+  # If there is an Assertion failure, use that; otherwise use the
+  # last five stack trace functions
+  assertion_re = r'Assertion `([^\']+)\' failed'
+  assertion_match = re.search(assertion_re, crash_output)
+  if assertion_match:
+msg = assertion_match.group(1)
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+  else:
+stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
+matches = re.findall(stacktrace_re, crash_output)
+del matches[:-5]
+output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+
+  return output
+
+def main():
+  parser = ArgumentParser(description=__doc__)
+  parser.add_argument('build_script', type=str, nargs=1,
+  help='Name of the script that generates the crash.')
+  parser.add_argument('file_to_reduce', type=str, nargs=1,
+  help='Name of the file to be reduced.')
+  parser.add_argument('-o', '--output', dest='output', type=str,
+  help='Name of the output file for the reduction. Optional.')
+  parser.add_argument('--llvm-not', dest='llvm_not', type=str,
+  help="The path to the llvm-not executable. "
+  "Required if 'not' is not in PATH environment.");
+  parser.add_argument('--creduce', dest='creduce', type=str,
+  help="The path to the C-Reduce executable. "
+  "Required if 'creduce' is not in PATH environment.");
+  args = parser.parse_args()
+
+  build_script = os.path.abspath(args.build_script[0])
+  file_to_reduce = os.path.abspath(args.file_to_reduce[0])
+  llvm_not = (find_executable(args.llvm_not) if args.llvm_not else
+  find_executable('not'))
+  creduce = (find_executable(args.creduce) if args.creduce else
+ find_executable('creduce'))
+
+  if not os.path.isfile(build_script):
+print(("ERROR: input file '%s' does not exist") % build_script)
+return 1
+
+  if not os.path.isfile(file_to_reduce):
+print(("ERROR: input file '%s' does not exist") % file_to_reduce)
+return 1
+
+  if not llvm_not:
+parser.print_help()
+return 1
+
+  if not creduce:
+parser.print_help()
+return 1
+
+  # Write interestingness test to file
+  test_contents = create_test(build_script, llvm_not)
+  testname, _ = os.path.splitext(file_to_reduce)
+  testfile = testname + '.test.sh'
+  with open(testfile, 'w') as f:
+f.write('\n'.join(test_contents))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+  # Confirm that the interestingness test passes
+  try:
+with open(os.devnull, 'w') as devnull:
+  subprocess.check_call(testfile, stdout=devnull)
+  except subprocess.CalledProcessError:
+print("For some reason the interestingness test does not return zero")
+return 1
+
+  # FIXME: try running clang preprocessor first
+
+  try:
+p = subprocess.Popen([creduce, testfile, file_to_reduce])
+p.communicate()
+  except KeyboardInterrupt:
+# Hack to kill C-Reduce because it jumps into its own pgid
+print('\n\nctrl-c detected, killed creduce')
+p.kill()
+
+if __name__ == '__main__':
+  sys.exit(main())
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-15 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
akhuang added reviewers: rnk, george.burgess.iv.
Herald added a reviewer: serge-sans-paille.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

-try to preprocess the file before reducing
-try to remove some command line arguments
-now requires a llvm bin directory since the generated crash script doesn't 
have an absolute path for clang


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D59440

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
-
-Requires C-Reduce and not (part of LLVM utils) to be installed.
 """
 
 from argparse import ArgumentParser
@@ -11,103 +9,231 @@
 import sys
 import subprocess
 import pipes
+import shlex
+import tempfile
+import shutil
 from distutils.spawn import find_executable
 
-def create_test(build_script, llvm_not):
+verbose = False
+llvm_bin = None
+creduce_cmd = None
+not_cmd = None
+
+def check_file(fname):
+  fname = os.path.abspath(fname)
+  if not os.path.isfile(fname):
+sys.exit("ERROR: %s does not exist" % (fname))
+  return fname
+
+def check_cmd(cmd_name, cmd_dir, cmd_path=None):
   """
-  Create an interestingness test from the crash output.
-  Return as a string.
+  Returns absolute path to cmd_path if it is given,
+  or absolute path to cmd_dir/cmd_name.
   """
-  # Get clang call from build script
-  # Assumes the call is the last line of the script
-  with open(build_script) as f:
-cmd = f.readlines()[-1].rstrip('\n\r')
-
-  # Get crash output
-  p = subprocess.Popen(build_script,
+  if cmd_path:
+cmd = find_executable(cmd_path)
+if cmd:
+  return cmd
+sys.exit("ERROR: %s not found")
+
+  cmd = find_executable(cmd_name, path=cmd_dir)
+  if cmd:
+return cmd
+  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
+
+def quote_cmd(cmd):
+  return ' '.join(pipes.quote(s) for s in cmd)
+
+def get_crash_cmd(crash_script):
+  with open(crash_script) as f:
+# Assume clang call is on the last line of the script
+line = f.readlines()[-1]
+cmd = shlex.split(line)
+
+# Overwrite the script's clang with the user's clang path
+clang_name = os.path.basename(cmd[0])
+new_clang = check_cmd(clang_name, llvm_bin)
+cmd[0] = pipes.quote(new_clang)
+return cmd
+
+def has_expected_output(crash_cmd, expected_output):
+  p = subprocess.Popen(crash_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
   crash_output, _ = p.communicate()
+  for msg in expected_output:
+if msg not in crash_output:
+  return False
+  return True
 
-  output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
-  cmd))
+def get_expected_output(crash_cmd):
+  p = subprocess.Popen(crash_cmd,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
 
-  # Add messages from crash output to the test
-  # If there is an Assertion failure, use that; otherwise use the
-  # last five stack trace functions
+  # If there is an assertion failure, use that;
+  # otherwise use the last five stack trace functions
   assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1)
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+return [assertion_match.group(1)]
   else:
 stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:-5]
-output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+return matches[-5:]
+
+def write_interestingness_test(testfile, crash_cmd, expected_output):
+  output = ['#!/bin/bash']
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
+  quote_cmd(crash_cmd)))
+
+  for msg in expected_output:
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
 
-  return output
+  with open(testfile, 'w') as f:
+f.write('\n'.join(output))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+def check_interestingness(testfile, file_to_reduce):
+  # Check that the test considers the original file interesting
+  with open(os.devnull, 'w') as devnull:
+p = subprocess.Popen(testfile, stdout=devnull)
+p.communicate()
+  if p.returncode:
+sys.exit("The interestingness test does not pass for the original file.")
+
+  # Check that an empty file is not interesting
+  # file_to_reduce is hardcoded into the test, so this is a roundabout
+

[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-15 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 190929.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59440/new/

https://reviews.llvm.org/D59440

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
-
-Requires C-Reduce and not (part of LLVM utils) to be installed.
 """
 
 from argparse import ArgumentParser
@@ -11,103 +9,231 @@
 import sys
 import subprocess
 import pipes
+import shlex
+import tempfile
+import shutil
 from distutils.spawn import find_executable
 
-def create_test(build_script, llvm_not):
+verbose = False
+llvm_bin = None
+creduce_cmd = None
+not_cmd = None
+
+def check_file(fname):
+  fname = os.path.abspath(fname)
+  if not os.path.isfile(fname):
+sys.exit("ERROR: %s does not exist" % (fname))
+  return fname
+
+def check_cmd(cmd_name, cmd_dir, cmd_path=None):
   """
-  Create an interestingness test from the crash output.
-  Return as a string.
+  Returns absolute path to cmd_path if it is given,
+  or absolute path to cmd_dir/cmd_name.
   """
-  # Get clang call from build script
-  # Assumes the call is the last line of the script
-  with open(build_script) as f:
-cmd = f.readlines()[-1].rstrip('\n\r')
-
-  # Get crash output
-  p = subprocess.Popen(build_script,
+  if cmd_path:
+cmd = find_executable(cmd_path)
+if cmd:
+  return cmd
+sys.exit("ERROR: %s not found")
+
+  cmd = find_executable(cmd_name, path=cmd_dir)
+  if cmd:
+return cmd
+  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
+
+def quote_cmd(cmd):
+  return ' '.join(pipes.quote(s) for s in cmd)
+
+def get_crash_cmd(crash_script):
+  with open(crash_script) as f:
+# Assume clang call is on the last line of the script
+line = f.readlines()[-1]
+cmd = shlex.split(line)
+
+# Overwrite the script's clang with the user's clang path
+clang_name = os.path.basename(cmd[0])
+new_clang = check_cmd(clang_name, llvm_bin)
+cmd[0] = pipes.quote(new_clang)
+return cmd
+
+def has_expected_output(crash_cmd, expected_output):
+  p = subprocess.Popen(crash_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
   crash_output, _ = p.communicate()
+  for msg in expected_output:
+if msg not in crash_output:
+  return False
+  return True
 
-  output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
-  cmd))
+def get_expected_output(crash_cmd):
+  p = subprocess.Popen(crash_cmd,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
 
-  # Add messages from crash output to the test
-  # If there is an Assertion failure, use that; otherwise use the
-  # last five stack trace functions
+  # If there is an assertion failure, use that;
+  # otherwise use the last five stack trace functions
   assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1)
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+return [assertion_match.group(1)]
   else:
 stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:-5]
-output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+return matches[-5:]
+
+def write_interestingness_test(testfile, crash_cmd, expected_output):
+  output = ['#!/bin/bash']
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
+  quote_cmd(crash_cmd)))
+
+  for msg in expected_output:
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
 
-  return output
+  with open(testfile, 'w') as f:
+f.write('\n'.join(output))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+def check_interestingness(testfile, file_to_reduce):
+  # Check that the test considers the original file interesting
+  with open(os.devnull, 'w') as devnull:
+p = subprocess.Popen(testfile, stdout=devnull)
+p.communicate()
+  if p.returncode:
+sys.exit("The interestingness test does not pass for the original file.")
+
+  # Check that an empty file is not interesting
+  # file_to_reduce is hardcoded into the test, so this is a roundabout
+  # way to run it on an empty file
+  _, tmpfile = tempfile.mkstemp()
+  _, empty_file = tempfile.mkstemp()
+  shutil.copy(file_to_reduce, tmpfile)
+  shutil.copy(empty_file, file_to_reduce)
+  with open(os.devnull, 'w') as devnull:
+p = subprocess.Popen(testfile, stdout=devnull)
+p.communicate()
+  shutil.copy

[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 191128.
akhuang added a comment.

fix some typos


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59440/new/

https://reviews.llvm.org/D59440

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
-
-Requires C-Reduce and not (part of LLVM utils) to be installed.
 """
 
 from argparse import ArgumentParser
@@ -11,103 +9,243 @@
 import sys
 import subprocess
 import pipes
+import shlex
+import tempfile
+import shutil
 from distutils.spawn import find_executable
 
-def create_test(build_script, llvm_not):
+verbose = False
+llvm_bin = None
+creduce_cmd = None
+not_cmd = None
+
+def check_file(fname):
+  fname = os.path.abspath(fname)
+  if not os.path.isfile(fname):
+sys.exit("ERROR: %s does not exist" % (fname))
+  return fname
+
+def check_cmd(cmd_name, cmd_dir, cmd_path=None):
   """
-  Create an interestingness test from the crash output.
-  Return as a string.
+  Returns absolute path to cmd_path if it is given,
+  or absolute path to cmd_dir/cmd_name.
   """
-  # Get clang call from build script
-  # Assumes the call is the last line of the script
-  with open(build_script) as f:
-cmd = f.readlines()[-1].rstrip('\n\r')
+  if cmd_path:
+cmd = find_executable(cmd_path)
+if cmd:
+  return cmd
+sys.exit("ERROR: executable %s not found" % (cmd_path))
+
+  cmd = find_executable(cmd_name, path=cmd_dir)
+  if cmd:
+return cmd
+  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
+
+def quote_cmd(cmd):
+  return ' '.join(pipes.quote(s) for s in cmd)
+
+def get_crash_cmd(crash_script):
+  with open(crash_script) as f:
+# Assume clang call is on the last line of the script
+line = f.readlines()[-1]
+cmd = shlex.split(line)
 
-  # Get crash output
-  p = subprocess.Popen(build_script,
+# Overwrite the script's clang with the user's clang path
+clang_name = os.path.basename(cmd[0])
+new_clang = check_cmd(clang_name, llvm_bin)
+cmd[0] = pipes.quote(new_clang)
+return cmd
+
+def has_expected_output(crash_cmd, expected_output):
+  p = subprocess.Popen(crash_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
   crash_output, _ = p.communicate()
+  for msg in expected_output:
+if msg not in crash_output:
+  return False
+  return True
 
-  output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
-  cmd))
+def get_expected_output(crash_cmd):
+  p = subprocess.Popen(crash_cmd,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
 
-  # Add messages from crash output to the test
-  # If there is an Assertion failure, use that; otherwise use the
-  # last five stack trace functions
+  # If there is an assertion failure, use that;
+  # otherwise use the last five stack trace functions
   assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1)
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+return [assertion_match.group(1)]
   else:
 stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:-5]
-output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+return matches[-5:]
+
+def write_interestingness_test(testfile, crash_cmd, expected_output):
+  output = ['#!/bin/bash']
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
+  quote_cmd(crash_cmd)))
+
+  for msg in expected_output:
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+
+  with open(testfile, 'w') as f:
+f.write('\n'.join(output))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+def check_interestingness(testfile, file_to_reduce):
+  # Check that the test considers the original file interesting
+  with open(os.devnull, 'w') as devnull:
+p = subprocess.Popen(testfile, stdout=devnull)
+p.communicate()
+  if p.returncode:
+sys.exit("The interestingness test does not pass for the original file.")
+
+  # Check that an empty file is not interesting
+  # file_to_reduce is hardcoded into the test, so this is a roundabout
+  # way to run it on an empty file
+  _, tmpfile = tempfile.mkstemp()
+  _, empty_file = tempfile.mkstemp()
+  shutil.copy(file_to_reduce, tmpfile)
+  shutil.copy(empty_file, file_to_reduce)
+  with open(os.devnull, 'w') as devnull:
+p = subprocess.Popen(testfile, stdo

[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 191192.
akhuang added a comment.

Modify interestingness test to take file as input


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59440/new/

https://reviews.llvm.org/D59440

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
-
-Requires C-Reduce and not (part of LLVM utils) to be installed.
 """
 
 from argparse import ArgumentParser
@@ -11,108 +9,238 @@
 import sys
 import subprocess
 import pipes
+import shlex
+import tempfile
+import shutil
 from distutils.spawn import find_executable
 
-def create_test(build_script, llvm_not):
+verbose = False
+llvm_bin = None
+creduce_cmd = None
+not_cmd = None
+
+def check_file(fname):
+  fname = os.path.abspath(fname)
+  if not os.path.isfile(fname):
+sys.exit("ERROR: %s does not exist" % (fname))
+  return fname
+
+def check_cmd(cmd_name, cmd_dir, cmd_path=None):
   """
-  Create an interestingness test from the crash output.
-  Return as a string.
+  Returns absolute path to cmd_path if it is given,
+  or absolute path to cmd_dir/cmd_name.
   """
-  # Get clang call from build script
-  # Assumes the call is the last line of the script
-  with open(build_script) as f:
-cmd = f.readlines()[-1].rstrip('\n\r')
-
-  # Get crash output
-  p = subprocess.Popen(build_script,
+  if cmd_path:
+cmd = find_executable(cmd_path)
+if cmd:
+  return cmd
+sys.exit("ERROR: executable %s not found" % (cmd_path))
+
+  cmd = find_executable(cmd_name, path=cmd_dir)
+  if cmd:
+return cmd
+  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
+
+def quote_cmd(cmd):
+  for i, arg in enumerate(cmd):
+if not arg.startswith('$'):
+  cmd[i] = pipes.quote(arg)
+  return ' '.join(cmd)
+
+def get_crash_cmd(crash_script):
+  with open(crash_script) as f:
+# Assume clang call is on the last line of the script
+line = f.readlines()[-1]
+cmd = shlex.split(line)
+
+# Overwrite the script's clang with the user's clang path
+clang_name = os.path.basename(cmd[0])
+new_clang = check_cmd(clang_name, llvm_bin)
+cmd[0] = pipes.quote(new_clang)
+return cmd
+
+def has_expected_output(crash_cmd, expected_output):
+  p = subprocess.Popen(crash_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
   crash_output, _ = p.communicate()
+  for msg in expected_output:
+if msg not in crash_output:
+  return False
+  return True
 
-  output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
-  cmd))
+def get_expected_output(crash_cmd):
+  p = subprocess.Popen(crash_cmd,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
 
-  # Add messages from crash output to the test
-  # If there is an Assertion failure, use that; otherwise use the
-  # last five stack trace functions
+  # If there is an assertion failure, use that;
+  # otherwise use the last five stack trace functions
   assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1)
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+return [assertion_match.group(1)]
   else:
 stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:-5]
-output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+return matches[-5:]
+
+def write_interestingness_test(testfile, crash_cmd, expected_output,
+   file_to_reduce):
+  # Replace all instances of file_to_reduce with a command line variable
+  _, filename = os.path.split(file_to_reduce)
+  output = ['#!/bin/bash',
+'if [ -z "$1" ] ; then',
+'  f=%s' % (pipes.quote(file_to_reduce)),
+'else',
+'  f="$1"',
+'fi']
+  cmd = ['$f' if s == filename else s for s in crash_cmd]
+
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
+  quote_cmd(cmd)))
+
+  for msg in expected_output:
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+
+  with open(testfile, 'w') as f:
+f.write('\n'.join(output))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
 
-  return output
+def check_interestingness(testfile, file_to_reduce):
+  # Check that the test considers the original file interesting
+  with open(os.devnull, 'w') as devnull:
+p = subprocess.Popen(testfile, stdout=devnull)
+p

[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 191199.
akhuang marked an inline comment as done.
akhuang added a comment.

fixed array copy mistake


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59440/new/

https://reviews.llvm.org/D59440

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
-
-Requires C-Reduce and not (part of LLVM utils) to be installed.
 """
 
 from argparse import ArgumentParser
@@ -11,108 +9,240 @@
 import sys
 import subprocess
 import pipes
+import shlex
+import tempfile
+import shutil
 from distutils.spawn import find_executable
 
-def create_test(build_script, llvm_not):
+verbose = False
+llvm_bin = None
+creduce_cmd = None
+not_cmd = None
+
+def check_file(fname):
+  fname = os.path.abspath(fname)
+  if not os.path.isfile(fname):
+sys.exit("ERROR: %s does not exist" % (fname))
+  return fname
+
+def check_cmd(cmd_name, cmd_dir, cmd_path=None):
   """
-  Create an interestingness test from the crash output.
-  Return as a string.
+  Returns absolute path to cmd_path if it is given,
+  or absolute path to cmd_dir/cmd_name.
   """
-  # Get clang call from build script
-  # Assumes the call is the last line of the script
-  with open(build_script) as f:
-cmd = f.readlines()[-1].rstrip('\n\r')
-
-  # Get crash output
-  p = subprocess.Popen(build_script,
+  if cmd_path:
+cmd = find_executable(cmd_path)
+if cmd:
+  return cmd
+sys.exit("ERROR: executable %s not found" % (cmd_path))
+
+  cmd = find_executable(cmd_name, path=cmd_dir)
+  if cmd:
+return cmd
+  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
+
+def quote_cmd(cmd):
+  result = []
+  for i, arg in enumerate(cmd):
+if arg.startswith('$'):
+  result.append(arg)
+else:
+  result.append(pipes.quote(arg))
+  return ' '.join(result)
+
+def get_crash_cmd(crash_script):
+  with open(crash_script) as f:
+# Assume clang call is on the last line of the script
+line = f.readlines()[-1]
+cmd = shlex.split(line)
+
+# Overwrite the script's clang with the user's clang path
+clang_name = os.path.basename(cmd[0])
+new_clang = check_cmd(clang_name, llvm_bin)
+cmd[0] = pipes.quote(new_clang)
+return cmd
+
+def has_expected_output(crash_cmd, expected_output):
+  p = subprocess.Popen(crash_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
   crash_output, _ = p.communicate()
+  for msg in expected_output:
+if msg not in crash_output:
+  return False
+  return True
 
-  output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
-  cmd))
+def get_expected_output(crash_cmd):
+  p = subprocess.Popen(crash_cmd,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
 
-  # Add messages from crash output to the test
-  # If there is an Assertion failure, use that; otherwise use the
-  # last five stack trace functions
+  # If there is an assertion failure, use that;
+  # otherwise use the last five stack trace functions
   assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1)
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+return [assertion_match.group(1)]
   else:
 stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:-5]
-output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+return matches[-5:]
+
+def write_interestingness_test(testfile, crash_cmd, expected_output,
+   file_to_reduce):
+  # Replace all instances of file_to_reduce with a command line variable
+  _, filename = os.path.split(file_to_reduce)
+  output = ['#!/bin/bash',
+'if [ -z "$1" ] ; then',
+'  f=%s' % (pipes.quote(file_to_reduce)),
+'else',
+'  f="$1"',
+'fi']
+  cmd = ['$f' if s == filename else s for s in crash_cmd]
+
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
+  quote_cmd(cmd)))
+
+  for msg in expected_output:
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+
+  with open(testfile, 'w') as f:
+f.write('\n'.join(output))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
 
-  return output
+def check_interestingness(testfile, file_to_reduce):
+  # Check that the test considers the original file interesting
+  with open(os.devnull, '

[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 191217.
akhuang marked 2 inline comments as done.
akhuang added a comment.

Fixed typo where it was writing the abspath of the file to the interestingness 
test.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59440/new/

https://reviews.llvm.org/D59440

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
-
-Requires C-Reduce and not (part of LLVM utils) to be installed.
 """
 
 from argparse import ArgumentParser
@@ -11,108 +9,245 @@
 import sys
 import subprocess
 import pipes
+import shlex
+import tempfile
+import shutil
 from distutils.spawn import find_executable
 
-def create_test(build_script, llvm_not):
+verbose = False
+llvm_bin = None
+creduce_cmd = None
+not_cmd = None
+
+def check_file(fname):
+  if not os.path.isfile(fname):
+sys.exit("ERROR: %s does not exist" % (fname))
+  return fname
+
+def check_cmd(cmd_name, cmd_dir, cmd_path=None):
   """
-  Create an interestingness test from the crash output.
-  Return as a string.
+  Returns absolute path to cmd_path if it is given,
+  or absolute path to cmd_dir/cmd_name.
   """
-  # Get clang call from build script
-  # Assumes the call is the last line of the script
-  with open(build_script) as f:
-cmd = f.readlines()[-1].rstrip('\n\r')
-
-  # Get crash output
-  p = subprocess.Popen(build_script,
+  if cmd_path:
+cmd = find_executable(cmd_path)
+if cmd:
+  return cmd
+sys.exit("ERROR: executable %s not found" % (cmd_path))
+
+  cmd = find_executable(cmd_name, path=cmd_dir)
+  if cmd:
+return cmd
+  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
+
+def quote_cmd(cmd):
+  result = []
+  for i, arg in enumerate(cmd):
+if arg.startswith('$'):
+  result.append(arg)
+else:
+  result.append(pipes.quote(arg))
+  return ' '.join(result)
+
+def get_crash_cmd(crash_script):
+  with open(crash_script) as f:
+# Assume clang call is on the last line of the script
+line = f.readlines()[-1]
+cmd = shlex.split(line)
+
+# Overwrite the script's clang with the user's clang path
+clang_name = os.path.basename(cmd[0])
+new_clang = check_cmd(clang_name, llvm_bin)
+cmd[0] = pipes.quote(new_clang)
+return cmd
+
+def has_expected_output(crash_cmd, expected_output):
+  p = subprocess.Popen(crash_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
   crash_output, _ = p.communicate()
+  for msg in expected_output:
+if msg not in crash_output:
+  return False
+  return True
 
-  output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
-  cmd))
+def get_expected_output(crash_cmd):
+  p = subprocess.Popen(crash_cmd,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
 
-  # Add messages from crash output to the test
-  # If there is an Assertion failure, use that; otherwise use the
-  # last five stack trace functions
+  # If there is an assertion failure, use that;
+  # otherwise use the last five stack trace functions
   assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1)
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+return [assertion_match.group(1)]
   else:
 stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:-5]
-output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+return matches[-5:]
+
+def write_interestingness_test(testfile, crash_cmd, expected_output,
+   file_to_reduce):
+  filename = os.path.basename(file_to_reduce)
+  if filename not in crash_cmd:
+sys.exit("ERROR: expected %s to be in the crash command" % filename)
+
+  # Replace all instances of file_to_reduce with a command line variable
+  output = ['#!/bin/bash',
+'if [ -z "$1" ] ; then',
+'  f=%s' % (pipes.quote(filename)),
+'else',
+'  f="$1"',
+'fi']
+  cmd = ['$f' if s == filename else s for s in crash_cmd]
+
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
+  quote_cmd(cmd)))
+
+  for msg in expected_output:
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+
+  with open(testfile, 'w') as f:
+f.write('\n'.join(output))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+def check_interestingness(testf

[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:106-117
+  # Check that an empty file is not interesting
+  # file_to_reduce is hardcoded into the test, so this is a roundabout
+  # way to run it on an empty file
+  _, tmpfile = tempfile.mkstemp()
+  _, empty_file = tempfile.mkstemp()
+  shutil.copy(file_to_reduce, tmpfile)
+  shutil.copy(empty_file, file_to_reduce)

rnk wrote:
> Another way to do this without the complexity of swapping the files around is 
> to construct the interestingness test to take the path to the file as a 
> parameter (`$1`). CReduce always passes the path to the file being reduced as 
> the first argument.
It seems like creduce isn't actually passing the filename as an argument  
(creduce had problems when I accidentally used the absolute path of the file as 
the default value when no arguments are found)


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59440/new/

https://reviews.llvm.org/D59440



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-19 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 191409.
akhuang added a comment.

style things


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59440/new/

https://reviews.llvm.org/D59440

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
-
-Requires C-Reduce and not (part of LLVM utils) to be installed.
 """
 
 from argparse import ArgumentParser
@@ -11,108 +9,238 @@
 import sys
 import subprocess
 import pipes
+import shlex
+import tempfile
+import shutil
 from distutils.spawn import find_executable
 
-def create_test(build_script, llvm_not):
+verbose = False
+llvm_bin = None
+creduce_cmd = None
+not_cmd = None
+
+def check_file(fname):
+  if not os.path.isfile(fname):
+sys.exit("ERROR: %s does not exist" % (fname))
+  return fname
+
+def check_cmd(cmd_name, cmd_dir, cmd_path=None):
   """
-  Create an interestingness test from the crash output.
-  Return as a string.
+  Returns absolute path to cmd_path if it is given,
+  or absolute path to cmd_dir/cmd_name.
   """
-  # Get clang call from build script
-  # Assumes the call is the last line of the script
-  with open(build_script) as f:
-cmd = f.readlines()[-1].rstrip('\n\r')
-
-  # Get crash output
-  p = subprocess.Popen(build_script,
+  if cmd_path:
+cmd = find_executable(cmd_path)
+if cmd:
+  return cmd
+sys.exit("ERROR: executable %s not found" % (cmd_path))
+
+  cmd = find_executable(cmd_name, path=cmd_dir)
+  if cmd:
+return cmd
+  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
+
+def quote_cmd(cmd):
+  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
+  for arg in cmd)
+
+def get_crash_cmd(crash_script):
+  with open(crash_script) as f:
+# Assume clang call is on the last line of the script
+line = f.readlines()[-1]
+cmd = shlex.split(line)
+
+# Overwrite the script's clang with the user's clang path
+clang_name = os.path.basename(cmd[0])
+new_clang = check_cmd(clang_name, llvm_bin)
+cmd[0] = pipes.quote(new_clang)
+return cmd
+
+def has_expected_output(crash_cmd, expected_output):
+  p = subprocess.Popen(crash_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
   crash_output, _ = p.communicate()
+  for msg in expected_output:
+if msg not in crash_output:
+  return False
+  return True
 
-  output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
-  cmd))
+def get_expected_output(crash_cmd):
+  p = subprocess.Popen(crash_cmd,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
 
-  # Add messages from crash output to the test
-  # If there is an Assertion failure, use that; otherwise use the
-  # last five stack trace functions
+  # If there is an assertion failure, use that;
+  # otherwise use the last five stack trace functions
   assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1)
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+return [assertion_match.group(1)]
   else:
 stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:-5]
-output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+return matches[-5:]
+
+def write_interestingness_test(testfile, crash_cmd, expected_output,
+   file_to_reduce):
+  filename = os.path.basename(file_to_reduce)
+  if filename not in crash_cmd:
+sys.exit("ERROR: expected %s to be in the crash command" % filename)
+
+  # Replace all instances of file_to_reduce with a command line variable
+  output = ['#!/bin/bash',
+'if [ -z "$1" ] ; then',
+'  f=%s' % (pipes.quote(filename)),
+'else',
+'  f="$1"',
+'fi']
+  cmd = ['$f' if s == filename else s for s in crash_cmd]
+
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
+  quote_cmd(cmd)))
+
+  for msg in expected_output:
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+
+  with open(testfile, 'w') as f:
+f.write('\n'.join(output))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
 
-  return output
+def check_interestingness(testfile, file_to_reduce):
+  testfile = os.path.abspath(testfile)
+
+  # Check that the test considers the original file interesting
+  with open(os.devnull, 'w') as devnull:
+   

[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-20 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 191598.
akhuang added a comment.

style nits, fixed thing in getting path to clang


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59440/new/

https://reviews.llvm.org/D59440

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,7 +1,5 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
-
-Requires C-Reduce and not (part of LLVM utils) to be installed.
 """
 
 from argparse import ArgumentParser
@@ -11,108 +9,232 @@
 import sys
 import subprocess
 import pipes
+import shlex
+import tempfile
+import shutil
 from distutils.spawn import find_executable
 
-def create_test(build_script, llvm_not):
+verbose = False
+llvm_bin = None
+creduce_cmd = None
+not_cmd = None
+
+def check_file(fname):
+  if not os.path.isfile(fname):
+sys.exit("ERROR: %s does not exist" % (fname))
+  return fname
+
+def check_cmd(cmd_name, cmd_dir, cmd_path=None):
   """
-  Create an interestingness test from the crash output.
-  Return as a string.
+  Returns absolute path to cmd_path if it is given,
+  or absolute path to cmd_dir/cmd_name.
   """
-  # Get clang call from build script
-  # Assumes the call is the last line of the script
-  with open(build_script) as f:
-cmd = f.readlines()[-1].rstrip('\n\r')
-
-  # Get crash output
-  p = subprocess.Popen(build_script,
+  if cmd_path:
+cmd = find_executable(cmd_path)
+if cmd:
+  return cmd
+sys.exit("ERROR: executable %s not found" % (cmd_path))
+
+  cmd = find_executable(cmd_name, path=cmd_dir)
+  if cmd:
+return cmd
+  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
+
+def quote_cmd(cmd):
+  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
+  for arg in cmd)
+
+def get_crash_cmd(crash_script):
+  with open(crash_script) as f:
+# Assume clang call is on the last line of the script
+line = f.readlines()[-1]
+cmd = shlex.split(line)
+
+# Overwrite the script's clang with the user's clang path
+new_clang = check_cmd('clang', llvm_bin)
+cmd[0] = pipes.quote(new_clang)
+return cmd
+
+def has_expected_output(crash_cmd, expected_output):
+  p = subprocess.Popen(crash_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
   crash_output, _ = p.communicate()
+  return all(msg in crash_output for msg in expected_output)
 
-  output = ['#!/bin/bash']
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(llvm_not),
-  cmd))
+def get_expected_output(crash_cmd):
+  p = subprocess.Popen(crash_cmd,
+   stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+  crash_output, _ = p.communicate()
 
-  # Add messages from crash output to the test
-  # If there is an Assertion failure, use that; otherwise use the
-  # last five stack trace functions
+  # If there is an assertion failure, use that;
+  # otherwise use the last five stack trace functions
   assertion_re = r'Assertion `([^\']+)\' failed'
   assertion_match = re.search(assertion_re, crash_output)
   if assertion_match:
-msg = assertion_match.group(1)
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
+return [assertion_match.group(1)]
   else:
 stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
 matches = re.findall(stacktrace_re, crash_output)
-del matches[:-5]
-output += ['grep %s t.log || exit 1' % pipes.quote(msg) for msg in matches]
+return matches[-5:]
+
+def write_interestingness_test(testfile, crash_cmd, expected_output,
+   file_to_reduce):
+  filename = os.path.basename(file_to_reduce)
+  if filename not in crash_cmd:
+sys.exit("ERROR: expected %s to be in the crash command" % filename)
+
+  # Replace all instances of file_to_reduce with a command line variable
+  output = ['#!/bin/bash',
+'if [ -z "$1" ] ; then',
+'  f=%s' % (pipes.quote(filename)),
+'else',
+'  f="$1"',
+'fi']
+  cmd = ['$f' if s == filename else s for s in crash_cmd]
+
+  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
+  quote_cmd(cmd)))
+
+  for msg in expected_output:
+output.append('grep %s t.log || exit 1' % pipes.quote(msg))
 
-  return output
+  with open(testfile, 'w') as f:
+f.write('\n'.join(output))
+  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
+
+def check_interestingness(testfile, file_to_reduce):
+  testfile = os.path.abspath(testfile)
+
+  # Check that the test considers the original file interesting
+  with open(os.devnull, 'w') as devnull:
+returncode = subprocess.call(testfile, stdout=

[PATCH] D59440: add steps to preprocess file and reduce command line args

2019-03-21 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

@arichardson Will add you next time, sorry I didn't do so on this one!


Repository:
  rC Clang

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59440/new/

https://reviews.llvm.org/D59440



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59725: Additions to creduce script

2019-03-22 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
akhuang added reviewers: rnk, george.burgess.iv, arichardson.
Herald added a reviewer: serge-sans-paille.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Some more additions to the script - mainly reducing the clang args after the 
creduce run by removing them one by one and seeing if the crash reproduces. 
Other things:

- remove the --crash flag when "fatal error" occurs
- fixed to read stack trace functions from the top
- run creduce on a copy of the original file


Repository:
  rC Clang

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,308 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_fi

[PATCH] D59725: Additions to creduce script

2019-03-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192145.
akhuang added a comment.

Fix some typos, pass --tidy flag to creduce


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,306 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)
-
-  cmd = crash_cmd + ['-E', '-P']
-  p = subprocess.Popen(cmd,
-   

[PATCH] D59725: Additions to creduce script

2019-03-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192149.
akhuang added a comment.

reuploaded diff with full context


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,306 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)
-
-  cmd = crash_cmd + ['-E', '-P']
-  p = subprocess.Popen(cmd,
-   stdout=sub

[PATCH] D59725: Additions to creduce script

2019-03-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked 15 inline comments as done.
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:137
+
+# If no message was found, use the top five stack trace functions,
+# ignoring some common functions

george.burgess.iv wrote:
> Please expand a bit on why 5 was chosen (is there some deep reason behind it, 
> or does it just seem like a sensible number?)
There is no deep reason - it was an arbitrary smallish number to hopefully not 
only pick up common stack trace functions



Comment at: clang/utils/creduce-clang-crash.py:202
+cmd = self.get_crash_cmd() + ['-E', '-P']
+p = subprocess.Popen(self.get_crash_cmd() + ['-E', '-P'],
+ stdout=subprocess.PIPE,

george.burgess.iv wrote:
> was this intended to use `cmd`?
yep



Comment at: clang/utils/creduce-clang-crash.py:205
+ stderr=subprocess.STDOUT)
+preprocessed, _ = p.communicate()
+

george.burgess.iv wrote:
> Do we want to check the exit code of this? Or do we assume that if clang 
> crashes during preprocessing, we'll just see a different error during 
> `check_expected_output`? (In the latter case, please add a comment)
I think checking the exit code is a good idea



Comment at: clang/utils/creduce-clang-crash.py:222
+def append_flags(x, y):
+  if len(x) > 0 and x[-1].startswith('-') and not y.startswith('-'):
+x[-1] += ' ' + y

george.burgess.iv wrote:
> Is it intentional to group multiple consecutive non-dashed args? e.g. it 
> seems that `clang -ffoo bar baz` will turn into `['clang', '-ffoo bar baz']`
> 
> 
I guess that was originally the intention, although now that I think of it it 
makes more sense to group at most one argument. 



Comment at: clang/utils/creduce-clang-crash.py:223
+  if len(x) > 0 and x[-1].startswith('-') and not y.startswith('-'):
+x[-1] += ' ' + y
+return x

george.burgess.iv wrote:
> Should we be `shlex.quote`'ing y here (and probably in the `return x + [y]` 
> below)?
It quotes everything right before writing to file - are there reasons to quote 
here instead?



Comment at: clang/utils/creduce-clang-crash.py:279
+ "-debugger-tuning=",
+ "-gdwarf"])
+new_args = self.try_remove_args(new_args,

george.burgess.iv wrote:
> If we're replacing other args with their effective negation, does it also 
> make sense to replace all debug-ish options with `-g0`?
I guess `-g0` is not a cc1 option, nor is `-gdwarf`? So this is essentially 
just removing `-gcodeview`. I'm actually not sure what the other flags do. 



Comment at: clang/utils/creduce-clang-crash.py:362
+  r = Reduce(crash_script, file_to_reduce)
+  r.simplify_clang_args()
+  r.write_interestingness_test()

george.burgess.iv wrote:
> I'm unclear on why we do a partial simplification of clang args here, then a 
> full reduction after creduce. Is there a disadvantage to instead doing:
> 
> r.write_interestingness_test()
> r.clang_preprocess()
> r.reduce_clang_args()
> r.run_creduce()
> r.reduce_clang_args()
> 
> ?
> 
> The final `reduce_clang_args` being there to remove extra `-D`/`-I`/etc. args 
> if preprocessing failed somehow, to remove `-std=foo` args if those aren't 
> relevant after reduction, etc.
> 
> The advantage to this being that we no longer need to maintain a `simplify` 
> function, and creduce runs with a relatively minimal set of args to start 
> with.
> 
> In any case, can we please add comments explaining why we chose whatever 
> order we end up going with, especially where subtleties make it counter to 
> what someone might naively expect?
Basically the disadvantage is that clang takes longer to run before the 
reduction, so it takes unnecessary time to iterate through all the arguments 
beforehand. 
And yeah, the final `reduce_clang_args` is there to minimize the clang 
arguments needed to reproduce the crash on the reduced source file. 

If that makes sense, I can add comments for this-


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59725: Additions to creduce script

2019-03-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192218.
akhuang marked an inline comment as done.
akhuang added a comment.

Style nits, added comments


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,326 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)
-
-  cmd = crash_cmd + ['-E', '-P']
-  p = subprocess.Popen(cmd,

[PATCH] D59725: Additions to creduce script

2019-03-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked 2 inline comments as done.
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:223
+  if len(x) > 0 and x[-1].startswith('-') and not y.startswith('-'):
+x[-1] += ' ' + y
+return x

george.burgess.iv wrote:
> akhuang wrote:
> > george.burgess.iv wrote:
> > > Should we be `shlex.quote`'ing y here (and probably in the `return x + 
> > > [y]` below)?
> > It quotes everything right before writing to file - are there reasons to 
> > quote here instead?
> We're `shlex.split`ing groups below, and I assume the intent is 
> `Reduce.ungroup_args(Reduce.group_args_by_dash(args)) == args`.
> 
> If we don't want to quote here, we can also have `ungroup_args` and 
> `group_args_by_dash` deal in lists of nonempty lists.
good point- I guess the whole grouping thing is unnecessarily complicated, so I 
got rid of it and it now removes the next arg in `try_remove_arg_by_index` 



Comment at: clang/utils/creduce-clang-crash.py:306
+# Remove other cases that aren't covered by the heuristic
+new_args = self.try_remove_args(new_args, msg="Removed -mllvm",
+opts_one_arg_startswith=["-mllvm"])

george.burgess.iv wrote:
> george.burgess.iv wrote:
> > Probably want to do a similar thing for `-Xclang` (which, as far as this 
> > code is concerned, acts a lot like `-mllvm`)
> (You can ignore this comment if we're dealing in cc1; `-Xclang` is just "pass 
> this directly as a cc1 arg")
ah, ok. 


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59725: Additions to creduce script

2019-03-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192230.
akhuang added a comment.

fix issue with grouping two command line args together


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,310 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)
-
-  cmd = crash_cmd + ['-E', '-P']
-  p = subprocess.Popen(cmd,
-

[PATCH] D59725: Additions to creduce script

2019-03-26 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked 8 inline comments as done.
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:145
+  matches = re.findall(stacktrace_re, crash_output)
+  result = filter(lambda x: x and x.strip() not in filters, matches)[:5]
+  for msg in result:

arichardson wrote:
> george.burgess.iv wrote:
> > nit: please prefer `[x for x in matches if x and x.strip() not in 
> > filters][:5]`. py3's filter returns a generator, whereas py2's returns a 
> > list.
> Stack traces also look different on macOS and it would be nice to handle that 
> too.
> 
> Here's a sample I got from adding a llvm_unreachable at a random location:
> ```
> My unreachable message...
> UNREACHABLE executed at 
> /Users/alex/cheri/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineCompares.cpp:4468!
> Stack dump:
> 0.Program arguments: 
> /Users/alex/cheri/llvm-project/cmake-build-debug/bin/opt 
> -mtriple=cheri-unknown-freebsd -mcpu=cheri128 -mattr=+cheri128 -target-abi 
> purecap -relocation-model pic -S -instcombine -simplifycfg 
> /Users/alex/cheri/llvm-project/llvm/test/CodeGen/Mips/cheri/simplifycfg-ptrtoint.ll
>  -o - 
> 1.Running pass 'Function Pass Manager' on module 
> '/Users/alex/cheri/llvm-project/llvm/test/CodeGen/Mips/cheri/simplifycfg-ptrtoint.ll'.
> 2.Running pass 'Combine redundant instructions' on function 
> '@cannot_fold_tag_unknown'
> 0  libLLVMSupport.dylib 0x000114515a9d 
> llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 45
> 1  libLLVMSupport.dylib 0x0001145153f1 llvm::sys::RunSignalHandlers() 
> + 65
> 2  libLLVMSupport.dylib 0x000114515fbf SignalHandler(int) + 111
> 3  libsystem_platform.dylib 0x7fff5b637b3d _sigtramp + 29
> 4  libsystem_platform.dylib 0x7ffee20d0cf0 _sigtramp + 2259259856
> 5  libsystem_c.dylib0x7fff5b4f51c9 abort + 127
> 6  libLLVMSupport.dylib 0x00011446bb12 
> llvm::llvm_unreachable_internal(char const*, char const*, unsigned int) + 162
> 7  libLLVMInstCombine.dylib 0x000112c345c8 
> llvm::InstCombiner::foldICmpUsingKnownBits(llvm::ICmpInst&) + 4136
> 8  libLLVMInstCombine.dylib 0x000112c34d19 
> llvm::InstCombiner::visitICmpInst(llvm::ICmpInst&) + 569
> 9  libLLVMInstCombine.dylib 0x000112bb9cf2 llvm::InstCombiner::run() + 
> 1522
> 10 libLLVMInstCombine.dylib 0x000112bbb310 
> combineInstructionsOverFunction(llvm::Function&, llvm::InstCombineWorklist&, 
> llvm::AAResults*, llvm::AssumptionCache&, llvm::TargetLibraryInfo&, 
> llvm::DominatorTree&, llvm::OptimizationRemarkEmitter&, bool, 
> llvm::LoopInfo*) + 624
> 11 libLLVMInstCombine.dylib 0x000112bbb6d6 
> llvm::InstructionCombiningPass::runOnFunction(llvm::Function&) + 214
> 12 libLLVMCore.dylib0x000111c0bb4d 
> llvm::FPPassManager::runOnFunction(llvm::Function&) + 317
> 13 libLLVMCore.dylib0x000111c0be83 
> llvm::FPPassManager::runOnModule(llvm::Module&) + 99
> 14 libLLVMCore.dylib0x000111c0c2c4 (anonymous 
> namespace)::MPPassManager::runOnModule(llvm::Module&) + 420
> 15 libLLVMCore.dylib0x000111c0c036 
> llvm::legacy::PassManagerImpl::run(llvm::Module&) + 182
> 16 opt  0x00010db6657b main + 7163
> 17 libdyld.dylib0x7fff5b44ced9 start + 1
> ```
I changed the regex to ignore the # at the beginning of the line - I think that 
should cover the mac os stack trace 



Comment at: clang/utils/creduce-clang-crash.py:303
+opts_startswith=["-O"])
+self.clang_args = new_args
+verbose_print("Simplified command:", quote_cmd(self.get_crash_cmd()))

arichardson wrote:
> george.burgess.iv wrote:
> > FWIW, opportunistically trying to add `-fsyntax-only` may help here: if the 
> > crash is in the frontend, it means that non-repros will stop before 
> > codegen, rather than trying to generate object files, or whatever they were 
> > trying to generate in the first place.
> Yes that sounds like a good idea! I just do -emit-llvm to avoid assembly 
> output but for parser/sema crashes -fsyntax-only would save some time.
> 
> Another one I found useful was `-Werror=implicit-int` to get more readable 
> test cases from creduce: 
> https://github.com/CTSRD-CHERI/llvm-project/blob/master/clang/utils/creduce_crash_testcase.py#L851
> 
> Without that flag lots of test cases look really weird due to the implicit 
> int and various inferred semicolons.
> 
Sounds good-- I added `-fsyntax-only`, `-emit-llvm` and `-Werror=implicit-int`



Comment at: clang/utils/creduce-clang-crash.py:64
+
+class Reduce:
+  def __init__(self, crash_script, file_to_reduce):

arichardson wrote:
> Does this need to be `Reduce(object):` for python2? 
I think it still works, but adding `object` makes sense. 



Comment at: clang/utils/creduce-clang-crash.py:123
+# Look for specific error messages
+regexes = [r"Asserti

[PATCH] D59725: Additions to creduce script

2019-03-26 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192350.
akhuang marked 2 inline comments as done.
akhuang added a comment.
Herald added a subscriber: jdoerfert.

added to error message regexes and command line flags


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,334 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)

[PATCH] D59725: Additions to creduce script

2019-03-27 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192499.
akhuang marked 3 inline comments as done.
akhuang added a comment.

change `mkstemp` to `NamedTemporaryFile` and add `decode(utf-8)` so it works on 
python3.5


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,337 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)

[PATCH] D59725: Additions to creduce script

2019-03-27 Thread Amy Huang via Phabricator via cfe-commits
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:198
+# Instead of modifying the filename in the test file, just run the command
+fd, empty_file = tempfile.mkstemp()
+if self.check_expected_output(filename=empty_file):

george.burgess.iv wrote:
> Did we want to use `NamedTemporaryFile` here as rnk suggested?
> 
> (If not, you can lift the `os.close`s to immediately after this line.)
switched to using `NamedTemporaryFile` here - 



Comment at: clang/utils/creduce-clang-crash.py:206
+print("\nTrying to preprocess the source file...")
+fd, tmpfile = tempfile.mkstemp()
+

george.burgess.iv wrote:
> Similar question about `NamedTemporaryFile`.
> 
> Please note that you'll probably have to pass `delete=False`, since 
> apparently `delete=True` sets O_TEMPORARY on Windows, which... might follow 
> the file across renames? I'm unsure.
moved to `NamedTemporaryFile` with comment about `delete=False`


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59725: Additions to creduce script

2019-03-28 Thread Amy Huang via Phabricator via cfe-commits
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:212
+
+cmd = self.get_crash_cmd() + ['-E', '-P']
+try:

arichardson wrote:
> Some crash messages might include the line numbers, do you think it makes 
> sense to fall back to running with -E but without -P and also checking that? 
> I do it in my script but I'm not sure preprocessing saves that much time 
> since creduce will try to remove those statements early.
Makes sense-- in my experience preprocessing is still quite a bit faster than 
letting creduce remove all the statements.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59725: Additions to creduce script

2019-03-28 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192669.
akhuang marked 3 inline comments as done.
akhuang added a comment.

Add preprocessing with clang -E only;
use `with` for opening files


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,340 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)
-
-  cmd = crash_cmd + [

[PATCH] D59725: Additions to creduce script

2019-03-29 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked 2 inline comments as done.
akhuang added inline comments.



Comment at: clang/utils/creduce-clang-crash.py:208
+print("\nTrying to preprocess the source file...")
+# use delete=False in case the tmpfile flag causes problems when copying
+with tempfile.NamedTemporaryFile(delete=False) as tmpfile:

arichardson wrote:
> I believe we are currently not deleting this temporary file.
> Can `delete=False` be removed since we are using `shutil.copy()` instead of a 
> move?
> 
Yeah, I think that should be fine. 


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59725: Additions to creduce script

2019-03-29 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 192846.
akhuang marked an inline comment as done.
akhuang added a comment.

Tmpfile was not being removed


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725

Files:
  clang/utils/creduce-clang-crash.py

Index: clang/utils/creduce-clang-crash.py
===
--- clang/utils/creduce-clang-crash.py
+++ clang/utils/creduce-clang-crash.py
@@ -1,8 +1,14 @@
 #!/usr/bin/env python
 """Calls C-Reduce to create a minimal reproducer for clang crashes.
+
+Output files:
+  *.reduced.sh -- crash reproducer with minimal arguments
+  *.reduced.cpp -- the reduced file
+  *.test.sh -- interestingness test for C-Reduce
 """
 
-from argparse import ArgumentParser
+from __future__ import print_function
+from argparse import ArgumentParser, RawTextHelpFormatter
 import os
 import re
 import stat
@@ -15,10 +21,14 @@
 from distutils.spawn import find_executable
 
 verbose = False
-llvm_bin = None
 creduce_cmd = None
+clang_cmd = None
 not_cmd = None
 
+def verbose_print(*args, **kwargs):
+  if verbose:
+print(*args, **kwargs)
+
 def check_file(fname):
   if not os.path.isfile(fname):
 sys.exit("ERROR: %s does not exist" % (fname))
@@ -33,166 +43,339 @@
 cmd = find_executable(cmd_path)
 if cmd:
   return cmd
-sys.exit("ERROR: executable %s not found" % (cmd_path))
+sys.exit("ERROR: executable `%s` not found" % (cmd_path))
 
   cmd = find_executable(cmd_name, path=cmd_dir)
   if cmd:
 return cmd
-  sys.exit("ERROR: %s not found in %s" % (cmd_name, cmd_dir))
 
-def quote_cmd(cmd):
-  return ' '.join(arg if arg.startswith('$') else pipes.quote(arg)
-  for arg in cmd)
-
-def get_crash_cmd(crash_script):
-  with open(crash_script) as f:
-# Assume clang call is on the last line of the script
-line = f.readlines()[-1]
-cmd = shlex.split(line)
-
-# Overwrite the script's clang with the user's clang path
-new_clang = check_cmd('clang', llvm_bin)
-cmd[0] = pipes.quote(new_clang)
-return cmd
+  if not cmd_dir:
+cmd_dir = "$PATH"
+  sys.exit("ERROR: `%s` not found in %s" % (cmd_name, cmd_dir))
 
-def has_expected_output(crash_cmd, expected_output):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-  return all(msg in crash_output for msg in expected_output)
-
-def get_expected_output(crash_cmd):
-  p = subprocess.Popen(crash_cmd,
-   stdout=subprocess.PIPE,
-   stderr=subprocess.STDOUT)
-  crash_output, _ = p.communicate()
-
-  # If there is an assertion failure, use that;
-  # otherwise use the last five stack trace functions
-  assertion_re = r'Assertion `([^\']+)\' failed'
-  assertion_match = re.search(assertion_re, crash_output)
-  if assertion_match:
-return [assertion_match.group(1)]
-  else:
-stacktrace_re = r'#[0-9]+\s+0[xX][0-9a-fA-F]+\s*([^(]+)\('
-matches = re.findall(stacktrace_re, crash_output)
-return matches[-5:]
-
-def write_interestingness_test(testfile, crash_cmd, expected_output,
-   file_to_reduce):
-  filename = os.path.basename(file_to_reduce)
-  if filename not in crash_cmd:
-sys.exit("ERROR: expected %s to be in the crash command" % filename)
-
-  # Replace all instances of file_to_reduce with a command line variable
-  output = ['#!/bin/bash',
-'if [ -z "$1" ] ; then',
-'  f=%s' % (pipes.quote(filename)),
-'else',
-'  f="$1"',
-'fi']
-  cmd = ['$f' if s == filename else s for s in crash_cmd]
-
-  output.append('%s --crash %s >& t.log || exit 1' % (pipes.quote(not_cmd),
-  quote_cmd(cmd)))
-
-  for msg in expected_output:
-output.append('grep %s t.log || exit 1' % pipes.quote(msg))
-
-  with open(testfile, 'w') as f:
-f.write('\n'.join(output))
-  os.chmod(testfile, os.stat(testfile).st_mode | stat.S_IEXEC)
-
-def check_interestingness(testfile, file_to_reduce):
-  testfile = os.path.abspath(testfile)
-
-  # Check that the test considers the original file interesting
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call(testfile, stdout=devnull)
-  if returncode:
-sys.exit("The interestingness test does not pass for the original file.")
-
-  # Check that an empty file is not interesting
-  _, empty_file = tempfile.mkstemp()
-  with open(os.devnull, 'w') as devnull:
-returncode = subprocess.call([testfile, empty_file], stdout=devnull)
-  os.remove(empty_file)
-  if not returncode:
-sys.exit("The interestingness test passes for an empty file.")
-
-def clang_preprocess(file_to_reduce, crash_cmd, expected_output):
-  _, tmpfile = tempfile.mkstemp()
-  shutil.copy(file_to_reduce, tmpfile)
-
-  cmd = crash_cmd + ['-E', '-P']
-  p = subprocess.Popen(c

[PATCH] D60236: add periods

2019-04-03 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
Herald added subscribers: cfe-commits, jfb.
Herald added a project: clang.

emit metadata for __declspec(allocator)

add tests for heapallocsite metadata


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D60236

Files:
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c

Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- /dev/null
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited -gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
+
+char buf[1024];
+__declspec(allocator) void *myalloc(int s) {
+  void *p = &buf[0];
+  return p;
+}
+
+void call_alloc() {
+  char *p = (char*)myalloc(sizeof(char));
+}
+
+// CHECK: !heapallocsite [[DBG_F1:!.*]]
+// CHECK: [[DBG_F1:!.*]] = !{}
Index: clang/lib/CodeGen/CGDebugInfo.h
===
--- clang/lib/CodeGen/CGDebugInfo.h
+++ clang/lib/CodeGen/CGDebugInfo.h
@@ -476,6 +476,9 @@
   /// Emit standalone debug info for a type.
   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
 
+  /// Get debug info for MSAllocator metadata.
+  llvm::MDNode *getMSAllocatorMetadata(QualType Ty, SourceLocation Loc);
+
   void completeType(const EnumDecl *ED);
   void completeType(const RecordDecl *RD);
   void completeRequiredType(const RecordDecl *RD);
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1959,6 +1959,20 @@
   return T;
 }
 
+llvm::MDNode *CGDebugInfo::getMSAllocatorMetadata(QualType D,
+  SourceLocation Loc) {
+  // FIXME: return the type that return value is cast to
+  llvm::MDNode *node;
+  if (D.getTypePtr()->isVoidPointerType()) {
+node = llvm::MDNode::get(CGM.getLLVMContext(), None);
+  } else {
+QualType PointeeTy = D.getTypePtr()->getPointeeType();
+node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
+  }
+  return node;
+}
+
+
 void CGDebugInfo::completeType(const EnumDecl *ED) {
   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
 return;
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -3800,6 +3800,8 @@
 
   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
 
+  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
+
 #ifndef NDEBUG
   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
 // For an inalloca varargs function, we don't expect CallInfo to match the
@@ -4288,11 +4290,7 @@
   // Apply always_inline to all calls within flatten functions.
   // FIXME: should this really take priority over __try, below?
   if (CurCodeDecl && CurCodeDecl->hasAttr() &&
-  !(Callee.getAbstractInfo().getCalleeDecl().getDecl() &&
-Callee.getAbstractInfo()
-.getCalleeDecl()
-.getDecl()
-->hasAttr())) {
+  !(TargetDecl && TargetDecl->hasAttr())) {
 Attrs =
 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
llvm::Attribute::AlwaysInline);
@@ -4376,11 +4374,17 @@
 
   // Suppress tail calls if requested.
   if (llvm::CallInst *Call = dyn_cast(CI)) {
-const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
 if (TargetDecl && TargetDecl->hasAttr())
   Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
   }
 
+  // Add metadata for calls to MSAllocator functions
+  if (!DisableDebugInfo) {
+if (TargetDecl && TargetDecl->hasAttr())
+  CI->setMetadata("heapallocsite", getDebugInfo()->
+   getMSAllocatorMetadata(RetTy, Loc));
+  }
+
   // 4. Finish the call.
 
   // If the call doesn't return, finish the basic block and clear the
@@ -4537,7 +4541,6 @@
   } ();
 
   // Emit the assume_aligned check on the return value.
-  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
   if (Ret.isScalar() && TargetDecl) {
 if (const auto *AA = TargetDecl->getAttr()) {
   llvm::Value *OffsetValue = nullptr;
Index: clang/lib/CodeGen/CGAtomic.cpp
===
--- clang/lib/CodeGen/CGAtomic.cpp
+++ clang/lib/CodeGen/CGAtomic.cpp
@@ -1688,7 +1688,7 @@
 UpRVal = OldRVal;
 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
   } else {
-// Build new lvalue for temp address
+// Build new lvalue for temp address.
 Address Ptr = Atomics.materializeRValue(OldRVal);
 LValue UpdateLVal;
 

[PATCH] D60237: [MS] Add metadata for __declspec(allocator)

2019-04-03 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
akhuang added a reviewer: rnk.
Herald added subscribers: cfe-commits, jfb.
Herald added a project: clang.

Emit !heapallocsite in the metadata for calls to functions marked with
__declspec(allocator). Eventually this will be emitted as S_HEAPALLOCSITE debug
info in codeview.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D60237

Files:
  clang/lib/CodeGen/CGAtomic.cpp
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c

Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- /dev/null
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -0,0 +1,14 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited -gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
+
+char buf[1024];
+__declspec(allocator) void *myalloc(int s) {
+  void *p = &buf[0];
+  return p;
+}
+
+void call_alloc() {
+  char *p = (char*)myalloc(sizeof(char));
+}
+
+// CHECK: !heapallocsite [[DBG_F1:!.*]]
+// CHECK: [[DBG_F1:!.*]] = !{}
Index: clang/lib/CodeGen/CGDebugInfo.h
===
--- clang/lib/CodeGen/CGDebugInfo.h
+++ clang/lib/CodeGen/CGDebugInfo.h
@@ -476,6 +476,9 @@
   /// Emit standalone debug info for a type.
   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
 
+  /// Get debug info for MSAllocator metadata.
+  llvm::MDNode *getMSAllocatorMetadata(QualType Ty, SourceLocation Loc);
+
   void completeType(const EnumDecl *ED);
   void completeType(const RecordDecl *RD);
   void completeRequiredType(const RecordDecl *RD);
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1959,6 +1959,20 @@
   return T;
 }
 
+llvm::MDNode *CGDebugInfo::getMSAllocatorMetadata(QualType D,
+  SourceLocation Loc) {
+  // FIXME: return the type that return value is cast to
+  llvm::MDNode *node;
+  if (D.getTypePtr()->isVoidPointerType()) {
+node = llvm::MDNode::get(CGM.getLLVMContext(), None);
+  } else {
+QualType PointeeTy = D.getTypePtr()->getPointeeType();
+node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
+  }
+  return node;
+}
+
+
 void CGDebugInfo::completeType(const EnumDecl *ED) {
   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
 return;
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -3800,6 +3800,8 @@
 
   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
 
+  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
+
 #ifndef NDEBUG
   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
 // For an inalloca varargs function, we don't expect CallInfo to match the
@@ -4288,11 +4290,7 @@
   // Apply always_inline to all calls within flatten functions.
   // FIXME: should this really take priority over __try, below?
   if (CurCodeDecl && CurCodeDecl->hasAttr() &&
-  !(Callee.getAbstractInfo().getCalleeDecl().getDecl() &&
-Callee.getAbstractInfo()
-.getCalleeDecl()
-.getDecl()
-->hasAttr())) {
+  !(TargetDecl && TargetDecl->hasAttr())) {
 Attrs =
 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
llvm::Attribute::AlwaysInline);
@@ -4376,11 +4374,17 @@
 
   // Suppress tail calls if requested.
   if (llvm::CallInst *Call = dyn_cast(CI)) {
-const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
 if (TargetDecl && TargetDecl->hasAttr())
   Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
   }
 
+  // Add metadata for calls to MSAllocator functions
+  if (!DisableDebugInfo) {
+if (TargetDecl && TargetDecl->hasAttr())
+  CI->setMetadata("heapallocsite", getDebugInfo()->
+   getMSAllocatorMetadata(RetTy, Loc));
+  }
+
   // 4. Finish the call.
 
   // If the call doesn't return, finish the basic block and clear the
@@ -4537,7 +4541,6 @@
   } ();
 
   // Emit the assume_aligned check on the return value.
-  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
   if (Ret.isScalar() && TargetDecl) {
 if (const auto *AA = TargetDecl->getAttr()) {
   llvm::Value *OffsetValue = nullptr;
Index: clang/lib/CodeGen/CGAtomic.cpp
===
--- clang/lib/CodeGen/CGAtomic.cpp
+++ clang/lib/CodeGen/CGAtomic.cpp
@@ -1688,7 +1688,7 @@
 UpRVal = OldRVal;
 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
   } else {
-// Build new lvalue for temp address
+

[PATCH] D60237: [MS] Add metadata for __declspec(allocator)

2019-04-04 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CGAtomic.cpp:1691
   } else {
-// Build new lvalue for temp address
+// Build new lvalue for temp address.
 Address Ptr = Atomics.materializeRValue(OldRVal);

rnk wrote:
> I don't have an issue with these changes if you want to make them, but they 
> should be committed separately.
Whoops, these were supposed to be a separate test commit but I guess they ended 
up in here too. 



Comment at: clang/lib/CodeGen/CGCall.cpp:4384-4385
+if (TargetDecl && TargetDecl->hasAttr())
+  CI->setMetadata("heapallocsite", getDebugInfo()->
+   getMSAllocatorMetadata(RetTy, Loc));
+  }

rnk wrote:
> I think we should make CGDebugInfo responsible for calling setMetadata. In 
> some sense, "heapallocsite" metadata is debug info, so it makes sense that it 
> would be documented there. Also, if there are other places where we need to 
> add this metadata, we won't have to duplicate this string literal.
> 
> So, CGDebugInfo should have some new method 
> `addHeapAllocSiteMetadata(Instruction *CallSite, QualType Ty)`, and that can 
> call the private getOrCreateType method. Sound good?
Makes sense.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60237/new/

https://reviews.llvm.org/D60237



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60237: [MS] Add metadata for __declspec(allocator)

2019-04-04 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 193751.
akhuang marked 2 inline comments as done.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60237/new/

https://reviews.llvm.org/D60237

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c

Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- /dev/null
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -0,0 +1,15 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited -gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
+
+char buf[1024];
+__declspec(allocator) void *myalloc(int s) {
+  void *p = &buf[0];
+  return p;
+}
+
+void call_alloc() {
+  char *p = (char*)myalloc(sizeof(char));
+}
+
+// CHECK-LABEL: define {{.*}}void @call_alloc
+// CHECK: call i8* @myalloc(i32 1){{.*}} !heapallocsite [[DBG_F1:!.*]]
+// CHECK: [[DBG_F1:!.*]] = !{}
Index: clang/lib/CodeGen/CGDebugInfo.h
===
--- clang/lib/CodeGen/CGDebugInfo.h
+++ clang/lib/CodeGen/CGDebugInfo.h
@@ -476,6 +476,10 @@
   /// Emit standalone debug info for a type.
   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
 
+  /// Add heapallocsite metadata for MSAllocator calls.
+  void addHeapAllocSiteMetadata(llvm::Instruction *CallSite, QualType Ty,
+SourceLocation Loc);
+
   void completeType(const EnumDecl *ED);
   void completeType(const RecordDecl *RD);
   void completeRequiredType(const RecordDecl *RD);
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1959,6 +1959,22 @@
   return T;
 }
 
+void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
+   QualType D,
+   SourceLocation Loc) {
+  // FIXME: use the type that return value is cast to
+  llvm::MDNode *node;
+  if (D.getTypePtr()->isVoidPointerType()) {
+node = llvm::MDNode::get(CGM.getLLVMContext(), None);
+  } else {
+QualType PointeeTy = D.getTypePtr()->getPointeeType();
+node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
+  }
+
+  CI->setMetadata("heapallocsite", node);
+}
+
+
 void CGDebugInfo::completeType(const EnumDecl *ED) {
   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
 return;
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -3800,6 +3800,8 @@
 
   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
 
+  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
+
 #ifndef NDEBUG
   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
 // For an inalloca varargs function, we don't expect CallInfo to match the
@@ -4288,11 +4290,7 @@
   // Apply always_inline to all calls within flatten functions.
   // FIXME: should this really take priority over __try, below?
   if (CurCodeDecl && CurCodeDecl->hasAttr() &&
-  !(Callee.getAbstractInfo().getCalleeDecl().getDecl() &&
-Callee.getAbstractInfo()
-.getCalleeDecl()
-.getDecl()
-->hasAttr())) {
+  !(TargetDecl && TargetDecl->hasAttr())) {
 Attrs =
 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
llvm::Attribute::AlwaysInline);
@@ -4376,11 +4374,16 @@
 
   // Suppress tail calls if requested.
   if (llvm::CallInst *Call = dyn_cast(CI)) {
-const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
 if (TargetDecl && TargetDecl->hasAttr())
   Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
   }
 
+  // Add metadata for calls to MSAllocator functions
+  if (!DisableDebugInfo) {
+if (TargetDecl && TargetDecl->hasAttr())
+  getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);
+  }
+
   // 4. Finish the call.
 
   // If the call doesn't return, finish the basic block and clear the
@@ -4537,7 +4540,6 @@
   } ();
 
   // Emit the assume_aligned check on the return value.
-  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
   if (Ret.isScalar() && TargetDecl) {
 if (const auto *AA = TargetDecl->getAttr()) {
   llvm::Value *OffsetValue = nullptr;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60236: add periods

2019-04-04 Thread Amy Huang via Phabricator via cfe-commits
akhuang abandoned this revision.
akhuang added a comment.

test commit with incorrect diff


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60236/new/

https://reviews.llvm.org/D60236



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60237: [MS] Add metadata for __declspec(allocator)

2019-04-04 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 193792.
akhuang marked 3 inline comments as done.
akhuang added a comment.

-added struct case to test
-style fixes


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60237/new/

https://reviews.llvm.org/D60237

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c

Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- /dev/null
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited -gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
+
+char buf[1024];
+__declspec(allocator) void *myalloc(int s) {
+  return &buf[0];
+}
+
+void call_alloc() {
+  char *p = (char*)myalloc(sizeof(char));
+}
+
+struct Foo {
+  int x;
+};
+
+struct Foo foo_buf[1024];
+__declspec(allocator) struct Foo *alloc_foo() {
+  return &foo_buf[0];
+}
+
+void call_alloc_foo() {
+  struct Foo *p = alloc_foo();
+}
+
+// CHECK-LABEL: define {{.*}}void @call_alloc
+// CHECK: call i8* @myalloc(i32 1){{.*}} !heapallocsite [[DBG1:!.*]]
+
+// CHECK-LABEL: define {{.*}}%struct.Foo* @alloc_foo
+// CHECK: call %struct.Foo* @alloc_foo(){{.*}} !heapallocsite [[DBG2:!.*]]
+
+// CHECK: [[DBG1]] = !{}
+// CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME: name: "Foo"
+
Index: clang/lib/CodeGen/CGDebugInfo.h
===
--- clang/lib/CodeGen/CGDebugInfo.h
+++ clang/lib/CodeGen/CGDebugInfo.h
@@ -476,6 +476,10 @@
   /// Emit standalone debug info for a type.
   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
 
+  /// Add heapallocsite metadata for MSAllocator calls.
+  void addHeapAllocSiteMetadata(llvm::Instruction *CallSite, QualType Ty,
+SourceLocation Loc);
+
   void completeType(const EnumDecl *ED);
   void completeType(const RecordDecl *RD);
   void completeRequiredType(const RecordDecl *RD);
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1959,6 +1959,21 @@
   return T;
 }
 
+void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
+   QualType D,
+   SourceLocation Loc) {
+  llvm::MDNode *node;
+  if (D.getTypePtr()->isVoidPointerType()) {
+node = llvm::MDNode::get(CGM.getLLVMContext(), None);
+  } else {
+QualType PointeeTy = D.getTypePtr()->getPointeeType();
+node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
+  }
+
+  CI->setMetadata("heapallocsite", node);
+}
+
+
 void CGDebugInfo::completeType(const EnumDecl *ED) {
   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
 return;
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -3800,6 +3800,8 @@
 
   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
 
+  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
+
 #ifndef NDEBUG
   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
 // For an inalloca varargs function, we don't expect CallInfo to match the
@@ -4288,11 +4290,7 @@
   // Apply always_inline to all calls within flatten functions.
   // FIXME: should this really take priority over __try, below?
   if (CurCodeDecl && CurCodeDecl->hasAttr() &&
-  !(Callee.getAbstractInfo().getCalleeDecl().getDecl() &&
-Callee.getAbstractInfo()
-.getCalleeDecl()
-.getDecl()
-->hasAttr())) {
+  !(TargetDecl && TargetDecl->hasAttr())) {
 Attrs =
 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
llvm::Attribute::AlwaysInline);
@@ -4376,11 +4374,16 @@
 
   // Suppress tail calls if requested.
   if (llvm::CallInst *Call = dyn_cast(CI)) {
-const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
 if (TargetDecl && TargetDecl->hasAttr())
   Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
   }
 
+  // Add metadata for calls to MSAllocator functions
+  // FIXME: Get the type that the return value is cast to.
+  if (!DisableDebugInfo && TargetDecl &&
+  TargetDecl->hasAttr())
+getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);
+
   // 4. Finish the call.
 
   // If the call doesn't return, finish the basic block and clear the
@@ -4537,7 +4540,6 @@
   } ();
 
   // Emit the assume_aligned check on the return value.
-  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
   if (Ret.isScalar() && TargetDe

[PATCH] D60237: [MS] Add metadata for __declspec(allocator)

2019-04-08 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 194164.
akhuang marked 2 inline comments as done.
akhuang added a comment.

Fixes to test case


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60237/new/

https://reviews.llvm.org/D60237

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c

Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- /dev/null
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited -gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
+
+struct Foo {
+  int x;
+};
+
+__declspec(allocator) void *alloc_void();
+__declspec(allocator) struct Foo *alloc_foo();
+
+void call_alloc_void() {
+  struct Foo *p = (struct Foo*)alloc_void();
+}
+
+void call_alloc_foo() {
+  struct Foo *p = alloc_foo();
+}
+
+// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
+
+// CHECK-LABEL: define {{.*}}void @call_alloc_foo
+// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+
+// CHECK: [[DBG1]] = !{}
+// CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME: name: "Foo"
+
Index: clang/lib/CodeGen/CGDebugInfo.h
===
--- clang/lib/CodeGen/CGDebugInfo.h
+++ clang/lib/CodeGen/CGDebugInfo.h
@@ -476,6 +476,10 @@
   /// Emit standalone debug info for a type.
   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Loc);
 
+  /// Add heapallocsite metadata for MSAllocator calls.
+  void addHeapAllocSiteMetadata(llvm::Instruction *CallSite, QualType Ty,
+SourceLocation Loc);
+
   void completeType(const EnumDecl *ED);
   void completeType(const RecordDecl *RD);
   void completeRequiredType(const RecordDecl *RD);
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -1959,6 +1959,21 @@
   return T;
 }
 
+void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
+   QualType D,
+   SourceLocation Loc) {
+  llvm::MDNode *node;
+  if (D.getTypePtr()->isVoidPointerType()) {
+node = llvm::MDNode::get(CGM.getLLVMContext(), None);
+  } else {
+QualType PointeeTy = D.getTypePtr()->getPointeeType();
+node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
+  }
+
+  CI->setMetadata("heapallocsite", node);
+}
+
+
 void CGDebugInfo::completeType(const EnumDecl *ED) {
   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
 return;
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -3800,6 +3800,8 @@
 
   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
 
+  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
+
 #ifndef NDEBUG
   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
 // For an inalloca varargs function, we don't expect CallInfo to match the
@@ -4288,11 +4290,7 @@
   // Apply always_inline to all calls within flatten functions.
   // FIXME: should this really take priority over __try, below?
   if (CurCodeDecl && CurCodeDecl->hasAttr() &&
-  !(Callee.getAbstractInfo().getCalleeDecl().getDecl() &&
-Callee.getAbstractInfo()
-.getCalleeDecl()
-.getDecl()
-->hasAttr())) {
+  !(TargetDecl && TargetDecl->hasAttr())) {
 Attrs =
 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
llvm::Attribute::AlwaysInline);
@@ -4376,11 +4374,16 @@
 
   // Suppress tail calls if requested.
   if (llvm::CallInst *Call = dyn_cast(CI)) {
-const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
 if (TargetDecl && TargetDecl->hasAttr())
   Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
   }
 
+  // Add metadata for calls to MSAllocator functions
+  // FIXME: Get the type that the return value is cast to.
+  if (!DisableDebugInfo && TargetDecl &&
+  TargetDecl->hasAttr())
+getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);
+
   // 4. Finish the call.
 
   // If the call doesn't return, finish the basic block and clear the
@@ -4537,7 +4540,6 @@
   } ();
 
   // Emit the assume_aligned check on the return value.
-  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
   if (Ret.isScalar() && TargetDecl) {
 if (const auto *AA = TargetDecl->getAttr()) {
   llvm::Value *OffsetValue = nullptr;
___

[PATCH] D60237: [MS] Add metadata for __declspec(allocator)

2019-04-08 Thread Amy Huang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL357928: [MS] Add metadata for __declspec(allocator) 
(authored by akhuang, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D60237?vs=194164&id=194174#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60237/new/

https://reviews.llvm.org/D60237

Files:
  cfe/trunk/lib/CodeGen/CGCall.cpp
  cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
  cfe/trunk/lib/CodeGen/CGDebugInfo.h
  cfe/trunk/test/CodeGen/debug-info-codeview-heapallocsite.c

Index: cfe/trunk/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- cfe/trunk/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ cfe/trunk/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited -gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
+
+struct Foo {
+  int x;
+};
+
+__declspec(allocator) void *alloc_void();
+__declspec(allocator) struct Foo *alloc_foo();
+
+void call_alloc_void() {
+  struct Foo *p = (struct Foo*)alloc_void();
+}
+
+void call_alloc_foo() {
+  struct Foo *p = alloc_foo();
+}
+
+// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
+
+// CHECK-LABEL: define {{.*}}void @call_alloc_foo
+// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+
+// CHECK: [[DBG1]] = !{}
+// CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME: name: "Foo"
+
Index: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
===
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
@@ -1959,6 +1959,20 @@
   return T;
 }
 
+void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
+   QualType D,
+   SourceLocation Loc) {
+  llvm::MDNode *node;
+  if (D.getTypePtr()->isVoidPointerType()) {
+node = llvm::MDNode::get(CGM.getLLVMContext(), None);
+  } else {
+QualType PointeeTy = D.getTypePtr()->getPointeeType();
+node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
+  }
+
+  CI->setMetadata("heapallocsite", node);
+}
+
 void CGDebugInfo::completeType(const EnumDecl *ED) {
   if (DebugKind <= codegenoptions::DebugLineTablesOnly)
 return;
Index: cfe/trunk/lib/CodeGen/CGCall.cpp
===
--- cfe/trunk/lib/CodeGen/CGCall.cpp
+++ cfe/trunk/lib/CodeGen/CGCall.cpp
@@ -3800,6 +3800,8 @@
 
   llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
 
+  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
+
 #ifndef NDEBUG
   if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
 // For an inalloca varargs function, we don't expect CallInfo to match the
@@ -4288,11 +4290,7 @@
   // Apply always_inline to all calls within flatten functions.
   // FIXME: should this really take priority over __try, below?
   if (CurCodeDecl && CurCodeDecl->hasAttr() &&
-  !(Callee.getAbstractInfo().getCalleeDecl().getDecl() &&
-Callee.getAbstractInfo()
-.getCalleeDecl()
-.getDecl()
-->hasAttr())) {
+  !(TargetDecl && TargetDecl->hasAttr())) {
 Attrs =
 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex,
llvm::Attribute::AlwaysInline);
@@ -4376,11 +4374,16 @@
 
   // Suppress tail calls if requested.
   if (llvm::CallInst *Call = dyn_cast(CI)) {
-const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
 if (TargetDecl && TargetDecl->hasAttr())
   Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
   }
 
+  // Add metadata for calls to MSAllocator functions
+  // FIXME: Get the type that the return value is cast to.
+  if (!DisableDebugInfo && TargetDecl &&
+  TargetDecl->hasAttr())
+getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);
+
   // 4. Finish the call.
 
   // If the call doesn't return, finish the basic block and clear the
@@ -4537,7 +4540,6 @@
   } ();
 
   // Emit the assume_aligned check on the return value.
-  const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
   if (Ret.isScalar() && TargetDecl) {
 if (const auto *AA = TargetDecl->getAttr()) {
   llvm::Value *OffsetValue = nullptr;
Index: cfe/trunk/lib/CodeGen/CGDebugInfo.h
===
--- cfe/trunk/lib/CodeGen/CGDebugInfo.h
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.h
@@ -476,6 +476,10 @@
   /// Emit standalone debug info for a type.
   llvm::DIType *getOrCreateStandaloneType(QualType Ty, SourceLocation Lo

[PATCH] D60572: creduce-clang-crash: Use `!` instead of `not`

2019-04-11 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

Looks good- if we remove `not` there are a few other things that should be 
removed




Comment at: clang/utils/creduce-clang-crash.py:138
 if "fatal error:" in msg_re:
   self.is_crash = False
 break

also wouldn't need `self.is_crash`



Comment at: clang/utils/creduce-clang-crash.py:178
 
 crash_flag = "--crash" if self.is_crash else ""
 

We should remove `crash_flag` as well


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60572/new/

https://reviews.llvm.org/D60572



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-16 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
akhuang added reviewers: hans, rnk.
Herald added subscribers: llvm-commits, cfe-commits, hiraditya, aprantl.
Herald added projects: clang, LLVM.

This emits labels around heapallocsite calls and S_HEAPALLOCSITE debug
info in codeview. Currently only changes FastISel, so emitting labels still
needs to be implemented in SelectionDAG.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D60800

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,73 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc();
+; void g();
+; void foo() {
+;   g();
+;   myalloc()
+;   g();
+; }
+
+; ModuleID = 'heapallocsite.c'
+source_filename = "heapallocsite.c"
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !7 {
+entry:
+  call void @g(), !dbg !11
+  %call = call i8* @myalloc(), !dbg !12, !heapallocsite !13
+  call void @g(), !dbg !14
+  ret void, !dbg !15
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: callq g
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32   .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short  .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 1539
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local void @g() #1
+
+declare dso_local i8* @myalloc() #1
+
+attributes #0 = { noinline nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+attributes #1 = { "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!7 = distinct !DISubprogram(name: "f", scope: !8, file: !8, line: 4, type: !9, scopeLine: 4, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!8 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 5, scope: !7)
+!12 = !DILocation(line: 6, scope: !7)
+!13 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!14 = !DILocation(line: 7, scope: !7)
+!15 = !DILocation(line: 8, scope: !7)
+
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,19 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruc

[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-16 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 195475.
akhuang added a comment.

remove comment


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,73 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc();
+; void g();
+; void foo() {
+;   g();
+;   myalloc()
+;   g();
+; }
+
+; ModuleID = 'heapallocsite.c'
+source_filename = "heapallocsite.c"
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !7 {
+entry:
+  call void @g(), !dbg !11
+  %call = call i8* @myalloc(), !dbg !12, !heapallocsite !13
+  call void @g(), !dbg !14
+  ret void, !dbg !15
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: callq g
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32   .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short  .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 1539
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local void @g() #1
+
+declare dso_local i8* @myalloc() #1
+
+attributes #0 = { noinline nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+attributes #1 = { "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!7 = distinct !DISubprogram(name: "f", scope: !8, file: !8, line: 4, type: !9, scopeLine: 4, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!8 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 5, scope: !7)
+!12 = !DILocation(line: 6, scope: !7)
+!13 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!14 = !DILocation(line: 7, scope: !7)
+!15 = !DILocation(line: 8, scope: !7)
+
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,11 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite"))
+MF->addCodeViewHeapAllocSite(CLI.Call, CLI.CS->g

[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-16 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 195478.
akhuang added a comment.

more typos


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,73 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc();
+; void g();
+; void foo() {
+;   g();
+;   myalloc()
+;   g();
+; }
+
+; ModuleID = 'heapallocsite.c'
+source_filename = "heapallocsite.c"
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !7 {
+entry:
+  call void @g(), !dbg !11
+  %call = call i8* @myalloc(), !dbg !12, !heapallocsite !13
+  call void @g(), !dbg !14
+  ret void, !dbg !15
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: callq g
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32   .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short  .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 1539
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local void @g() #1
+
+declare dso_local i8* @myalloc() #1
+
+attributes #0 = { noinline nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+attributes #1 = { "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!7 = distinct !DISubprogram(name: "f", scope: !8, file: !8, line: 4, type: !9, scopeLine: 4, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!8 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 5, scope: !7)
+!12 = !DILocation(line: 6, scope: !7)
+!13 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!14 = !DILocation(line: 7, scope: !7)
+!15 = !DILocation(line: 8, scope: !7)
+
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,11 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite"))
+MF->addCodeViewHeapAllocSite(CLI.Call, CLI.CS->getIn

[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-16 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 195480.
akhuang added a comment.

Fix test case


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,73 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc();
+; void g();
+; void foo() {
+;   g();
+;   myalloc()
+;   g();
+; }
+
+; ModuleID = 'heapallocsite.c'
+source_filename = "heapallocsite.c"
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !7 {
+entry:
+  call void @g(), !dbg !11
+  %call = call i8* @myalloc(), !dbg !12, !heapallocsite !13
+  call void @g(), !dbg !14
+  ret void, !dbg !15
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: callq g
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32   .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short  .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 112
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local void @g() #1
+
+declare dso_local i8* @myalloc() #1
+
+attributes #0 = { noinline nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+attributes #1 = { "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!7 = distinct !DISubprogram(name: "f", scope: !8, file: !8, line: 4, type: !9, scopeLine: 4, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!8 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 5, scope: !7)
+!12 = !DILocation(line: 6, scope: !7)
+!13 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!14 = !DILocation(line: 7, scope: !7)
+!15 = !DILocation(line: 8, scope: !7)
+
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,11 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite"))
+MF->addCodeViewHeapAllocSite(CLI.Call, CLI.CS->get

[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 195783.
akhuang marked 4 inline comments as done.
akhuang added a comment.

Removed extraneous information from test; changed type to DIType


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,68 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc();
+; void g();
+; void foo() {
+;   g();
+;   myalloc()
+;   g();
+; }
+
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !7 {
+entry:
+  call void @g(), !dbg !11
+  %call = call i8* @myalloc(), !dbg !12, !heapallocsite !13
+  call void @g(), !dbg !14
+  ret void, !dbg !15
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: callq g
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32   .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short  .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 112
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local void @g() #1
+
+declare dso_local i8* @myalloc() #1
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!7 = distinct !DISubprogram(name: "f", scope: !8, file: !8, line: 4, type: !9, scopeLine: 4, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!8 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 5, scope: !7)
+!12 = !DILocation(line: 6, scope: !7)
+!13 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!14 = !DILocation(line: 7, scope: !7)
+!15 = !DILocation(line: 8, scope: !7)
+
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,13 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite")) {
+DIType *DI = cast(CLI.CS->getInstruction()->
+  getMetadata("heapallocsite"));
+MF->addCodeViewHeapAllocSite(CLI.Call, DI);
+  }
+
   return true;
 }
 
Index: llvm/lib/CodeGen/MachineFunction.cpp
===
--- llvm/lib/CodeGen/MachineFunction.cpp
+++ llvm/lib/CodeGen/MachineFunction.cpp
@@ -806,6 +806,14 @@
   return FilterID;
 }
 
+void MachineFunction::addCodeViewHeapAllocSite(MachineInstr *I, DIType *DI) {
+  MCSymbol *BeginLabel = Ctx.createTempSymbol("heapallocsite", true);
+  MCSymbol *EndLabel = Ctx.createTempSymbol("heapallocsite", true);
+  I->setPreInstrSymbol(*this, BeginLabel);
+  I->setPostInstrSymbol(*this, EndLabel);
+  CodeViewHeapAllocSites.push_back({BeginLabel, EndLabel, DI});
+}
+
 /// \}
 
 //===--===//
Index: llvm/lib/Co

[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:1966
+  QualType PointeeTy = D.getTypePtr()->getPointeeType();
+  llvm::DIType *DI = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
+  CI->setMetadata("heapallocsite", DI);

hans wrote:
> I don't really know this code, but does this also work for void pointers, 
> i.e. the if statement in the old code was unnecessary?
I think `getOrCreateType` returns null if it gets a void type, so it doesn't 
quite work for void pointers. In theory we shouldn't be getting void pointers 
here since the type should be cast to something but that hasn't been 
implemented yet.



Comment at: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp:1078
+  MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
+  DIType *DITy = cast(std::get<2>(HeapAllocSite));
+

hans wrote:
> Is the cast necessary? Couldn't the tuple member be made a DIType* in the 
> first place?
Changed the tuple member to be a DIType.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 195818.
akhuang marked 2 inline comments as done.
akhuang added a comment.

- Pass void metadata as null DIType


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,68 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc();
+; void g();
+; void foo() {
+;   g();
+;   myalloc()
+;   g();
+; }
+
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !7 {
+entry:
+  call void @g(), !dbg !11
+  %call = call i8* @myalloc(), !dbg !12, !heapallocsite !13
+  call void @g(), !dbg !14
+  ret void, !dbg !15
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: callq g
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32   .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short  .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 112
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local void @g() #1
+
+declare dso_local i8* @myalloc() #1
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!7 = distinct !DISubprogram(name: "f", scope: !8, file: !8, line: 4, type: !9, scopeLine: 4, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!8 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 5, scope: !7)
+!12 = !DILocation(line: 6, scope: !7)
+!13 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!14 = !DILocation(line: 7, scope: !7)
+!15 = !DILocation(line: 8, scope: !7)
+
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,12 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite")) {
+MDNode *MD = CLI.CS->getInstruction()->getMetadata("heapallocsite");
+MF->addCodeViewHeapAllocSite(CLI.Call, MD);
+  }
+
   return true;
 }
 
Index: llvm/lib/CodeGen/MachineFunction.cpp
===
--- llvm/lib/CodeGen/MachineFunction.cpp
+++ llvm/lib/CodeGen/MachineFunction.cpp
@@ -43,6 +43,7 @@
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constant.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalValue.h"
@@ -806,6 +807,16 @@
   return FilterID;
 }
 
+void MachineFunction::addCodeViewHeapAllocSite(MachineInstr *I, MDNode *MD) {
+  MCSymbol *BeginLabel = Ctx.createTempSymbol("heapallocsite", true);
+  MCSymbol *EndLabel = Ctx.createTempSymbol("heapallocsite", true);
+  I->setPreInstrSymbol(*this, BeginLabel);
+  I->setPostInstrSymbol(*this, End

[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 195821.
akhuang marked 2 inline comments as done.
akhuang added a comment.

- Changed test case back to original


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,68 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc();
+; void g();
+; void foo() {
+;   g();
+;   myalloc()
+;   g();
+; }
+
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !7 {
+entry:
+  call void @g(), !dbg !11
+  %call = call i8* @myalloc(), !dbg !12, !heapallocsite !13
+  call void @g(), !dbg !14
+  ret void, !dbg !15
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: callq g
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32   .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short  .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 112
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local void @g() #1
+
+declare dso_local i8* @myalloc() #1
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!7 = distinct !DISubprogram(name: "f", scope: !8, file: !8, line: 4, type: !9, scopeLine: 4, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!8 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 5, scope: !7)
+!12 = !DILocation(line: 6, scope: !7)
+!13 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!14 = !DILocation(line: 7, scope: !7)
+!15 = !DILocation(line: 8, scope: !7)
+
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,12 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite")) {
+MDNode *MD = CLI.CS->getInstruction()->getMetadata("heapallocsite");
+MF->addCodeViewHeapAllocSite(CLI.Call, MD);
+  }
+
   return true;
 }
 
Index: llvm/lib/CodeGen/MachineFunction.cpp
===
--- llvm/lib/CodeGen/MachineFunction.cpp
+++ llvm/lib/CodeGen/MachineFunction.cpp
@@ -43,6 +43,7 @@
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constant.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalValue.h"
@@ -806,6 +807,16 @@
   return FilterID;
 }
 
+void MachineFunction::addCodeViewHeapAllocSite(MachineInstr *I, MDNode *MD) {
+  MCSymbol *BeginLabel = Ctx.createTempSymbol("heapallocsite", true);
+  MCSymbol *EndLabel = Ctx.createTempSymbol("heapallocsite", true);
+  I->setPreInstrSymbol(*this, BeginLabel);
+  I->setPostInstrSymbol(*this, EndLabel);
+
+  DIType *DI = dyn_cast(MD);
+  CodeViewHeapA

[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added inline comments.



Comment at: llvm/test/CodeGen/X86/label-heapallocsite.ll:1
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.

hans wrote:
> Does llc have a "-fast-isel" flag or similar that could be used instead, to 
> make it more clear that it's fast-isel that's significant for the test?
I couldn't find a flag that makes llc use fast-isel; it should soon work for 
both cases though.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-19 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 195877.
akhuang added a comment.

whitespace fix


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,68 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc();
+; void g();
+; void foo() {
+;   g();
+;   myalloc()
+;   g();
+; }
+
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !7 {
+entry:
+  call void @g(), !dbg !11
+  %call = call i8* @myalloc(), !dbg !12, !heapallocsite !13
+  call void @g(), !dbg !14
+  ret void, !dbg !15
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: callq g
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32   .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short  .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 112
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local void @g() #1
+
+declare dso_local i8* @myalloc() #1
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5}
+!llvm.ident = !{!6}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!7 = distinct !DISubprogram(name: "f", scope: !8, file: !8, line: 4, type: !9, scopeLine: 4, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!8 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 5, scope: !7)
+!12 = !DILocation(line: 6, scope: !7)
+!13 = !DIBasicType(name: "char", size: 8, encoding: DW_ATE_signed_char)
+!14 = !DILocation(line: 7, scope: !7)
+!15 = !DILocation(line: 8, scope: !7)
+
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,12 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite")) {
+MDNode *MD = CLI.CS->getInstruction()->getMetadata("heapallocsite");
+MF->addCodeViewHeapAllocSite(CLI.Call, MD);
+  }
+
   return true;
 }
 
Index: llvm/lib/CodeGen/MachineFunction.cpp
===
--- llvm/lib/CodeGen/MachineFunction.cpp
+++ llvm/lib/CodeGen/MachineFunction.cpp
@@ -43,6 +43,7 @@
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constant.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalValue.h"
@@ -806,6 +807,16 @@
   return FilterID;
 }
 
+void MachineFunction::addCodeViewHeapAllocSite(MachineInstr *I, MDNode *MD) {
+  MCSymbol *BeginLabel = Ctx.createTempSymbol("heapallocsite", true);
+  MCSymbol *EndLabel = Ctx.createTempSymbol("heapallocsite", true);
+  I->setPreInstrSymbol(*this, BeginLabel);
+  I->setPostInstrSymbol(*this, EndLabel);
+
+  DIType *DI = dyn_cast(MD);
+  CodeViewHeapAllocSites.push_back({BeginLabel, EndLabel, DI});
+}
+
 /// \}
 

[PATCH] D60800: [MS] Emit S_HEAPALLOCSITE debug info

2019-04-19 Thread Amy Huang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL358783: [MS] Emit S_HEAPALLOCSITE debug info (authored by 
akhuang, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D60800?vs=195877&id=195909#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D60800/new/

https://reviews.llvm.org/D60800

Files:
  cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
  llvm/trunk/include/llvm/CodeGen/MachineFunction.h
  llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/trunk/lib/CodeGen/MachineFunction.cpp
  llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/trunk/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/trunk/lib/CodeGen/MachineFunction.cpp
===
--- llvm/trunk/lib/CodeGen/MachineFunction.cpp
+++ llvm/trunk/lib/CodeGen/MachineFunction.cpp
@@ -43,6 +43,7 @@
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constant.h"
 #include "llvm/IR/DataLayout.h"
+#include "llvm/IR/DebugInfoMetadata.h"
 #include "llvm/IR/DerivedTypes.h"
 #include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalValue.h"
@@ -806,6 +807,16 @@
   return FilterID;
 }
 
+void MachineFunction::addCodeViewHeapAllocSite(MachineInstr *I, MDNode *MD) {
+  MCSymbol *BeginLabel = Ctx.createTempSymbol("heapallocsite", true);
+  MCSymbol *EndLabel = Ctx.createTempSymbol("heapallocsite", true);
+  I->setPreInstrSymbol(*this, BeginLabel);
+  I->setPostInstrSymbol(*this, EndLabel);
+
+  DIType *DI = dyn_cast(MD);
+  CodeViewHeapAllocSites.push_back({BeginLabel, EndLabel, DI});
+}
+
 /// \}
 
 //===--===//
Index: llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,12 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite")) {
+MDNode *MD = CLI.CS->getInstruction()->getMetadata("heapallocsite");
+MF->addCodeViewHeapAllocSite(CLI.Call, MD);
+  }
+
   return true;
 }
 
Index: llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.h
===
--- llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.h
+++ llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.h
@@ -147,6 +147,7 @@
 SmallVector ChildBlocks;
 
 std::vector> Annotations;
+std::vector> HeapAllocSites;
 
 const MCSymbol *Begin = nullptr;
 const MCSymbol *End = nullptr;
Index: llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1072,6 +1072,23 @@
   endSymbolRecord(AnnotEnd);
 }
 
+for (auto HeapAllocSite : FI.HeapAllocSites) {
+  MCSymbol *BeginLabel = std::get<0>(HeapAllocSite);
+  MCSymbol *EndLabel = std::get<1>(HeapAllocSite);
+  DIType *DITy = std::get<2>(HeapAllocSite);
+
+  MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE);
+  OS.AddComment("Call site offset");
+  OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0);
+  OS.AddComment("Call site section index");
+  OS.EmitCOFFSectionIndex(BeginLabel);
+  OS.AddComment("Call instruction length");
+  OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
+  OS.AddComment("Type index");
+  OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
+  endSymbolRecord(HeapAllocEnd);
+}
+
 if (SP != nullptr)
   emitDebugInfoForUDTs(LocalUDTs);
 
@@ -2807,6 +2824,7 @@
   }
 
   CurFn->Annotations = MF->getCodeViewAnnotations();
+  CurFn->HeapAllocSites = MF->getCodeViewHeapAllocSites();
 
   CurFn->End = Asm->getFunctionEnd();
 
Index: llvm/trunk/include/llvm/CodeGen/MachineFunction.h
===
--- llvm/trunk/include/llvm/CodeGen/MachineFunction.h
+++ llvm/trunk/include/llvm/CodeGen/MachineFunction.h
@@ -321,6 +321,10 @@
   /// CodeView label annotations.
   std::vector> CodeViewAnnotations;
 
+  /// CodeView heapallocsites.
+  std::vector>
+  CodeViewHeapAllocSites;
+
   bool CallsEHReturn = false;
   bool CallsUnwindInit = false;
   bool HasEHScopes = false;
@@ -906,6 +910,14 @@
 return CodeViewAnnotations;
   }
 
+  /// Record heapallocsites
+  void addCodeViewHeapAllocSite(MachineInstr *I, MDNode *MD);
+
+  ArrayRef>
+  getCodeViewHeapAllocSites() const {
+return CodeViewHeapAllocSites;
+  }
+
   /// Return a reference to the C++ typeinfo for the current function.
   const std::vector &getTypeInfos() const {
 ret

[PATCH] D61083: Recommitting r358783 and r358786 "[MS] Emit S_HEAPALLOCSITE debug info" with fixes for buildbot error (undefined assembler label).

2019-04-24 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
akhuang added a reviewer: rnk.
Herald added subscribers: llvm-commits, cfe-commits, hiraditya, aprantl.
Herald added projects: clang, LLVM.

This emits labels around heapallocsite calls and S_HEAPALLOCSITE debug
info in codeview. Currently only changes FastISel, so emitting labels still
needs to be implemented in SelectionDAG.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D61083

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/include/llvm/CodeGen/MachineInstr.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/MachineInstr.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/lib/Target/X86/X86FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,57 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc(void);
+; void foo() {
+;   myalloc()
+; }
+
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !8 {
+entry:
+  %call = call i8* @myalloc(), !dbg !11, !heapallocsite !2
+  ret void, !dbg !12
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32 .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 3
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local i8* @myalloc() #1
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5, !6}
+!llvm.ident = !{!7}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{i32 7, !"PIC Level", i32 2}
+!7 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 3, type: !9, scopeLine: 3, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 4, scope: !8)
+!12 = !DILocation(line: 5, scope: !8)
+
Index: llvm/lib/Target/X86/X86FastISel.cpp
===
--- llvm/lib/Target/X86/X86FastISel.cpp
+++ llvm/lib/Target/X86/X86FastISel.cpp
@@ -3985,6 +3985,7 @@
   }
 
   Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
+  Result->cloneInstrSymbols(*FuncInfo.MF, *MI);
   MachineBasicBlock::iterator I(MI);
   removeDeadCode(I, std::next(I));
   return true;
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,12 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite")) {
+MDNode *MD = CLI.CS->getInstruction()->getMetadata("heapallocsite");
+MF->addCodeViewHeapAllocSite(CLI.Call, MD);
+  }
+
   return true;
 }
 
Index: llvm/lib/CodeGen/MachineInstr.cpp
===
--- llvm/lib/CodeGen/MachineInstr.cpp
+++ llvm/lib/CodeGen/MachineInstr.cpp
@@ -513,6 +513,19 @@
   MF.createMIExtraInfo(memoperands(), getPreInstrSymbol(), Symbol));
 }
 
+void MachineInstr::cloneInstrSymbols(MachineFunction &MF,
+ const MachineInstr &MI) {
+  if (this == &MI)
+// Nothing to do for a self-clone!
+return;
+
+  assert(&MF == MI.getMF() &&
+ "Invalid machine functions when cloning inst

[PATCH] D61083: Recommitting r358783 and r358786 "[MS] Emit S_HEAPALLOCSITE debug info" with fixes for buildbot error (undefined assembler label).

2019-04-24 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 196496.
akhuang added a comment.

- remove added whitespace


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61083/new/

https://reviews.llvm.org/D61083

Files:
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/include/llvm/CodeGen/MachineInstr.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/MachineInstr.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/lib/Target/X86/X86FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,57 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc(void);
+; void foo() {
+;   myalloc()
+; }
+
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+; Function Attrs: noinline nounwind optnone
+define dso_local void @f() #0 !dbg !8 {
+entry:
+  %call = call i8* @myalloc(), !dbg !11, !heapallocsite !2
+  ret void, !dbg !12
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32 .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 3
+; CHECK-NEXT:  .p2align 2
+
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+declare dso_local i8* @myalloc() #1
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5, !6}
+!llvm.ident = !{!7}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "heapallocsite.c", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{i32 7, !"PIC Level", i32 2}
+!7 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 3, type: !9, scopeLine: 3, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 4, scope: !8)
+!12 = !DILocation(line: 5, scope: !8)
+
Index: llvm/lib/Target/X86/X86FastISel.cpp
===
--- llvm/lib/Target/X86/X86FastISel.cpp
+++ llvm/lib/Target/X86/X86FastISel.cpp
@@ -3985,6 +3985,7 @@
   }
 
   Result->addMemOperand(*FuncInfo.MF, createMachineMemOperandFor(LI));
+  Result->cloneInstrSymbols(*FuncInfo.MF, *MI);
   MachineBasicBlock::iterator I(MI);
   removeDeadCode(I, std::next(I));
   return true;
Index: llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
===
--- llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
+++ llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
@@ -1234,6 +1234,12 @@
   if (CLI.NumResultRegs && CLI.CS)
 updateValueMap(CLI.CS->getInstruction(), CLI.ResultReg, CLI.NumResultRegs);
 
+  // Set labels for heapallocsite call.
+  if (CLI.CS && CLI.CS->getInstruction()->getMetadata("heapallocsite")) {
+MDNode *MD = CLI.CS->getInstruction()->getMetadata("heapallocsite");
+MF->addCodeViewHeapAllocSite(CLI.Call, MD);
+  }
+
   return true;
 }
 
Index: llvm/lib/CodeGen/MachineInstr.cpp
===
--- llvm/lib/CodeGen/MachineInstr.cpp
+++ llvm/lib/CodeGen/MachineInstr.cpp
@@ -513,6 +513,19 @@
   MF.createMIExtraInfo(memoperands(), getPreInstrSymbol(), Symbol));
 }
 
+void MachineInstr::cloneInstrSymbols(MachineFunction &MF,
+ const MachineInstr &MI) {
+  if (this == &MI)
+// Nothing to do for a self-clone!
+return;
+
+  assert(&MF == MI.getMF() &&
+ "Invalid machine functions when cloning instruction symbols!");
+
+  setPreInstrSymbol(MF, MI.getPreInstrSymbol());
+  setPostInstrSymbol(MF, MI.getPostInstrSymbol());
+}
+
 uint16_t MachineInstr::mergeFlagsWith(const MachineInstr &Other) const {
   // For now, the just retur

[PATCH] D61083: Recommitting r358783 and r358786 "[MS] Emit S_HEAPALLOCSITE debug info" with fixes for buildbot error (undefined assembler label).

2019-04-24 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 196525.
akhuang added a comment.

- Add test case and comment for undefined labels


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61083/new/

https://reviews.llvm.org/D61083

Files:
  llvm/include/llvm/CodeGen/MachineFunction.h
  llvm/include/llvm/CodeGen/MachineInstr.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/lib/CodeGen/MachineFunction.cpp
  llvm/lib/CodeGen/MachineInstr.cpp
  llvm/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/lib/Target/X86/X86FastISel.cpp
  llvm/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/test/CodeGen/X86/label-heapallocsite.ll
===
--- /dev/null
+++ llvm/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,111 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc(void);
+; void f() {
+;   myalloc()
+; }
+;
+; struct Foo {
+;   __declspec(allocator) virtual void *alloc();
+; };
+; void use_alloc(void*);
+; void do_alloc(Foo *p) {
+;   use_alloc(p->alloc());
+; }
+
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+%struct.Foo = type { i32 (...)** }
+
+; Function Attrs: noinline optnone uwtable
+define dso_local void @f() #0 !dbg !8 {
+entry:
+  %call = call i8* @myalloc(), !dbg !11, !heapallocsite !2
+  ret void, !dbg !12
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+declare dso_local i8* @myalloc() #1
+
+; Function Attrs: noinline optnone uwtable
+define dso_local void @do_alloc(%struct.Foo* %p) #0 !dbg !13 {
+entry:
+  %p.addr = alloca %struct.Foo*, align 8
+  store %struct.Foo* %p, %struct.Foo** %p.addr, align 8
+  call void @llvm.dbg.declare(metadata %struct.Foo** %p.addr, metadata !18, metadata !DIExpression()), !dbg !19
+  %0 = load %struct.Foo*, %struct.Foo** %p.addr, align 8, !dbg !20
+  %1 = bitcast %struct.Foo* %0 to i8* (%struct.Foo*)***, !dbg !20
+  %vtable = load i8* (%struct.Foo*)**, i8* (%struct.Foo*)*** %1, align 8, !dbg !20
+  %vfn = getelementptr inbounds i8* (%struct.Foo*)*, i8* (%struct.Foo*)** %vtable, i64 0, !dbg !20
+  %2 = load i8* (%struct.Foo*)*, i8* (%struct.Foo*)** %vfn, align 8, !dbg !20
+  %call = call i8* %2(%struct.Foo* %0), !dbg !20, !heapallocsite !2
+  call void @use_alloc(i8* %call), !dbg !20
+  ret void, !dbg !21
+}
+
+; CHECK-LABEL: do_alloc: # @do_alloc
+; CHECK: .Lheapallocsite2:
+; CHECK: callq *(%rax)
+; CHECK: .Lheapallocsite3:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32 .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 3
+; CHECK-NEXT:  .p2align 2
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32 .Lheapallocsite2
+; CHECK-NEXT:  .secidx .Lheapallocsite2
+; CHECK-NEXT:  .short .Lheapallocsite3-.Lheapallocsite2
+; CHECK-NEXT:  .long 3
+; CHECK-NEXT:  .p2align 2
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+; Function Attrs: nounwind readnone speculatable
+declare void @llvm.dbg.declare(metadata, metadata, metadata) #2
+
+declare dso_local void @use_alloc(i8*) #1
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5, !6}
+!llvm.ident = !{!7}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "heapallocsite.cpp", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{i32 7, !"PIC Level", i32 2}
+!7 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 3, type: !9, scopeLine: 3, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
+!9 = !DISubroutineType(types: !10)
+!10 = !{null}
+!11 = !DILocation(line: 4, scope: !8)
+!12 = !DILocation(line: 5, scope: !8)
+!13 = distinct !DISubprogram(name: "do_allo

[PATCH] D61083: Recommitting r358783 and r358786 "[MS] Emit S_HEAPALLOCSITE debug info" with fixes for buildbot error (undefined assembler label).

2019-04-24 Thread Amy Huang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL359149: Recommitting r358783 and r358786 "[MS] Emit 
S_HEAPALLOCSITE debug info" with… (authored by akhuang, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D61083?vs=196525&id=196540#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61083/new/

https://reviews.llvm.org/D61083

Files:
  llvm/trunk/include/llvm/CodeGen/MachineFunction.h
  llvm/trunk/include/llvm/CodeGen/MachineInstr.h
  llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.h
  llvm/trunk/lib/CodeGen/MachineFunction.cpp
  llvm/trunk/lib/CodeGen/MachineInstr.cpp
  llvm/trunk/lib/CodeGen/SelectionDAG/FastISel.cpp
  llvm/trunk/lib/Target/X86/X86FastISel.cpp
  llvm/trunk/test/CodeGen/X86/label-heapallocsite.ll

Index: llvm/trunk/test/CodeGen/X86/label-heapallocsite.ll
===
--- llvm/trunk/test/CodeGen/X86/label-heapallocsite.ll
+++ llvm/trunk/test/CodeGen/X86/label-heapallocsite.ll
@@ -0,0 +1,111 @@
+; RUN: llc -O0 < %s | FileCheck %s
+; FIXME: Add test for llc with optimizations once it is implemented.
+
+; Source to regenerate:
+; $ clang --target=x86_64-windows-msvc -S heapallocsite.c  -g -gcodeview -o t.ll \
+;  -emit-llvm -O0 -Xclang -disable-llvm-passes -fms-extensions
+; __declspec(allocator) char *myalloc(void);
+; void f() {
+;   myalloc()
+; }
+;
+; struct Foo {
+;   __declspec(allocator) virtual void *alloc();
+; };
+; void use_alloc(void*);
+; void do_alloc(Foo *p) {
+;   use_alloc(p->alloc());
+; }
+
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-unknown-windows-msvc"
+
+%struct.Foo = type { i32 (...)** }
+
+; Function Attrs: noinline optnone uwtable
+define dso_local void @f() #0 !dbg !8 {
+entry:
+  %call = call i8* @myalloc(), !dbg !11, !heapallocsite !2
+  ret void, !dbg !12
+}
+
+; CHECK-LABEL: f: # @f
+; CHECK: .Lheapallocsite0:
+; CHECK: callq myalloc
+; CHECK: .Lheapallocsite1:
+; CHECK: retq
+
+declare dso_local i8* @myalloc() #1
+
+; Function Attrs: noinline optnone uwtable
+define dso_local void @do_alloc(%struct.Foo* %p) #0 !dbg !13 {
+entry:
+  %p.addr = alloca %struct.Foo*, align 8
+  store %struct.Foo* %p, %struct.Foo** %p.addr, align 8
+  call void @llvm.dbg.declare(metadata %struct.Foo** %p.addr, metadata !18, metadata !DIExpression()), !dbg !19
+  %0 = load %struct.Foo*, %struct.Foo** %p.addr, align 8, !dbg !20
+  %1 = bitcast %struct.Foo* %0 to i8* (%struct.Foo*)***, !dbg !20
+  %vtable = load i8* (%struct.Foo*)**, i8* (%struct.Foo*)*** %1, align 8, !dbg !20
+  %vfn = getelementptr inbounds i8* (%struct.Foo*)*, i8* (%struct.Foo*)** %vtable, i64 0, !dbg !20
+  %2 = load i8* (%struct.Foo*)*, i8* (%struct.Foo*)** %vfn, align 8, !dbg !20
+  %call = call i8* %2(%struct.Foo* %0), !dbg !20, !heapallocsite !2
+  call void @use_alloc(i8* %call), !dbg !20
+  ret void, !dbg !21
+}
+
+; CHECK-LABEL: do_alloc: # @do_alloc
+; CHECK: .Lheapallocsite2:
+; CHECK: callq *(%rax)
+; CHECK: .Lheapallocsite3:
+; CHECK: retq
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32 .Lheapallocsite0
+; CHECK-NEXT:  .secidx .Lheapallocsite0
+; CHECK-NEXT:  .short .Lheapallocsite1-.Lheapallocsite0
+; CHECK-NEXT:  .long 3
+; CHECK-NEXT:  .p2align 2
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+; CHECK-LABEL: .short  4423# Record kind: S_GPROC32_ID
+; CHECK:   .short  4446# Record kind: S_HEAPALLOCSITE
+; CHECK-NEXT:  .secrel32 .Lheapallocsite2
+; CHECK-NEXT:  .secidx .Lheapallocsite2
+; CHECK-NEXT:  .short .Lheapallocsite3-.Lheapallocsite2
+; CHECK-NEXT:  .long 3
+; CHECK-NEXT:  .p2align 2
+; CHECK-LABEL: .short  4431# Record kind: S_PROC_ID_END
+
+; Function Attrs: nounwind readnone speculatable
+declare void @llvm.dbg.declare(metadata, metadata, metadata) #2
+
+declare dso_local void @use_alloc(i8*) #1
+
+!llvm.dbg.cu = !{!0}
+!llvm.module.flags = !{!3, !4, !5, !6}
+!llvm.ident = !{!7}
+
+!0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, nameTableKind: None)
+!1 = !DIFile(filename: "heapallocsite.cpp", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "6d758cfa3834154a04ce8a55102772a9")
+!2 = !{}
+!3 = !{i32 2, !"CodeView", i32 1}
+!4 = !{i32 2, !"Debug Info Version", i32 3}
+!5 = !{i32 1, !"wchar_size", i32 2}
+!6 = !{i32 7, !"PIC Level", i32 2}
+!7 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4eff3de99423a62fd6e833e29c71c1e62ba6140b)"}
+!8 = distinct !DISubprogram(name: "f", scope: !1, fil

[PATCH] D59725: Additions to creduce script

2019-04-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added inline comments.



Comment at: cfe/trunk/utils/creduce-clang-crash.py:185
+for msg in self.expected_output:
+  output += 'grep %s t.log || exit 1\n' % pipes.quote(msg)
+

lebedev.ri wrote:
> >>! In D59725#1477362, @arichardson wrote:
> >>>! In D59725#1477042, @lebedev.ri wrote:
> >> I've stumbled into an issue with the script:
> >> It got a line: `clang: 
> >> /build/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp:2582: bool 
> >> {anonymous}::IndVarSimplify::run(llvm::Loop*): Assertion 
> >> `L->isRecursivelyLCSSAForm(*DT, *LI) && "LCSSA required to run indvars!"' 
> >> failed.`
> >> And produced the following grep: `grep 'L->isRecursivelyLCSSAForm(*DT, 
> >> *LI) && "LCSSA required to run indvars!"' t.log || exit 1`
> >> But that doesn't work, escapes should be applied. it should be
> >> `grep 'L->isRecursivelyLCSSAForm(\*DT, \*LI) && \"LCSSA required to run 
> >> indvars!\"' t.log || exit 1`
> > 
> > In my script I use `grep -F " + shlex.quote(self.args.crash_message)` which 
> > should escape both the message and ensure that the grep argument is not 
> > interpreted as a regex.
> 
> Great to hear!
> It appears that the script is currently more primitive than that currently 
> though.
Thanks; I added a `-F` flag (r359216), and it seems like that fixes the issue. 


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D59725: Additions to creduce script

2019-04-25 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added inline comments.



Comment at: cfe/trunk/utils/creduce-clang-crash.py:185
+for msg in self.expected_output:
+  output += 'grep %s t.log || exit 1\n' % pipes.quote(msg)
+

lebedev.ri wrote:
> akhuang wrote:
> > lebedev.ri wrote:
> > > >>! In D59725#1477362, @arichardson wrote:
> > > >>>! In D59725#1477042, @lebedev.ri wrote:
> > > >> I've stumbled into an issue with the script:
> > > >> It got a line: `clang: 
> > > >> /build/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp:2582: bool 
> > > >> {anonymous}::IndVarSimplify::run(llvm::Loop*): Assertion 
> > > >> `L->isRecursivelyLCSSAForm(*DT, *LI) && "LCSSA required to run 
> > > >> indvars!"' failed.`
> > > >> And produced the following grep: `grep 'L->isRecursivelyLCSSAForm(*DT, 
> > > >> *LI) && "LCSSA required to run indvars!"' t.log || exit 1`
> > > >> But that doesn't work, escapes should be applied. it should be
> > > >> `grep 'L->isRecursivelyLCSSAForm(\*DT, \*LI) && \"LCSSA required to 
> > > >> run indvars!\"' t.log || exit 1`
> > > > 
> > > > In my script I use `grep -F " + shlex.quote(self.args.crash_message)` 
> > > > which should escape both the message and ensure that the grep argument 
> > > > is not interpreted as a regex.
> > > 
> > > Great to hear!
> > > It appears that the script is currently more primitive than that 
> > > currently though.
> > Thanks; I added a `-F` flag (r359216), and it seems like that fixes the 
> > issue. 
> Thanks!
> What about `shlex`? How do you know bash won't expand that as regex already?
Sorry, not sure what you mean by bash expanding `shlex` as regex? It should be 
printing a quoted string to the bash script. 


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D59725/new/

https://reviews.llvm.org/D59725



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61407: [MS] Change the metadata for heapallocsite calls when the function return type is cast.

2019-05-01 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
Herald added subscribers: llvm-commits, cfe-commits, hiraditya.
Herald added projects: clang, LLVM.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D61407

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp


Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1090,7 +1090,7 @@
   OS.AddComment("Call instruction length");
   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
   OS.AddComment("Type index");
-  OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
+  OS.EmitIntValue(getTypeIndex(DITy).getIndex(), 4);
   endSymbolRecord(HeapAllocEnd);
 }
 
Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -5,23 +5,16 @@
 };
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
 
 // CHECK: [[DBG1]] = !{}
 // CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
 // CHECK-SAME: name: "Foo"
-
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -569,6 +569,7 @@
   }
   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
+
 return VisitCastExpr(E);
   }
   Value *VisitCastExpr(CastExpr *E);
@@ -2063,6 +2064,12 @@
   }
 }
 
+// Update heapallocsite metadata when there is an explicit cast.
+if (llvm::CallInst *CI = dyn_cast(Src))
+  if (CI->getMetadata("heapallocsite") && dyn_cast(CE))
+  CGF.getDebugInfo()->
+  addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
+
 return Builder.CreateBitCast(Src, DstTy);
   }
   case CK_AddressSpaceConversion: {
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -4370,7 +4370,6 @@
   }
 
   // Add metadata for calls to MSAllocator functions
-  // FIXME: Get the type that the return value is cast to.
   if (getDebugInfo() && TargetDecl &&
   TargetDecl->hasAttr())
 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);


Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1090,7 +1090,7 @@
   OS.AddComment("Call instruction length");
   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
   OS.AddComment("Type index");
-  OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
+  OS.EmitIntValue(getTypeIndex(DITy).getIndex(), 4);
   endSymbolRecord(HeapAllocEnd);
 }
 
Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -5,23 +5,16 @@
 };
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
 
 // CHECK: [[DBG1]] = !{}
 // CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
 // CHECK-S

[PATCH] D61407: [MS] Change the metadata for heapallocsite calls when the function return type is cast.

2019-05-01 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 197651.
akhuang added a comment.

.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61407/new/

https://reviews.llvm.org/D61407

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp


Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1090,7 +1090,7 @@
   OS.AddComment("Call instruction length");
   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
   OS.AddComment("Type index");
-  OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
+  OS.EmitIntValue(getTypeIndex(DITy).getIndex(), 4);
   endSymbolRecord(HeapAllocEnd);
 }
 
Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -5,23 +5,16 @@
 };
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
 
 // CHECK: [[DBG1]] = !{}
 // CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
 // CHECK-SAME: name: "Foo"
-
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -569,6 +569,7 @@
   }
   Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
+
 return VisitCastExpr(E);
   }
   Value *VisitCastExpr(CastExpr *E);
@@ -2063,6 +2064,12 @@
   }
 }
 
+// Update heapallocsite metadata when there is an explicit cast.
+if (llvm::CallInst *CI = dyn_cast(Src))
+  if (CI->getMetadata("heapallocsite") && dyn_cast(CE))
+  CGF.getDebugInfo()->
+  addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
+
 return Builder.CreateBitCast(Src, DstTy);
   }
   case CK_AddressSpaceConversion: {
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -4370,7 +4370,6 @@
   }
 
   // Add metadata for calls to MSAllocator functions
-  // FIXME: Get the type that the return value is cast to.
   if (getDebugInfo() && TargetDecl &&
   TargetDecl->hasAttr())
 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);


Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1090,7 +1090,7 @@
   OS.AddComment("Call instruction length");
   OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2);
   OS.AddComment("Type index");
-  OS.EmitIntValue(getCompleteTypeIndex(DITy).getIndex(), 4);
+  OS.EmitIntValue(getTypeIndex(DITy).getIndex(), 4);
   endSymbolRecord(HeapAllocEnd);
 }
 
Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -5,23 +5,16 @@
 };
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
 
 // CHECK: [[DBG1]] = !{}
 // CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
 

[PATCH] D61455: Change the metadata for heapallocsite calls when the type is cast.

2019-05-02 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.
akhuang abandoned this revision.
akhuang added a comment.

accidentally created a new revision


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D61455

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c


Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -1,27 +1,23 @@
 // RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited 
-gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
 
-struct Foo {
-  int x;
-};
+struct Foo;
+struct Bar;
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
+  struct Foo *r = (struct Foo*)(struct Bar*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG3:!.*]]
 
 // CHECK: [[DBG1]] = !{}
-// CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK: [[DBG2]] = !DICompositeType(tag: DW_TAG_structure_type,
 // CHECK-SAME: name: "Foo"
-
+// CHECK: [[DBG3]] = !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME: name: "Bar"
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -2063,6 +2063,12 @@
   }
 }
 
+// Update heapallocsite metadata when there is an explicit cast.
+if (llvm::CallInst *CI = dyn_cast(Src))
+  if (CI->getMetadata("heapallocsite") && dyn_cast(CE))
+  CGF.getDebugInfo()->
+  addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
+
 return Builder.CreateBitCast(Src, DstTy);
   }
   case CK_AddressSpaceConversion: {
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -4370,7 +4370,6 @@
   }
 
   // Add metadata for calls to MSAllocator functions
-  // FIXME: Get the type that the return value is cast to.
   if (getDebugInfo() && TargetDecl &&
   TargetDecl->hasAttr())
 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);


Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -1,27 +1,23 @@
 // RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited -gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
 
-struct Foo {
-  int x;
-};
+struct Foo;
+struct Bar;
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
+  struct Foo *r = (struct Foo*)(struct Bar*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG3:!.*]]
 
 // CHECK: [[DBG1]] = !{}
-// CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK: [[DBG2]] = !DICompositeType(tag: DW_TAG_structure_type,
 // CHECK-SAME: name: "Foo"
-
+// CHECK: [[DBG3]] = !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME: name: "Bar"
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -2063,6 +2063,12 @@
   }
 }
 
+//

[PATCH] D61455: Change the metadata for heapallocsite calls when the type is cast.

2019-05-02 Thread Amy Huang via Phabricator via cfe-commits
akhuang abandoned this revision.
akhuang added a comment.

accidentally created a new revision


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61455/new/

https://reviews.llvm.org/D61455



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61407: [MS] Change the metadata for heapallocsite calls when the function return type is cast.

2019-05-02 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 197830.
akhuang marked an inline comment as done.
akhuang added a comment.

- Add test case for multiple casts
- Remove unrelated changes


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61407/new/

https://reviews.llvm.org/D61407

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c


Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -1,27 +1,23 @@
 // RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited 
-gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
 
-struct Foo {
-  int x;
-};
+struct Foo;
+struct Bar;
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
+  struct Foo *r = (struct Foo*)(struct Bar*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG3:!.*]]
 
 // CHECK: [[DBG1]] = !{}
-// CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK: [[DBG2]] = !DICompositeType(tag: DW_TAG_structure_type,
 // CHECK-SAME: name: "Foo"
-
+// CHECK: [[DBG3]] = !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME: name: "Bar"
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -2063,6 +2063,12 @@
   }
 }
 
+// Update heapallocsite metadata when there is an explicit cast.
+if (llvm::CallInst *CI = dyn_cast(Src))
+  if (CI->getMetadata("heapallocsite") && dyn_cast(CE))
+  CGF.getDebugInfo()->
+  addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
+
 return Builder.CreateBitCast(Src, DstTy);
   }
   case CK_AddressSpaceConversion: {
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -4370,7 +4370,6 @@
   }
 
   // Add metadata for calls to MSAllocator functions
-  // FIXME: Get the type that the return value is cast to.
   if (getDebugInfo() && TargetDecl &&
   TargetDecl->hasAttr())
 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);


Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -1,27 +1,23 @@
 // RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited -gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
 
-struct Foo {
-  int x;
-};
+struct Foo;
+struct Bar;
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
+  struct Foo *r = (struct Foo*)(struct Bar*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG3:!.*]]
 
 // CHECK: [[DBG1]] = !{}
-// CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK: [[DBG2]] = !DICompositeType(tag: DW_TAG_structure_type,
 // CHECK-SAME: name: "Foo"
-
+// CHECK: [[DBG3]] = !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME: name: "Bar"
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ 

[PATCH] D61407: [MS] Change the metadata for heapallocsite calls when the function return type is cast.

2019-05-02 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked 2 inline comments as done.
akhuang added a comment.

Reverted `getCompleteTypeIndex` change, to be fixed elsewhere


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61407/new/

https://reviews.llvm.org/D61407



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D61407: [MS] Change the metadata for heapallocsite calls when the function return type is cast.

2019-05-02 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 197851.
akhuang added a comment.

Change dyn_cast to isa


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61407/new/

https://reviews.llvm.org/D61407

Files:
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/CGExprScalar.cpp
  clang/test/CodeGen/debug-info-codeview-heapallocsite.c


Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -1,27 +1,23 @@
 // RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited 
-gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
 
-struct Foo {
-  int x;
-};
+struct Foo;
+struct Bar;
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
+  struct Foo *r = (struct Foo*)(struct Bar*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG3:!.*]]
 
 // CHECK: [[DBG1]] = !{}
-// CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK: [[DBG2]] = !DICompositeType(tag: DW_TAG_structure_type,
 // CHECK-SAME: name: "Foo"
-
+// CHECK: [[DBG3]] = !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME: name: "Bar"
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -2063,6 +2063,12 @@
   }
 }
 
+// Update heapallocsite metadata when there is an explicit cast.
+if (llvm::CallInst *CI = dyn_cast(Src))
+  if (CI->getMetadata("heapallocsite") && isa(CE))
+  CGF.getDebugInfo()->
+  addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
+
 return Builder.CreateBitCast(Src, DstTy);
   }
   case CK_AddressSpaceConversion: {
Index: clang/lib/CodeGen/CGCall.cpp
===
--- clang/lib/CodeGen/CGCall.cpp
+++ clang/lib/CodeGen/CGCall.cpp
@@ -4370,7 +4370,6 @@
   }
 
   // Add metadata for calls to MSAllocator functions
-  // FIXME: Get the type that the return value is cast to.
   if (getDebugInfo() && TargetDecl &&
   TargetDecl->hasAttr())
 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc);


Index: clang/test/CodeGen/debug-info-codeview-heapallocsite.c
===
--- clang/test/CodeGen/debug-info-codeview-heapallocsite.c
+++ clang/test/CodeGen/debug-info-codeview-heapallocsite.c
@@ -1,27 +1,23 @@
 // RUN: %clang_cc1 -triple x86_64-windows-msvc -debug-info-kind=limited -gcodeview -fdeclspec -S -emit-llvm < %s | FileCheck %s
 
-struct Foo {
-  int x;
-};
+struct Foo;
+struct Bar;
 
 __declspec(allocator) void *alloc_void();
-__declspec(allocator) struct Foo *alloc_foo();
 
-void call_alloc_void() {
-  struct Foo *p = (struct Foo*)alloc_void();
+void call_alloc() {
+  struct Foo *p = alloc_void();
+  struct Foo *q = (struct Foo*)alloc_void();
+  struct Foo *r = (struct Foo*)(struct Bar*)alloc_void();
 }
 
-void call_alloc_foo() {
-  struct Foo *p = alloc_foo();
-}
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_void
+// CHECK-LABEL: define {{.*}}void @call_alloc
 // CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG1:!.*]]
-
-// CHECK-LABEL: define {{.*}}void @call_alloc_foo
-// CHECK: call %struct.Foo* {{.*}}@alloc_foo{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG2:!.*]]
+// CHECK: call i8* {{.*}}@alloc_void{{.*}} !heapallocsite [[DBG3:!.*]]
 
 // CHECK: [[DBG1]] = !{}
-// CHECK: [[DBG2]] = distinct !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK: [[DBG2]] = !DICompositeType(tag: DW_TAG_structure_type,
 // CHECK-SAME: name: "Foo"
-
+// CHECK: [[DBG3]] = !DICompositeType(tag: DW_TAG_structure_type,
+// CHECK-SAME: name: "Bar"
Index: clang/lib/CodeGen/CGExprScalar.cpp
===
--- clang/lib/CodeGen/CGExprScalar.cpp
+++ clang/lib/CodeGen/CGExprScalar.cpp
@@ -2063,6 +2063,12 @@
   }
 }
 
+// Update heapallocsite metadata when there

[PATCH] D61407: [MS] Change the metadata for heapallocsite calls when the function return type is cast.

2019-05-02 Thread Amy Huang via Phabricator via cfe-commits
akhuang closed this revision.
akhuang added a comment.

Committed in r359823


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D61407/new/

https://reviews.llvm.org/D61407



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62635: Add enums as global variables in the IR metadata.

2019-05-30 Thread Amy Huang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL362166: Add enums as global variables in the IR metadata. 
(authored by akhuang, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D62635?vs=202079&id=202312#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62635/new/

https://reviews.llvm.org/D62635

Files:
  cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
  cfe/trunk/test/CodeGenCXX/debug-info-enum.cpp
  llvm/trunk/test/DebugInfo/COFF/global-constants.ll

Index: llvm/trunk/test/DebugInfo/COFF/global-constants.ll
===
--- llvm/trunk/test/DebugInfo/COFF/global-constants.ll
+++ llvm/trunk/test/DebugInfo/COFF/global-constants.ll
@@ -2,26 +2,41 @@
 ; RUN: llc < %s -filetype=obj | llvm-readobj - --codeview | FileCheck %s --check-prefix=OBJ
 
 ; C++ source to regenerate:
-; const int Test1 = 1;
-; struct Foo { static const int Test2 = 2; };
-; int main() {
-;   return Test1 + Foo::Test2;
+; const float TestConst1 = 3.14;
+; struct S {
+;   static const int TestConst2 = -10;
+; }
+; enum TestEnum : int {
+;ENUM_A = 214700,
+;ENUM_B = -214700,
+; };
+; void useConst(int);
+; void foo() {
+;   useConst(TestConst1);
+;   useConst(S::TestConst2);
+;   useConst(ENUM_B);
 ; }
 ; $ clang t.cpp -S -emit-llvm -g -gcodeview -o t.ll
 
-; ASM-LABEL:  .long 241 # Symbol subsection for globals
-
-; ASM:.short {{.*-.*}}  # Record length
-; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4099# Type
-; ASM-NEXT:   .byte 0x01, 0x00  # Value
-; ASM-NEXT:   .asciz "Test1"# Name
-
-; ASM:.short {{.*-.*}}  # Record length
-; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM:.long 4099# Type
-; ASM:.byte 0x02, 0x00  # Value
-; ASM:.asciz "Foo::Test2"   # Name
+; ASM-LABEL:  .long 241 # Symbol subsection for globals
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4099# Type
+; ASM-NEXT:   .byte 0x04, 0x80, 0xc3, 0xf5  # Value
+; ASM-NEXT:   .byte 0x48, 0x40
+; ASM-NEXT:   .asciz "TestConst1"   # Name
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4100# Type
+; ASM-NEXT:   .byte 0x61, 0x00  # Value
+; ASM-NEXT:   .asciz "S::TestConst2"# Name
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4102# Type
+; ASM-NEXT:   .byte 0x0a, 0x80, 0x40, 0x61  # Value
+; ASM-NEXT:   .byte 0x07, 0x80, 0xff, 0xff
+; ASM-NEXT:   .byte 0xff, 0xff
+; ASM-NEXT:   .asciz "ENUM_B"   # Name
 
 ; OBJ:CodeViewDebugInfo [
 ; OBJ:  Section: .debug$S
@@ -30,56 +45,77 @@
 ; OBJ:SubSectionType: Symbols (0xF1)
 ; OBJ:ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: const int (0x1003)
-; OBJ-NEXT: Value: 1
-; OBJ-NEXT: Name: Test1
+; OBJ-NEXT: Type: const float (0x1003)
+; OBJ-NEXT: Value: 1078523331
+; OBJ-NEXT: Name: TestConst1
 ; OBJ-NEXT:   }
-; OBJ:ConstantSym {
+; OBJ-NEXT:   ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: const int (0x1003)
-; OBJ-NEXT: Value: 2
-; OBJ-NEXT: Name: Foo::Test2
+; OBJ-NEXT: Type: const char (0x1004)
+; OBJ-NEXT: Value: 97
+; OBJ-NEXT: Name: S::TestConst2
 ; OBJ-NEXT:   }
+; OBJ-NEXT:   ConstantSym {
+; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
+; OBJ-NEXT: Type: TestEnum (0x1006)
+; OBJ-NEXT: Value: 18446744071562551616
+; OBJ-NEXT: Name: ENUM_B
+; OBJ-NEXT:   }
+
 
 ; ModuleID = 't.cpp'
 source_filename = "t.cpp"
 target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
-target triple = "x86_64-pc-windows-msvc"
+target triple = "x86_64-w64-windows-gnu"
 
-; Function Attrs: noinline norecurse nounwind optnone
-define dso_local i32 @main() #0 !dbg !19 {
+; Function Attrs: noinline nounwind optnone
+define dso_local void @_Z3foov() #0 !dbg !28 {
 entry:
-  %retval = alloca i32, align 4
-  store i32 0, i32* %retval, align 4
-  ret i32 3, !dbg !22
+  call void @_Z8useConsti(i32 3), !dbg !32
+  call void @_Z8useConsti(i32 97), !dbg !33
+  call void @_Z8useConsti(i32 -214700), !dbg !34
+  ret void, !dbg !35
 }
 
-attributes #0 = { noinline norecurse nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math

[PATCH] D63012: Use fully qualified name when printing S_CONSTANT records

2019-06-11 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 204137.
akhuang added a comment.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Change to not emit DIGlobalVariable for enums when they are defined in a class, 
which
matches MSVC's behavior and gets around the issue of having to create a name 
with scope.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63012/new/

https://reviews.llvm.org/D63012

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/test/DebugInfo/COFF/global-constants.ll

Index: llvm/test/DebugInfo/COFF/global-constants.ll
===
--- llvm/test/DebugInfo/COFF/global-constants.ll
+++ llvm/test/DebugInfo/COFF/global-constants.ll
@@ -2,9 +2,12 @@
 ; RUN: llc < %s -filetype=obj | llvm-readobj - --codeview | FileCheck %s --check-prefix=OBJ
 
 ; C++ source to regenerate:
+; namespace Test1 {
 ; const float TestConst1 = 3.14;
+; }
 ; struct S {
 ;   static const int TestConst2 = -10;
+;   enum { SEnum = 42 };
 ; }
 ; enum TestEnum : int {
 ;ENUM_A = 214700,
@@ -12,31 +15,33 @@
 ; };
 ; void useConst(int);
 ; void foo() {
-;   useConst(TestConst1);
+;   useConst(Test1::TestConst1);
 ;   useConst(S::TestConst2);
 ;   useConst(ENUM_B);
+;   useConst(S::SEnum);
 ; }
 ; $ clang t.cpp -S -emit-llvm -g -gcodeview -o t.ll
 
 ; ASM-LABEL:  .long 241 # Symbol subsection for globals
 ; ASM:.short {{.*-.*}}  # Record length
 ; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4099# Type
+; ASM-NEXT:   .long 4102# Type
 ; ASM-NEXT:   .byte 0x04, 0x80, 0xc3, 0xf5  # Value
 ; ASM-NEXT:   .byte 0x48, 0x40
-; ASM-NEXT:   .asciz "TestConst1"   # Name
+; ASM-NEXT:   .asciz "Test1::TestConst1"# Name
 ; ASM:.short {{.*-.*}}  # Record length
 ; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4100# Type
+; ASM-NEXT:   .long 4103# Type
 ; ASM-NEXT:   .byte 0x61, 0x00  # Value
 ; ASM-NEXT:   .asciz "S::TestConst2"# Name
 ; ASM:.short {{.*-.*}}  # Record length
 ; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4102# Type
+; ASM-NEXT:   .long 4105# Type
 ; ASM-NEXT:   .byte 0x0a, 0x80, 0x40, 0x61  # Value
 ; ASM-NEXT:   .byte 0x07, 0x80, 0xff, 0xff
 ; ASM-NEXT:   .byte 0xff, 0xff
 ; ASM-NEXT:   .asciz "ENUM_B"   # Name
+; ASM-NOT:.asciz "S::SEnum" # Name
 
 ; OBJ:CodeViewDebugInfo [
 ; OBJ:  Section: .debug$S
@@ -45,77 +50,110 @@
 ; OBJ:SubSectionType: Symbols (0xF1)
 ; OBJ:ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: const float (0x1003)
+; OBJ-NEXT: Type: const float (0x1006)
 ; OBJ-NEXT: Value: 1078523331
-; OBJ-NEXT: Name: TestConst1
+; OBJ-NEXT: Name: Test1::TestConst1
 ; OBJ-NEXT:   }
 ; OBJ-NEXT:   ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: const char (0x1004)
+; OBJ-NEXT: Type: const char (0x1007)
 ; OBJ-NEXT: Value: 97
 ; OBJ-NEXT: Name: S::TestConst2
 ; OBJ-NEXT:   }
 ; OBJ-NEXT:   ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: TestEnum (0x1006)
+; OBJ-NEXT: Type: TestEnum (0x1009)
 ; OBJ-NEXT: Value: 18446744071562551616
 ; OBJ-NEXT: Name: ENUM_B
 ; OBJ-NEXT:   }
-
+; OBJ-NOT:  Name: S::SEnum
 
 ; ModuleID = 't.cpp'
 source_filename = "t.cpp"
 target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
-target triple = "x86_64-w64-windows-gnu"
+target triple = "x86_64-pc-windows-msvc19.16.27030"
 
-; Function Attrs: noinline nounwind optnone
-define dso_local void @_Z3foov() #0 !dbg !28 {
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local void @"?useConst@@YAXH@Z"(i32) #0 !dbg !32 {
 entry:
-  call void @_Z8useConsti(i32 3), !dbg !32
-  call void @_Z8useConsti(i32 97), !dbg !33
-  call void @_Z8useConsti(i32 -214700), !dbg !34
-  ret void, !dbg !35
+  %.addr = alloca i32, align 4
+  store i32 %0, i32* %.addr, align 4
+  call void @llvm.dbg.declare(metadata i32* %.addr, metadata !36, metadata !DIExpression()), !dbg !37
+  ret void, !dbg !37
 }
 
-declare dso_local void @_Z8useConsti(i32) #1
+; Function Attrs: nounwind readnone speculatable
+declare void @llvm.dbg.declare(metadata, metadata, metadata) #1
+
+; Function Attrs: noinline norecurse nounwind optnone uwtable
+define dso_local i32 @main() #2 !dbg !38 {
+entry:
+  %retval = alloca i32, align 4
+  store i32 0, i32* %retval, align 4
+  call void @"?useConst@@YAXH@Z"(i32 3), !dbg !41
+  call void @"?useConst@@YAXH@Z"(i3

[PATCH] D63012: Use fully qualified name when printing S_CONSTANT records

2019-06-13 Thread Amy Huang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL363335: Use fully qualified name when printing S_CONSTANT 
records (authored by akhuang, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D63012?vs=204137&id=204649#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63012/new/

https://reviews.llvm.org/D63012

Files:
  cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
  llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/trunk/test/DebugInfo/COFF/global-constants.ll

Index: llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -3069,12 +3069,13 @@
 OS.EmitBinaryData(SRef);
 
 OS.AddComment("Name");
-// Get fully qualified name if global is a static data member.
-std::string Name = DIGV->getDisplayName();
+const DIScope *Scope = DIGV->getScope();
+// For static data members, get the scope from the declaration.
 if (const auto *MemberDecl = dyn_cast_or_null(
 DIGV->getRawStaticDataMemberDeclaration()))
-  Name = getFullyQualifiedName(MemberDecl->getScope(), Name);
-emitNullTerminatedSymbolName(OS, Name);
+  Scope = MemberDecl->getScope();
+emitNullTerminatedSymbolName(OS,
+ getFullyQualifiedName(Scope, DIGV->getName()));
 endSymbolRecord(SConstantEnd);
   }
 }
Index: llvm/trunk/test/DebugInfo/COFF/global-constants.ll
===
--- llvm/trunk/test/DebugInfo/COFF/global-constants.ll
+++ llvm/trunk/test/DebugInfo/COFF/global-constants.ll
@@ -2,9 +2,12 @@
 ; RUN: llc < %s -filetype=obj | llvm-readobj - --codeview | FileCheck %s --check-prefix=OBJ
 
 ; C++ source to regenerate:
+; namespace Test1 {
 ; const float TestConst1 = 3.14;
+; }
 ; struct S {
 ;   static const int TestConst2 = -10;
+;   enum { SEnum = 42 };
 ; }
 ; enum TestEnum : int {
 ;ENUM_A = 214700,
@@ -12,31 +15,33 @@
 ; };
 ; void useConst(int);
 ; void foo() {
-;   useConst(TestConst1);
+;   useConst(Test1::TestConst1);
 ;   useConst(S::TestConst2);
 ;   useConst(ENUM_B);
+;   useConst(S::SEnum);
 ; }
 ; $ clang t.cpp -S -emit-llvm -g -gcodeview -o t.ll
 
 ; ASM-LABEL:  .long 241 # Symbol subsection for globals
 ; ASM:.short {{.*-.*}}  # Record length
 ; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4099# Type
+; ASM-NEXT:   .long 4102# Type
 ; ASM-NEXT:   .byte 0x04, 0x80, 0xc3, 0xf5  # Value
 ; ASM-NEXT:   .byte 0x48, 0x40
-; ASM-NEXT:   .asciz "TestConst1"   # Name
+; ASM-NEXT:   .asciz "Test1::TestConst1"# Name
 ; ASM:.short {{.*-.*}}  # Record length
 ; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4100# Type
+; ASM-NEXT:   .long 4103# Type
 ; ASM-NEXT:   .byte 0x61, 0x00  # Value
 ; ASM-NEXT:   .asciz "S::TestConst2"# Name
 ; ASM:.short {{.*-.*}}  # Record length
 ; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4102# Type
+; ASM-NEXT:   .long 4105# Type
 ; ASM-NEXT:   .byte 0x0a, 0x80, 0x40, 0x61  # Value
 ; ASM-NEXT:   .byte 0x07, 0x80, 0xff, 0xff
 ; ASM-NEXT:   .byte 0xff, 0xff
 ; ASM-NEXT:   .asciz "ENUM_B"   # Name
+; ASM-NOT:.asciz "S::SEnum" # Name
 
 ; OBJ:CodeViewDebugInfo [
 ; OBJ:  Section: .debug$S
@@ -45,77 +50,110 @@
 ; OBJ:SubSectionType: Symbols (0xF1)
 ; OBJ:ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: const float (0x1003)
+; OBJ-NEXT: Type: const float (0x1006)
 ; OBJ-NEXT: Value: 1078523331
-; OBJ-NEXT: Name: TestConst1
+; OBJ-NEXT: Name: Test1::TestConst1
 ; OBJ-NEXT:   }
 ; OBJ-NEXT:   ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: const char (0x1004)
+; OBJ-NEXT: Type: const char (0x1007)
 ; OBJ-NEXT: Value: 97
 ; OBJ-NEXT: Name: S::TestConst2
 ; OBJ-NEXT:   }
 ; OBJ-NEXT:   ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: TestEnum (0x1006)
+; OBJ-NEXT: Type: TestEnum (0x1009)
 ; OBJ-NEXT: Value: 18446744071562551616
 ; OBJ-NEXT: Name: ENUM_B
 ; OBJ-NEXT:   }
-
+; OBJ-NOT:  Name: S::SEnum
 
 ; ModuleID = 't.cpp'
 source_filename = "t.cpp"
 target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
-target triple = "x86_64-w64-windows-gnu"
+target triple = "x86_64-pc-windows-msvc19.16.27030"
 
-; Function Attrs: noinline nounwind optnone
-define dso_loca

[PATCH] D63361: Pretend NRVO variables are references so that CodeView can get their value

2019-06-14 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
Herald added subscribers: llvm-commits, cfe-commits, hiraditya.
Herald added projects: clang, LLVM.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D63361

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDecl.cpp
  debuginfo-tests/nrvo-string.cpp
  llvm/include/llvm/IR/DebugInfoMetadata.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/IR/DebugInfoMetadata.cpp

Index: llvm/lib/IR/DebugInfoMetadata.cpp
===
--- llvm/lib/IR/DebugInfoMetadata.cpp
+++ llvm/lib/IR/DebugInfoMetadata.cpp
@@ -936,12 +936,20 @@
   }
 }
 
-bool DIExpression::extractIfOffset(int64_t &Offset) const {
+bool DIExpression::extractIfOffset(int64_t &Offset, bool &Deref) const {
+  Deref = false;
+
   if (getNumElements() == 0) {
 Offset = 0;
 return true;
   }
 
+  if (getNumElements() == 1 && Elements[0] == dwarf::DW_OP_deref) {
+Offset = 0;
+Deref = true;
+return true;
+  }
+
   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
 Offset = Elements[1];
 return true;
Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1142,9 +1142,11 @@
 // If the variable has an attached offset expression, extract it.
 // FIXME: Try to handle DW_OP_deref as well.
 int64_t ExprOffset = 0;
-if (VI.Expr)
-  if (!VI.Expr->extractIfOffset(ExprOffset))
+bool Deref = false;
+if (VI.Expr) {
+  if (!VI.Expr->extractIfOffset(ExprOffset, Deref))
 continue;
+}
 
 // Get the frame register used and the offset.
 unsigned FrameReg = 0;
@@ -1154,6 +1156,7 @@
 // Calculate the label ranges.
 LocalVarDefRange DefRange =
 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
+
 for (const InsnRange &Range : Scope->getRanges()) {
   const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
   const MCSymbol *End = getLabelAfterInsn(Range.second);
@@ -1164,6 +1167,9 @@
 LocalVariable Var;
 Var.DIVar = VI.Var;
 Var.DefRanges.emplace_back(std::move(DefRange));
+if (Deref)
+  Var.UseReferenceType = true;
+
 recordLocalVariable(std::move(Var), Scope);
   }
 }
Index: llvm/include/llvm/IR/DebugInfoMetadata.h
===
--- llvm/include/llvm/IR/DebugInfoMetadata.h
+++ llvm/include/llvm/IR/DebugInfoMetadata.h
@@ -2468,8 +2468,9 @@
   static void appendOffset(SmallVectorImpl &Ops, int64_t Offset);
 
   /// If this is a constant offset, extract it. If there is no expression,
-  /// return true with an offset of zero.
-  bool extractIfOffset(int64_t &Offset) const;
+  /// or if there is one expression of DW_OP_deref, return true with an offset
+  /// of zero. Also set Deref.
+  bool extractIfOffset(int64_t &Offset, bool &Deref) const;
 
   /// Checks if the last 4 elements of the expression are DW_OP_constu  DW_OP_swap DW_OP_xderef and extracts the isConstantSizeType()) {
-bool NRVO = getLangOpts().ElideConstructors &&
-  D.isNRVOVariable();
-
 // If this value is an array or struct with a statically determinable
 // constant initializer, there are optimizations we can do.
 //
@@ -1561,8 +1560,20 @@
 
   // Emit debug info for local var declaration.
   if (EmitDebugInfo && HaveInsertPoint()) {
+Address DebugAddr = address;
 DI->setLocation(D.getLocation());
-(void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
+
+// NRVO variables are stored in the return register and are not always
+// readable by the debugger. Get around this by storing a reference to
+// the variable.
+if (NRVO) {
+  llvm::Type *RefTy =
+  ConvertTypeForMem(getContext().getLValueReferenceType(Ty));
+  DebugAddr = CreateTempAlloca(RefTy, getPointerAlign(), "nrvo_ref");
+  Builder.CreateStore(ReturnValue.getPointer(), DebugAddr);
+}
+
+(void)DI->EmitDeclareOfAutoVariable(&D, DebugAddr.getPointer(), Builder);
   }
 
   if (D.hasAttr() && HaveInsertPoint())
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3937,6 +3937,11 @@
 }
   }
 
+  // Add DW_OP_deref to NRVO variables because we set their debug values to be
+  // references.
+  if (VD->isNRVOVariable())
+Expr.push_back(llvm::dwarf::DW_OP_deref);
+
   // Create the descriptor for the variable.
   auto *D = ArgNo ? DBuilder.createParameterVariable(
 Scope, Name, *ArgNo, Unit, Line, Ty,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-14 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 204878.
akhuang added a comment.

- fix test case


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDecl.cpp
  debuginfo-tests/nrvo-string.cpp
  llvm/include/llvm/IR/DebugInfoMetadata.h
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/lib/IR/DebugInfoMetadata.cpp

Index: llvm/lib/IR/DebugInfoMetadata.cpp
===
--- llvm/lib/IR/DebugInfoMetadata.cpp
+++ llvm/lib/IR/DebugInfoMetadata.cpp
@@ -936,12 +936,20 @@
   }
 }
 
-bool DIExpression::extractIfOffset(int64_t &Offset) const {
+bool DIExpression::extractIfOffset(int64_t &Offset, bool &Deref) const {
+  Deref = false;
+
   if (getNumElements() == 0) {
 Offset = 0;
 return true;
   }
 
+  if (getNumElements() == 1 && Elements[0] == dwarf::DW_OP_deref) {
+Offset = 0;
+Deref = true;
+return true;
+  }
+
   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
 Offset = Elements[1];
 return true;
Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1142,9 +1142,11 @@
 // If the variable has an attached offset expression, extract it.
 // FIXME: Try to handle DW_OP_deref as well.
 int64_t ExprOffset = 0;
-if (VI.Expr)
-  if (!VI.Expr->extractIfOffset(ExprOffset))
+bool Deref = false;
+if (VI.Expr) {
+  if (!VI.Expr->extractIfOffset(ExprOffset, Deref))
 continue;
+}
 
 // Get the frame register used and the offset.
 unsigned FrameReg = 0;
@@ -1154,6 +1156,7 @@
 // Calculate the label ranges.
 LocalVarDefRange DefRange =
 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
+
 for (const InsnRange &Range : Scope->getRanges()) {
   const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
   const MCSymbol *End = getLabelAfterInsn(Range.second);
@@ -1164,6 +1167,9 @@
 LocalVariable Var;
 Var.DIVar = VI.Var;
 Var.DefRanges.emplace_back(std::move(DefRange));
+if (Deref)
+  Var.UseReferenceType = true;
+
 recordLocalVariable(std::move(Var), Scope);
   }
 }
Index: llvm/include/llvm/IR/DebugInfoMetadata.h
===
--- llvm/include/llvm/IR/DebugInfoMetadata.h
+++ llvm/include/llvm/IR/DebugInfoMetadata.h
@@ -2468,8 +2468,9 @@
   static void appendOffset(SmallVectorImpl &Ops, int64_t Offset);
 
   /// If this is a constant offset, extract it. If there is no expression,
-  /// return true with an offset of zero.
-  bool extractIfOffset(int64_t &Offset) const;
+  /// or if there is one expression of DW_OP_deref, return true with an offset
+  /// of zero. Also set Deref.
+  bool extractIfOffset(int64_t &Offset, bool &Deref) const;
 
   /// Checks if the last 4 elements of the expression are DW_OP_constu  DW_OP_swap DW_OP_xderef and extracts the isConstantSizeType()) {
-bool NRVO = getLangOpts().ElideConstructors &&
-  D.isNRVOVariable();
-
 // If this value is an array or struct with a statically determinable
 // constant initializer, there are optimizations we can do.
 //
@@ -1561,8 +1560,20 @@
 
   // Emit debug info for local var declaration.
   if (EmitDebugInfo && HaveInsertPoint()) {
+Address DebugAddr = address;
 DI->setLocation(D.getLocation());
-(void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder);
+
+// NRVO variables are stored in the return register and are not always
+// readable by the debugger. Get around this by storing a reference to
+// the variable.
+if (NRVO) {
+  llvm::Type *RefTy =
+  ConvertTypeForMem(getContext().getLValueReferenceType(Ty));
+  DebugAddr = CreateTempAlloca(RefTy, getPointerAlign(), "nrvo_ref");
+  Builder.CreateStore(ReturnValue.getPointer(), DebugAddr);
+}
+
+(void)DI->EmitDeclareOfAutoVariable(&D, DebugAddr.getPointer(), Builder);
   }
 
   if (D.hasAttr() && HaveInsertPoint())
Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -3937,6 +3937,11 @@
 }
   }
 
+  // Add DW_OP_deref to NRVO variables because we set their debug values to be
+  // references.
+  if (VD->isNRVOVariable())
+Expr.push_back(llvm::dwarf::DW_OP_deref);
+
   // Create the descriptor for the variable.
   auto *D = ArgNo ? DBuilder.createParameterVariable(
 Scope, Name, *ArgNo, Unit, Line, Ty,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62635: Add enums as global variables in the IR metadata.

2019-06-17 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

I think the main issue was keeping track of which enums are used?


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62635/new/

https://reviews.llvm.org/D62635



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62635: Add enums as global variables in the IR metadata.

2019-06-17 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

They should all be there, but emitting the unused enums makes the binary sizes 
larger. (I think around 6% increase? I forget the size difference for only 
emitting used enums)


Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62635/new/

https://reviews.llvm.org/D62635



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 205382.
akhuang marked 2 inline comments as done.
akhuang added a comment.

Now creates a pointer to the return location in the function prolog, whenever 
sret is being used.

Also addressed some other comments.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  debuginfo-tests/nrvo-string.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp

Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1142,9 +1142,15 @@
 // If the variable has an attached offset expression, extract it.
 // FIXME: Try to handle DW_OP_deref as well.
 int64_t ExprOffset = 0;
-if (VI.Expr)
-  if (!VI.Expr->extractIfOffset(ExprOffset))
+bool Deref = false;
+if (VI.Expr) {
+  // If there is one DW_OP_deref element, use offset of 0 and keep going.
+  if (VI.Expr->getNumElements() == 1 &&
+  VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
+Deref = true;
+  else if (!VI.Expr->extractIfOffset(ExprOffset))
 continue;
+}
 
 // Get the frame register used and the offset.
 unsigned FrameReg = 0;
@@ -1154,6 +1160,7 @@
 // Calculate the label ranges.
 LocalVarDefRange DefRange =
 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
+
 for (const InsnRange &Range : Scope->getRanges()) {
   const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
   const MCSymbol *End = getLabelAfterInsn(Range.second);
@@ -1164,6 +1171,9 @@
 LocalVariable Var;
 Var.DIVar = VI.Var;
 Var.DefRanges.emplace_back(std::move(DefRange));
+if (Deref)
+  Var.UseReferenceType = true;
+
 recordLocalVariable(std::move(Var), Scope);
   }
 }
Index: debuginfo-tests/nrvo-string.cpp
===
--- debuginfo-tests/nrvo-string.cpp
+++ debuginfo-tests/nrvo-string.cpp
@@ -17,11 +17,31 @@
 string get_string() {
   string unused;
   string result = 3;
-// DEBUGGER: break 21
+  // DEBUGGER: break 21
   return result;
 }
-int main() { get_string(); }
+void some_function(int) {}
+struct string2 {
+  string2() = default;
+  string2(string2 &&other) { i = other.i; }
+  int i;
+} string2 get_string2() {
+  string2 result;
+  result.i = 5;
+  some_function(result.i);
+  // Test that the debugger can get the value of result after another
+  // function is called.
+  // DEBUGGER: break 35
+  return result;
+}
+int main() {
+  get_string();
+  get_string2();
+}
 
 // DEBUGGER: r
 // DEBUGGER: print result.i
 // CHECK:  = 3
+// DEBUGGER: c
+// DEBUGGER: print result.i
+// CHECK:  = 5
Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -327,6 +327,10 @@
   /// value. This is invalid iff the function has no return value.
   Address ReturnValue = Address::invalid();
 
+  /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
+  /// This is invalid if sret is not in use.
+  Address ReturnValuePointer = Address::invalid();
+
   /// Return true if a label was seen in the current scope.
   bool hasLabelBeenSeenInCurrentScope() const {
 if (CurLexicalScope)
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -895,6 +895,10 @@
 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
   ++AI;
 ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
+ReturnValuePointer = CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
+Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
+ReturnValue.getPointer(), Int8PtrTy),
+ReturnValuePointer);
   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
 // Load the sret pointer from the argument struct and return into that.
@@ -904,6 +908,10 @@
 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
 ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
+ReturnValuePointer = CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
+Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
+ReturnValue.getPointer(), Int8PtrTy),
+ReturnValuePointer);
   } else {
 ReturnValue = 

[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang added inline comments.



Comment at: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp:1145-1149
+bool Deref = false;
+if (VI.Expr) {
+  if (!VI.Expr->extractIfOffset(ExprOffset, Deref))
 continue;
+}

rnk wrote:
> I see. I thought this code was using the stuff I added in 
> `DbgVariableLocation::extractFromMachineInstruction`. Hm.
> 
> In practice, do you actually see DIExpression offsets here? I think maybe we 
> should just special case a single DW_OP_deref expression, since that's what 
> we get at O0.
That should work


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-18 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 205385.
akhuang added a comment.

- add semicolon


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  debuginfo-tests/nrvo-string.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp

Index: llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1142,9 +1142,15 @@
 // If the variable has an attached offset expression, extract it.
 // FIXME: Try to handle DW_OP_deref as well.
 int64_t ExprOffset = 0;
-if (VI.Expr)
-  if (!VI.Expr->extractIfOffset(ExprOffset))
+bool Deref = false;
+if (VI.Expr) {
+  // If there is one DW_OP_deref element, use offset of 0 and keep going.
+  if (VI.Expr->getNumElements() == 1 &&
+  VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
+Deref = true;
+  else if (!VI.Expr->extractIfOffset(ExprOffset))
 continue;
+}
 
 // Get the frame register used and the offset.
 unsigned FrameReg = 0;
@@ -1154,6 +1160,7 @@
 // Calculate the label ranges.
 LocalVarDefRange DefRange =
 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
+
 for (const InsnRange &Range : Scope->getRanges()) {
   const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
   const MCSymbol *End = getLabelAfterInsn(Range.second);
@@ -1164,6 +1171,9 @@
 LocalVariable Var;
 Var.DIVar = VI.Var;
 Var.DefRanges.emplace_back(std::move(DefRange));
+if (Deref)
+  Var.UseReferenceType = true;
+
 recordLocalVariable(std::move(Var), Scope);
   }
 }
Index: debuginfo-tests/nrvo-string.cpp
===
--- debuginfo-tests/nrvo-string.cpp
+++ debuginfo-tests/nrvo-string.cpp
@@ -17,11 +17,32 @@
 string get_string() {
   string unused;
   string result = 3;
-// DEBUGGER: break 21
+  // DEBUGGER: break 21
   return result;
 }
-int main() { get_string(); }
+void some_function(int) {}
+struct string2 {
+  string2() = default;
+  string2(string2 &&other) { i = other.i; }
+  int i;
+};
+string2 get_string2() {
+  string2 result;
+  result.i = 5;
+  some_function(result.i);
+  // Test that the debugger can get the value of result after another
+  // function is called.
+  // DEBUGGER: break 35
+  return result;
+}
+int main() {
+  get_string();
+  get_string2();
+}
 
 // DEBUGGER: r
 // DEBUGGER: print result.i
 // CHECK:  = 3
+// DEBUGGER: c
+// DEBUGGER: print result.i
+// CHECK:  = 5
Index: clang/lib/CodeGen/CodeGenFunction.h
===
--- clang/lib/CodeGen/CodeGenFunction.h
+++ clang/lib/CodeGen/CodeGenFunction.h
@@ -327,6 +327,10 @@
   /// value. This is invalid iff the function has no return value.
   Address ReturnValue = Address::invalid();
 
+  /// ReturnValuePointer - The temporary alloca to hold a pointer to sret.
+  /// This is invalid if sret is not in use.
+  Address ReturnValuePointer = Address::invalid();
+
   /// Return true if a label was seen in the current scope.
   bool hasLabelBeenSeenInCurrentScope() const {
 if (CurLexicalScope)
Index: clang/lib/CodeGen/CodeGenFunction.cpp
===
--- clang/lib/CodeGen/CodeGenFunction.cpp
+++ clang/lib/CodeGen/CodeGenFunction.cpp
@@ -895,6 +895,10 @@
 if (CurFnInfo->getReturnInfo().isSRetAfterThis())
   ++AI;
 ReturnValue = Address(&*AI, CurFnInfo->getReturnInfo().getIndirectAlign());
+ReturnValuePointer = CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
+Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
+ReturnValue.getPointer(), Int8PtrTy),
+ReturnValuePointer);
   } else if (CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::InAlloca &&
  !hasScalarEvaluationKind(CurFnInfo->getReturnType())) {
 // Load the sret pointer from the argument struct and return into that.
@@ -904,6 +908,10 @@
 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");
 ReturnValue = Address(Addr, getNaturalTypeAlignment(RetTy));
+ReturnValuePointer = CreateDefaultAlignTempAlloca(Int8PtrTy, "result.ptr");
+Builder.CreateStore(Builder.CreatePointerBitCastOrAddrSpaceCast(
+ReturnValue.getPointer(), Int8PtrTy),
+ReturnValuePointer);
   } else {
 ReturnValue = CreateIRTemp(RetTy, "retval");
 
Index: clang/lib/CodeGen/CGDecl.cpp
===
--- clang/lib/CodeGen/C

[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-19 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:3946
+  // the address of the variable.
+  if (VD->isNRVOVariable())
+Expr.push_back(llvm::dwarf::DW_OP_deref);

rnk wrote:
> I think we should check for `getLangOpts().ElideConstructors` here, and check 
> that the debug info is correct (no deref) in that mode.
Makes sense, though now I realized there is also an issue because CGDecl checks 
whether `ReturnValuePointer` is valid before changing the debug value, but 
CGDebugInfo doesn't check this when adding DW_OP_deref.. so maybe it makes 
sense to pass something through to `EmitDeclare`?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-19 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 205649.
akhuang added a comment.

- Add clang and llvm tests, and windows debuginfo test
- Use GEP as returnValuePointer in inalloca case
- Add bool parameter for EmitDeclare when pointer is being used


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/CodeGenCXX/debug-info-nrvo.cpp
  debuginfo-tests/nrvo-string.cpp
  debuginfo-tests/win_cdb/nrvo.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/test/DebugInfo/COFF/nrvo.ll

Index: llvm/test/DebugInfo/COFF/nrvo.ll
===
--- /dev/null
+++ llvm/test/DebugInfo/COFF/nrvo.ll
@@ -0,0 +1,144 @@
+; RUN: llc < %s | FileCheck %s --check-prefix=ASM
+; RUN: llc < %s -filetype=obj | llvm-readobj - --codeview | FileCheck %s --check-prefix=OBJ
+
+; C++ source to regenerate:
+; struct Foo {
+;   Foo() = default;
+;   Foo(Foo &&other) { x = other.x; }
+;   int x;
+; };
+; void some_function(int);
+; Foo getFoo() {
+;   Foo foo;
+;   foo.x = 41;
+;   some_function(foo.x);
+;   return foo;
+; }
+;
+; int main() {
+;   Foo bar = getFoo();
+;   return bar.x;
+; }
+; $ clang t.cpp -S -emit-llvm -g -o t.ll
+
+; ASM-LABEL:  .long  241  # Symbol subsection for GetFoo 
+; ASM:.short 4414 # Record kind: S_LOCAL
+; ASM-NEXT:   .long 4113  # TypeIndex
+; ASM-NEXT:   .short 0# Flags
+; ASM-NEXT:   .asciz "foo"
+; ASM-NEXT:   .p2align 2
+; ASM-NEXT: .Ltmp
+; ASM:.cv_def_range  .Ltmp{{.*}} .Ltmp{{.*}}, "B\021(\000\000\000"
+
+; OBJ: Subsection [
+; OBJ:   SubSectionType: Symbols (0xF1)
+; OBJ:   LocalSym {
+; OBJ: Kind: S_LOCAL (0x113E)
+; OBJ: Type: Foo& (0x1011)
+; OBJ: Flags [ (0x0)
+; OBJ: ]
+; OBJ: VarName: foo
+; OBJ:   }
+; OBJ:   DefRangeFramePointerRelSym {
+; OBJ: Kind: S_DEFRANGE_FRAMEPOINTER_REL (0x1142)
+; OBJ: Offset: 40
+; OBJ: LocalVariableAddrRange {
+; OBJ:   OffsetStart: .text+0x1D
+; OBJ:   ISectStart: 0x0
+; OBJ:   Range: 0x16
+; OBJ:   }
+
+; ModuleID = 't.cpp'
+source_filename = "t.cpp"
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-pc-windows-msvc19.16.27030"
+
+%struct.Foo = type { i32 }
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local void @"?some_function@@YAXH@Z"(i32) #0 !dbg !8 {
+entry:
+  %.addr = alloca i32, align 4
+  store i32 %0, i32* %.addr, align 4
+  call void @llvm.dbg.declare(metadata i32* %.addr, metadata !12, metadata !DIExpression()), !dbg !13
+  ret void, !dbg !13
+}
+
+; Function Attrs: nounwind readnone speculatable
+declare void @llvm.dbg.declare(metadata, metadata, metadata) #1
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local void @"?GetFoo@@YA?AUFoo@@XZ"(%struct.Foo* noalias sret %agg.result) #0 !dbg !14 {
+entry:
+  %result.ptr = alloca i8*, align 8
+  %0 = bitcast %struct.Foo* %agg.result to i8*
+  store i8* %0, i8** %result.ptr, align 8
+  call void @llvm.dbg.declare(metadata i8** %result.ptr, metadata !28, metadata !DIExpression(DW_OP_deref)), !dbg !29
+  %x = getelementptr inbounds %struct.Foo, %struct.Foo* %agg.result, i32 0, i32 0, !dbg !30
+  store i32 41, i32* %x, align 4, !dbg !30
+  %x1 = getelementptr inbounds %struct.Foo, %struct.Foo* %agg.result, i32 0, i32 0, !dbg !31
+  %1 = load i32, i32* %x1, align 4, !dbg !31
+  call void @"?some_function@@YAXH@Z"(i32 %1), !dbg !31
+  ret void, !dbg !32
+}
+
+; Function Attrs: noinline norecurse nounwind optnone uwtable
+define dso_local i32 @main() #2 !dbg !33 {
+entry:
+  %retval = alloca i32, align 4
+  %bar = alloca %struct.Foo, align 4
+  store i32 0, i32* %retval, align 4
+  call void @llvm.dbg.declare(metadata %struct.Foo* %bar, metadata !36, metadata !DIExpression()), !dbg !37
+  call void @"?GetFoo@@YA?AUFoo@@XZ"(%struct.Foo* sret %bar), !dbg !37
+  %x = getelementptr inbounds %struct.Foo, %struct.Foo* %bar, i32 0, i32 0, !dbg !38
+  %0 = load i32, i32* %x, align 4, !dbg !38
+  ret i32 %0, !dbg !38
+}
+
+attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+cx8,+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+attributes #1 = { nounwind readnone speculatable }
+attributes #2 = { noinline norecurse nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"=

[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-19 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:908
 --EI;
 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");

rnk wrote:
> What I had in mind was to use this GEP as the ReturnValuePointer here. The 
> inalloca parameter is also a pointer to stack memory, and a GEP is an offset, 
> so it should end up being handled like a static alloca.
Oh, ok. I changed it, but not sure how to test debug info for the inalloca case


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-19 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 205712.
akhuang marked 2 inline comments as done.
akhuang added a comment.
Herald added a subscriber: javed.absar.

- fix alignment of pointer in inalloca case
- make existing tests stop failing by changing some and adding a check for 
existing return value alloca (I think?) before adding the ReturnValuePointer 
alloca


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/lib/CodeGen/CGDebugInfo.h
  clang/lib/CodeGen/CGDecl.cpp
  clang/lib/CodeGen/CodeGenFunction.cpp
  clang/lib/CodeGen/CodeGenFunction.h
  clang/test/CodeGen/arm64-microsoft-arguments.cpp
  clang/test/CodeGenCXX/conditional-gnu-ext.cpp
  clang/test/CodeGenCXX/debug-info-nrvo.cpp
  clang/test/CodeGenCXX/lambda-expressions.cpp
  clang/test/CodeGenObjC/objc-non-trivial-struct-nrvo.m
  debuginfo-tests/nrvo-string.cpp
  debuginfo-tests/win_cdb/nrvo.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/test/DebugInfo/COFF/nrvo.ll

Index: llvm/test/DebugInfo/COFF/nrvo.ll
===
--- /dev/null
+++ llvm/test/DebugInfo/COFF/nrvo.ll
@@ -0,0 +1,144 @@
+; RUN: llc < %s | FileCheck %s --check-prefix=ASM
+; RUN: llc < %s -filetype=obj | llvm-readobj - --codeview | FileCheck %s --check-prefix=OBJ
+
+; C++ source to regenerate:
+; struct Foo {
+;   Foo() = default;
+;   Foo(Foo &&other) { x = other.x; }
+;   int x;
+; };
+; void some_function(int);
+; Foo getFoo() {
+;   Foo foo;
+;   foo.x = 41;
+;   some_function(foo.x);
+;   return foo;
+; }
+;
+; int main() {
+;   Foo bar = getFoo();
+;   return bar.x;
+; }
+; $ clang t.cpp -S -emit-llvm -g -o t.ll
+
+; ASM-LABEL:  .long  241  # Symbol subsection for GetFoo 
+; ASM:.short 4414 # Record kind: S_LOCAL
+; ASM-NEXT:   .long 4113  # TypeIndex
+; ASM-NEXT:   .short 0# Flags
+; ASM-NEXT:   .asciz "foo"
+; ASM-NEXT:   .p2align 2
+; ASM-NEXT: .Ltmp
+; ASM:.cv_def_range  .Ltmp{{.*}} .Ltmp{{.*}}, "B\021(\000\000\000"
+
+; OBJ: Subsection [
+; OBJ:   SubSectionType: Symbols (0xF1)
+; OBJ:   LocalSym {
+; OBJ: Kind: S_LOCAL (0x113E)
+; OBJ: Type: Foo& (0x1011)
+; OBJ: Flags [ (0x0)
+; OBJ: ]
+; OBJ: VarName: foo
+; OBJ:   }
+; OBJ:   DefRangeFramePointerRelSym {
+; OBJ: Kind: S_DEFRANGE_FRAMEPOINTER_REL (0x1142)
+; OBJ: Offset: 40
+; OBJ: LocalVariableAddrRange {
+; OBJ:   OffsetStart: .text+0x1D
+; OBJ:   ISectStart: 0x0
+; OBJ:   Range: 0x16
+; OBJ:   }
+
+; ModuleID = 't.cpp'
+source_filename = "t.cpp"
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-pc-windows-msvc19.16.27030"
+
+%struct.Foo = type { i32 }
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local void @"?some_function@@YAXH@Z"(i32) #0 !dbg !8 {
+entry:
+  %.addr = alloca i32, align 4
+  store i32 %0, i32* %.addr, align 4
+  call void @llvm.dbg.declare(metadata i32* %.addr, metadata !12, metadata !DIExpression()), !dbg !13
+  ret void, !dbg !13
+}
+
+; Function Attrs: nounwind readnone speculatable
+declare void @llvm.dbg.declare(metadata, metadata, metadata) #1
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local void @"?GetFoo@@YA?AUFoo@@XZ"(%struct.Foo* noalias sret %agg.result) #0 !dbg !14 {
+entry:
+  %result.ptr = alloca i8*, align 8
+  %0 = bitcast %struct.Foo* %agg.result to i8*
+  store i8* %0, i8** %result.ptr, align 8
+  call void @llvm.dbg.declare(metadata i8** %result.ptr, metadata !28, metadata !DIExpression(DW_OP_deref)), !dbg !29
+  %x = getelementptr inbounds %struct.Foo, %struct.Foo* %agg.result, i32 0, i32 0, !dbg !30
+  store i32 41, i32* %x, align 4, !dbg !30
+  %x1 = getelementptr inbounds %struct.Foo, %struct.Foo* %agg.result, i32 0, i32 0, !dbg !31
+  %1 = load i32, i32* %x1, align 4, !dbg !31
+  call void @"?some_function@@YAXH@Z"(i32 %1), !dbg !31
+  ret void, !dbg !32
+}
+
+; Function Attrs: noinline norecurse nounwind optnone uwtable
+define dso_local i32 @main() #2 !dbg !33 {
+entry:
+  %retval = alloca i32, align 4
+  %bar = alloca %struct.Foo, align 4
+  store i32 0, i32* %retval, align 4
+  call void @llvm.dbg.declare(metadata %struct.Foo* %bar, metadata !36, metadata !DIExpression()), !dbg !37
+  call void @"?GetFoo@@YA?AUFoo@@XZ"(%struct.Foo* sret %bar), !dbg !37
+  %x = getelementptr inbounds %struct.Foo, %struct.Foo* %bar, i32 0, i32 0, !dbg !38
+  %0 = load i32, i32* %x, align 4, !dbg !38
+  ret i32 %0, !dbg !38
+}
+
+attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="f

[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-19 Thread Amy Huang via Phabricator via cfe-commits
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CodeGenFunction.cpp:908
 --EI;
 llvm::Value *Addr = Builder.CreateStructGEP(nullptr, &*EI, Idx);
 Addr = Builder.CreateAlignedLoad(Addr, getPointerAlign(), "agg.result");

rnk wrote:
> akhuang wrote:
> > rnk wrote:
> > > What I had in mind was to use this GEP as the ReturnValuePointer here. 
> > > The inalloca parameter is also a pointer to stack memory, and a GEP is an 
> > > offset, so it should end up being handled like a static alloca.
> > Oh, ok. I changed it, but not sure how to test debug info for the inalloca 
> > case
> I don't think this is the correct alignment. The sret slot in the inalloca 
> has a pointer type, so I think you want pointer alignment here. I think you 
> can substitute Int8PtrTy for RetTy here.
I suppose getPointerAlign() should work?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63361: Pretend NRVO variables are references so they can be found by debug info

2019-06-20 Thread Amy Huang via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was automatically updated to reflect the committed changes.
Closed by commit rL363952: Store a pointer to the return value in a static 
alloca and let the debugger use… (authored by akhuang, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D63361?vs=205712&id=205855#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63361/new/

https://reviews.llvm.org/D63361

Files:
  cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
  cfe/trunk/lib/CodeGen/CGDebugInfo.h
  cfe/trunk/lib/CodeGen/CGDecl.cpp
  cfe/trunk/lib/CodeGen/CodeGenFunction.cpp
  cfe/trunk/lib/CodeGen/CodeGenFunction.h
  cfe/trunk/test/CodeGen/arm64-microsoft-arguments.cpp
  cfe/trunk/test/CodeGenCXX/conditional-gnu-ext.cpp
  cfe/trunk/test/CodeGenCXX/debug-info-nrvo.cpp
  cfe/trunk/test/CodeGenCXX/lambda-expressions.cpp
  cfe/trunk/test/CodeGenObjC/objc-non-trivial-struct-nrvo.m
  debuginfo-tests/trunk/nrvo-string.cpp
  debuginfo-tests/trunk/win_cdb/nrvo.cpp
  llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/trunk/test/DebugInfo/COFF/nrvo.ll

Index: llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
===
--- llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
+++ llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
@@ -1142,9 +1142,15 @@
 // If the variable has an attached offset expression, extract it.
 // FIXME: Try to handle DW_OP_deref as well.
 int64_t ExprOffset = 0;
-if (VI.Expr)
-  if (!VI.Expr->extractIfOffset(ExprOffset))
+bool Deref = false;
+if (VI.Expr) {
+  // If there is one DW_OP_deref element, use offset of 0 and keep going.
+  if (VI.Expr->getNumElements() == 1 &&
+  VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref)
+Deref = true;
+  else if (!VI.Expr->extractIfOffset(ExprOffset))
 continue;
+}
 
 // Get the frame register used and the offset.
 unsigned FrameReg = 0;
@@ -1154,6 +1160,7 @@
 // Calculate the label ranges.
 LocalVarDefRange DefRange =
 createDefRangeMem(CVReg, FrameOffset + ExprOffset);
+
 for (const InsnRange &Range : Scope->getRanges()) {
   const MCSymbol *Begin = getLabelBeforeInsn(Range.first);
   const MCSymbol *End = getLabelAfterInsn(Range.second);
@@ -1164,6 +1171,9 @@
 LocalVariable Var;
 Var.DIVar = VI.Var;
 Var.DefRanges.emplace_back(std::move(DefRange));
+if (Deref)
+  Var.UseReferenceType = true;
+
 recordLocalVariable(std::move(Var), Scope);
   }
 }
Index: llvm/trunk/test/DebugInfo/COFF/nrvo.ll
===
--- llvm/trunk/test/DebugInfo/COFF/nrvo.ll
+++ llvm/trunk/test/DebugInfo/COFF/nrvo.ll
@@ -0,0 +1,144 @@
+; RUN: llc < %s | FileCheck %s --check-prefix=ASM
+; RUN: llc < %s -filetype=obj | llvm-readobj - --codeview | FileCheck %s --check-prefix=OBJ
+
+; C++ source to regenerate:
+; struct Foo {
+;   Foo() = default;
+;   Foo(Foo &&other) { x = other.x; }
+;   int x;
+; };
+; void some_function(int);
+; Foo getFoo() {
+;   Foo foo;
+;   foo.x = 41;
+;   some_function(foo.x);
+;   return foo;
+; }
+;
+; int main() {
+;   Foo bar = getFoo();
+;   return bar.x;
+; }
+; $ clang t.cpp -S -emit-llvm -g -o t.ll
+
+; ASM-LABEL:  .long  241  # Symbol subsection for GetFoo
+; ASM:.short 4414 # Record kind: S_LOCAL
+; ASM-NEXT:   .long 4113  # TypeIndex
+; ASM-NEXT:   .short 0# Flags
+; ASM-NEXT:   .asciz "foo"
+; ASM-NEXT:   .p2align 2
+; ASM-NEXT: .Ltmp
+; ASM:.cv_def_range  .Ltmp{{.*}} .Ltmp{{.*}}, "B\021(\000\000\000"
+
+; OBJ: Subsection [
+; OBJ:   SubSectionType: Symbols (0xF1)
+; OBJ:   LocalSym {
+; OBJ: Kind: S_LOCAL (0x113E)
+; OBJ: Type: Foo& (0x1011)
+; OBJ: Flags [ (0x0)
+; OBJ: ]
+; OBJ: VarName: foo
+; OBJ:   }
+; OBJ:   DefRangeFramePointerRelSym {
+; OBJ: Kind: S_DEFRANGE_FRAMEPOINTER_REL (0x1142)
+; OBJ: Offset: 40
+; OBJ: LocalVariableAddrRange {
+; OBJ:   OffsetStart: .text+0x1D
+; OBJ:   ISectStart: 0x0
+; OBJ:   Range: 0x16
+; OBJ:   }
+
+; ModuleID = 't.cpp'
+source_filename = "t.cpp"
+target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "x86_64-pc-windows-msvc19.16.27030"
+
+%struct.Foo = type { i32 }
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local void @"?some_function@@YAXH@Z"(i32) #0 !dbg !8 {
+entry:
+  %.addr = alloca i32, align 4
+  store i32 %0, i32* %.addr, align 4
+  call void @llvm.dbg.declare(metadata i32* %.addr, metadata !12, metadata !DIExpression()), !dbg !13
+  ret void, !dbg !13
+}
+
+; Function Attrs: nounwind readnone speculatable
+declare void @llvm.dbg.declare(metadata, metadata, metadata) #1
+
+; Function Attrs: noinline nounwind optnone uwtable
+define dso_local void @"?GetFoo@@YA?AUFoo@@XZ"

[PATCH] D64931: Change X86 datalayout for three address spaces that specify pointer sizes.

2019-08-08 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

The llvm-dev discussion is here 
http://lists.llvm.org/pipermail/llvm-dev/2019-July/134035.html
I think the consensus is that it should be fine to change the data layout.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64931/new/

https://reviews.llvm.org/D64931



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64931: Change X86 datalayout for three address spaces that specify pointer sizes.

2019-08-08 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

For some reason the tests were failing before without the datalayout change? 
I'm not sure why, but I changed them back and they're fine.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64931/new/

https://reviews.llvm.org/D64931



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64931: Change X86 datalayout for three address spaces that specify pointer sizes.

2019-08-08 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 214202.
akhuang added a comment.

Remove test case changes.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64931/new/

https://reviews.llvm.org/D64931

Files:
  clang/lib/Basic/Targets/OSTargets.h
  clang/lib/Basic/Targets/X86.h
  clang/test/CodeGen/iamcu-abi.c
  clang/test/CodeGen/target-data.c
  llvm/lib/Target/X86/X86TargetMachine.cpp

Index: llvm/lib/Target/X86/X86TargetMachine.cpp
===
--- llvm/lib/Target/X86/X86TargetMachine.cpp
+++ llvm/lib/Target/X86/X86TargetMachine.cpp
@@ -116,6 +116,9 @@
   !TT.isArch64Bit())
 Ret += "-p:32:32";
 
+  // Address spaces for 32 bit signed, 32 bit unsigned, and 64 bit pointers.
+  Ret += "-p253:32:32-p254:32:32-p255:64:64";
+
   // Some ABIs align 64 bit integers and doubles to 64 bits, others to 32.
   if (TT.isArch64Bit() || TT.isOSWindows() || TT.isOSNaCl())
 Ret += "-i64:64";
Index: clang/test/CodeGen/target-data.c
===
--- clang/test/CodeGen/target-data.c
+++ clang/test/CodeGen/target-data.c
@@ -1,22 +1,22 @@
 // RUN: %clang_cc1 -triple i686-unknown-unknown -emit-llvm -o - %s | \
 // RUN: FileCheck --check-prefix=I686-UNKNOWN %s
-// I686-UNKNOWN: target datalayout = "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128"
+// I686-UNKNOWN: target datalayout = "e-m:e-p:32:32-p253:32:32-p254:32:32-p255:64:64-f64:32:64-f80:32-n8:16:32-S128"
 
 // RUN: %clang_cc1 -triple i686-apple-darwin9 -emit-llvm -o - %s | \
 // RUN: FileCheck --check-prefix=I686-DARWIN %s
-// I686-DARWIN: target datalayout = "e-m:o-p:32:32-f64:32:64-f80:128-n8:16:32-S128"
+// I686-DARWIN: target datalayout = "e-m:o-p:32:32-p253:32:32-p254:32:32-p255:64:64-f64:32:64-f80:128-n8:16:32-S128"
 
 // RUN: %clang_cc1 -triple i686-unknown-win32 -emit-llvm -o - %s | \
 // RUN: FileCheck --check-prefix=I686-WIN32 %s
-// I686-WIN32: target datalayout = "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32"
+// I686-WIN32: target datalayout = "e-m:x-p:32:32-p253:32:32-p254:32:32-p255:64:64-i64:64-f80:32-n8:16:32-a:0:32-S32"
 
 // RUN: %clang_cc1 -triple i686-unknown-cygwin -emit-llvm -o - %s | \
 // RUN: FileCheck --check-prefix=I686-CYGWIN %s
-// I686-CYGWIN: target datalayout = "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32"
+// I686-CYGWIN: target datalayout = "e-m:x-p:32:32-p253:32:32-p254:32:32-p255:64:64-i64:64-f80:32-n8:16:32-a:0:32-S32"
 
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s | \
 // RUN: FileCheck --check-prefix=X86_64 %s
-// X86_64: target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
+// X86_64: target datalayout = "e-m:e-p253:32:32-p254:32:32-p255:64:64-i64:64-f80:128-n8:16:32:64-S128"
 
 // RUN: %clang_cc1 -triple xcore-unknown-unknown -emit-llvm -o - %s | \
 // RUN: FileCheck --check-prefix=XCORE %s
@@ -88,11 +88,11 @@
 
 // RUN: %clang_cc1 -triple i686-nacl -o - -emit-llvm %s | \
 // RUN: FileCheck %s -check-prefix=I686-NACL
-// I686-NACL: target datalayout = "e-m:e-p:32:32-i64:64-n8:16:32-S128"
+// I686-NACL: target datalayout = "e-m:e-p:32:32-p253:32:32-p254:32:32-p255:64:64-i64:64-n8:16:32-S128"
 
 // RUN: %clang_cc1 -triple x86_64-nacl -o - -emit-llvm %s | \
 // RUN: FileCheck %s -check-prefix=X86_64-NACL
-// X86_64-NACL: target datalayout = "e-m:e-p:32:32-i64:64-n8:16:32:64-S128"
+// X86_64-NACL: target datalayout = "e-m:e-p:32:32-p253:32:32-p254:32:32-p255:64:64-i64:64-n8:16:32:64-S128"
 
 // RUN: %clang_cc1 -triple arm-nacl -o - -emit-llvm %s | \
 // RUN: FileCheck %s -check-prefix=ARM-NACL
Index: clang/test/CodeGen/iamcu-abi.c
===
--- clang/test/CodeGen/iamcu-abi.c
+++ clang/test/CodeGen/iamcu-abi.c
@@ -1,6 +1,6 @@
 // RUN: %clang_cc1 -triple i386-pc-elfiamcu -emit-llvm -o - %s | FileCheck %s
 
-// CHECK: target datalayout = "e-m:e-p:32:32-i64:32-f64:32-f128:32-n8:16:32-a:0:32-S32"
+// CHECK: target datalayout = "e-m:e-p:32:32-p253:32:32-p254:32:32-p255:64:64-i64:32-f64:32-f128:32-n8:16:32-a:0:32-S32"
 // CHECK: target triple = "i386-pc-elfiamcu"
 
 
Index: clang/lib/Basic/Targets/X86.h
===
--- clang/lib/Basic/Targets/X86.h
+++ clang/lib/Basic/Targets/X86.h
@@ -340,7 +340,7 @@
 LongDoubleWidth = 96;
 LongDoubleAlign = 32;
 SuitableAlign = 128;
-resetDataLayout("e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128");
+resetDataLayout("e-m:e-p:32:32-p253:32:32-p254:32:32-p255:64:64-f64:32:64-f80:32-n8:16:32-S128");
 SizeType = UnsignedInt;
 PtrDiffType = SignedInt;
 IntPtrType = SignedInt;
@@ -440,7 +440,7 @@
   UseSignedCharForObjCBool = false;
 SizeType = UnsignedLong;
 IntPtrType = SignedLong;
-resetDataLayout("e-m:o-p:32:32-f64:32:64-f80:128-n8:16:32-S128");
+resetDataLayout("e-m:o-p:32:32-p253:32:32-p254:32:32-p255:64:64-f64:32:64-f80:128-n8:1

[PATCH] D64931: Change X86 datalayout for three address spaces that specify pointer sizes.

2019-08-08 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

@lebedev.ri The test case datalayout strings were changed because somewhere 
llvm asserts that the string in the IR matches the backend datalayout. I don't 
know why I wasn't getting the assert error now, but I think they'll all have to 
be changed if we change the X86 datalayout?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64931/new/

https://reviews.llvm.org/D64931



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64931: Change X86 datalayout for three address spaces that specify pointer sizes.

2019-08-08 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

> Can you post a reproducer?

Turns out I just didn't have assertions enabled. With assertions the changed 
test cases should fail.

> I think this is precisely what was discussed in replies to RFC - this 
> hardcodes these address spaces, and thus either makes them unavaliable for 
> other front-ends and/or forces them to use them with Precisely Same Meaning.

It seems like the RFC replies agreed that this should be implemented with 
address spaces, and that the information for these is encoded in the data 
layout. I think there was some confusion as to whether there would be more 
changes in addition to the data layout change?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64931/new/

https://reviews.llvm.org/D64931



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D64931: Change X86 datalayout for three address spaces that specify pointer sizes.

2019-08-16 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

> Address space have backend defined semantics, and aren’t really reserved for 
> front end use. I think the fact that non-0 address spaces on X86 codegen the 
> same as address space 0 and could be used for something by a front end is an 
> accident of how SelectionDAG is implemented. If X86 wants to reserve address 
> space ranges for frontend use, that would need to be decided and documented. 
> You don’t necessarily get the current behavior for free in GlobalISel since 
> pointer types are distinct, so this would specifically need to be implemented.

By this do you mean that this would be an instance of address spaces being used 
by the frontend? Or just that adding meaning to address spaces shouldn't be 
breaking other frontends?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D64931/new/

https://reviews.llvm.org/D64931



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63625: [CodeGen][test] Use -fno-discard-value-names for better test support

2019-06-20 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

Looks good, alternatively I think we can just change `%result.ptr` into a 
variable match?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63625/new/

https://reviews.llvm.org/D63625



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63625: [CodeGen][test] Use -fno-discard-value-names for better test support

2019-06-20 Thread Amy Huang via Phabricator via cfe-commits
akhuang added a comment.

> Why isn't this using FileCheck variable matching in the first place? That's 
> the least fragile solution.

No reason, just something I overlooked when I wrote it-


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63625/new/

https://reviews.llvm.org/D63625



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D63625: [CodeGen][test] Use -fno-discard-value-names for better test support

2019-06-20 Thread Amy Huang via Phabricator via cfe-commits
akhuang accepted this revision.
akhuang added a comment.
This revision is now accepted and ready to land.

lgtm


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D63625/new/

https://reviews.llvm.org/D63625



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62167: CodeView - add static data members to global variable debug info.

2019-05-20 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
akhuang added a reviewer: rnk.
Herald added subscribers: llvm-commits, cfe-commits, aprantl.
Herald added projects: clang, LLVM.

Add static data members to IR debug info's list of global variables
so that they are emitted as S_CONSTANT records.

Related to https://bugs.llvm.org/show_bug.cgi?id=41615.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D62167

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  llvm/test/DebugInfo/COFF/global-constants.ll

Index: llvm/test/DebugInfo/COFF/global-constants.ll
===
--- llvm/test/DebugInfo/COFF/global-constants.ll
+++ llvm/test/DebugInfo/COFF/global-constants.ll
@@ -3,18 +3,25 @@
 
 ; C++ source to regenerate:
 ; const int Test1 = 1;
+; struct Foo { static const int Test2 = 2; };
 ; int main() {
-;   return Test1;
+;   return Test1 + Foo::Test2;
 ; }
 ; $ clang t.cpp -S -emit-llvm -g -gcodeview -o t.ll
 
-; ASM-LABEL:  .long 241  # Symbol subsection for globals
+; ASM-LABEL:  .long 241 # Symbol subsection for globals
 
-; ASM:.short {{.*-.*}}   # Record length
-; ASM:.short 4359# Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4099 # Type
-; ASM-NEXT:   .byte 0x01, 0x00   # Value
-; ASM-NEXT:   .asciz "Test1" # Name
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4099# Type
+; ASM-NEXT:   .byte 0x01, 0x00  # Value
+; ASM-NEXT:   .asciz "Test1"# Name
+
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM:.long 4099# Type
+; ASM:.byte 0x02, 0x00  # Value
+; ASM:.asciz "Test2"# Name
 
 ; OBJ:CodeViewDebugInfo [
 ; OBJ:  Section: .debug$S
@@ -27,6 +34,12 @@
 ; OBJ-NEXT: Value: 1
 ; OBJ-NEXT: Name: Test1
 ; OBJ-NEXT:   }
+; OBJ:ConstantSym {
+; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
+; OBJ-NEXT: Type: const int (0x1003)
+; OBJ-NEXT: Value: 2
+; OBJ-NEXT: Name: Test2
+; OBJ-NEXT:   }
 
 ; ModuleID = 't.cpp'
 source_filename = "t.cpp"
@@ -34,31 +47,39 @@
 target triple = "x86_64-pc-windows-msvc"
 
 ; Function Attrs: noinline norecurse nounwind optnone
-define dso_local i32 @main() #0 !dbg !13 {
+define dso_local i32 @main() #0 !dbg !19 {
 entry:
   %retval = alloca i32, align 4
   store i32 0, i32* %retval, align 4
-  ret i32 1, !dbg !16
+  ret i32 3, !dbg !22
 }
 
+attributes #0 = { noinline norecurse nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+
 !llvm.dbg.cu = !{!0}
-!llvm.module.flags = !{!9, !10, !11}
-!llvm.ident = !{!12}
+!llvm.module.flags = !{!15, !16, !17}
+!llvm.ident = !{!18}
 
-!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4a1902b6739e3087a03c0ac7ab85b640764e9335)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, globals: !3, nameTableKind: None)
-!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "0d5ef00bdd80bdb409a3deac9938f20d")
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 2b66a49044196d8b90d95d7d3b5246ccbe3abc05)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, retainedTypes: !3, globals: !10, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "77cff5e1c7b260440ed03b23c18809c3")
 !2 = !{}
 !3 = !{!4}
-!4 = !DIGlobalVariableExpression(var: !5, expr: !DIExpression(DW_OP_constu, 1, DW_OP_stack_value))
-!5 = distinct !DIGlobalVariable(name: "Test1", scope: !0, file: !6, line: 1, type: !7, isLocal: true, isDefinition: true)
-!6 = !DIFile(filename: "t.cpp", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "0d5ef00bdd80bdb409a3deac9938f20d")
-!7 = !DIDerivedType(tag: DW_TAG_const_type, baseType: !8)
-!8 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
-!9 = !{i32 2, !"CodeView", i32 1}
-!10 = !{i32 2, !"Debug Info Version", i32 3}
-!11 = !{i32 1, !"wchar_size", i32 2}
-!12 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4a1902b6739e3087a03c0ac7ab85b640764e9335)"}
-!13 = distinct !DISubprogram(name: "main", scope: !6, file: !6, line: 3, type: !14, scopeLine: 3, flags: DIFlagPrototype

[PATCH] D62214: Remove extra if case.

2019-05-21 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D62214

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp


Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -4348,16 +4348,14 @@
   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
   StringRef Name = VD->getName();
   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
+
+  // Do not use global variables for enums.
   if (const auto *ECD = dyn_cast(VD)) {
 const auto *ED = cast(ECD->getDeclContext());
 assert(isa(ED->getTypeForDecl()) && "Enum without EnumType?");
-Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
-  }
-  // Do not use global variables for enums.
-  //
-  // FIXME: why not?
-  if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
 return;
+  }
+
   // Do not emit separate definitions for function local const/statics.
   if (isa(VD->getDeclContext()))
 return;


Index: clang/lib/CodeGen/CGDebugInfo.cpp
===
--- clang/lib/CodeGen/CGDebugInfo.cpp
+++ clang/lib/CodeGen/CGDebugInfo.cpp
@@ -4348,16 +4348,14 @@
   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
   StringRef Name = VD->getName();
   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
+
+  // Do not use global variables for enums.
   if (const auto *ECD = dyn_cast(VD)) {
 const auto *ED = cast(ECD->getDeclContext());
 assert(isa(ED->getTypeForDecl()) && "Enum without EnumType?");
-Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
-  }
-  // Do not use global variables for enums.
-  //
-  // FIXME: why not?
-  if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
 return;
+  }
+
   // Do not emit separate definitions for function local const/statics.
   if (isa(VD->getDeclContext()))
 return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62167: CodeView - add static data members to global variable debug info.

2019-05-21 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added a subscriber: dblaikie.
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:4385
+// Use the global scope for static members.
+DContext = getContextDescriptor(
+   cast(CGM.getContext().getTranslationUnitDecl()), TheCU);

@dblaikie I'm using the global scope here because if the class type is used as 
the scope it runs into the [[ 
https://github.com/llvm/llvm-project/blob/a2ee80b084e5c0b20364ed4379384706f5e059b1/llvm/lib/IR/DIBuilder.cpp#L630
 | assert message ]] `Context of a global variable should not be a type with 
identifier`. Is there a reason for the assert? 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62167/new/

https://reviews.llvm.org/D62167



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62214: Remove extra if case.

2019-05-22 Thread Amy Huang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL361400: Combine two if cases because the second one is never 
reached. (authored by akhuang, committed by ).
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Changed prior to commit:
  https://reviews.llvm.org/D62214?vs=200558&id=200765#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62214/new/

https://reviews.llvm.org/D62214

Files:
  cfe/trunk/lib/CodeGen/CGDebugInfo.cpp


Index: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
===
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
@@ -4352,16 +4352,14 @@
   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
   StringRef Name = VD->getName();
   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
+
+  // Do not use global variables for enums.
   if (const auto *ECD = dyn_cast(VD)) {
 const auto *ED = cast(ECD->getDeclContext());
 assert(isa(ED->getTypeForDecl()) && "Enum without EnumType?");
-Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
-  }
-  // Do not use global variables for enums.
-  //
-  // FIXME: why not?
-  if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
 return;
+  }
+
   // Do not emit separate definitions for function local const/statics.
   if (isa(VD->getDeclContext()))
 return;


Index: cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
===
--- cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
+++ cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
@@ -4352,16 +4352,14 @@
   llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
   StringRef Name = VD->getName();
   llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
+
+  // Do not use global variables for enums.
   if (const auto *ECD = dyn_cast(VD)) {
 const auto *ED = cast(ECD->getDeclContext());
 assert(isa(ED->getTypeForDecl()) && "Enum without EnumType?");
-Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
-  }
-  // Do not use global variables for enums.
-  //
-  // FIXME: why not?
-  if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
 return;
+  }
+
   // Do not emit separate definitions for function local const/statics.
   if (isa(VD->getDeclContext()))
 return;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62167: CodeView - add static data members to global variable debug info.

2019-05-23 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 201004.
akhuang added a comment.

Add llvm IR test.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62167/new/

https://reviews.llvm.org/D62167

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/debug-info-static-member.cpp
  llvm/test/DebugInfo/COFF/global-constants.ll

Index: llvm/test/DebugInfo/COFF/global-constants.ll
===
--- llvm/test/DebugInfo/COFF/global-constants.ll
+++ llvm/test/DebugInfo/COFF/global-constants.ll
@@ -3,18 +3,25 @@
 
 ; C++ source to regenerate:
 ; const int Test1 = 1;
+; struct Foo { static const int Test2 = 2; };
 ; int main() {
-;   return Test1;
+;   return Test1 + Foo::Test2;
 ; }
 ; $ clang t.cpp -S -emit-llvm -g -gcodeview -o t.ll
 
-; ASM-LABEL:  .long 241  # Symbol subsection for globals
+; ASM-LABEL:  .long 241 # Symbol subsection for globals
 
-; ASM:.short {{.*-.*}}   # Record length
-; ASM:.short 4359# Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4099 # Type
-; ASM-NEXT:   .byte 0x01, 0x00   # Value
-; ASM-NEXT:   .asciz "Test1" # Name
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4099# Type
+; ASM-NEXT:   .byte 0x01, 0x00  # Value
+; ASM-NEXT:   .asciz "Test1"# Name
+
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM:.long 4099# Type
+; ASM:.byte 0x02, 0x00  # Value
+; ASM:.asciz "Test2"# Name
 
 ; OBJ:CodeViewDebugInfo [
 ; OBJ:  Section: .debug$S
@@ -27,6 +34,12 @@
 ; OBJ-NEXT: Value: 1
 ; OBJ-NEXT: Name: Test1
 ; OBJ-NEXT:   }
+; OBJ:ConstantSym {
+; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
+; OBJ-NEXT: Type: const int (0x1003)
+; OBJ-NEXT: Value: 2
+; OBJ-NEXT: Name: Test2
+; OBJ-NEXT:   }
 
 ; ModuleID = 't.cpp'
 source_filename = "t.cpp"
@@ -34,31 +47,39 @@
 target triple = "x86_64-pc-windows-msvc"
 
 ; Function Attrs: noinline norecurse nounwind optnone
-define dso_local i32 @main() #0 !dbg !13 {
+define dso_local i32 @main() #0 !dbg !19 {
 entry:
   %retval = alloca i32, align 4
   store i32 0, i32* %retval, align 4
-  ret i32 1, !dbg !16
+  ret i32 3, !dbg !22
 }
 
+attributes #0 = { noinline norecurse nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+
 !llvm.dbg.cu = !{!0}
-!llvm.module.flags = !{!9, !10, !11}
-!llvm.ident = !{!12}
+!llvm.module.flags = !{!15, !16, !17}
+!llvm.ident = !{!18}
 
-!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4a1902b6739e3087a03c0ac7ab85b640764e9335)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, globals: !3, nameTableKind: None)
-!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "0d5ef00bdd80bdb409a3deac9938f20d")
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 2b66a49044196d8b90d95d7d3b5246ccbe3abc05)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, retainedTypes: !3, globals: !10, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "77cff5e1c7b260440ed03b23c18809c3")
 !2 = !{}
 !3 = !{!4}
-!4 = !DIGlobalVariableExpression(var: !5, expr: !DIExpression(DW_OP_constu, 1, DW_OP_stack_value))
-!5 = distinct !DIGlobalVariable(name: "Test1", scope: !0, file: !6, line: 1, type: !7, isLocal: true, isDefinition: true)
-!6 = !DIFile(filename: "t.cpp", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "0d5ef00bdd80bdb409a3deac9938f20d")
-!7 = !DIDerivedType(tag: DW_TAG_const_type, baseType: !8)
-!8 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
-!9 = !{i32 2, !"CodeView", i32 1}
-!10 = !{i32 2, !"Debug Info Version", i32 3}
-!11 = !{i32 1, !"wchar_size", i32 2}
-!12 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4a1902b6739e3087a03c0ac7ab85b640764e9335)"}
-!13 = distinct !DISubprogram(name: "main", scope: !6, file: !6, line: 3, type: !14, scopeLine: 3, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
-!14 = !DISubroutineType(types: !15)
-!15 = !{!8}
-!16 = !DILoca

[PATCH] D62167: CodeView - add static data members to global variable debug info.

2019-05-23 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:4385
+// Use the global scope for static members.
+DContext = getContextDescriptor(
+   cast(CGM.getContext().getTranslationUnitDecl()), TheCU);

dblaikie wrote:
> akhuang wrote:
> > @dblaikie I'm using the global scope here because if the class type is used 
> > as the scope it runs into the [[ 
> > https://github.com/llvm/llvm-project/blob/a2ee80b084e5c0b20364ed4379384706f5e059b1/llvm/lib/IR/DIBuilder.cpp#L630
> >  | assert message ]] `Context of a global variable should not be a type 
> > with identifier`. Is there a reason for the assert? 
> I think it's generally how LLVM handles definitions for the most part - 
> putting them at the global scope.
> 
> Though I'm confused by this patch - it has a source change in clang, but a 
> test in LLVM. Generally there should be testing to cover where the source 
> change is, I think?
yep, there should be a test for this - added now. 


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62167/new/

https://reviews.llvm.org/D62167



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62167: CodeView - add static data members to global variable debug info.

2019-05-24 Thread Amy Huang via Phabricator via cfe-commits
akhuang marked an inline comment as done.
akhuang added inline comments.



Comment at: clang/lib/CodeGen/CGDebugInfo.cpp:4385
+// Use the global scope for static members.
+DContext = getContextDescriptor(
+   cast(CGM.getContext().getTranslationUnitDecl()), TheCU);

akhuang wrote:
> dblaikie wrote:
> > akhuang wrote:
> > > @dblaikie I'm using the global scope here because if the class type is 
> > > used as the scope it runs into the [[ 
> > > https://github.com/llvm/llvm-project/blob/a2ee80b084e5c0b20364ed4379384706f5e059b1/llvm/lib/IR/DIBuilder.cpp#L630
> > >  | assert message ]] `Context of a global variable should not be a type 
> > > with identifier`. Is there a reason for the assert? 
> > I think it's generally how LLVM handles definitions for the most part - 
> > putting them at the global scope.
> > 
> > Though I'm confused by this patch - it has a source change in clang, but a 
> > test in LLVM. Generally there should be testing to cover where the source 
> > change is, I think?
> yep, there should be a test for this - added now. 
So for the global scope, it seems like [[ 
https://github.com/llvm-mirror/clang/blob/900624ef605b60c613342dac071228539a402ce9/lib/CodeGen/CGDebugInfo.cpp#L3274
 | elsewhere ]], when creating the debug info for a static data member global 
variable, the scope is set to be the global scope. But it would be helpful for 
codeview debug info if the scope remained as the class type, partially so we 
can use the class type information in the variable name that we emit.

Does it seem reasonable to remove the assert for global variable scope so that 
the scope can be the class here?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62167/new/

https://reviews.llvm.org/D62167



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D62167: CodeView - add static data members to global variable debug info.

2019-05-29 Thread Amy Huang via Phabricator via cfe-commits
akhuang updated this revision to Diff 202027.
akhuang added a comment.
Herald added a subscriber: hiraditya.

Append class name to static data member debug info name.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62167/new/

https://reviews.llvm.org/D62167

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/debug-info-static-member.cpp
  llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/test/DebugInfo/COFF/global-constants.ll

Index: llvm/test/DebugInfo/COFF/global-constants.ll
===
--- llvm/test/DebugInfo/COFF/global-constants.ll
+++ llvm/test/DebugInfo/COFF/global-constants.ll
@@ -3,18 +3,25 @@
 
 ; C++ source to regenerate:
 ; const int Test1 = 1;
+; struct Foo { static const int Test2 = 2; };
 ; int main() {
-;   return Test1;
+;   return Test1 + Foo::Test2;
 ; }
 ; $ clang t.cpp -S -emit-llvm -g -gcodeview -o t.ll
 
-; ASM-LABEL:  .long 241  # Symbol subsection for globals
+; ASM-LABEL:  .long 241 # Symbol subsection for globals
 
-; ASM:.short {{.*-.*}}   # Record length
-; ASM:.short 4359# Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4099 # Type
-; ASM-NEXT:   .byte 0x01, 0x00   # Value
-; ASM-NEXT:   .asciz "Test1" # Name
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4099# Type
+; ASM-NEXT:   .byte 0x01, 0x00  # Value
+; ASM-NEXT:   .asciz "Test1"# Name
+
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM:.long 4099# Type
+; ASM:.byte 0x02, 0x00  # Value
+; ASM:.asciz "Foo::Test2"   # Name
 
 ; OBJ:CodeViewDebugInfo [
 ; OBJ:  Section: .debug$S
@@ -27,6 +34,12 @@
 ; OBJ-NEXT: Value: 1
 ; OBJ-NEXT: Name: Test1
 ; OBJ-NEXT:   }
+; OBJ:ConstantSym {
+; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
+; OBJ-NEXT: Type: const int (0x1003)
+; OBJ-NEXT: Value: 2
+; OBJ-NEXT: Name: Foo::Test2
+; OBJ-NEXT:   }
 
 ; ModuleID = 't.cpp'
 source_filename = "t.cpp"
@@ -34,31 +47,39 @@
 target triple = "x86_64-pc-windows-msvc"
 
 ; Function Attrs: noinline norecurse nounwind optnone
-define dso_local i32 @main() #0 !dbg !13 {
+define dso_local i32 @main() #0 !dbg !19 {
 entry:
   %retval = alloca i32, align 4
   store i32 0, i32* %retval, align 4
-  ret i32 1, !dbg !16
+  ret i32 3, !dbg !22
 }
 
+attributes #0 = { noinline norecurse nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+
 !llvm.dbg.cu = !{!0}
-!llvm.module.flags = !{!9, !10, !11}
-!llvm.ident = !{!12}
+!llvm.module.flags = !{!15, !16, !17}
+!llvm.ident = !{!18}
 
-!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4a1902b6739e3087a03c0ac7ab85b640764e9335)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, globals: !3, nameTableKind: None)
-!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "0d5ef00bdd80bdb409a3deac9938f20d")
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 2b66a49044196d8b90d95d7d3b5246ccbe3abc05)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, retainedTypes: !3, globals: !10, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "77cff5e1c7b260440ed03b23c18809c3")
 !2 = !{}
 !3 = !{!4}
-!4 = !DIGlobalVariableExpression(var: !5, expr: !DIExpression(DW_OP_constu, 1, DW_OP_stack_value))
-!5 = distinct !DIGlobalVariable(name: "Test1", scope: !0, file: !6, line: 1, type: !7, isLocal: true, isDefinition: true)
-!6 = !DIFile(filename: "t.cpp", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "0d5ef00bdd80bdb409a3deac9938f20d")
-!7 = !DIDerivedType(tag: DW_TAG_const_type, baseType: !8)
-!8 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
-!9 = !{i32 2, !"CodeView", i32 1}
-!10 = !{i32 2, !"Debug Info Version", i32 3}
-!11 = !{i32 1, !"wchar_size", i32 2}
-!12 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4a1902b6739e3087a03c0ac7ab85b640764e9335)"}
-!13 = distinct !DISubprogram(name: "main", scope: !6, file: !6, line: 3, type: !14, scopeLine: 3, flags: DIFlagProt

[PATCH] D62167: CodeView - add static data members to global variable debug info.

2019-05-29 Thread Amy Huang via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rL362038: CodeView - add static data members to global 
variable debug info. (authored by akhuang, committed by ).

Changed prior to commit:
  https://reviews.llvm.org/D62167?vs=202027&id=202063#toc

Repository:
  rL LLVM

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D62167/new/

https://reviews.llvm.org/D62167

Files:
  cfe/trunk/lib/CodeGen/CGDebugInfo.cpp
  cfe/trunk/test/CodeGenCXX/debug-info-static-member.cpp
  llvm/trunk/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp
  llvm/trunk/test/DebugInfo/COFF/global-constants.ll

Index: llvm/trunk/test/DebugInfo/COFF/global-constants.ll
===
--- llvm/trunk/test/DebugInfo/COFF/global-constants.ll
+++ llvm/trunk/test/DebugInfo/COFF/global-constants.ll
@@ -3,18 +3,25 @@
 
 ; C++ source to regenerate:
 ; const int Test1 = 1;
+; struct Foo { static const int Test2 = 2; };
 ; int main() {
-;   return Test1;
+;   return Test1 + Foo::Test2;
 ; }
 ; $ clang t.cpp -S -emit-llvm -g -gcodeview -o t.ll
 
-; ASM-LABEL:  .long 241  # Symbol subsection for globals
+; ASM-LABEL:  .long 241 # Symbol subsection for globals
 
-; ASM:.short {{.*-.*}}   # Record length
-; ASM:.short 4359# Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4099 # Type
-; ASM-NEXT:   .byte 0x01, 0x00   # Value
-; ASM-NEXT:   .asciz "Test1" # Name
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4099# Type
+; ASM-NEXT:   .byte 0x01, 0x00  # Value
+; ASM-NEXT:   .asciz "Test1"# Name
+
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM:.long 4099# Type
+; ASM:.byte 0x02, 0x00  # Value
+; ASM:.asciz "Foo::Test2"   # Name
 
 ; OBJ:CodeViewDebugInfo [
 ; OBJ:  Section: .debug$S
@@ -27,6 +34,12 @@
 ; OBJ-NEXT: Value: 1
 ; OBJ-NEXT: Name: Test1
 ; OBJ-NEXT:   }
+; OBJ:ConstantSym {
+; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
+; OBJ-NEXT: Type: const int (0x1003)
+; OBJ-NEXT: Value: 2
+; OBJ-NEXT: Name: Foo::Test2
+; OBJ-NEXT:   }
 
 ; ModuleID = 't.cpp'
 source_filename = "t.cpp"
@@ -34,31 +47,39 @@
 target triple = "x86_64-pc-windows-msvc"
 
 ; Function Attrs: noinline norecurse nounwind optnone
-define dso_local i32 @main() #0 !dbg !13 {
+define dso_local i32 @main() #0 !dbg !19 {
 entry:
   %retval = alloca i32, align 4
   store i32 0, i32* %retval, align 4
-  ret i32 1, !dbg !16
+  ret i32 3, !dbg !22
 }
 
+attributes #0 = { noinline norecurse nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-features"="+cx8,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" }
+
 !llvm.dbg.cu = !{!0}
-!llvm.module.flags = !{!9, !10, !11}
-!llvm.ident = !{!12}
+!llvm.module.flags = !{!15, !16, !17}
+!llvm.ident = !{!18}
 
-!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4a1902b6739e3087a03c0ac7ab85b640764e9335)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, globals: !3, nameTableKind: None)
-!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "0d5ef00bdd80bdb409a3deac9938f20d")
+!0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus, file: !1, producer: "clang version 9.0.0 (https://github.com/llvm/llvm-project.git 2b66a49044196d8b90d95d7d3b5246ccbe3abc05)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, retainedTypes: !3, globals: !10, nameTableKind: None)
+!1 = !DIFile(filename: "", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "77cff5e1c7b260440ed03b23c18809c3")
 !2 = !{}
 !3 = !{!4}
-!4 = !DIGlobalVariableExpression(var: !5, expr: !DIExpression(DW_OP_constu, 1, DW_OP_stack_value))
-!5 = distinct !DIGlobalVariable(name: "Test1", scope: !0, file: !6, line: 1, type: !7, isLocal: true, isDefinition: true)
-!6 = !DIFile(filename: "t.cpp", directory: "C:\5Csrc\5Ctest", checksumkind: CSK_MD5, checksum: "0d5ef00bdd80bdb409a3deac9938f20d")
-!7 = !DIDerivedType(tag: DW_TAG_const_type, baseType: !8)
-!8 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
-!9 = !{i32 2, !"CodeView", i32 1}
-!10 = !{i32 2, !"Debug Info Version", i32 3}
-!11 = !{i32 1, !"wchar_size", i32 2}
-!12 = !{!"clang version 9.0.0 (https://github.com/llvm/llvm-project.git 4a1902b6739e3087

[PATCH] D62635: Add enums as global variables in the IR metadata.

2019-05-29 Thread Amy Huang via Phabricator via cfe-commits
akhuang created this revision.
akhuang added a reviewer: rnk.
Herald added subscribers: llvm-commits, cfe-commits, aprantl.
Herald added projects: clang, LLVM.

Keeps track of the enums that were used by saving them as DIGlobalVariables,
since CodeView emits debug info for global constants.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D62635

Files:
  clang/lib/CodeGen/CGDebugInfo.cpp
  clang/test/CodeGenCXX/debug-info-enum.cpp
  llvm/test/DebugInfo/COFF/global-constants.ll

Index: llvm/test/DebugInfo/COFF/global-constants.ll
===
--- llvm/test/DebugInfo/COFF/global-constants.ll
+++ llvm/test/DebugInfo/COFF/global-constants.ll
@@ -2,26 +2,41 @@
 ; RUN: llc < %s -filetype=obj | llvm-readobj - --codeview | FileCheck %s --check-prefix=OBJ
 
 ; C++ source to regenerate:
-; const int Test1 = 1;
-; struct Foo { static const int Test2 = 2; };
-; int main() {
-;   return Test1 + Foo::Test2;
+; const float TestConst1 = 3.14;
+; struct S {
+;   static const int TestConst2 = -10;
+; }
+; enum TestEnum : int {
+;ENUM_A = 214700,
+;ENUM_B = -214700,
+; };
+; void useConst(int);
+; void foo() {
+;   useConst(TestConst1);
+;   useConst(S::TestConst2);
+;   useConst(ENUM_B);
 ; }
 ; $ clang t.cpp -S -emit-llvm -g -gcodeview -o t.ll
 
-; ASM-LABEL:  .long 241 # Symbol subsection for globals
-
-; ASM:.short {{.*-.*}}  # Record length
-; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM-NEXT:   .long 4099# Type
-; ASM-NEXT:   .byte 0x01, 0x00  # Value
-; ASM-NEXT:   .asciz "Test1"# Name
-
-; ASM:.short {{.*-.*}}  # Record length
-; ASM:.short 4359   # Record kind: S_CONSTANT
-; ASM:.long 4099# Type
-; ASM:.byte 0x02, 0x00  # Value
-; ASM:.asciz "Foo::Test2"   # Name
+; ASM-LABEL:  .long 241 # Symbol subsection for globals
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4099# Type
+; ASM-NEXT:   .byte 0x04, 0x80, 0xc3, 0xf5  # Value
+; ASM-NEXT:   .byte 0x48, 0x40
+; ASM-NEXT:   .asciz "TestConst1"   # Name
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4100# Type
+; ASM-NEXT:   .byte 0x61, 0x00  # Value
+; ASM-NEXT:   .asciz "S::TestConst2"# Name
+; ASM:.short {{.*-.*}}  # Record length
+; ASM:.short 4359   # Record kind: S_CONSTANT
+; ASM-NEXT:   .long 4102# Type
+; ASM-NEXT:   .byte 0x0a, 0x80, 0x40, 0x61  # Value
+; ASM-NEXT:   .byte 0x07, 0x80, 0xff, 0xff
+; ASM-NEXT:   .byte 0xff, 0xff
+; ASM-NEXT:   .asciz "ENUM_B"   # Name
 
 ; OBJ:CodeViewDebugInfo [
 ; OBJ:  Section: .debug$S
@@ -30,56 +45,77 @@
 ; OBJ:SubSectionType: Symbols (0xF1)
 ; OBJ:ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: const int (0x1003)
-; OBJ-NEXT: Value: 1
-; OBJ-NEXT: Name: Test1
+; OBJ-NEXT: Type: const float (0x1003)
+; OBJ-NEXT: Value: 1078523331
+; OBJ-NEXT: Name: TestConst1
 ; OBJ-NEXT:   }
-; OBJ:ConstantSym {
+; OBJ-NEXT:   ConstantSym {
 ; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
-; OBJ-NEXT: Type: const int (0x1003)
-; OBJ-NEXT: Value: 2
-; OBJ-NEXT: Name: Foo::Test2
+; OBJ-NEXT: Type: const char (0x1004)
+; OBJ-NEXT: Value: 97
+; OBJ-NEXT: Name: S::TestConst2
 ; OBJ-NEXT:   }
+; OBJ-NEXT:   ConstantSym {
+; OBJ-NEXT: Kind: S_CONSTANT (0x1107)
+; OBJ-NEXT: Type: TestEnum (0x1006)
+; OBJ-NEXT: Value: 18446744071562551616
+; OBJ-NEXT: Name: ENUM_B
+; OBJ-NEXT:   }
+
 
 ; ModuleID = 't.cpp'
 source_filename = "t.cpp"
 target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
-target triple = "x86_64-pc-windows-msvc"
+target triple = "x86_64-w64-windows-gnu"
 
-; Function Attrs: noinline norecurse nounwind optnone
-define dso_local i32 @main() #0 !dbg !19 {
+; Function Attrs: noinline nounwind optnone
+define dso_local void @_Z3foov() #0 !dbg !28 {
 entry:
-  %retval = alloca i32, align 4
-  store i32 0, i32* %retval, align 4
-  ret i32 3, !dbg !22
+  call void @_Z8useConsti(i32 3), !dbg !32
+  call void @_Z8useConsti(i32 97), !dbg !33
+  call void @_Z8useConsti(i32 -214700), !dbg !34
+  ret void, !dbg !35
 }
 
-attributes #0 = { noinline norecurse nounwind optnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "n

  1   2   3   4   5   >