text:
import os, sys, math
import numpy as np
import scipy
import pylab
from subprocess import call
import scipy.optimize
from scipy.interpolate import UnivariateSpline
import lib.LammpsIO as lmp_io
import lib.DataAnalysis as da
import lib.DataMorphing as dm
import shutil
# We only need one potential to be optimised, so will use interaction_list_from_file
# This will require the user to supply a file with the potential being optimised.

def generate_interaction_list(num_of_types):
  int_set = []
  for ii in xrange(1, num_of_types+1):
    for iii in xrange(ii, num_of_types+1):
      int_set.append([ii, iii])
  return int_set

def interaction_list_from_file(interaction_filename):
  int_set = []
  LIST_IN = open(interaction_filename, 'r')
  for line in LIST_IN:
    if line[0:1] != "#":
      NewRow = (line.strip()).split()
      if len(NewRow) == 2:
        int_set.append([int(NewRow[0]), int(NewRow[1])])
  LIST_IN.close()
  return int_set
#-----------------------------------------------------------------------------------------------------

def read_in_WHAM_file(filename,base_dir='./'):
    """ subroutine to read in the WHAM file - note, the format must be distance is first column, and RDF is the third column
      ASSUMPTION: ALL WHAM FILES HAVE THE SAME NUMBER OF BINS AND CUTOFF AS THE POTENTIAL FILES. """
    print "reading WHAM %s" % (filename)
    #numofbins, cutoff, o = lmp_io.get_number_of_bins_and_cutoff("%s" % (filename), 0)
    numofbins=0
    # TODO - what if we have a NAN in our data set, due to incomplete sampling?
    LIST_IN = open("%s" % (os.path.join(base_dir,filename)), 'r')
    index = 0
    x = []
    y = []
    number_of_inf=0
    number_of_non_inf=0

    print numofbins
    wham_array = [] #np.zeros(numofbins+1)
    wham_array_distance= [] #np.zeros(numofbins+1)
    extrapolate_list=[]
    interpolate_list=[]
    for line in LIST_IN:
        NewRow = (line.strip()).split()
        mystring = NewRow[0][0:1]
        if mystring != "#":
            if len(NewRow)>2:

                if NewRow[1] != "inf":
#                    wham_array[index] = float(NewRow[1])
                    number_of_non_inf +=1
                    x.append(float(NewRow[0]))
                    y.append(float(NewRow[1]))
                else:
                    if number_of_non_inf == 0:
                        extrapolate_list.append(index)
                    else:
                        interpolate_list.append(index)
                if number_of_non_inf > 0:

                    wham_array_distance.append(float(NewRow[0]))
                    if NewRow[1] == "inf":
                        wham_array.append(0.0)
                    else :
                        wham_array.append(float(NewRow[1]))
                    index += 1
    LIST_IN.close()
    np.asarray(x)
    np.asarray(y)
    np.asarray(wham_array_distance)
    np.asarray(wham_array)
    spl = UnivariateSpline(x, y)
    spl.set_smoothing_factor(0.2)
    for i, distance  in enumerate(wham_array_distance):
        if i in interpolate_list:
            wham_array[i]=float(spl(distance))
            print "WHAM INTER", distance, wham_array[i]
    #print wham_array_distance
    #print wham_array
    np.trim_zeros(wham_array, 'b')
    np.trim_zeros(wham_array_distance, 'b')

    last_element=wham_array[index-1]
    np.subtract(wham_array,last_element)
    # check whether this is the same as the the one in the potential file
    cutoff=wham_array_distance[index-1]
    print wham_array_distance
    print wham_array
    print len(wham_array_distance)
    print len(wham_array)
# need to fill in the infs

    return  wham_array, wham_array_distance, len(wham_array_distance), float(cutoff)

def find_dir_value_dict(CG_in_file,base_dir='./'):
    dir_value_dict={}
    dir_spring_const_dict={}
    dir_log_file_dict={}
    dir_data_file_dict={}
    files=os.listdir(base_dir)
    print "FILES", files
    for subdirs in files:
        if os.path.isdir(os.path.join(base_dir,subdirs)):
#            CG_in_file="in.CG.lammps.1"
            full_in_file=os.path.join(*[base_dir,subdirs, CG_in_file])

            print "FULL ", full_in_file, CG_in_file
            if os.path.isfile(full_in_file):
                IN_FILE=open(full_in_file, 'r')
                for line in IN_FILE:
                    row = line.split()
                    if len(row) > 7 and row[3] == 'spring' and row[4] == 'couple':
                        if 'NULL' in row:
                            constraint_value=float(row[9])
                        else:
                            constraint_value=float(row[10])
                        spring_constant=float(row[6])
                        dir_value_dict[constraint_value]=subdirs
                        dir_spring_const_dict[constraint_value]=spring_constant
                    if len(row) > 0 and row[0] == 'log':
                        log_file=row[1]
                        dir_log_file_dict[constraint_value]=log_file
                    if len(row) > 0 and row[0] == 'read_data':
                        data_file=row[1]
                dir_data_file_dict[constraint_value]=data_file
    print dir_value_dict, "\n"
    print dir_spring_const_dict, "\n"
    print dir_log_file_dict, "\n"
    print "\n"
    return dir_value_dict, dir_spring_const_dict, dir_log_file_dict, dir_data_file_dict

def create_WHAM_files(dir_values_dict, dir_spring_const_dict,dir_log_file,dir_value_dict, wham_list,base_dir_1='./'):
    wham_listings=[]
    for constraint_values, subdir in dir_values_dict.iteritems():
        base_dir=os.path.abspath(base_dir_1)
        r1_index=0
        success=False
	if base_dir_1.startswith('/net/tesla/srv/home/james/'):
            base_dir_1= base_dir_1[14:]
        print "BASE", base_dir
        CG_log_file=dir_log_file[constraint_values]
        print constraint_values, CG_log_file
        full_log_file=os.path.join(*[base_dir,subdir, CG_log_file])
        if os.path.isfile(full_log_file):
            LOG_FILE=open(full_log_file, 'r')

            WHAM_FILE = open("%s.%.2f" % (os.path.join(base_dir,"wham_file"), float(constraint_values)),'w')
            for line in LOG_FILE:
                row = line.split()
                if 'r1' in row:
                    ind=row.index("r1")
                    r1_index+=1
                    if r1_index > 1:
                        value=row[ind+2]
                        success=True
                        WHAM_FILE.write("%d %f\n" % (r1_index-1, float(value)))
            WHAM_FILE.close()
        if success:
            wham_listings.append([float(constraint_values), float(dir_value_dict[constraint_values]),float(2*dir_spring_const_dict[constraint_values])])
            print "APPEND ", float(constraint_values), float(dir_value_dict[constraint_values]),float(2*dir_spring_const_dict[constraint_values])
    wham_listings.sort()
    wham_list_full=os.path.join(base_dir, wham_list)
    WHAM_LIST = open("%s" % (wham_list_full),'w')
    for l in wham_listings:
        print l
        WHAM_LIST.write("%s/%s.%.2f %f %f \n" % ( base_dir_1, "wham_file", l[0], l[1], l[2]))
    WHAM_LIST.close()

def write_pot_file(filename, distance, derivative, potential, numofbins,  ii, iii, number, smoothing="yes"):

  print "WRITING POT FILE AT:", filename
  OUTPUT_FILE_POT = open (filename, 'w')
  # outputting the updated potential and forces to a new LAMMPS potential file
  OUTPUT_FILE_POT.write("# POTENTIAL FOR type %d and type %d\n\nTABLE_%d.%d\nN %d\n\n" % (ii, iii, ii, iii, int(numofbins)))
  #OUTPUT_FILE_POT.write("# POTENTIAL WITH NAME %s with %d bins.\n\n\n\n\n" % (filename, numofbins))
  index = 0

  if smoothing=="yes":
    #filtered_derivative = dm.smooth_data(np.append(derivative,[0]))
    #workaround to improve smoothing
 #  potential[0] = potential[1]
    filtered_derivative = np.append(derivative,[0])
    filtered_potential  = potential
    if number % 3 ==0:
        filtered_potential  = dm.smooth_data(filtered_potential,window_len=7,window='hamming') #Temporary
    #filtered_potential  = dm.smooth_data(filtered_potential)

    # add thresholding to avoid smoothing of charged particles at low distances
    #for i in xrange(0, len(filtered_potential)):
    #  if np.abs(filtered_potential[i]) > 10.0:
    #    blend_factor = np.log(10.0)/np.log(np.abs(filtered_potential[i]))
    #    filtered_potential[i] = filtered_potential[i]*blend_factor + potential[i]*(1.0-blend_factor)

  else:
      filtered_potential=potential
      filtered_derivative=derivative

  filtered_derivative = da.derivatives(distance, filtered_potential)
  print "LEN DERIVATIVE", len(filtered_derivative), len(filtered_potential), "smoothing: ", smoothing
  last_element=filtered_potential[numofbins-1]
  print "LAST ", last_element
  sub_filtered_potential=np.subtract(filtered_potential,last_element)

  for i in xrange(0, numofbins):
    #          if i>340:
    #            print i*DeltaR, derivative[ii][iii][i], len(dy)

      OUTPUT_FILE_POT.write("%d\t%f\t%f\t%f   \n" % (i+1, distance[i], sub_filtered_potential[i], filtered_derivative[i]*-1))

  OUTPUT_FILE_POT.close()

def update_one_file_wham(number, numofbins, new_distance_wham, new_wham, correct_distance_wham, correct_wham, previous_distance, previous_potential,atom1,atom2,dir_value_dict,pot_file_new,CG_in_file_base,out_path,base_dir='./'):

  number = int(number)
  potential = np.zeros((numofbins+1))
  derivative = np.zeros((numofbins+1))
  new_number = number + 1

# TODO - check the relationships between correct WHAM distances and the potential file
  index = length = 0
  x_data = []
  y_data = []
  success = False
  extrapolate_list=[]
  kB = 0.0019858775

  error=0.0
  index_error=0
  mapping_array=np.searchsorted(previous_distance,new_distance_wham)
  mapping_array_whams=np.searchsorted(correct_distance_wham,new_distance_wham)
  a=mapping_array.tolist()
  b=mapping_array_whams.tolist()
  print mapping_array
  print mapping_array_whams
  print numofbins
  for i in xrange(0, numofbins+1):
      print i
      if i in a:

          ind=a.index(i)
          print ind
          ind2=b[ind]
          diff=correct_wham[ind2] - new_wham[ind]
          print new_wham[ind], correct_wham[ind2], previous_distance[i], previous_potential[i]
          print "DIFF ", ind, new_wham[ind], ind2, correct_wham[ind2], previous_distance[i], previous_potential[i]
#        print old_distance[1], i, i*DeltaR

          potential[i] = previous_potential[i] + diff
          if (math.exp(-1*abs(correct_wham[ind2])/(kB*300)) > 1E-9):
              error+=diff*diff
              index_error+=1
              print "ERROR index", index_error, previous_distance[i], correct_wham[ind2], error, math.exp(-1*abs(correct_wham[ind2])/(kB*300))
          y_data.append(float(potential[i]))
          x_data.append(float(previous_distance[i]))

      else:
        # this array indicates which values we need to an extrapolation for the potential and for the forces (negative of the potential derivative) - defined as where
        # the RDF is less than 0.15, yet is defined in the old potential file.
        extrapolate_list.append(i)
  final_error=error/index_error
  print "ERROR is ", final_error, math.sqrt(final_error)
  #exit()
  h=np.asarray(x_data)
  l=np.asarray(y_data)

  dy = da.derivatives(h, l)

#      print y_data, dy, len(y_data), len(dy)
#      exit()

  parameters = {}
  square_residual = 0

    # fitting the potential derivative (i.e. negative forces) using CurveFit.pm to a Lennard Jones 6 - 3 potential (i.e. 7 - 4 when differentiated )
  fitfunc = lambda p, x: - 6 * (( ( 4 * p[0] * p[1]**6) / x**7) - ( (4 * p[0] * p[1]**3) / (2*x**4)) )
  errfunc = lambda p, x, y: fitfunc(p, x) - y
    #print "X_DATA = ", x_data, dy, y_data

  p0 = np.array([0.5, 4.5]) #was 0.5,4.5
  p1, success = scipy.optimize.leastsq(errfunc, p0[:], maxfev=5000, args=(h, dy))  #use [:int(4.0/DeltaR)] to optimize up to a cutoff of 4.

  if success == 0:
      print "Scipy.optimize did not manage to converge the fit on dataset", "! Exiting now."
      exit()

  LJ_OUT = open("LJ_parameters",'w')
  LJ_OUT.write("LJ PARAMETERS %d %d p0 = %f, p1 = %f\n" % (atom1, atom2, p1[0], p1[1]))
  LJ_OUT.close()

  for i in xrange(numofbins+1, 0, -1):
      if i in extrapolate_list: #77-31
        #print i

            new_distance = previous_distance[i]
          # These Lennard-Jones forces are then numerically integrated to get the potential
            derivative[i] = -np.abs(fitfunc(p1, new_distance))
            diff = x_data[0] - new_distance
            ave = 0.5 * fitfunc(p1, new_distance) - 0.5 * dy[0]
            r_y = np.abs(y_data[0] - diff * ave)
            potential[i] = r_y
            print i, derivative[i], potential[i], "!"

  a=np.delete(previous_distance,0)
  b=np.delete(potential,0)

  derivatives = da.derivatives(a, b)
#    index = 0
  for i in xrange(numofbins):
#      if i not in conversion_extrapolate_tmp.keys():
      print i, a[i], b[i], derivatives[i]
  for constraint_values, subdir in dir_value_dict.iteritems():
      CG_in_file= CG_in_file_base #+ str(number)
      new_CG_in_file= CG_in_file_base #+ str(new_number)
      full_in_file=os.path.join(*[base_dir,subdir, CG_in_file])

      full_out_file=os.path.join(*[out_path,subdir, new_CG_in_file])
      print "FULL OUT", full_out_file
      new_dir=os.path.dirname(full_out_file)
      if not os.path.exists(new_dir):
        os.makedirs(new_dir)
      pot_file_relative = os.path.split(pot_file_new)
      relative_pot_file= '../' + str(pot_file_relative[1])
      if os.path.isfile(full_in_file):
          IN_FILE=open(full_in_file, 'r')
          OUT_FILE=open(full_out_file, 'w+')
          for line in IN_FILE:
                row = (line.strip()).split()
                if len(row) > 0:
                    print row
                    if row[0] == "pair_coeff":
                        if (row[1] == str(atom1) and row[2] == str(atom2)) or (row[1] == atom2 and row[2] == atom1 ):
                            OUT_FILE.write("pair_coeff %d %d %s TABLE_%d.%d \n" % (atom1, atom2,relative_pot_file,atom1,atom2))
                        else:
                            OUT_FILE.write("%s\n" % (line.strip()))

                    else:
                        OUT_FILE.write("%s\n" % (line.strip()))
                    if row[0] == "read_data":
                        full_lammps_datafile=os.path.join(*[base_dir,subdir, str(row[1])])
                        full_new_lammps_datafile=os.path.join(*[out_path,subdir, str(row[1])])
                        shutil.copy2(full_lammps_datafile, full_new_lammps_datafile)

#        derivative[i] = dy[index]
#        index += 1
#
#    index = 0
#    for i in xrange(0, numofbins+1):
#      if len(derivative) > i:
#        if abs(derivative[i]) > 0:
#          index += 1
#          # determining the number of potential values
  write_pot_file(pot_file_new, a,  derivatives, b, numofbins, atom1, atom2,number)
#  write_pot_file(pot_file_new, previous_distance,  derivative, potential, numofbins, atom1, atom2,number)
    #first index was numofbins
def production():

    print "ARGUMENTS to the PMF calculation are: ", sys.argv
    wham_correct_file = ""
    number=""
    atom_type1=""
    atom_type2=""
    out_path=""
    CG_in_file_base=""
    pot_base=""
    wham_executable=""
    lammps_input_file = ""

    number_of_arguments = len(sys.argv)
    for i in xrange(0, number_of_arguments):
        if sys.argv[i].lower() == "wham_correct_file":
            wham_correct_file = sys.argv[i+1]
            print "THE WHAM CORRECT FILE IS ", wham_correct_file
        elif ((sys.argv[i] == "potential_base") or (sys.argv[i] == "potential") or (sys.argv[i] == "pot_base")):
             pot_base_full = os.path.split(sys.argv[i+1])
             pot_base_file = pot_base_full[1]
             pot_base_dir=pot_base_full[0]
             pot_base=sys.argv[i+1]
        elif ((sys.argv[i].lower() == "atom_type1") or (sys.argv[i].lower() == "atom1") or (sys.argv[i].lower() == "type1")):
            atom_type1 = int(sys.argv[i+1])
        elif ((sys.argv[i].lower() == "atom_type2") or (sys.argv[i].lower() == "atom2") or (sys.argv[i].lower() == "type2")):
            atom_type2 = int(sys.argv[i+1])
        elif ((sys.argv[i] == "number") or (sys.argv[i] == "current_number") or (sys.argv[i] == "iteration_number")):
            number = int(sys.argv[i+1])
            print "THE CURRENT ITERATION NUMBER IS ", number
        elif ((sys.argv[i] == "CG_in_file") or (sys.argv[i] == "CG_lammps_file") or (sys.argv[i] == "CG_input")):

            CG_in_file = sys.argv[i+1]
        elif ((sys.argv[i].lower() == "lammps_in_file") or (sys.argv[i] == "lammps_input_file") or (sys.argv[i] == "lammps_input")):
            lammps_input_file_full=os.path.split(sys.argv[i+1])
            lammps_input_file = lammps_input_file_full[1]
            lammps_input_file_dir=lammps_input_file_full[0]
            lammps_input_file_full=sys.argv[i+1]
        elif ((sys.argv[i] == "wham_executable") or (sys.argv[i] == "wham_executable_path") or (sys.argv[i] == "wham_path")):
            wham_executable = sys.argv[i+1]
        elif ((sys.argv[i] == "out_directory") or (sys.argv[i] == "out")):
            out_path = sys.argv[i+1]
            if not os.path.isdir(out_path):
                os.makedirs(out_path)

#wham_correct_file=sys.argv[1]
#number=sys.argv[2]
#atom_type_1=int(sys.argv[3])
#atom_type_2=int(sys.argv[4])
#out_path=sys.argv[5]
#CG_in_file_base="in.CG.lammps.1"
    wham_array_correct, wham_array_distance_correct, numofbins_wham, cutoff_wham= read_in_WHAM_file(wham_correct_file)
    dir_value_dict, dir_spring_const_dict, dir_log_file_dict, dir_data_file_dict =find_dir_value_dict(CG_in_file,lammps_input_file_dir)
    print "LAMMPS input_dir", lammps_input_file_dir
    wham_spacing=wham_array_distance_correct[1]-wham_array_distance_correct[0]
    wham_minimum=wham_array_distance_correct[0]-(wham_spacing/2)
    wham_maximum=wham_array_distance_correct[numofbins_wham-1]+(wham_spacing/2)
    wham_list_base="wham_list_CG"
    wham_list=os.path.join(lammps_input_file_dir, str(wham_list_base + '.' + str(number)))
    wham_output=os.path.join(lammps_input_file_dir, str("wham_output"+ '.' + str(number)))
    print "WHAMLIST", wham_list, wham_output
    pot_file=pot_base + str(number)
    new_number=int(number)+1
    print "NEW NUMBER", new_number, number
    pot_new=pot_base_file+str(new_number)
    pot_file_new=os.path.join(out_path,pot_new)
    print "POT_FILE NEW", pot_file_new, out_path
    print "NUMOFBINS IS ", numofbins_wham
    create_WHAM_files(dir_value_dict, dir_spring_const_dict,dir_log_file_dict,dir_value_dict,wham_list,lammps_input_file_dir)
    print "WHAM", wham_list, wham_output
    call("'%s' '%f' '%f' '%d' 0.0001 500 0 '%s' '%s' " % (wham_executable, wham_minimum, wham_maximum, numofbins_wham, wham_list, wham_output), shell=True)
#2.875  20.125 69 0.0001 500 0  wham_list_CG.number wham_output.number')
    wham_array_new, wham_array_distance_new, numofbins_new, cutoff_wham_new= read_in_WHAM_file(wham_output,lammps_input_file_dir)
    num_of_pot_bins, cutoff_pot, offset_pot = lmp_io.get_number_of_bins_and_cutoff(pot_file,0)
    pot_distance, pot_potential, pot_derivative=lmp_io.read_in_interaction_file(pot_file,num_of_pot_bins)

    update_one_file_wham(number, num_of_pot_bins, wham_array_distance_new, wham_array_new, wham_array_distance_correct, wham_array_correct, pot_distance, pot_potential,atom_type1,atom_type2,dir_value_dict,pot_file_new,CG_in_file,out_path,lammps_input_file_dir)
    new_lammps_input_file=os.path.join(out_path,lammps_input_file)
    shutil.copy2(lammps_input_file_full, new_lammps_input_file)
if __name__ == "__main__":
  production()


text:
!function($) {
  function replaceSonglistWithFormattedData(data) {
    var $songlistContainer = $(".song-list");
    $songlistContainer.html("");

    data.forEach(function(songData,index){
      var $newContent = songElement(songData,index);
      $songlistContainer.append($newContent);
    });
  }

  function songElement(songData, index) {
    return $("

"+songData['artist']+"

"+songData['title']+"

");
  }

  $("#search").keyup(_.debounce(function() {
    var searchString = $("#search").val();
    var searchUrl = "/api/search/"+encodeURIComponent(searchString);

    if (searchString == "") {
      searchUrl = "/api/songs";
    }

    $.getJSON(searchUrl, function(data, statusString) {
      replaceSonglistWithFormattedData(data);
    });
  }, 300));
}(jQuery);

redpajama_set_name: RedPajamaGithub


text:
/**
 * @author benvanik@google.com (Ben Vanik)
 */

goog.provide('gf.io.FileReader');

goog.require('goog.disposable.IDisposable');

/**
 * Provides efficient asynchronous read access to files in the file system.
 *
 * @interface
 * @extends {goog.disposable.IDisposable}
 */
gf.io.FileReader = function() {};

/**
 * @return {number} Length of the file, in bytes.
 */
gf.io.FileReader.prototype.getLength = goog.nullFunction;

/**
 * Read data from the file at the current position.
 *
 * If the starting offset is at the end of the file an INVALID_STATE error
 * will be emitted. If a size is specified such that the end is past the end
 * of the file the new end will be set to the end of the file.
 *
 * @param {number=} opt_offset Starting offset, in bytes, to begin reading at.
 * @param {number=} opt_size Number of bytes to read, or omit for full file.
 * @param {ArrayBuffer=} opt_value Buffer to hold the data.
 * @return {!goog.async.Deferred} A deferred fulfilled when the read has
 *     completed. Successful callbacks receive an ArrayBuffer as their only
 *     argument, which may not be the given buffer if it was improperly sized.
 */
gf.io.FileReader.prototype.read = goog.nullFunction;


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _index = _interopRequireDefault(require("./_lib/formatDistance/index.js"));

var _index2 = _interopRequireDefault(require("./_lib/formatLong/index.js"));

var _index3 = _interopRequireDefault(require("./_lib/formatRelative/index.js"));

var _index4 = _interopRequireDefault(require("./_lib/localize/index.js"));

var _index5 = _interopRequireDefault(require("./_lib/match/index.js"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * @type {Locale}
 * @category Locales
 * @summary Arabic locale (Moroccan Arabic).
 * @language Moroccan Arabic
 * @iso-639-2 ara
 * @author Achraf Rrami [@rramiachraf]{@link https://github.com/rramiachraf}
 */
var locale = {
  code: 'ar-MA',
  formatDistance: _index.default,
  formatLong: _index2.default,
  formatRelative: _index3.default,
  localize: _index4.default,
  match: _index5.default,
  options: {
    // Monday is 1
    weekStartsOn: 1,
    firstWeekContainsDate: 1
  }
};
var _default = locale;
exports.default = _default;
module.exports = exports.default;


text:
package impl;

import utils.Lucene;

public abstract class GraphCreatorThread extends Thread{

	private Lucene l;

	public GraphCreatorThread(Lucene l) {
		this.l = l;
	}

	public abstract void execute();

	public final void run() {

		try {
			execute();
			System.out.println("Graph created ... DONE");
			l.printlnToConsole("Graph created ... DONE");

		} catch (Throwable t) {
			t.printStackTrace();
			System.out.println(" Could not execute()");
			// app.showStatus(t.getMessage());
		}

	}
}


text:
<?php

namespace Point\PointSales\Http\Controllers\Service;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Point\Core\Helpers\QueueHelper;
use Point\Framework\Models\Master\Service;
use Point\PointSales\Helpers\ServiceInvoiceHelper;
use Point\PointSales\Helpers\ServiceReportHelper;
use Point\PointSales\Models\Service\Invoice;
use Point\PointSales\Models\Service\InvoiceService;

class ServiceReportController extends Controller
{
    public function index()
    {
        access_is_allowed('read.point.sales.service.report');
        $view = view('point-sales::app.sales.point.service.report');
        $view->list_service = Service::active()->paginate(100);

        return $view;
    }

    public function detail($service_id)
    {
        access_is_allowed('read.point.sales.service.report');

        $date_from = \Input::get('date_from');
        $date_to = \Input::get('date_to');

        $view = view('point-sales::app.sales.point.service.report-detail');
        $view->list_report = ServiceReportHelper::getDetailByService($service_id, $date_from, $date_to)->paginate(100);
        $view->service = Service::find($service_id);

        return $view;
    }

    public function export(Request $request)
    {
        access_is_allowed('export.point.sales.service.report');

        $date_from = \Input::get('date_from');
        $date_to = \Input::get('date_to');
        $storage = storage_path('app/'.$request->project->url.'/sales-service-report/');
        $file_name = strtotime(date('Y-m-d h:i:s'));
        $cRequest = $request->input();
        \Queue::push(function ($job) use ($cRequest, $file_name, $storage, $date_from, $date_to) {
            QueueHelper::reconnectAppDatabase($cRequest['database_name']);
            \Excel::create($file_name, function ($excel) use ($cRequest, $storage, $date_from, $date_to) {
                # Sheet Data
                $excel->sheet('Data', function ($sheet) use ($date_from, $date_to) {
                    $sheet->setWidth(array(
                        'A' => 10,
                        'B' => 25,
                        'C' => 25,
                        'D' => 25,
                    ));

                    // MERGER COLUMN
                    $sheet->mergeCells('A1:D1', 'center');
                    $sheet->mergeCells('A2:D2', 'center');
                    $sheet->cell('A1', function ($cell) {
                        // Set font
                        $cell->setFont(array(
                            'family'     => 'Times New Roman',
                            'size'       => '14',
                            'bold'       =>  true
                        ));

                        $cell->setValue(strtoupper('Sales Service Report'));
                    });
                    $sheet->cell('A2', function ($cell) use ($date_from, $date_to) {
                        // Set font
                        $cell->setFont(array(
                            'family'     => 'Times New Roman',
                            'size'       => '12',
                            'bold'       =>  true
                        ));
                        $period = 'All Time';
                        if ($date_from && $date_to) {
                            $period = date_format_view($date_from);
                            if ($date_from != $date_to) {
                                $period = date_format_view($date_from) .' - '. date_format_view($date_to);
                            }
                        }

                        $cell->setValue(strtoupper('PERIOD : ' . $period));
                    });
                    $sheet->cell('A3:D3', function ($cell) {
                        // Set font
                        $cell->setFont(array(
                            'family'     => 'Times New Roman',
                            'size'       => '12',
                            'bold'       =>  true
                        ));
                    });

                    $date_from = $date_from ? date_format_db($date_from, 'start') : '';
                    $date_to = $date_to ? date_format_db($date_to, 'end') : '';

                    $list_service = Service::active()->get();
                    $content = array(array('NO', 'SERVICE', 'TOTAL QUANTITY', 'TOTAL AMOUNT'));

                    $total_data = count($list_service);
                    $total_price = 0;
                    $total_quantity = 0;
                    $i = 0;
                    foreach ($list_service as $service) {
                        $data = ServiceReportHelper::detailByService($service->id, $date_from, $date_to);
                        if ($data) {
                            $total_price += $data->price;
                            $total_quantity += $data->quantity;
                        }
                        array_push($content, [++$i,
                            strtoupper($service->name),
                            strtoupper(number_format_quantity($data->quantity, 0)),
                            strtoupper(number_format_quantity($data->price))
                        ]);
                    }

                    $total_data = $total_data+3;
                    $sheet->fromArray($content, null, 'A3', false, false);
                    $sheet->setBorder('A3:D'.$total_data, 'thin');

                    $next_row = $total_data + 1;
                    $sheet->cell('C'.$next_row, function ($cell) use ($total_quantity) {
                        $cell->setFont(array(
                            'family'     => 'Times New Roman',
                            'size'       => '12',
                            'bold'       =>  true
                        ));
                        $cell->setValue(number_format_quantity($total_quantity, 0));
                    });
                    $sheet->cell('D'.$next_row, function ($cell) use ($total_price) {
                        $cell->setFont(array(
                            'family'     => 'Times New Roman',
                            'size'       => '12',
                            'bold'       =>  true
                        ));
                        $cell->setValue(number_format_quantity($total_price));
                    });
                });
            })->store('xls', $storage);

            $job->delete();
        });

        $data_email = [
            'username' => auth()->user()->name,
            'link' => url('download/'.$request->project->url.'/sales-service-report/'.$file_name.'.xls'),
            'email' => auth()->user()->email
        ];

        \Queue::push(function ($job) use ($data_email, $cRequest) {
            QueueHelper::reconnectAppDatabase($cRequest['database_name']);
            \Mail::send('point-sales::app.emails.sales.point.external.service-report', $data_email, function ($message) use ($data_email) {
                $message->to($data_email['email'])->subject('SERVICE SALES REPORT ' . date('ymdHi'));
            });
            $job->delete();
        });

        $response = array(
            'status' => 'success'
        );

        return response()->json($response);
    }
}


text:
namespace spvtools {
namespace val {
namespace {

bool AreLayoutCompatibleStructs(ValidationState_t&, const Instruction*,
                                const Instruction*);
bool HaveLayoutCompatibleMembers(ValidationState_t&, const Instruction*,
                                 const Instruction*);
bool HaveSameLayoutDecorations(ValidationState_t&, const Instruction*,
                               const Instruction*);
bool HasConflictingMemberOffsets(const std::vector<Decoration>&,
                                 const std::vector<Decoration>&);

bool IsAllowedTypeOrArrayOfSame(ValidationState_t& _, const Instruction* type,
                                std::initializer_list<uint32_t> allowed) {
  if (std::find(allowed.begin(), allowed.end(), type->opcode()) !=
      allowed.end()) {
    return true;
  }
  if (type->opcode() == SpvOpTypeArray ||
      type->opcode() == SpvOpTypeRuntimeArray) {
    auto elem_type = _.FindDef(type->word(2));
    return std::find(allowed.begin(), allowed.end(), elem_type->opcode()) !=
           allowed.end();
  }
  return false;
}

// Returns true if the two instructions represent structs that, as far as the
// validator can tell, have the exact same data layout.
bool AreLayoutCompatibleStructs(ValidationState_t& _, const Instruction* type1,
                                const Instruction* type2) {
  if (type1->opcode() != SpvOpTypeStruct) {
    return false;
  }
  if (type2->opcode() != SpvOpTypeStruct) {
    return false;
  }

  if (!HaveLayoutCompatibleMembers(_, type1, type2)) return false;

  return HaveSameLayoutDecorations(_, type1, type2);
}

// Returns true if the operands to the OpTypeStruct instruction defining the
// types are the same or are layout compatible types. |type1| and |type2| must
// be OpTypeStruct instructions.
bool HaveLayoutCompatibleMembers(ValidationState_t& _, const Instruction* type1,
                                 const Instruction* type2) {
  assert(type1->opcode() == SpvOpTypeStruct &&
         "type1 must be an OpTypeStruct instruction.");
  assert(type2->opcode() == SpvOpTypeStruct &&
         "type2 must be an OpTypeStruct instruction.");
  const auto& type1_operands = type1->operands();
  const auto& type2_operands = type2->operands();
  if (type1_operands.size() != type2_operands.size()) {
    return false;
  }

  for (size_t operand = 2; operand < type1_operands.size(); ++operand) {
    if (type1->word(operand) != type2->word(operand)) {
      auto def1 = _.FindDef(type1->word(operand));
      auto def2 = _.FindDef(type2->word(operand));
      if (!AreLayoutCompatibleStructs(_, def1, def2)) {
        return false;
      }
    }
  }
  return true;
}

// Returns true if all decorations that affect the data layout of the struct
// (like Offset), are the same for the two types. |type1| and |type2| must be
// OpTypeStruct instructions.
bool HaveSameLayoutDecorations(ValidationState_t& _, const Instruction* type1,
                               const Instruction* type2) {
  assert(type1->opcode() == SpvOpTypeStruct &&
         "type1 must be an OpTypeStruct instruction.");
  assert(type2->opcode() == SpvOpTypeStruct &&
         "type2 must be an OpTypeStruct instruction.");
  const std::vector<Decoration>& type1_decorations =
      _.id_decorations(type1->id());
  const std::vector<Decoration>& type2_decorations =
      _.id_decorations(type2->id());

  // TODO: Will have to add other check for arrays an matricies if we want to
  // handle them.
  if (HasConflictingMemberOffsets(type1_decorations, type2_decorations)) {
    return false;
  }

  return true;
}

bool HasConflictingMemberOffsets(
    const std::vector<Decoration>& type1_decorations,
    const std::vector<Decoration>& type2_decorations) {
  {
    // We are interested in conflicting decoration.  If a decoration is in one
    // list but not the other, then we will assume the code is correct.  We are
    // looking for things we know to be wrong.
    //
    // We do not have to traverse type2_decoration because, after traversing
    // type1_decorations, anything new will not be found in
    // type1_decoration.  Therefore, it cannot lead to a conflict.
    for (const Decoration& decoration : type1_decorations) {
      switch (decoration.dec_type()) {
        case SpvDecorationOffset: {
          // Since these affect the layout of the struct, they must be present
          // in both structs.
          auto compare = [&decoration](const Decoration& rhs) {
            if (rhs.dec_type() != SpvDecorationOffset) return false;
            return decoration.struct_member_index() ==
                   rhs.struct_member_index();
          };
          auto i = std::find_if(type2_decorations.begin(),
                                type2_decorations.end(), compare);
          if (i != type2_decorations.end() &&
              decoration.params().front() != i->params().front()) {
            return true;
          }
        } break;
        default:
          // This decoration does not affect the layout of the structure, so
          // just moving on.
          break;
      }
    }
  }
  return false;
}

// If |skip_builtin| is true, returns true if |storage| contains bool within
// it and no storage that contains the bool is builtin.
// If |skip_builtin| is false, returns true if |storage| contains bool within
// it.
bool ContainsInvalidBool(ValidationState_t& _, const Instruction* storage,
                         bool skip_builtin) {
  if (skip_builtin) {
    for (const Decoration& decoration : _.id_decorations(storage->id())) {
      if (decoration.dec_type() == SpvDecorationBuiltIn) return false;
    }
  }

  const size_t elem_type_index = 1;
  uint32_t elem_type_id;
  Instruction* elem_type;

  switch (storage->opcode()) {
    case SpvOpTypeBool:
      return true;
    case SpvOpTypeVector:
    case SpvOpTypeMatrix:
    case SpvOpTypeArray:
    case SpvOpTypeRuntimeArray:
      elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
      elem_type = _.FindDef(elem_type_id);
      return ContainsInvalidBool(_, elem_type, skip_builtin);
    case SpvOpTypeStruct:
      for (size_t member_type_index = 1;
           member_type_index < storage->operands().size();
           ++member_type_index) {
        auto member_type_id =
            storage->GetOperandAs<uint32_t>(member_type_index);
        auto member_type = _.FindDef(member_type_id);
        if (ContainsInvalidBool(_, member_type, skip_builtin)) return true;
      }
    default:
      break;
  }
  return false;
}

bool ContainsCooperativeMatrix(ValidationState_t& _,
                               const Instruction* storage) {
  const size_t elem_type_index = 1;
  uint32_t elem_type_id;
  Instruction* elem_type;

  switch (storage->opcode()) {
    case SpvOpTypeCooperativeMatrixNV:
      return true;
    case SpvOpTypeArray:
    case SpvOpTypeRuntimeArray:
      elem_type_id = storage->GetOperandAs<uint32_t>(elem_type_index);
      elem_type = _.FindDef(elem_type_id);
      return ContainsCooperativeMatrix(_, elem_type);
    case SpvOpTypeStruct:
      for (size_t member_type_index = 1;
           member_type_index < storage->operands().size();
           ++member_type_index) {
        auto member_type_id =
            storage->GetOperandAs<uint32_t>(member_type_index);
        auto member_type = _.FindDef(member_type_id);
        if (ContainsCooperativeMatrix(_, member_type)) return true;
      }
      break;
    default:
      break;
  }
  return false;
}

std::pair<SpvStorageClass, SpvStorageClass> GetStorageClass(
    ValidationState_t& _, const Instruction* inst) {
  SpvStorageClass dst_sc = SpvStorageClassMax;
  SpvStorageClass src_sc = SpvStorageClassMax;
  switch (inst->opcode()) {
    case SpvOpCooperativeMatrixLoadNV:
    case SpvOpLoad: {
      auto load_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(2));
      auto load_pointer_type = _.FindDef(load_pointer->type_id());
      dst_sc = load_pointer_type->GetOperandAs<SpvStorageClass>(1);
      break;
    }
    case SpvOpCooperativeMatrixStoreNV:
    case SpvOpStore: {
      auto store_pointer = _.FindDef(inst->GetOperandAs<uint32_t>(0));
      auto store_pointer_type = _.FindDef(store_pointer->type_id());
      dst_sc = store_pointer_type->GetOperandAs<SpvStorageClass>(1);
      break;
    }
    case SpvOpCopyMemory:
    case SpvOpCopyMemorySized: {
      auto dst = _.FindDef(inst->GetOperandAs<uint32_t>(0));
      auto dst_type = _.FindDef(dst->type_id());
      dst_sc = dst_type->GetOperandAs<SpvStorageClass>(1);
      auto src = _.FindDef(inst->GetOperandAs<uint32_t>(1));
      auto src_type = _.FindDef(src->type_id());
      src_sc = src_type->GetOperandAs<SpvStorageClass>(1);
      break;
    }
    default:
      break;
  }

  return std::make_pair(dst_sc, src_sc);
}

// Returns the number of instruction words taken up by a memory access
// argument and its implied operands.
int MemoryAccessNumWords(uint32_t mask) {
  int result = 1;  // Count the mask
  if (mask & SpvMemoryAccessAlignedMask) ++result;
  if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) ++result;
  if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) ++result;
  return result;
}

// Returns the scope ID operand for MakeAvailable memory access with mask
// at the given operand index.
// This function is only called for OpLoad, OpStore, OpCopyMemory and
// OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
// OpCooperativeMatrixStoreNV.
uint32_t GetMakeAvailableScope(const Instruction* inst, uint32_t mask,
                               uint32_t mask_index) {
  assert(mask & SpvMemoryAccessMakePointerAvailableKHRMask);
  uint32_t this_bit = uint32_t(SpvMemoryAccessMakePointerAvailableKHRMask);
  uint32_t index =
      mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
  return inst->GetOperandAs<uint32_t>(index);
}

// This function is only called for OpLoad, OpStore, OpCopyMemory,
// OpCopyMemorySized, OpCooperativeMatrixLoadNV, and
// OpCooperativeMatrixStoreNV.
uint32_t GetMakeVisibleScope(const Instruction* inst, uint32_t mask,
                             uint32_t mask_index) {
  assert(mask & SpvMemoryAccessMakePointerVisibleKHRMask);
  uint32_t this_bit = uint32_t(SpvMemoryAccessMakePointerVisibleKHRMask);
  uint32_t index =
      mask_index - 1 + MemoryAccessNumWords(mask & (this_bit | (this_bit - 1)));
  return inst->GetOperandAs<uint32_t>(index);
}

bool DoesStructContainRTA(const ValidationState_t& _, const Instruction* inst) {
  for (size_t member_index = 1; member_index < inst->operands().size();
       ++member_index) {
    const auto member_id = inst->GetOperandAs<uint32_t>(member_index);
    const auto member_type = _.FindDef(member_id);
    if (member_type->opcode() == SpvOpTypeRuntimeArray) return true;
  }
  return false;
}

spv_result_t CheckMemoryAccess(ValidationState_t& _, const Instruction* inst,
                               uint32_t index) {
  SpvStorageClass dst_sc, src_sc;
  std::tie(dst_sc, src_sc) = GetStorageClass(_, inst);
  if (inst->operands().size() <= index) {
    if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
        dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Memory accesses with PhysicalStorageBufferEXT must use "
                "Aligned.";
    }
    return SPV_SUCCESS;
  }

  const uint32_t mask = inst->GetOperandAs<uint32_t>(index);
  if (mask & SpvMemoryAccessMakePointerAvailableKHRMask) {
    if (inst->opcode() == SpvOpLoad ||
        inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "MakePointerAvailableKHR cannot be used with OpLoad.";
    }

    if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "NonPrivatePointerKHR must be specified if "
                "MakePointerAvailableKHR is specified.";
    }

    // Check the associated scope for MakeAvailableKHR.
    const auto available_scope = GetMakeAvailableScope(inst, mask, index);
    if (auto error = ValidateMemoryScope(_, inst, available_scope))
      return error;
  }

  if (mask & SpvMemoryAccessMakePointerVisibleKHRMask) {
    if (inst->opcode() == SpvOpStore ||
        inst->opcode() == SpvOpCooperativeMatrixStoreNV) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "MakePointerVisibleKHR cannot be used with OpStore.";
    }

    if (!(mask & SpvMemoryAccessNonPrivatePointerKHRMask)) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "NonPrivatePointerKHR must be specified if "
             << "MakePointerVisibleKHR is specified.";
    }

    // Check the associated scope for MakeVisibleKHR.
    const auto visible_scope = GetMakeVisibleScope(inst, mask, index);
    if (auto error = ValidateMemoryScope(_, inst, visible_scope)) return error;
  }

  if (mask & SpvMemoryAccessNonPrivatePointerKHRMask) {
    if (dst_sc != SpvStorageClassUniform &&
        dst_sc != SpvStorageClassWorkgroup &&
        dst_sc != SpvStorageClassCrossWorkgroup &&
        dst_sc != SpvStorageClassGeneric && dst_sc != SpvStorageClassImage &&
        dst_sc != SpvStorageClassStorageBuffer &&
        dst_sc != SpvStorageClassPhysicalStorageBufferEXT) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "NonPrivatePointerKHR requires a pointer in Uniform, "
             << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
             << "storage classes.";
    }
    if (src_sc != SpvStorageClassMax && src_sc != SpvStorageClassUniform &&
        src_sc != SpvStorageClassWorkgroup &&
        src_sc != SpvStorageClassCrossWorkgroup &&
        src_sc != SpvStorageClassGeneric && src_sc != SpvStorageClassImage &&
        src_sc != SpvStorageClassStorageBuffer &&
        src_sc != SpvStorageClassPhysicalStorageBufferEXT) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "NonPrivatePointerKHR requires a pointer in Uniform, "
             << "Workgroup, CrossWorkgroup, Generic, Image or StorageBuffer "
             << "storage classes.";
    }
  }

  if (!(mask & SpvMemoryAccessAlignedMask)) {
    if (src_sc == SpvStorageClassPhysicalStorageBufferEXT ||
        dst_sc == SpvStorageClassPhysicalStorageBufferEXT) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Memory accesses with PhysicalStorageBufferEXT must use "
                "Aligned.";
    }
  }

  return SPV_SUCCESS;
}

spv_result_t ValidateVariable(ValidationState_t& _, const Instruction* inst) {
  auto result_type = _.FindDef(inst->type_id());
  if (!result_type || result_type->opcode() != SpvOpTypePointer) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpVariable Result Type <id> '" << _.getIdName(inst->type_id())
           << "' is not a pointer type.";
  }

  const auto initializer_index = 3;
  const auto storage_class_index = 2;
  if (initializer_index < inst->operands().size()) {
    const auto initializer_id = inst->GetOperandAs<uint32_t>(initializer_index);
    const auto initializer = _.FindDef(initializer_id);
    const auto is_module_scope_var =
        initializer && (initializer->opcode() == SpvOpVariable) &&
        (initializer->GetOperandAs<SpvStorageClass>(storage_class_index) !=
         SpvStorageClassFunction);
    const auto is_constant =
        initializer && spvOpcodeIsConstant(initializer->opcode());
    if (!initializer || !(is_constant || is_module_scope_var)) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "OpVariable Initializer <id> '" << _.getIdName(initializer_id)
             << "' is not a constant or module-scope variable.";
    }
    if (initializer->type_id() != result_type->GetOperandAs<uint32_t>(2u)) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Initializer type must match the type pointed to by the Result "
                "Type";
    }
  }

  auto storage_class = inst->GetOperandAs<SpvStorageClass>(storage_class_index);
  if (storage_class != SpvStorageClassWorkgroup &&
      storage_class != SpvStorageClassCrossWorkgroup &&
      storage_class != SpvStorageClassPrivate &&
      storage_class != SpvStorageClassFunction &&
      storage_class != SpvStorageClassRayPayloadNV &&
      storage_class != SpvStorageClassIncomingRayPayloadNV &&
      storage_class != SpvStorageClassHitAttributeNV &&
      storage_class != SpvStorageClassCallableDataNV &&
      storage_class != SpvStorageClassIncomingCallableDataNV) {
    const auto storage_index = 2;
    const auto storage_id = result_type->GetOperandAs<uint32_t>(storage_index);
    const auto storage = _.FindDef(storage_id);
    bool storage_input_or_output = storage_class == SpvStorageClassInput ||
                                   storage_class == SpvStorageClassOutput;
    bool builtin = false;
    if (storage_input_or_output) {
      for (const Decoration& decoration : _.id_decorations(inst->id())) {
        if (decoration.dec_type() == SpvDecorationBuiltIn) {
          builtin = true;
          break;
        }
      }
    }
    if (!(storage_input_or_output && builtin) &&
        ContainsInvalidBool(_, storage, storage_input_or_output)) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "If OpTypeBool is stored in conjunction with OpVariable, it "
             << "can only be used with non-externally visible shader Storage "
             << "Classes: Workgroup, CrossWorkgroup, Private, and Function";
    }
  }

  if (!_.IsValidStorageClass(storage_class)) {
    return _.diag(SPV_ERROR_INVALID_BINARY, inst)
           << "Invalid storage class for target environment";
  }

  if (storage_class == SpvStorageClassGeneric) {
    return _.diag(SPV_ERROR_INVALID_BINARY, inst)
           << "OpVariable storage class cannot be Generic";
  }

  if (inst->function() && storage_class != SpvStorageClassFunction) {
    return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
           << "Variables must have a function[7] storage class inside"
              " of a function";
  }

  if (!inst->function() && storage_class == SpvStorageClassFunction) {
    return _.diag(SPV_ERROR_INVALID_LAYOUT, inst)
           << "Variables can not have a function[7] storage class "
              "outside of a function";
  }

  // SPIR-V 3.32.8: Check that pointer type and variable type have the same
  // storage class.
  const auto result_storage_class_index = 1;
  const auto result_storage_class =
      result_type->GetOperandAs<uint32_t>(result_storage_class_index);
  if (storage_class != result_storage_class) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "From SPIR-V spec, section 3.32.8 on OpVariable:\n"
           << "Its Storage Class operand must be the same as the Storage Class "
           << "operand of the result type.";
  }

  // Variable pointer related restrictions.
  const auto pointee = _.FindDef(result_type->word(3));
  if (_.addressing_model() == SpvAddressingModelLogical &&
      !_.options()->relax_logical_pointer) {
    // VariablePointersStorageBuffer is implied by VariablePointers.
    if (pointee->opcode() == SpvOpTypePointer) {
      if (!_.HasCapability(SpvCapabilityVariablePointersStorageBuffer)) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "In Logical addressing, variables may not allocate a pointer "
               << "type";
      } else if (storage_class != SpvStorageClassFunction &&
                 storage_class != SpvStorageClassPrivate) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "In Logical addressing with variable pointers, variables "
               << "that allocate pointers must be in Function or Private "
               << "storage classes";
      }
    }
  }

  // Vulkan 14.5.1: Check type of PushConstant variables.
  // Vulkan 14.5.2: Check type of UniformConstant and Uniform variables.
  if (spvIsVulkanEnv(_.context()->target_env)) {
    if (storage_class == SpvStorageClassPushConstant) {
      if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "PushConstant OpVariable <id> '" << _.getIdName(inst->id())
               << "' has illegal type.\n"
               << "From Vulkan spec, section 14.5.1:\n"
               << "Such variables must be typed as OpTypeStruct, "
               << "or an array of this type";
      }
    }

    if (storage_class == SpvStorageClassUniformConstant) {
      if (!IsAllowedTypeOrArrayOfSame(
              _, pointee,
              {SpvOpTypeImage, SpvOpTypeSampler, SpvOpTypeSampledImage,
               SpvOpTypeAccelerationStructureNV,
               SpvOpTypeAccelerationStructureKHR,
               SpvOpTypeRayQueryProvisionalKHR})) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "UniformConstant OpVariable <id> '" << _.getIdName(inst->id())
               << "' has illegal type.\n"
               << "From Vulkan spec, section 14.5.2:\n"
               << "Variables identified with the UniformConstant storage class "
               << "are used only as handles to refer to opaque resources. Such "
               << "variables must be typed as OpTypeImage, OpTypeSampler, "
               << "OpTypeSampledImage, OpTypeAccelerationStructureNV, "
                  "OpTypeAccelerationStructureKHR, "
                  "OpTypeRayQueryProvisionalKHR, "
               << "or an array of one of these types.";
      }
    }

    if (storage_class == SpvStorageClassUniform) {
      if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "Uniform OpVariable <id> '" << _.getIdName(inst->id())
               << "' has illegal type.\n"
               << "From Vulkan spec, section 14.5.2:\n"
               << "Variables identified with the Uniform storage class are "
               << "used to access transparent buffer backed resources. Such "
               << "variables must be typed as OpTypeStruct, or an array of "
               << "this type";
      }
    }

    if (storage_class == SpvStorageClassStorageBuffer) {
      if (!IsAllowedTypeOrArrayOfSame(_, pointee, {SpvOpTypeStruct})) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "StorageBuffer OpVariable <id> '" << _.getIdName(inst->id())
               << "' has illegal type.\n"
               << "From Vulkan spec, section 14.5.2:\n"
               << "Variables identified with the StorageBuffer storage class "
                  "are used to access transparent buffer backed resources. "
                  "Such variables must be typed as OpTypeStruct, or an array "
                  "of this type";
      }
    }
  }

  // WebGPU & Vulkan Appendix A: Check that if contains initializer, then
  // storage class is Output, Private, or Function.
  if (inst->operands().size() > 3 && storage_class != SpvStorageClassOutput &&
      storage_class != SpvStorageClassPrivate &&
      storage_class != SpvStorageClassFunction) {
    if (spvIsVulkanOrWebGPUEnv(_.context()->target_env)) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "OpVariable, <id> '" << _.getIdName(inst->id())
             << "', has a disallowed initializer & storage class "
             << "combination.\n"
             << "From " << spvLogStringForEnv(_.context()->target_env)
             << " spec:\n"
             << "Variable declarations that include initializers must have "
             << "one of the following storage classes: Output, Private, or "
             << "Function";
    }
  }

  // WebGPU: All variables with storage class Output, Private, or Function MUST
  // have an initializer.
  if (spvIsWebGPUEnv(_.context()->target_env) && inst->operands().size() <= 3 &&
      (storage_class == SpvStorageClassOutput ||
       storage_class == SpvStorageClassPrivate ||
       storage_class == SpvStorageClassFunction)) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpVariable, <id> '" << _.getIdName(inst->id())
           << "', must have an initializer.\n"
           << "From WebGPU execution environment spec:\n"
           << "All variables in the following storage classes must have an "
           << "initializer: Output, Private, or Function";
  }

  if (storage_class == SpvStorageClassPhysicalStorageBufferEXT) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "PhysicalStorageBufferEXT must not be used with OpVariable.";
  }

  auto pointee_base = pointee;
  while (pointee_base->opcode() == SpvOpTypeArray) {
    pointee_base = _.FindDef(pointee_base->GetOperandAs<uint32_t>(1u));
  }
  if (pointee_base->opcode() == SpvOpTypePointer) {
    if (pointee_base->GetOperandAs<uint32_t>(1u) ==
        SpvStorageClassPhysicalStorageBufferEXT) {
      // check for AliasedPointerEXT/RestrictPointerEXT
      bool foundAliased =
          _.HasDecoration(inst->id(), SpvDecorationAliasedPointerEXT);
      bool foundRestrict =
          _.HasDecoration(inst->id(), SpvDecorationRestrictPointerEXT);
      if (!foundAliased && !foundRestrict) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "OpVariable " << inst->id()
               << ": expected AliasedPointerEXT or RestrictPointerEXT for "
               << "PhysicalStorageBufferEXT pointer.";
      }
      if (foundAliased && foundRestrict) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "OpVariable " << inst->id()
               << ": can't specify both AliasedPointerEXT and "
               << "RestrictPointerEXT for PhysicalStorageBufferEXT pointer.";
      }
    }
  }

  // Vulkan specific validation rules for OpTypeRuntimeArray
  const auto type_index = 2;
  const auto value_id = result_type->GetOperandAs<uint32_t>(type_index);
  auto value_type = _.FindDef(value_id);
  if (spvIsVulkanEnv(_.context()->target_env)) {
    // OpTypeRuntimeArray should only ever be in a container like OpTypeStruct,
    // so should never appear as a bare variable.
    // Unless the module has the RuntimeDescriptorArrayEXT capability.
    if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
      if (!_.HasCapability(SpvCapabilityRuntimeDescriptorArrayEXT)) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "OpVariable, <id> '" << _.getIdName(inst->id())
               << "', is attempting to create memory for an illegal type, "
               << "OpTypeRuntimeArray.\nFor Vulkan OpTypeRuntimeArray can only "
               << "appear as the final member of an OpTypeStruct, thus cannot "
               << "be instantiated via OpVariable";
      } else {
        // A bare variable OpTypeRuntimeArray is allowed in this context, but
        // still need to check the storage class.
        if (storage_class != SpvStorageClassStorageBuffer &&
            storage_class != SpvStorageClassUniform &&
            storage_class != SpvStorageClassUniformConstant) {
          return _.diag(SPV_ERROR_INVALID_ID, inst)
                 << "For Vulkan with RuntimeDescriptorArrayEXT, a variable "
                 << "containing OpTypeRuntimeArray must have storage class of "
                 << "StorageBuffer, Uniform, or UniformConstant.";
        }
      }
    }

    // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
    // must either have the storage class StorageBuffer and be decorated
    // with Block, or it must be in the Uniform storage class and be decorated
    // as BufferBlock.
    if (value_type && value_type->opcode() == SpvOpTypeStruct) {
      if (DoesStructContainRTA(_, value_type)) {
        if (storage_class == SpvStorageClassStorageBuffer) {
          if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
            return _.diag(SPV_ERROR_INVALID_ID, inst)
                   << "For Vulkan, an OpTypeStruct variable containing an "
                   << "OpTypeRuntimeArray must be decorated with Block if it "
                   << "has storage class StorageBuffer.";
          }
        } else if (storage_class == SpvStorageClassUniform) {
          if (!_.HasDecoration(value_id, SpvDecorationBufferBlock)) {
            return _.diag(SPV_ERROR_INVALID_ID, inst)
                   << "For Vulkan, an OpTypeStruct variable containing an "
                   << "OpTypeRuntimeArray must be decorated with BufferBlock "
                   << "if it has storage class Uniform.";
          }
        } else {
          return _.diag(SPV_ERROR_INVALID_ID, inst)
                 << "For Vulkan, OpTypeStruct variables containing "
                 << "OpTypeRuntimeArray must have storage class of "
                 << "StorageBuffer or Uniform.";
        }
      }
    }
  }

  // WebGPU specific validation rules for OpTypeRuntimeArray
  if (spvIsWebGPUEnv(_.context()->target_env)) {
    // OpTypeRuntimeArray should only ever be in an OpTypeStruct,
    // so should never appear as a bare variable.
    if (value_type && value_type->opcode() == SpvOpTypeRuntimeArray) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "OpVariable, <id> '" << _.getIdName(inst->id())
             << "', is attempting to create memory for an illegal type, "
             << "OpTypeRuntimeArray.\nFor WebGPU OpTypeRuntimeArray can only "
             << "appear as the final member of an OpTypeStruct, thus cannot "
             << "be instantiated via OpVariable";
    }

    // If an OpStruct has an OpTypeRuntimeArray somewhere within it, then it
    // must have the storage class StorageBuffer and be decorated
    // with Block.
    if (value_type && value_type->opcode() == SpvOpTypeStruct) {
      if (DoesStructContainRTA(_, value_type)) {
        if (storage_class == SpvStorageClassStorageBuffer) {
          if (!_.HasDecoration(value_id, SpvDecorationBlock)) {
            return _.diag(SPV_ERROR_INVALID_ID, inst)
                   << "For WebGPU, an OpTypeStruct variable containing an "
                   << "OpTypeRuntimeArray must be decorated with Block if it "
                   << "has storage class StorageBuffer.";
          }
        } else {
          return _.diag(SPV_ERROR_INVALID_ID, inst)
                 << "For WebGPU, OpTypeStruct variables containing "
                 << "OpTypeRuntimeArray must have storage class of "
                 << "StorageBuffer";
        }
      }
    }
  }

  // Cooperative matrix types can only be allocated in Function or Private
  if ((storage_class != SpvStorageClassFunction &&
       storage_class != SpvStorageClassPrivate) &&
      ContainsCooperativeMatrix(_, pointee)) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Cooperative matrix types (or types containing them) can only be "
              "allocated "
           << "in Function or Private storage classes or as function "
              "parameters";
  }

  if (_.HasCapability(SpvCapabilityShader)) {
    // Don't allow variables containing 16-bit elements without the appropriate
    // capabilities.
    if ((!_.HasCapability(SpvCapabilityInt16) &&
         _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 16)) ||
        (!_.HasCapability(SpvCapabilityFloat16) &&
         _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeFloat, 16))) {
      auto underlying_type = value_type;
      while (underlying_type->opcode() == SpvOpTypePointer) {
        storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
        underlying_type =
            _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
      }
      bool storage_class_ok = true;
      std::string sc_name = _.grammar().lookupOperandName(
          SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
      switch (storage_class) {
        case SpvStorageClassStorageBuffer:
        case SpvStorageClassPhysicalStorageBufferEXT:
          if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess)) {
            storage_class_ok = false;
          }
          break;
        case SpvStorageClassUniform:
          if (!_.HasCapability(
                  SpvCapabilityUniformAndStorageBuffer16BitAccess)) {
            if (underlying_type->opcode() == SpvOpTypeArray ||
                underlying_type->opcode() == SpvOpTypeRuntimeArray) {
              underlying_type =
                  _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
            }
            if (!_.HasCapability(SpvCapabilityStorageBuffer16BitAccess) ||
                !_.HasDecoration(underlying_type->id(),
                                 SpvDecorationBufferBlock)) {
              storage_class_ok = false;
            }
          }
          break;
        case SpvStorageClassPushConstant:
          if (!_.HasCapability(SpvCapabilityStoragePushConstant16)) {
            storage_class_ok = false;
          }
          break;
        case SpvStorageClassInput:
        case SpvStorageClassOutput:
          if (!_.HasCapability(SpvCapabilityStorageInputOutput16)) {
            storage_class_ok = false;
          }
          break;
        default:
          return _.diag(SPV_ERROR_INVALID_ID, inst)
                 << "Cannot allocate a variable containing a 16-bit type in "
                 << sc_name << " storage class";
      }
      if (!storage_class_ok) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "Allocating a variable containing a 16-bit element in "
               << sc_name << " storage class requires an additional capability";
      }
    }
    // Don't allow variables containing 8-bit elements without the appropriate
    // capabilities.
    if (!_.HasCapability(SpvCapabilityInt8) &&
        _.ContainsSizedIntOrFloatType(value_id, SpvOpTypeInt, 8)) {
      auto underlying_type = value_type;
      while (underlying_type->opcode() == SpvOpTypePointer) {
        storage_class = underlying_type->GetOperandAs<SpvStorageClass>(1u);
        underlying_type =
            _.FindDef(underlying_type->GetOperandAs<uint32_t>(2u));
      }
      bool storage_class_ok = true;
      std::string sc_name = _.grammar().lookupOperandName(
          SPV_OPERAND_TYPE_STORAGE_CLASS, storage_class);
      switch (storage_class) {
        case SpvStorageClassStorageBuffer:
        case SpvStorageClassPhysicalStorageBufferEXT:
          if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess)) {
            storage_class_ok = false;
          }
          break;
        case SpvStorageClassUniform:
          if (!_.HasCapability(
                  SpvCapabilityUniformAndStorageBuffer8BitAccess)) {
            if (underlying_type->opcode() == SpvOpTypeArray ||
                underlying_type->opcode() == SpvOpTypeRuntimeArray) {
              underlying_type =
                  _.FindDef(underlying_type->GetOperandAs<uint32_t>(1u));
            }
            if (!_.HasCapability(SpvCapabilityStorageBuffer8BitAccess) ||
                !_.HasDecoration(underlying_type->id(),
                                 SpvDecorationBufferBlock)) {
              storage_class_ok = false;
            }
          }
          break;
        case SpvStorageClassPushConstant:
          if (!_.HasCapability(SpvCapabilityStoragePushConstant8)) {
            storage_class_ok = false;
          }
          break;
        default:
          return _.diag(SPV_ERROR_INVALID_ID, inst)
                 << "Cannot allocate a variable containing a 8-bit type in "
                 << sc_name << " storage class";
      }
      if (!storage_class_ok) {
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "Allocating a variable containing a 8-bit element in "
               << sc_name << " storage class requires an additional capability";
      }
    }
  }

  return SPV_SUCCESS;
}

spv_result_t ValidateLoad(ValidationState_t& _, const Instruction* inst) {
  const auto result_type = _.FindDef(inst->type_id());
  if (!result_type) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
           << "' is not defined.";
  }

  const bool uses_variable_pointers =
      _.features().variable_pointers ||
      _.features().variable_pointers_storage_buffer;
  const auto pointer_index = 2;
  const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  const auto pointer = _.FindDef(pointer_id);
  if (!pointer ||
      ((_.addressing_model() == SpvAddressingModelLogical) &&
       ((!uses_variable_pointers &&
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
        (uses_variable_pointers &&
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpLoad Pointer <id> '" << _.getIdName(pointer_id)
           << "' is not a logical pointer.";
  }

  const auto pointer_type = _.FindDef(pointer->type_id());
  if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpLoad type for pointer <id> '" << _.getIdName(pointer_id)
           << "' is not a pointer type.";
  }

  const auto pointee_type = _.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  if (!pointee_type || result_type->id() != pointee_type->id()) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpLoad Result Type <id> '" << _.getIdName(inst->type_id())
           << "' does not match Pointer <id> '" << _.getIdName(pointer->id())
           << "'s type.";
  }

  if (auto error = CheckMemoryAccess(_, inst, 3)) return error;

  if (_.HasCapability(SpvCapabilityShader) &&
      _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
      result_type->opcode() != SpvOpTypePointer) {
    if (result_type->opcode() != SpvOpTypeInt &&
        result_type->opcode() != SpvOpTypeFloat &&
        result_type->opcode() != SpvOpTypeVector &&
        result_type->opcode() != SpvOpTypeMatrix) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "8- or 16-bit loads must be a scalar, vector or matrix type";
    }
  }

  return SPV_SUCCESS;
}

spv_result_t ValidateStore(ValidationState_t& _, const Instruction* inst) {
  const bool uses_variable_pointer =
      _.features().variable_pointers ||
      _.features().variable_pointers_storage_buffer;
  const auto pointer_index = 0;
  const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  const auto pointer = _.FindDef(pointer_id);
  if (!pointer ||
      (_.addressing_model() == SpvAddressingModelLogical &&
       ((!uses_variable_pointer &&
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
        (uses_variable_pointer &&
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
           << "' is not a logical pointer.";
  }
  const auto pointer_type = _.FindDef(pointer->type_id());
  if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpStore type for pointer <id> '" << _.getIdName(pointer_id)
           << "' is not a pointer type.";
  }
  const auto type_id = pointer_type->GetOperandAs<uint32_t>(2);
  const auto type = _.FindDef(type_id);
  if (!type || SpvOpTypeVoid == type->opcode()) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
           << "'s type is void.";
  }

  // validate storage class
  {
    uint32_t data_type;
    uint32_t storage_class;
    if (!_.GetPointerTypeInfo(pointer_type->id(), &data_type, &storage_class)) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
             << "' is not pointer type";
    }

    if (storage_class == SpvStorageClassUniformConstant ||
        storage_class == SpvStorageClassInput ||
        storage_class == SpvStorageClassPushConstant) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
             << "' storage class is read-only";
    }

    if (spvIsVulkanEnv(_.context()->target_env) &&
        storage_class == SpvStorageClassUniform) {
      auto base_ptr = _.TracePointer(pointer);
      if (base_ptr->opcode() == SpvOpVariable) {
        // If it's not a variable a different check should catch the problem.
        auto base_type = _.FindDef(base_ptr->GetOperandAs<uint32_t>(0));
        // Get the pointed-to type.
        base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(2u));
        if (base_type->opcode() == SpvOpTypeArray ||
            base_type->opcode() == SpvOpTypeRuntimeArray) {
          base_type = _.FindDef(base_type->GetOperandAs<uint32_t>(1u));
        }
        if (_.HasDecoration(base_type->id(), SpvDecorationBlock)) {
          return _.diag(SPV_ERROR_INVALID_ID, inst)
                 << "In the Vulkan environment, cannot store to Uniform Blocks";
        }
      }
    }
  }

  const auto object_index = 1;
  const auto object_id = inst->GetOperandAs<uint32_t>(object_index);
  const auto object = _.FindDef(object_id);
  if (!object || !object->type_id()) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpStore Object <id> '" << _.getIdName(object_id)
           << "' is not an object.";
  }
  const auto object_type = _.FindDef(object->type_id());
  if (!object_type || SpvOpTypeVoid == object_type->opcode()) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "OpStore Object <id> '" << _.getIdName(object_id)
           << "'s type is void.";
  }

  if (type->id() != object_type->id()) {
    if (!_.options()->relax_struct_store || type->opcode() != SpvOpTypeStruct ||
        object_type->opcode() != SpvOpTypeStruct) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
             << "'s type does not match Object <id> '"
             << _.getIdName(object->id()) << "'s type.";
    }

    // TODO: Check for layout compatible matricies and arrays as well.
    if (!AreLayoutCompatibleStructs(_, type, object_type)) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "OpStore Pointer <id> '" << _.getIdName(pointer_id)
             << "'s layout does not match Object <id> '"
             << _.getIdName(object->id()) << "'s layout.";
    }
  }

  if (auto error = CheckMemoryAccess(_, inst, 2)) return error;

  if (_.HasCapability(SpvCapabilityShader) &&
      _.ContainsLimitedUseIntOrFloatType(inst->type_id()) &&
      object_type->opcode() != SpvOpTypePointer) {
    if (object_type->opcode() != SpvOpTypeInt &&
        object_type->opcode() != SpvOpTypeFloat &&
        object_type->opcode() != SpvOpTypeVector &&
        object_type->opcode() != SpvOpTypeMatrix) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "8- or 16-bit stores must be a scalar, vector or matrix type";
    }
  }

  return SPV_SUCCESS;
}

spv_result_t ValidateCopyMemoryMemoryAccess(ValidationState_t& _,
                                            const Instruction* inst) {
  assert(inst->opcode() == SpvOpCopyMemory ||
         inst->opcode() == SpvOpCopyMemorySized);
  const uint32_t first_access_index = inst->opcode() == SpvOpCopyMemory ? 2 : 3;
  if (inst->operands().size() > first_access_index) {
    if (auto error = CheckMemoryAccess(_, inst, first_access_index))
      return error;

    const auto first_access = inst->GetOperandAs<uint32_t>(first_access_index);
    const uint32_t second_access_index =
        first_access_index + MemoryAccessNumWords(first_access);
    if (inst->operands().size() > second_access_index) {
      if (_.features().copy_memory_permits_two_memory_accesses) {
        if (auto error = CheckMemoryAccess(_, inst, second_access_index))
          return error;

        // In the two-access form in SPIR-V 1.4 and later:
        //  - the first is the target (write) access and it can't have
        //  make-visible.
        //  - the second is the source (read) access and it can't have
        //  make-available.
        if (first_access & SpvMemoryAccessMakePointerVisibleKHRMask) {
          return _.diag(SPV_ERROR_INVALID_DATA, inst)
                 << "Target memory access must not include "
                    "MakePointerVisibleKHR";
        }
        const auto second_access =
            inst->GetOperandAs<uint32_t>(second_access_index);
        if (second_access & SpvMemoryAccessMakePointerAvailableKHRMask) {
          return _.diag(SPV_ERROR_INVALID_DATA, inst)
                 << "Source memory access must not include "
                    "MakePointerAvailableKHR";
        }
      } else {
        return _.diag(SPV_ERROR_INVALID_DATA, inst)
               << spvOpcodeString(static_cast<SpvOp>(inst->opcode()))
               << " with two memory access operands requires SPIR-V 1.4 or "
                  "later";
      }
    }
  }
  return SPV_SUCCESS;
}

spv_result_t ValidateCopyMemory(ValidationState_t& _, const Instruction* inst) {
  const auto target_index = 0;
  const auto target_id = inst->GetOperandAs<uint32_t>(target_index);
  const auto target = _.FindDef(target_id);
  if (!target) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Target operand <id> '" << _.getIdName(target_id)
           << "' is not defined.";
  }

  const auto source_index = 1;
  const auto source_id = inst->GetOperandAs<uint32_t>(source_index);
  const auto source = _.FindDef(source_id);
  if (!source) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Source operand <id> '" << _.getIdName(source_id)
           << "' is not defined.";
  }

  const auto target_pointer_type = _.FindDef(target->type_id());
  if (!target_pointer_type ||
      target_pointer_type->opcode() != SpvOpTypePointer) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Target operand <id> '" << _.getIdName(target_id)
           << "' is not a pointer.";
  }

  const auto source_pointer_type = _.FindDef(source->type_id());
  if (!source_pointer_type ||
      source_pointer_type->opcode() != SpvOpTypePointer) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Source operand <id> '" << _.getIdName(source_id)
           << "' is not a pointer.";
  }

  if (inst->opcode() == SpvOpCopyMemory) {
    const auto target_type =
        _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
    if (!target_type || target_type->opcode() == SpvOpTypeVoid) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Target operand <id> '" << _.getIdName(target_id)
             << "' cannot be a void pointer.";
    }

    const auto source_type =
        _.FindDef(source_pointer_type->GetOperandAs<uint32_t>(2));
    if (!source_type || source_type->opcode() == SpvOpTypeVoid) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Source operand <id> '" << _.getIdName(source_id)
             << "' cannot be a void pointer.";
    }

    if (target_type->id() != source_type->id()) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Target <id> '" << _.getIdName(source_id)
             << "'s type does not match Source <id> '"
             << _.getIdName(source_type->id()) << "'s type.";
    }

    if (auto error = CheckMemoryAccess(_, inst, 2)) return error;
  } else {
    const auto size_id = inst->GetOperandAs<uint32_t>(2);
    const auto size = _.FindDef(size_id);
    if (!size) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Size operand <id> '" << _.getIdName(size_id)
             << "' is not defined.";
    }

    const auto size_type = _.FindDef(size->type_id());
    if (!_.IsIntScalarType(size_type->id())) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Size operand <id> '" << _.getIdName(size_id)
             << "' must be a scalar integer type.";
    }

    bool is_zero = true;
    switch (size->opcode()) {
      case SpvOpConstantNull:
        return _.diag(SPV_ERROR_INVALID_ID, inst)
               << "Size operand <id> '" << _.getIdName(size_id)
               << "' cannot be a constant zero.";
      case SpvOpConstant:
        if (size_type->word(3) == 1 &&
            size->word(size->words().size() - 1) & 0x80000000) {
          return _.diag(SPV_ERROR_INVALID_ID, inst)
                 << "Size operand <id> '" << _.getIdName(size_id)
                 << "' cannot have the sign bit set to 1.";
        }
        for (size_t i = 3; is_zero && i < size->words().size(); ++i) {
          is_zero &= (size->word(i) == 0);
        }
        if (is_zero) {
          return _.diag(SPV_ERROR_INVALID_ID, inst)
                 << "Size operand <id> '" << _.getIdName(size_id)
                 << "' cannot be a constant zero.";
        }
        break;
      default:
        // Cannot infer any other opcodes.
        break;
    }

    if (auto error = CheckMemoryAccess(_, inst, 3)) return error;
  }
  if (auto error = ValidateCopyMemoryMemoryAccess(_, inst)) return error;

  // Get past the pointers to avoid checking a pointer copy.
  auto sub_type = _.FindDef(target_pointer_type->GetOperandAs<uint32_t>(2));
  while (sub_type->opcode() == SpvOpTypePointer) {
    sub_type = _.FindDef(sub_type->GetOperandAs<uint32_t>(2));
  }
  if (_.HasCapability(SpvCapabilityShader) &&
      _.ContainsLimitedUseIntOrFloatType(sub_type->id())) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Cannot copy memory of objects containing 8- or 16-bit types";
  }

  return SPV_SUCCESS;
}

spv_result_t ValidateAccessChain(ValidationState_t& _,
                                 const Instruction* inst) {
  std::string instr_name =
      "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));

  // The result type must be OpTypePointer.
  auto result_type = _.FindDef(inst->type_id());
  if (SpvOpTypePointer != result_type->opcode()) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "The Result Type of " << instr_name << " <id> '"
           << _.getIdName(inst->id()) << "' must be OpTypePointer. Found Op"
           << spvOpcodeString(static_cast<SpvOp>(result_type->opcode())) << ".";
  }

  // Result type is a pointer. Find out what it's pointing to.
  // This will be used to make sure the indexing results in the same type.
  // OpTypePointer word 3 is the type being pointed to.
  const auto result_type_pointee = _.FindDef(result_type->word(3));

  // Base must be a pointer, pointing to the base of a composite object.
  const auto base_index = 2;
  const auto base_id = inst->GetOperandAs<uint32_t>(base_index);
  const auto base = _.FindDef(base_id);
  const auto base_type = _.FindDef(base->type_id());
  if (!base_type || SpvOpTypePointer != base_type->opcode()) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "The Base <id> '" << _.getIdName(base_id) << "' in " << instr_name
           << " instruction must be a pointer.";
  }

  // The result pointer storage class and base pointer storage class must match.
  // Word 2 of OpTypePointer is the Storage Class.
  auto result_type_storage_class = result_type->word(2);
  auto base_type_storage_class = base_type->word(2);
  if (result_type_storage_class != base_type_storage_class) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "The result pointer storage class and base "
              "pointer storage class in "
           << instr_name << " do not match.";
  }

  // The type pointed to by OpTypePointer (word 3) must be a composite type.
  auto type_pointee = _.FindDef(base_type->word(3));

  // Check Universal Limit (SPIR-V Spec. Section 2.17).
  // The number of indexes passed to OpAccessChain may not exceed 255
  // The instruction includes 4 words + N words (for N indexes)
  size_t num_indexes = inst->words().size() - 4;
  if (inst->opcode() == SpvOpPtrAccessChain ||
      inst->opcode() == SpvOpInBoundsPtrAccessChain) {
    // In pointer access chains, the element operand is required, but not
    // counted as an index.
    --num_indexes;
  }
  const size_t num_indexes_limit =
      _.options()->universal_limits_.max_access_chain_indexes;
  if (num_indexes > num_indexes_limit) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "The number of indexes in " << instr_name << " may not exceed "
           << num_indexes_limit << ". Found " << num_indexes << " indexes.";
  }
  // Indexes walk the type hierarchy to the desired depth, potentially down to
  // scalar granularity. The first index in Indexes will select the top-level
  // member/element/component/element of the base composite. All composite
  // constituents use zero-based numbering, as described by their OpType...
  // instruction. The second index will apply similarly to that result, and so
  // on. Once any non-composite type is reached, there must be no remaining
  // (unused) indexes.
  auto starting_index = 4;
  if (inst->opcode() == SpvOpPtrAccessChain ||
      inst->opcode() == SpvOpInBoundsPtrAccessChain) {
    ++starting_index;
  }
  for (size_t i = starting_index; i < inst->words().size(); ++i) {
    const uint32_t cur_word = inst->words()[i];
    // Earlier ID checks ensure that cur_word definition exists.
    auto cur_word_instr = _.FindDef(cur_word);
    // The index must be a scalar integer type (See OpAccessChain in the Spec.)
    auto index_type = _.FindDef(cur_word_instr->type_id());
    if (!index_type || SpvOpTypeInt != index_type->opcode()) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Indexes passed to " << instr_name
             << " must be of type integer.";
    }
    switch (type_pointee->opcode()) {
      case SpvOpTypeMatrix:
      case SpvOpTypeVector:
      case SpvOpTypeCooperativeMatrixNV:
      case SpvOpTypeArray:
      case SpvOpTypeRuntimeArray: {
        // In OpTypeMatrix, OpTypeVector, SpvOpTypeCooperativeMatrixNV,
        // OpTypeArray, and OpTypeRuntimeArray, word 2 is the Element Type.
        type_pointee = _.FindDef(type_pointee->word(2));
        break;
      }
      case SpvOpTypeStruct: {
        // In case of structures, there is an additional constraint on the
        // index: the index must be an OpConstant.
        if (SpvOpConstant != cur_word_instr->opcode()) {
          return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
                 << "The <id> passed to " << instr_name
                 << " to index into a "
                    "structure must be an OpConstant.";
        }
        // Get the index value from the OpConstant (word 3 of OpConstant).
        // OpConstant could be a signed integer. But it's okay to treat it as
        // unsigned because a negative constant int would never be seen as
        // correct as a struct offset, since structs can't have more than 2
        // billion members.
        const uint32_t cur_index = cur_word_instr->word(3);
        // The index points to the struct member we want, therefore, the index
        // should be less than the number of struct members.
        const uint32_t num_struct_members =
            static_cast<uint32_t>(type_pointee->words().size() - 2);
        if (cur_index >= num_struct_members) {
          return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
                 << "Index is out of bounds: " << instr_name
                 << " can not find index " << cur_index
                 << " into the structure <id> '"
                 << _.getIdName(type_pointee->id()) << "'. This structure has "
                 << num_struct_members << " members. Largest valid index is "
                 << num_struct_members - 1 << ".";
        }
        // Struct members IDs start at word 2 of OpTypeStruct.
        auto structMemberId = type_pointee->word(cur_index + 2);
        type_pointee = _.FindDef(structMemberId);
        break;
      }
      default: {
        // Give an error. reached non-composite type while indexes still remain.
        return _.diag(SPV_ERROR_INVALID_ID, cur_word_instr)
               << instr_name
               << " reached non-composite type while indexes "
                  "still remain to be traversed.";
      }
    }
  }
  // At this point, we have fully walked down from the base using the indeces.
  // The type being pointed to should be the same as the result type.
  if (type_pointee->id() != result_type_pointee->id()) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << instr_name << " result type (Op"
           << spvOpcodeString(static_cast<SpvOp>(result_type_pointee->opcode()))
           << ") does not match the type that results from indexing into the "
              "base "
              "<id> (Op"
           << spvOpcodeString(static_cast<SpvOp>(type_pointee->opcode()))
           << ").";
  }

  return SPV_SUCCESS;
}

spv_result_t ValidatePtrAccessChain(ValidationState_t& _,
                                    const Instruction* inst) {
  if (_.addressing_model() == SpvAddressingModelLogical) {
    if (!_.features().variable_pointers &&
        !_.features().variable_pointers_storage_buffer) {
      return _.diag(SPV_ERROR_INVALID_DATA, inst)
             << "Generating variable pointers requires capability "
             << "VariablePointers or VariablePointersStorageBuffer";
    }
  }
  return ValidateAccessChain(_, inst);
}

spv_result_t ValidateArrayLength(ValidationState_t& state,
                                 const Instruction* inst) {
  std::string instr_name =
      "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));

  // Result type must be a 32-bit unsigned int.
  auto result_type = state.FindDef(inst->type_id());
  if (result_type->opcode() != SpvOpTypeInt ||
      result_type->GetOperandAs<uint32_t>(1) != 32 ||
      result_type->GetOperandAs<uint32_t>(2) != 0) {
    return state.diag(SPV_ERROR_INVALID_ID, inst)
           << "The Result Type of " << instr_name << " <id> '"
           << state.getIdName(inst->id())
           << "' must be OpTypeInt with width 32 and signedness 0.";
  }

  // The structure that is passed in must be an pointer to a structure, whose
  // last element is a runtime array.
  auto pointer = state.FindDef(inst->GetOperandAs<uint32_t>(2));
  auto pointer_type = state.FindDef(pointer->type_id());
  if (pointer_type->opcode() != SpvOpTypePointer) {
    return state.diag(SPV_ERROR_INVALID_ID, inst)
           << "The Struture's type in " << instr_name << " <id> '"
           << state.getIdName(inst->id())
           << "' must be a pointer to an OpTypeStruct.";
  }

  auto structure_type = state.FindDef(pointer_type->GetOperandAs<uint32_t>(2));
  if (structure_type->opcode() != SpvOpTypeStruct) {
    return state.diag(SPV_ERROR_INVALID_ID, inst)
           << "The Struture's type in " << instr_name << " <id> '"
           << state.getIdName(inst->id())
           << "' must be a pointer to an OpTypeStruct.";
  }

  auto num_of_members = structure_type->operands().size() - 1;
  auto last_member =
      state.FindDef(structure_type->GetOperandAs<uint32_t>(num_of_members));
  if (last_member->opcode() != SpvOpTypeRuntimeArray) {
    return state.diag(SPV_ERROR_INVALID_ID, inst)
           << "The Struture's last member in " << instr_name << " <id> '"
           << state.getIdName(inst->id()) << "' must be an OpTypeRuntimeArray.";
  }

  // The array member must the the index of the last element (the run time
  // array).
  if (inst->GetOperandAs<uint32_t>(3) != num_of_members - 1) {
    return state.diag(SPV_ERROR_INVALID_ID, inst)
           << "The array member in " << instr_name << " <id> '"
           << state.getIdName(inst->id())
           << "' must be an the last member of the struct.";
  }
  return SPV_SUCCESS;
}

spv_result_t ValidateCooperativeMatrixLengthNV(ValidationState_t& state,
                                               const Instruction* inst) {
  std::string instr_name =
      "Op" + std::string(spvOpcodeString(static_cast<SpvOp>(inst->opcode())));

  // Result type must be a 32-bit unsigned int.
  auto result_type = state.FindDef(inst->type_id());
  if (result_type->opcode() != SpvOpTypeInt ||
      result_type->GetOperandAs<uint32_t>(1) != 32 ||
      result_type->GetOperandAs<uint32_t>(2) != 0) {
    return state.diag(SPV_ERROR_INVALID_ID, inst)
           << "The Result Type of " << instr_name << " <id> '"
           << state.getIdName(inst->id())
           << "' must be OpTypeInt with width 32 and signedness 0.";
  }

  auto type_id = inst->GetOperandAs<uint32_t>(2);
  auto type = state.FindDef(type_id);
  if (type->opcode() != SpvOpTypeCooperativeMatrixNV) {
    return state.diag(SPV_ERROR_INVALID_ID, inst)
           << "The type in " << instr_name << " <id> '"
           << state.getIdName(type_id)
           << "' must be OpTypeCooperativeMatrixNV.";
  }
  return SPV_SUCCESS;
}

spv_result_t ValidateCooperativeMatrixLoadStoreNV(ValidationState_t& _,
                                                  const Instruction* inst) {
  uint32_t type_id;
  const char* opname;
  if (inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
    type_id = inst->type_id();
    opname = "SpvOpCooperativeMatrixLoadNV";
  } else {
    // get Object operand's type
    type_id = _.FindDef(inst->GetOperandAs<uint32_t>(1))->type_id();
    opname = "SpvOpCooperativeMatrixStoreNV";
  }

  auto matrix_type = _.FindDef(type_id);

  if (matrix_type->opcode() != SpvOpTypeCooperativeMatrixNV) {
    if (inst->opcode() == SpvOpCooperativeMatrixLoadNV) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "SpvOpCooperativeMatrixLoadNV Result Type <id> '"
             << _.getIdName(type_id) << "' is not a cooperative matrix type.";
    } else {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "SpvOpCooperativeMatrixStoreNV Object type <id> '"
             << _.getIdName(type_id) << "' is not a cooperative matrix type.";
    }
  }

  const bool uses_variable_pointers =
      _.features().variable_pointers ||
      _.features().variable_pointers_storage_buffer;
  const auto pointer_index =
      (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 2u : 0u;
  const auto pointer_id = inst->GetOperandAs<uint32_t>(pointer_index);
  const auto pointer = _.FindDef(pointer_id);
  if (!pointer ||
      ((_.addressing_model() == SpvAddressingModelLogical) &&
       ((!uses_variable_pointers &&
         !spvOpcodeReturnsLogicalPointer(pointer->opcode())) ||
        (uses_variable_pointers &&
         !spvOpcodeReturnsLogicalVariablePointer(pointer->opcode()))))) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << opname << " Pointer <id> '" << _.getIdName(pointer_id)
           << "' is not a logical pointer.";
  }

  const auto pointer_type_id = pointer->type_id();
  const auto pointer_type = _.FindDef(pointer_type_id);
  if (!pointer_type || pointer_type->opcode() != SpvOpTypePointer) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << opname << " type for pointer <id> '" << _.getIdName(pointer_id)
           << "' is not a pointer type.";
  }

  const auto storage_class_index = 1u;
  const auto storage_class =
      pointer_type->GetOperandAs<uint32_t>(storage_class_index);

  if (storage_class != SpvStorageClassWorkgroup &&
      storage_class != SpvStorageClassStorageBuffer &&
      storage_class != SpvStorageClassPhysicalStorageBufferEXT) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << opname << " storage class for pointer type <id> '"
           << _.getIdName(pointer_type_id)
           << "' is not Workgroup or StorageBuffer.";
  }

  const auto pointee_id = pointer_type->GetOperandAs<uint32_t>(2);
  const auto pointee_type = _.FindDef(pointee_id);
  if (!pointee_type || !(_.IsIntScalarOrVectorType(pointee_id) ||
                         _.IsFloatScalarOrVectorType(pointee_id))) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << opname << " Pointer <id> '" << _.getIdName(pointer->id())
           << "'s Type must be a scalar or vector type.";
  }

  const auto stride_index =
      (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 3u : 2u;
  const auto stride_id = inst->GetOperandAs<uint32_t>(stride_index);
  const auto stride = _.FindDef(stride_id);
  if (!stride || !_.IsIntScalarType(stride->type_id())) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Stride operand <id> '" << _.getIdName(stride_id)
           << "' must be a scalar integer type.";
  }

  const auto colmajor_index =
      (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 4u : 3u;
  const auto colmajor_id = inst->GetOperandAs<uint32_t>(colmajor_index);
  const auto colmajor = _.FindDef(colmajor_id);
  if (!colmajor || !_.IsBoolScalarType(colmajor->type_id()) ||
      !(spvOpcodeIsConstant(colmajor->opcode()) ||
        spvOpcodeIsSpecConstant(colmajor->opcode()))) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Column Major operand <id> '" << _.getIdName(colmajor_id)
           << "' must be a boolean constant instruction.";
  }

  const auto memory_access_index =
      (inst->opcode() == SpvOpCooperativeMatrixLoadNV) ? 5u : 4u;
  if (inst->operands().size() > memory_access_index) {
    if (auto error = CheckMemoryAccess(_, inst, memory_access_index))
      return error;
  }

  return SPV_SUCCESS;
}

spv_result_t ValidatePtrComparison(ValidationState_t& _,
                                   const Instruction* inst) {
  if (_.addressing_model() == SpvAddressingModelLogical &&
      !_.features().variable_pointers_storage_buffer) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Instruction cannot be used without a variable pointers "
              "capability";
  }

  const auto result_type = _.FindDef(inst->type_id());
  if (inst->opcode() == SpvOpPtrDiff) {
    if (!result_type || result_type->opcode() != SpvOpTypeInt) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Result Type must be an integer scalar";
    }
  } else {
    if (!result_type || result_type->opcode() != SpvOpTypeBool) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Result Type must be OpTypeBool";
    }
  }

  const auto op1 = _.FindDef(inst->GetOperandAs<uint32_t>(2u));
  const auto op2 = _.FindDef(inst->GetOperandAs<uint32_t>(3u));
  if (!op1 || !op2 || op1->type_id() != op2->type_id()) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "The types of Operand 1 and Operand 2 must match";
  }
  const auto op1_type = _.FindDef(op1->type_id());
  if (!op1_type || op1_type->opcode() != SpvOpTypePointer) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Operand type must be a pointer";
  }

  SpvStorageClass sc = op1_type->GetOperandAs<SpvStorageClass>(1u);
  if (_.addressing_model() == SpvAddressingModelLogical) {
    if (sc != SpvStorageClassWorkgroup && sc != SpvStorageClassStorageBuffer) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Invalid pointer storage class";
    }

    if (sc == SpvStorageClassWorkgroup && !_.features().variable_pointers) {
      return _.diag(SPV_ERROR_INVALID_ID, inst)
             << "Workgroup storage class pointer requires VariablePointers "
                "capability to be specified";
    }
  } else if (sc == SpvStorageClassPhysicalStorageBuffer) {
    return _.diag(SPV_ERROR_INVALID_ID, inst)
           << "Cannot use a pointer in the PhysicalStorageBuffer storage class";
  }

  return SPV_SUCCESS;
}

}  // namespace

spv_result_t MemoryPass(ValidationState_t& _, const Instruction* inst) {
  switch (inst->opcode()) {
    case SpvOpVariable:
      if (auto error = ValidateVariable(_, inst)) return error;
      break;
    case SpvOpLoad:
      if (auto error = ValidateLoad(_, inst)) return error;
      break;
    case SpvOpStore:
      if (auto error = ValidateStore(_, inst)) return error;
      break;
    case SpvOpCopyMemory:
    case SpvOpCopyMemorySized:
      if (auto error = ValidateCopyMemory(_, inst)) return error;
      break;
    case SpvOpPtrAccessChain:
      if (auto error = ValidatePtrAccessChain(_, inst)) return error;
      break;
    case SpvOpAccessChain:
    case SpvOpInBoundsAccessChain:
    case SpvOpInBoundsPtrAccessChain:
      if (auto error = ValidateAccessChain(_, inst)) return error;
      break;
    case SpvOpArrayLength:
      if (auto error = ValidateArrayLength(_, inst)) return error;
      break;
    case SpvOpCooperativeMatrixLoadNV:
    case SpvOpCooperativeMatrixStoreNV:
      if (auto error = ValidateCooperativeMatrixLoadStoreNV(_, inst))
        return error;
      break;
    case SpvOpCooperativeMatrixLengthNV:
      if (auto error = ValidateCooperativeMatrixLengthNV(_, inst)) return error;
      break;
    case SpvOpPtrEqual:
    case SpvOpPtrNotEqual:
    case SpvOpPtrDiff:
      if (auto error = ValidatePtrComparison(_, inst)) return error;
      break;
    case SpvOpImageTexelPointer:
    case SpvOpGenericPtrMemSemantics:
    default:
      break;
  }

  return SPV_SUCCESS;
}
}  // namespace val
}  // namespace spvtools