//package com.cloudera.solr;
//
//import com.cloudera.bean.Message;
//import org.apache.commons.codec.binary.Base64;
//import org.apache.hadoop.conf.Configuration;
//import org.apache.hadoop.security.UserGroupInformation;
//import org.apache.http.*;
//import org.apache.http.auth.AuthScope;
//import org.apache.http.auth.Credentials;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.methods.HttpUriRequest;
//import org.apache.http.client.params.AuthPolicy;
//import org.apache.http.impl.auth.SPNegoSchemeFactory;
//import org.apache.http.impl.client.DefaultHttpClient;
//import org.apache.http.protocol.HttpContext;
//import org.apache.solr.client.solrj.SolrQuery;
//import org.apache.solr.client.solrj.SolrServerException;
//import org.apache.solr.client.solrj.impl.CloudSolrServer;
//import org.apache.solr.client.solrj.impl.LBHttpSolrServer;
//import org.apache.solr.client.solrj.response.QueryResponse;
//import org.apache.solr.common.SolrDocument;
//import org.apache.solr.common.SolrDocumentList;
//import sun.security.acl.PrincipalImpl;
//
//import java.io.IOException;
//import java.security.Principal;
//import java.security.PrivilegedAction;
//
///**
// * package: com.cloudera.solr
// * describe: TODO
// * creat_user: Fayson
// * email: htechinfo@163.com
// * creat_date: 2017/11/25
// * creat_time: 下午11:40
// * 公众号：Hadoop实操
// */
//public class KBSolrTest1 {
//
//    public static void main(String[] args) {
//
//        final String zkHost = "ip-172-31-22-86.ap-southeast-1.compute.internal:2181/solr";
//        final String  defaultCollection = "collection1";
//        final int  socketTimeout = 20000;
//        final int zkConnectTimeout = 1000;
//
//        try {
//            System.setProperty("java.security.krb5.conf", "/Volumes/Transcend/keytab/krb5.conf");
//
//            //使用Kerberos账号登录
//            Configuration configuration = new Configuration();
//            configuration.set("hadoop.security.authentication" , "Kerberos");
//            UserGroupInformation. setConfiguration(configuration);
//            UserGroupInformation.loginUserFromKeytab("fayson@CLOUDERA.COM", "/Volumes/Transcend/keytab/fayson.keytab");
//            System.out.println(UserGroupInformation.getCurrentUser() + "------" + UserGroupInformation.getLoginUser());
//
//            UserGroupInformation loginUser = UserGroupInformation.getLoginUser();
//
//
//            System.setProperty("java.security.auth.login.config", "/Volumes/Transcend/keytab/http-login.conf");
//            System.setProperty("sun.security.krb5.debug", "true");
////            System.setProperty("javax.security.auth.useSubjectCredsOnly","false");
//
//            loginUser.doAs(new PrivilegedAction<Object>(){
//
//                public Object run() {
//
//                    DefaultHttpClient client = new DefaultHttpClient();
//                    //采用拦截器加权限验证
//                    client.addRequestInterceptor(new HttpRequestInterceptor() {
//                        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
//                            String enc = "fayson@CLOUDERA.COM" + ":" + "123456";
//                            request.addHeader("Authorization", "Basic " + Base64.encodeBase64String(enc.getBytes()));
//                        }
//                    });
//
//                    //采用robin环方式负载
//                    LBHttpSolrServer server = new LBHttpSolrServer(client,
//                            "http://ec2-13-229-49-186.ap-southeast-1.compute.amazonaws.com:8983/solr/" + defaultCollection);
//
//                    CloudSolrServer cloudSolrServer = new CloudSolrServer(zkHost, server);
//                    cloudSolrServer.setDefaultCollection(defaultCollection);
//                    cloudSolrServer.setZkConnectTimeout(zkConnectTimeout);
//                    cloudSolrServer.setZkClientTimeout(socketTimeout);
//                    cloudSolrServer.connect();
//
//                    search(cloudSolrServer, "id:999247449312");
//
//                    return null;
//                }
//            });
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 查找
//     * @param solrClient
//     * @param String
//     */
//    public static void search(CloudSolrServer solrClient, String String) {
//        SolrQuery query = new SolrQuery();
//        query.setQuery(String);
//        try {
//            QueryResponse response = solrClient.query(query);
//            SolrDocumentList docs = response.getResults();
//
//            System.out.println("文档个数：" + docs.getNumFound());
//            System.out.println("查询时间：" + response.getQTime());
//
//            for (SolrDocument doc : docs) {
//                String id = (String) doc.getFieldValue("id");
//                String created_at = (String) doc.getFieldValue("created_at");
//                String text = (String) doc.getFieldValue("text");
//                String text_cn = (String) doc.getFieldValue("text_cn");
//                System.out.println("id: " + id);
//                System.out.println("created_at: " + created_at);
//                System.out.println("text: " + text);
//                System.out.println("text_cn: " + text_cn);
//                System.out.println();
//            }
//        } catch (SolrServerException e) {
//            e.printStackTrace();
//        } catch (Exception e) {
//            System.out.println("Unknowned Exception!!!!");
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 添加索引，暂未测试通过
//     * @param solrClient
//     */
//    public static void addIndex(CloudSolrServer solrClient) {
//        try {
//
////            SolrInputDocument solrInputDocument = new SolrInputDocument();
////            solrInputDocument.setField("id", "1234567890");
////            solrInputDocument.setField("created_at", "2017-11-25 02:35:07");
////            solrInputDocument.setField("text", "hello world");
////            solrInputDocument.setField("text_cn", "张三是个农民，勤劳致富，奔小康");
////            solrClient.add("collection1", solrInputDocument);
//
//            Message message = new Message("1234567890", "2017-11-25 02:35:07","hello world","张三是个农民，勤劳致富，奔小康");
//            solrClient.addBean(message);
//            solrClient.commit();
//
//        } catch (SolrServerException e) {
//            System.out.println("Add docs Exception !!!");
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (Exception e) {
//            System.out.println("Unknowned Exception!!!!!");
//            e.printStackTrace();
//        }
//    }
//}


<!-- ============================================
     ::DATATOOL:: Generated from "pub.asn"
     ::DATATOOL:: by application DATATOOL version 1.5.0
     ::DATATOOL:: on 06/06/2006 23:03:48
     ============================================ -->

<!-- NCBI_Pub.dtd
  This file is built from a series of basic modules.
  The actual ELEMENT and ENTITY declarations are in the modules.
  This file is used to put them together.
-->

<!ENTITY % NCBI_Entity_module PUBLIC "-//NCBI//NCBI Entity Module//EN" "NCBI_Entity.mod.dtd">
%NCBI_Entity_module;

<!ENTITY % NCBI_Biblio_module PUBLIC "-//NCBI//NCBI Biblio Module//EN" "NCBI_Biblio.mod.dtd">
%NCBI_Biblio_module;

<!ENTITY % NCBI_General_module PUBLIC "-//NCBI//NCBI General Module//EN" "NCBI_General.mod.dtd">
%NCBI_General_module;

<!ENTITY % NCBI_Medline_module PUBLIC "-//NCBI//NCBI Medline Module//EN" "NCBI_Medline.mod.dtd">
%NCBI_Medline_module;

<!ENTITY % NCBI_Pub_module PUBLIC "-//NCBI//NCBI Pub Module//EN" "NCBI_Pub.mod.dtd">
%NCBI_Pub_module;


<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Hello World</string>
    <string name="newstring">Test</string>
</resources>


fileFormatVersion: 2
guid: e0c2082d5facde8429c252bc250f8656
timeCreated: 1485146945
licenseType: Pro
MonoImporter:
  serializedVersion: 2
  defaultReferences: []
  executionOrder: 0
  icon: {instanceID: 0}
  userData:
  assetBundleName:
  assetBundleVariant:


//
//     Generated by class-dump 3.5 (64 bit) (Debug version compiled Oct 25 2017 03:49:04).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

@class CWSecurityMismatchDialog;

@protocol CWSecurityMismatchDialogDelegate
- (void)userDidDenyJoin:(CWSecurityMismatchDialog *)arg1;
- (void)userDidConfirmJoin:(CWSecurityMismatchDialog *)arg1;
@end


/*
 * Seven Kingdoms: Ancient Adversaries
 *
 * Copyright 1997,1998 Enlight Software Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

//Filename   : OU_GOD.CPP
//Description: Unit God header file

#ifndef __OU_GOD_H
#define __OU_GOD_H

#ifndef __OUNIT_H
#include <OUNIT.h>
#endif

#ifndef __OFIRM_H
#include <OFIRM.h>
#endif

struct UnitGodCrc;

//----------- Define class God -----------//

#pragma pack(1)
class UnitGod : public Unit
{
public:
	short god_id;
	short base_firm_recno;		// recno of the seat of power which creates and supports this god unit
	char	cast_power_type;
	short	cast_origin_x, cast_origin_y;
	short cast_target_x, cast_target_y;

public:
	virtual void init_derived();
	void pre_process();
	int  process_attack();

	void disp_info(int refreshFlag);
	void detect_info();
	bool is_in_build_menu();

	void cast_power(int castXLoc, int castYLoc);

	//-------------- multiplayer checking codes ---------------//
	virtual	uint8_t crc8();
	virtual	void	clear_ptr();
	virtual void    init_crc(UnitGodCrc *c);

private:
	void consume_power_pray_points();

	void cast_on_loc(int castXLoc, int castYLoc);
	void cast_on_unit(int unitRecno, int divider);
	void cast_on_worker(Worker* workerPtr, int nationRecno, int divider);

	void viking_summon_rain();
	void viking_summon_tornado();

	void persian_cast_power(int unitRecno, int divider);
	void japanese_cast_power(int unitRecno, int divider);
	void maya_cast_power(int unitRecno, int divider);
	void egyptian_cast_power(int unitRecno, int divider);
	void indian_cast_power(int unitRecno, int divider);
	void zulu_cast_power(int unitRecno, int divider);

	void persian_cast_power(Worker* workerPtr, int nationRecno, int divider);
	void japanese_cast_power(Worker* workerPtr, int nationRecno, int divider);
	void maya_cast_power(Worker* workerPtr, int nationRecno, int divider);
	void egyptian_cast_power(Worker *workerPtr, int nationRecno, int divider);
	void indian_cast_power(Worker *workerPtr, int nationRecno, int divider);
	void zulu_cast_power(Worker *workerPtr, int nationRecno, int divider);

	//--------- AI functions ----------//

	void process_ai();
	void think_dragon();
	void think_maya_god();
	void think_phoenix();
	void think_viking_god();
	void think_persian_god();
	void think_chinese_dragon();
	void think_japanese_god();
	int  think_god_attack_target(int& targetXLoc, int& targetYLoc);

	void think_egyptian_god();
	void think_indian_god();
	void think_zulu_god();
};
#pragma pack()

//--------------------------------------------//

#endif


/*---------------------------------------------------------------------------*\
  =========                 |
  \\      /  F ield         | OpenFOAM: The Open Source CFD Toolbox
   \\    /   O peration     |
    \\  /    A nd           | Copyright (C) 2011-2014 OpenFOAM Foundation
     \\/     M anipulation  |
-------------------------------------------------------------------------------
License
    This file is part of OpenFOAM.

    OpenFOAM is free software: you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    for more details.

    You should have received a copy of the GNU General Public License
    along with OpenFOAM.  If not, see <http://www.gnu.org/licenses/>.

\*---------------------------------------------------------------------------*/

#include "sphericalAngularSpring.H"
#include "addToRunTimeSelectionTable.H"
#include "sixDoFRigidBodyMotion.H"

// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //

namespace Foam
{
namespace sixDoFRigidBodyMotionRestraints
{
    defineTypeNameAndDebug(sphericalAngularSpring, 0);

    addToRunTimeSelectionTable
    (
        sixDoFRigidBodyMotionRestraint,
        sphericalAngularSpring,
        dictionary
    );
}
}

// * * * * * * * * * * * * * * * * Constructors  * * * * * * * * * * * * * * //

Foam::sixDoFRigidBodyMotionRestraints::sphericalAngularSpring::
sphericalAngularSpring
(
    const word& name,
    const dictionary& sDoFRBMRDict
)
:
    sixDoFRigidBodyMotionRestraint(name, sDoFRBMRDict),
    refQ_(),
    stiffness_(),
    damping_()
{
    read(sDoFRBMRDict);
}

// * * * * * * * * * * * * * * * * Destructors * * * * * * * * * * * * * * * //

Foam::sixDoFRigidBodyMotionRestraints::sphericalAngularSpring::
~sphericalAngularSpring()
{}

// * * * * * * * * * * * * * * Member Functions  * * * * * * * * * * * * * * //

void Foam::sixDoFRigidBodyMotionRestraints::sphericalAngularSpring::restrain
(
    const sixDoFRigidBodyMotion& motion,
    vector& restraintPosition,
    vector& restraintForce,
    vector& restraintMoment
) const
{
    restraintMoment = vector::zero;

    for (direction cmpt=0; cmpt<vector::nComponents; cmpt++)
    {
        vector axis = vector::zero;
        axis[cmpt] = 1;

        vector refDir = vector::zero;
        refDir[(cmpt + 1) % 3] = 1;

        vector newDir = motion.orientation() & refDir;

        axis = (refQ_ & axis);
        refDir = (refQ_ & refDir);
        newDir -= (axis & newDir)*axis;

        restraintMoment += -stiffness_*(refDir ^ newDir);
    }

    restraintMoment += -damping_*motion.omega();

    restraintForce = vector::zero;

    // Not needed to be altered as restraintForce is zero, but set to
    // centreOfRotation to be sure of no spurious moment
    restraintPosition = motion.centreOfRotation();

    if (motion.report())
    {
        Info<< " moment " << restraintMoment
            << endl;
    }
}

bool Foam::sixDoFRigidBodyMotionRestraints::sphericalAngularSpring::read
(
    const dictionary& sDoFRBMRDict
)
{
    sixDoFRigidBodyMotionRestraint::read(sDoFRBMRDict);

    refQ_ = sDoFRBMRCoeffs_.lookupOrDefault<tensor>("referenceOrientation", I);

    if (mag(mag(refQ_) - sqrt(3.0)) > 1e-9)
    {
        FatalErrorIn
        (
            "Foam::sixDoFRigidBodyMotionRestraints::sphericalAngularSpring::"
            "read"
            "("
                "const dictionary& sDoFRBMRDict"
            ")"
        )
            << "referenceOrientation " << refQ_ << " is not a rotation tensor. "
            << "mag(referenceOrientation) - sqrt(3) = "
            << mag(refQ_) - sqrt(3.0) << nl
            << exit(FatalError);
    }

    sDoFRBMRCoeffs_.lookup("stiffness") >> stiffness_;
    sDoFRBMRCoeffs_.lookup("damping") >> damping_;

    return true;
}

void Foam::sixDoFRigidBodyMotionRestraints::sphericalAngularSpring::write
(
    Ostream& os
) const
{
    os.writeKeyword("referenceOrientation")
        << refQ_ << token::END_STATEMENT << nl;

    os.writeKeyword("stiffness") << stiffness_ << token::END_STATEMENT << nl;

    os.writeKeyword("damping") << damping_ << token::END_STATEMENT << nl;
}

// ************************************************************************* //


<?xml version="1.0"?>
<!--
 *************************************************************************
 * Copyright (c) 2004, 2005 Actuate Corporation.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Actuate Corporation  - initial API and implementation
 *
 *************************************************************************
 *
 *  Build.xml
 *
 *  Created on 03/15/2005
 *  Build script for project org.eclipse.birt.core
 *
 *
 * The following are public targets callable by external users.
 *
 * "Clean" - Clean all objects created by this script. Individual project build script can not call this target;
 * "Jar" - Compile source code and generate jar for this project.
 *          The compile dependency on other projects should be defined explicitly.
 *         eclipse.home should be passed in when Individual project build script  call this target;
 *          the property of "failonerror" should be set true(default) when compiling source code
 * "UnitTest" - Run unit tests. This task must be called after calling Jar task,
 *              so it needn't depend on Jar explicitly
 * "Export" - Export the project, for instance, jar files are copied to a designated folder.
 *            this task must be called after calling Jar task, so it needn't depend on Jar explicitly
 * "JavaDoc" - generate java documents
 *
 * Usage:
 *    ant [any one or more of the public targets]
 *        -Declipse.home=<your eclipse home>
 *
 * Default target is "Jar".
 *
 *
 * This script may also additional targets. These targets are private to this build script only.
 *
 * "utest" - Run unit tests
 *
 * Notes:
 *  1. classpath need to be set for junit.jar
 *  2. This file now requires Ant 1.6
 *
 * Change History:
 *
 *    1. 09/22/2005: initial version
 *
-->

<project name="BIRT Core UI" default="Jar" basedir=".">
	<description>BIRT Core Project.</description>
	<!-- set global properties for this build -->
	<!-- Public properties, used by public targets, top level build script
		     will pass on the value at runtime. Properties will have there default
		     value.
		     eclipse.home
		     utest.report.dir
		     javadoc.dir
	-->

	<!-- ===== Default value for public properties ============= -->
	<property file="META-INF/MANIFEST.MF" />
	<property name="javadoc.dir" location="docs/api" />
	<property name="export.dir" location="export" />
	<property name="eclipse.home" location="." />
 	<property name="dir.src" value="src" />
 	<property name="dir.test" value="test" />
 	<property name="dir.bin" value="bin" />
 	<property name="dir.lib" value="lib" />

	<property name="core.dir" location="../org.eclipse.birt.core"/>

 	<property name="module.name" value="org.eclipse.birt.core.ui" />
	<property name="jar.name" value="${module.name}_${Bundle-Version}.jar" />

	<path id="class.path">
		<pathelement path="${dir.bin}"/>
		<!--
		<fileset dir="${dir.lib}">
			<include name="**/*.jar"/>
		</fileset>
		-->
		<!-- depends on eclispe runtime plugin -->
		<fileset dir="${eclipse.home}/plugins">
			<include name="org.eclipse.core.runtime_*/runtime.jar"/>
			<include name="org.eclipse.osgi_*/*.jar"/>
			<include name="org.eclipse.core.*.jar"/>
			<include name="org.eclipse.osgi*.jar"/>
			<include name="org.eclipse.swt*.jar"/>
			<include name="org.eclipse.jface*.jar"/>
			<include name="org.eclipse.equinox*.jar"/>
			<include name="com.ibm.icu_*.jar"/>
		</fileset>

		<fileset file="${core.dir}/*.jar" />
	</path>

	<!-- Compile source code and generate jar for this project.
		 Input parameters:
		 	eclipse.home
	-->
	<target name="Jar" depends="compileSource">
		<jar destfile="${jar.name}" manifest="./META-INF/MANIFEST.MF">
			<fileset dir="${dir.bin}">
				<include name="**/*.class"/>
				<include name="**/*.xml"/>
				<include name="**/*.def"/>
				<include name="**/*.properties"/>
				<exclude name="**/*Test.class"/>
			</fileset>
			<fileset dir="." includes="about.html,plugin.xml,.options,schema/**,icons/**"/>
		</jar>
	</target>

	<!-- compile the source code -->
	<target name="compileSource" depends="init, buildDependents" description="compile the source ">
		<mkdir dir="${dir.bin}"/>

		<!-- copy any resource file we needed into the bin directory-->
		<copy todir="${dir.bin}">
			<fileset dir="${dir.src}">
				<include name="**/*.txt"/>
				<include name="**/*.xml"/>
				<include name="**/*.properties"/>
			</fileset>
		</copy>

		<!-- Compile the java code from ${src} ${test_src} into ${bin} -->
		<javac srcdir="${dir.src}"
			   destdir="${dir.bin}"
			   encoding="utf-8"
			   source="1.4"
			   debug="true">

			<classpath refid="class.path"/>
		</javac>
	</target>

	<!-- Compile Source code and test code. -->
	<target name="compile" depends="compileSource, compileTest" description="compile all the source " />

	<!-- Export the project, for instance, jar files are copied to a designated folder
		 the dependency on Jar should implement in top level script by call sequence
		 Parameters:
		 		- ${export.dir} target directory to put the plugin binaries
		 		- ${plugin.version} the version of plugin exported
	 -->
	<target name="Export">
		<copy todir="${export.dir}">
	        <fileset dir="." includes="${jar.name}"/>
	  </copy>
	</target>

	<!-- Compile Core Test Files
		 javac.failonerror should be true.
	-->
	<target name="compileTest" description="compile the test ">
		<copy todir="${dir.bin}">
			<fileset dir="${dir.test}">
				<include name="**/*.txt"/>
				<include name="**/*.xml"/>
				<include name="**/*.golden"/>
				<include name="**/*.jpg"/>
				<include name="**/*.zip"/>
			</fileset>
		</copy>

		<!-- Compile the java code from ${dir.test} into ${dir.bin} -->
		<javac srcdir="${dir.test}"
			   destdir="${dir.bin}"
			   encoding="utf-8"
			   source="1.4"
			   debug="true"
			   failonerror="true" >

			<classpath refid="class.path"/>
		</javac>
	</target>

	<!-- No unit tests, dummy target -->
	<target name="UnitTest" />

	<!-- Clean all objects created by this script -->
	<target name="Clean" description="clean up">
		<!-- Delete the ${bin} and ${utest} directory trees -->
		<delete dir="${dir.bin}"/>
		<delete dir="${dir.utest}"/>
		<delete dir="${utes.report.dir}"/>
		<delete file="${jar.name}"/>
	</target>

	<!-- Generate the JavaDoc.
		 Parameters:
		 		- ${javadoc.dir} target directory to put the java document
	 -->
	<target name="Javadoc">
		<mkdir dir="${javadoc.dir}" />
		<javadoc destdir="${javadoc.dir}"
				 author="true"
				 version="true"
				 use="true"
				 windowtitle="Birt Wizard Framework API"
				 source="1.4"
				 packagenames="${module.name}.*">
				<packageset dir="${dir.src}" defaultexcludes="yes" />
	 	        <bottom><![CDATA[<i>Copyright ©  2005 Actuate Corp. All rights reserved. </i>]]></bottom>
				<classpath refid="class.path" />
		</javadoc>
	</target>

	<target name="init" description="initialization">
		<condition property="eclipse.home.isset">
			<isset property="eclipse.home" />
		</condition>

		<!-- eclipse.home must be set -->
		<fail unless="eclipse.home.isset" message="Property eclipse.home should be set, build failed!"/>
	</target>

	<!-- Build the dependent projects -->
	<target name="buildDependents" description="Build all the projects it depends on">
		<echo message="start call Jar task in ${core.dir}" level="info"/>
		<ant dir="${core.dir}" antfile="BuildCore.xml" target="Jar" inheritall="false">
		 	<property name="eclipse.home" value="${eclipse.home}" />
		</ant>
		<echo message="end call Jar task in ${core.dir}" level="info" />
	</target>

	<!-- private task, compile source and test code and run unit test-->
	<target name="utest" depends="compileSource, UnitTest" />
</project>


============================================================================

   JSONlab - a toolbox to encode/decode JSON/UBJSON files in MATLAB/Octave

----------------------------------------------------------------------------

JSONlab ChangeLog (key features marked by *):

== JSONlab 1.0 (codename: Optimus - Final), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2015/01/02 polish help info for all major functions, update examples, finalize 1.0
 2014/12/19 fix a bug to strictly respect NoRowBracket in savejson

== JSONlab 1.0.0-RC2 (codename: Optimus - RC2), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2014/11/22 show progress bar in loadjson ('ShowProgress')
 2014/11/17 add Compact option in savejson to output compact JSON format ('Compact')
 2014/11/17 add FastArrayParser in loadjson to specify fast parser applicable levels
 2014/09/18 start official github mirror: https://github.com/fangq/jsonlab

== JSONlab 1.0.0-RC1 (codename: Optimus - RC1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2014/09/17  fix several compatibility issues when running on octave versions 3.2-3.8
 2014/09/17  support 2D cell and struct arrays in both savejson and saveubjson
 2014/08/04  escape special characters in a JSON string
 2014/02/16  fix a bug when saving ubjson files

== JSONlab 0.9.9 (codename: Optimus - beta), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2014/01/22  use binary read and write in saveubjson and loadubjson

== JSONlab 0.9.8-1 (codename: Optimus - alpha update 1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2013/10/07 better round-trip conservation for empty arrays and structs (patch submitted by Yul Kang)

== JSONlab 0.9.8 (codename: Optimus - alpha), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
 2013/08/23 *universal Binary JSON (UBJSON) support, including both saveubjson and loadubjson

== JSONlab 0.9.1 (codename: Rodimus, update 1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==
 2012/12/18 *handling of various empty and sparse matrices (fixes submitted by Niclas Borlin)

== JSONlab 0.9.0 (codename: Rodimus), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2012/06/17 *new format for an invalid leading char, unpacking hex code in savejson
 2012/06/01  support JSONP in savejson
 2012/05/25  fix the empty cell bug (reported by Cyril Davin)
 2012/04/05  savejson can save to a file (suggested by Patrick Rapin)

== JSONlab 0.8.1 (codename: Sentiel, Update 1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2012/02/28  loadjson quotation mark escape bug, see http://bit.ly/yyk1nS
 2012/01/25  patch to handle root-less objects, contributed by Blake Johnson

== JSONlab 0.8.0 (codename: Sentiel), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2012/01/13 *speed up loadjson by 20 fold when parsing large data arrays in matlab
 2012/01/11  remove row bracket if an array has 1 element, suggested by Mykel Kochenderfer
 2011/12/22 *accept sequence of 'param',value input in savejson and loadjson
 2011/11/18  fix struct array bug reported by Mykel Kochenderfer

== JSONlab 0.5.1 (codename: Nexus Update 1), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2011/10/21  fix a bug in loadjson, previous code does not use any of the acceleration
 2011/10/20  loadjson supports JSON collections - concatenated JSON objects

== JSONlab 0.5.0 (codename: Nexus), FangQ <fangq (at) nmr.mgh.harvard.edu> ==

 2011/10/16  package and release jsonlab 0.5.0
 2011/10/15 *add json demo and regression test, support cpx numbers, fix double quote bug
 2011/10/11 *speed up readjson dramatically, interpret _Array* tags, show data in root level
 2011/10/10  create jsonlab project, start jsonlab website, add online documentation
 2011/10/07 *speed up savejson by 25x using sprintf instead of mat2str, add options support
 2011/10/06 *savejson works for structs, cells and arrays
 2011/09/09  derive loadjson from JSON parser from MATLAB Central, draft savejson.m


using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FakeXrmEasy.Tests.2015")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FakeXrmEasy.Tests.2015")]
[assembly: AssemblyCopyright("Copyright ©  2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("19a1f076-fbe5-42fd-9792-b98d90615b6f")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.44.0.0")]
[assembly: AssemblyVersion("1.57.1.0")]
[assembly: AssemblyFileVersion("1.57.1.0")]


<% title "Shopping Cart" %>

    Product
    Qty
    Unit Price
    Full Price

  <% for line_item in @cart.line_items %>
    <tr class="<%= cycle :odd, :even %>">
      <%=h line_item.product.name %>
      <%= line_item.quantity %>
      <%= number_to_currency(line_item.unit_price) %>
      <%= number_to_currency(line_item.full_price) %>

  <% end %>

      Total: <%= number_to_currency @cart.total_price %>

  <%= link_to "Continue Shopping", products_path %> |
  <%= link_to "Checkout", new_order_path %>


# Project-wide Gradle settings.

# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

HOCKEYAPP_BINTRAY_USER=
HOCKEYAPP_BINTRAY_KEY=


#test originally coded to prove aslongas was broken, it is corrected now. this test now shows that he remains a 3/3 and survives.

#Test to confirm that "aslongas" in combination with ">" or "<" does not work.
#You control 4 arifacts and Auriok Sunchaser. It is 3/3 due to its Metalcraft bonus (+2/+2).
#1 of the 4 artifacts gets destroyed by Shatter. Auriok Sunchaser should stay 3/3 because there are still enough artifacts on your side,
#but in fact, Metalcraft is turned off, so Shock can kill Auriok Sunchaser.

[INIT]
FIRSTMAIN
[PLAYER1]
inplay:Auriok Sunchaser,Bottle Gnomes,Mox Pearl,Bonesplitter,Mox Emerald
hand:Shatter,Shock
manapool:{1}{R}{R}
[PLAYER2]
[DO]
Shatter
Mox Pearl
Shock
Auriok Sunchaser
[ASSERT]
FIRSTMAIN
[PLAYER1]
inplay:Bottle Gnomes,Bonesplitter,Mox Emerald,Auriok Sunchaser
graveyard:Shatter,Mox Pearl,Shock
manapool:{0}
life:20
[PLAYER2]
[END]


## 在会议标准化及服务提升项目汇报会上的讲话

2017年10月18日

一、会议室即作战室，我们的目标是胜利。会议室建设全球标准化，适应现代化作战需求，用最先进的软、硬件装备支撑业务“多产粮食”。

我们不要在会议设施投入上省钱，而要快速行动去改进装备，用世界上最先进的“武器”打赢现代化“战争”。华为公司现在每天最低支付的工资就有几个亿……，如果因设备落后导致会议效率低，浪费的是人力高成本。所以，我们要开放思想，浪费人力成本的钱，不如让作战装备更先进一些。

1、在硬件方面，首先要做到多屏显示，支撑会议实用和远程会议。

会议室应该是多屏显示、大屏显示、多接入，屏之间可以互动、重叠。我支持简单、高效的会议，但不支持简单的会议设备，一定要有便捷使用的工具，把复杂问题留给IT部门去解决。比如，与会人需要各自调出一张数据，没有必要一屏多用（在一个屏幕上不断切换内容），如果会议室有多屏显示，每个人都可以把自己意见投在不同屏幕上，信息直观，便于比对、磋商、决策。所以，我认为大型会议室应该是多屏、大屏，中型会议室至少3屏。只要是合理的显示方式，不一定都需要用投影仪，有些电子屏还可以方便书写。屏幕可以大一些，视觉效果好，即使员工坐在最不利的角度，也能有清晰的感受。各业务部门和各代表处至少规划1-2个综合会议室支持业务作战，我看到有些小国的会议室小小的，还是过去的习惯。

会议室、咖啡厅都要配置高速WIFI，这样3-5人的小型会议可以到咖啡厅召开，看个人电脑屏幕。如果这么大的会议室只有3-5人使用，高成本不如补贴咖啡费用。

2、在软件方面，IT部门要开放，引入世界上最先进的软件系统来构建华为的“万里长城”。

会议室的硬件设施改造好了，软件设施也要跟上来。引入最先进的软件，建立联动机制，让作战体系更高效。比如，把会议室预订、纪要、会场连接、三朵云、运营中心、大T能力中心调入、会务服务管理系统……这些软服务要做好，标准化。开放环境，每个人都可以使用手机、电脑方便接入视频会议系统，我们不要过于保密，自己捆住自己的手脚。

IT部门要开放，引进世界上最优秀的软件来构建我们的“万里长城”，尽量不要去自主开发，“自己的狗粮自己吃”是针对我们的产品部门。比如，会议室能否引进讯飞的语音软件？开完会自动生成文字纪要初稿，修改后，会议纪要就能在最短时间内发布。作战命令早一天到前线，就能早一天产出粮食。而且，会议系统要支持多种语言同时使用，我们有这么多外籍员工，中文、英语、日语、法语……都可以借助翻译软件方便交流。即使翻译得不精准也没关系，我们还有胶片辅助理解。

3、会议室装修要服从于作战需要，不能为了美观而不实用。

将来会议室应该叫作战室，不用装修得多高档，要简洁、大方，更要适合现代化办公，营造出积极的作战氛围。比如，可以把墙面改成白板、屏幕、玻璃……，也可以在墙上挂满作战地图，一边挂上网络拓扑图，一边挂上GOOGLE地图。

B1会议室继续改造，首先要做到实用。现在你们的会议室很整洁，没有看到一条明线，如果改造后做不到全都走暗线，可以先走明线，便于使用。林彪的作战地图也是随意挂在墙上的，我们要的是胜利，不是外观美丽。

你们梳理出会议室标准，基建协助完成。大家一起来改，改出一个新会议室样板来，然后全公司统一。

二、构建标准化的会议服务管理系统，同时能支持个性化会务需求，让员工聚焦会议。

1、一站式会议管家做好会议室的基础保障服务。

建立会议服务支持中心，借鉴业界优秀实践，结合华为业务，持续优化会议室建设及服务标准；建设数字化运营平台，变被动为主动，确保会议系统安全稳定运行；同时，统一会议室服务接口，提供一站式会议管家服务。

2、我们要基于信任管理，为员工提供增值服务。

其他会务服务，比如咖啡、水果、餐点……都纳入会务服务管理系统。会议室是授权单位，只要员工按了服务按钮，点击了需要的服务，就提供相应服务，连报销都不用管了，全部自动完成。让员工聚焦开会，提升效率。会议室消费及小型在会议室外面的会议消费的报销模式，财务拿出一个规定，灵活一点。预订和结算系统在一起，可以每个月结算一次。

机关不要限制住会议室服务方式，服务多姿多彩，鼓励改变，快速响应个性化要求。比如，有贵客要在咖啡厅开会，需要哪种台布、哪一种花……都可以要求，只要能帮助作战胜利；还可以提供充电宝，方便电脑使用。当然，价格可以比标准服务适当提高一些，不冲突。我们是鼓励涨价的，降价是走进恶性竞争，涨价就是提高服务质量。

三、会议室改造预算单列，2018年底前全球会议室按新标准完成改造。

在会议室改造上，你们的思路方向大致正确，但还要敢于投资。由流程IT、行政、基建、慧通成立新的会议变革项目组，陶景文任组长。预算单列，充分授权，预算内的事情由这个小组直接决策。

项目组快速改造一两间实用的会议室，请一批使用会议室最多的人来评价和验收，制定出会议室装修标准初稿。然后与财经沟通预算、核算方式，文件定稿后，全球会议室都按此标准执行。希望2017年底，至少在每个国家或者每个地区部有一两个样板点；2018年年底，华为全球所有的会议室都要按新标准完成改造，我来参加你们的庆功会！


//===- StructurizeCFG.cpp -------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SCCIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Analysis/InstructionSimplify.h"
#include "llvm/Analysis/LegacyDivergenceAnalysis.h"
#include "llvm/Analysis/RegionInfo.h"
#include "llvm/Analysis/RegionIterator.h"
#include "llvm/Analysis/RegionPass.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CFG.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueHandle.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/SSAUpdater.h"
#include <algorithm>
#include <cassert>
#include <utility>

using namespace llvm;
using namespace llvm::PatternMatch;

#define DEBUG_TYPE "structurizecfg"

// The name for newly created blocks.
static const char *const FlowBlockName = "Flow";

namespace {

static cl::opt<bool> ForceSkipUniformRegions(
  "structurizecfg-skip-uniform-regions",
  cl::Hidden,
  cl::desc("Force whether the StructurizeCFG pass skips uniform regions"),
  cl::init(false));

static cl::opt<bool>
    RelaxedUniformRegions("structurizecfg-relaxed-uniform-regions", cl::Hidden,
                          cl::desc("Allow relaxed uniform region checks"),
                          cl::init(true));

// Definition of the complex types used in this pass.

using BBValuePair = std::pair<BasicBlock *, Value *>;

using RNVector = SmallVector<RegionNode *, 8>;
using BBVector = SmallVector<BasicBlock *, 8>;
using BranchVector = SmallVector<BranchInst *, 8>;
using BBValueVector = SmallVector<BBValuePair, 2>;

using BBSet = SmallPtrSet<BasicBlock *, 8>;

using PhiMap = MapVector<PHINode *, BBValueVector>;
using BB2BBVecMap = MapVector<BasicBlock *, BBVector>;

using BBPhiMap = DenseMap<BasicBlock *, PhiMap>;
using BBPredicates = DenseMap<BasicBlock *, Value *>;
using PredMap = DenseMap<BasicBlock *, BBPredicates>;
using BB2BBMap = DenseMap<BasicBlock *, BasicBlock *>;

// A traits type that is intended to be used in graph algorithms. The graph
// traits starts at an entry node, and traverses the RegionNodes that are in
// the Nodes set.
struct SubGraphTraits {
  using NodeRef = std::pair<RegionNode *, SmallDenseSet<RegionNode *> *>;
  using BaseSuccIterator = GraphTraits<RegionNode *>::ChildIteratorType;

  // This wraps a set of Nodes into the iterator, so we know which edges to
  // filter out.
  class WrappedSuccIterator
      : public iterator_adaptor_base<
            WrappedSuccIterator, BaseSuccIterator,
            typename std::iterator_traits<BaseSuccIterator>::iterator_category,
            NodeRef, std::ptrdiff_t, NodeRef *, NodeRef> {
    SmallDenseSet<RegionNode *> *Nodes;

  public:
    WrappedSuccIterator(BaseSuccIterator It, SmallDenseSet<RegionNode *> *Nodes)
        : iterator_adaptor_base(It), Nodes(Nodes) {}

    NodeRef operator*() const { return {*I, Nodes}; }
  };

  static bool filterAll(const NodeRef &N) { return true; }
  static bool filterSet(const NodeRef &N) { return N.second->count(N.first); }

  using ChildIteratorType =
      filter_iterator<WrappedSuccIterator, bool (*)(const NodeRef &)>;

  static NodeRef getEntryNode(Region *R) {
    return {GraphTraits<Region *>::getEntryNode(R), nullptr};
  }

  static NodeRef getEntryNode(NodeRef N) { return N; }

  static iterator_range<ChildIteratorType> children(const NodeRef &N) {
    auto *filter = N.second ? &filterSet : &filterAll;
    return make_filter_range(
        make_range<WrappedSuccIterator>(
            {GraphTraits<RegionNode *>::child_begin(N.first), N.second},
            {GraphTraits<RegionNode *>::child_end(N.first), N.second}),
        filter);
  }

  static ChildIteratorType child_begin(const NodeRef &N) {
    return children(N).begin();
  }

  static ChildIteratorType child_end(const NodeRef &N) {
    return children(N).end();
  }
};

/// Finds the nearest common dominator of a set of BasicBlocks.
///
/// For every BB you add to the set, you can specify whether we "remember" the
/// block.  When you get the common dominator, you can also ask whether it's one
/// of the blocks we remembered.
class NearestCommonDominator {
  DominatorTree *DT;
  BasicBlock *Result = nullptr;
  bool ResultIsRemembered = false;

  /// Add BB to the resulting dominator.
  void addBlock(BasicBlock *BB, bool Remember) {
    if (!Result) {
      Result = BB;
      ResultIsRemembered = Remember;
      return;
    }

    BasicBlock *NewResult = DT->findNearestCommonDominator(Result, BB);
    if (NewResult != Result)
      ResultIsRemembered = false;
    if (NewResult == BB)
      ResultIsRemembered |= Remember;
    Result = NewResult;
  }

public:
  explicit NearestCommonDominator(DominatorTree *DomTree) : DT(DomTree) {}

  void addBlock(BasicBlock *BB) {
    addBlock(BB, /* Remember = */ false);
  }

  void addAndRememberBlock(BasicBlock *BB) {
    addBlock(BB, /* Remember = */ true);
  }

  /// Get the nearest common dominator of all the BBs added via addBlock() and
  /// addAndRememberBlock().
  BasicBlock *result() { return Result; }

  /// Is the BB returned by getResult() one of the blocks we added to the set
  /// with addAndRememberBlock()?
  bool resultIsRememberedBlock() { return ResultIsRemembered; }
};

/// Transforms the control flow graph on one single entry/exit region
/// at a time.
///
/// After the transform all "If"/"Then"/"Else" style control flow looks like
/// this:
///
/// \verbatim
/// 1
/// ||
/// | |
/// 2 |
/// | /
/// |/
/// 3
/// ||   Where:
/// | |  1 = "If" block, calculates the condition
/// 4 |  2 = "Then" subregion, runs if the condition is true
/// | /  3 = "Flow" blocks, newly inserted flow blocks, rejoins the flow
/// |/   4 = "Else" optional subregion, runs if the condition is false
/// 5    5 = "End" block, also rejoins the control flow
/// \endverbatim
///
/// Control flow is expressed as a branch where the true exit goes into the
/// "Then"/"Else" region, while the false exit skips the region
/// The condition for the optional "Else" region is expressed as a PHI node.
/// The incoming values of the PHI node are true for the "If" edge and false
/// for the "Then" edge.
///
/// Additionally to that even complicated loops look like this:
///
/// \verbatim
/// 1
/// ||
/// | |
/// 2 ^  Where:
/// | /  1 = "Entry" block
/// |/   2 = "Loop" optional subregion, with all exits at "Flow" block
/// 3    3 = "Flow" block, with back edge to entry block
/// |
/// \endverbatim
///
/// The back edge of the "Flow" block is always on the false side of the branch
/// while the true side continues the general flow. So the loop condition
/// consist of a network of PHI nodes where the true incoming values expresses
/// breaks and the false values expresses continue states.
class StructurizeCFG : public RegionPass {
  bool SkipUniformRegions;

  Type *Boolean;
  ConstantInt *BoolTrue;
  ConstantInt *BoolFalse;
  UndefValue *BoolUndef;

  Function *Func;
  Region *ParentRegion;

  LegacyDivergenceAnalysis *DA;
  DominatorTree *DT;

  SmallVector<RegionNode *, 8> Order;
  BBSet Visited;

  SmallVector<WeakVH, 8> AffectedPhis;
  BBPhiMap DeletedPhis;
  BB2BBVecMap AddedPhis;

  PredMap Predicates;
  BranchVector Conditions;

  BB2BBMap Loops;
  PredMap LoopPreds;
  BranchVector LoopConds;

  RegionNode *PrevNode;

  void orderNodes();

  void analyzeLoops(RegionNode *N);

  Value *buildCondition(BranchInst *Term, unsigned Idx, bool Invert);

  void gatherPredicates(RegionNode *N);

  void collectInfos();

  void insertConditions(bool Loops);

  void delPhiValues(BasicBlock *From, BasicBlock *To);

  void addPhiValues(BasicBlock *From, BasicBlock *To);

  void setPhiValues();

  void simplifyAffectedPhis();

  void killTerminator(BasicBlock *BB);

  void changeExit(RegionNode *Node, BasicBlock *NewExit,
                  bool IncludeDominator);

  BasicBlock *getNextFlow(BasicBlock *Dominator);

  BasicBlock *needPrefix(bool NeedEmpty);

  BasicBlock *needPostfix(BasicBlock *Flow, bool ExitUseAllowed);

  void setPrevNode(BasicBlock *BB);

  bool dominatesPredicates(BasicBlock *BB, RegionNode *Node);

  bool isPredictableTrue(RegionNode *Node);

  void wireFlow(bool ExitUseAllowed, BasicBlock *LoopEnd);

  void handleLoops(bool ExitUseAllowed, BasicBlock *LoopEnd);

  void createFlow();

  void rebuildSSA();

public:
  static char ID;

  explicit StructurizeCFG(bool SkipUniformRegions_ = false)
      : RegionPass(ID),
        SkipUniformRegions(SkipUniformRegions_) {
    if (ForceSkipUniformRegions.getNumOccurrences())
      SkipUniformRegions = ForceSkipUniformRegions.getValue();
    initializeStructurizeCFGPass(*PassRegistry::getPassRegistry());
  }

  bool doInitialization(Region *R, RGPassManager &RGM) override;

  bool runOnRegion(Region *R, RGPassManager &RGM) override;

  StringRef getPassName() const override { return "Structurize control flow"; }

  void getAnalysisUsage(AnalysisUsage &AU) const override {
    if (SkipUniformRegions)
      AU.addRequired<LegacyDivergenceAnalysis>();
    AU.addRequiredID(LowerSwitchID);
    AU.addRequired<DominatorTreeWrapperPass>();

    AU.addPreserved<DominatorTreeWrapperPass>();
    RegionPass::getAnalysisUsage(AU);
  }
};

} // end anonymous namespace

char StructurizeCFG::ID = 0;

INITIALIZE_PASS_BEGIN(StructurizeCFG, "structurizecfg", "Structurize the CFG",
                      false, false)
INITIALIZE_PASS_DEPENDENCY(LegacyDivergenceAnalysis)
INITIALIZE_PASS_DEPENDENCY(LowerSwitchLegacyPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(RegionInfoPass)
INITIALIZE_PASS_END(StructurizeCFG, "structurizecfg", "Structurize the CFG",
                    false, false)

/// Initialize the types and constants used in the pass
bool StructurizeCFG::doInitialization(Region *R, RGPassManager &RGM) {
  LLVMContext &Context = R->getEntry()->getContext();

  Boolean = Type::getInt1Ty(Context);
  BoolTrue = ConstantInt::getTrue(Context);
  BoolFalse = ConstantInt::getFalse(Context);
  BoolUndef = UndefValue::get(Boolean);

  return false;
}

/// Build up the general order of nodes, by performing a topological sort of the
/// parent region's nodes, while ensuring that there is no outer cycle node
/// between any two inner cycle nodes.
void StructurizeCFG::orderNodes() {
  Order.resize(std::distance(GraphTraits<Region *>::nodes_begin(ParentRegion),
                             GraphTraits<Region *>::nodes_end(ParentRegion)));
  if (Order.empty())
    return;

  SmallDenseSet<RegionNode *> Nodes;
  auto EntryNode = SubGraphTraits::getEntryNode(ParentRegion);

  // A list of range indices of SCCs in Order, to be processed.
  SmallVector<std::pair<unsigned, unsigned>, 8> WorkList;
  unsigned I = 0, E = Order.size();
  while (true) {
    // Run through all the SCCs in the subgraph starting with Entry.
    for (auto SCCI =
             scc_iterator<SubGraphTraits::NodeRef, SubGraphTraits>::begin(
                 EntryNode);
         !SCCI.isAtEnd(); ++SCCI) {
      auto &SCC = *SCCI;

      // An SCC up to the size of 2, can be reduced to an entry (the last node),
      // and a possible additional node. Therefore, it is already in order, and
      // there is no need to add it to the work-list.
      unsigned Size = SCC.size();
      if (Size > 2)
        WorkList.emplace_back(I, I + Size);

      // Add the SCC nodes to the Order array.
      for (auto &N : SCC) {
        assert(I < E && "SCC size mismatch!");
        Order[I++] = N.first;
      }
    }
    assert(I == E && "SCC size mismatch!");

    // If there are no more SCCs to order, then we are done.
    if (WorkList.empty())
      break;

    std::tie(I, E) = WorkList.pop_back_val();

    // Collect the set of nodes in the SCC's subgraph. These are only the
    // possible child nodes; we do not add the entry (last node) otherwise we
    // will have the same exact SCC all over again.
    Nodes.clear();
    Nodes.insert(Order.begin() + I, Order.begin() + E - 1);

    // Update the entry node.
    EntryNode.first = Order[E - 1];
    EntryNode.second = &Nodes;
  }
}

/// Determine the end of the loops
void StructurizeCFG::analyzeLoops(RegionNode *N) {
  if (N->isSubRegion()) {
    // Test for exit as back edge
    BasicBlock *Exit = N->getNodeAs<Region>()->getExit();
    if (Visited.count(Exit))
      Loops[Exit] = N->getEntry();

  } else {
    // Test for successors as back edge
    BasicBlock *BB = N->getNodeAs<BasicBlock>();
    BranchInst *Term = cast<BranchInst>(BB->getTerminator());

    for (BasicBlock *Succ : Term->successors())
      if (Visited.count(Succ))
        Loops[Succ] = BB;
  }
}

/// Build the condition for one edge
Value *StructurizeCFG::buildCondition(BranchInst *Term, unsigned Idx,
                                      bool Invert) {
  Value *Cond = Invert ? BoolFalse : BoolTrue;
  if (Term->isConditional()) {
    Cond = Term->getCondition();

    if (Idx != (unsigned)Invert)
      Cond = invertCondition(Cond);
  }
  return Cond;
}

/// Analyze the predecessors of each block and build up predicates
void StructurizeCFG::gatherPredicates(RegionNode *N) {
  RegionInfo *RI = ParentRegion->getRegionInfo();
  BasicBlock *BB = N->getEntry();
  BBPredicates &Pred = Predicates[BB];
  BBPredicates &LPred = LoopPreds[BB];

  for (BasicBlock *P : predecessors(BB)) {
    // Ignore it if it's a branch from outside into our region entry
    if (!ParentRegion->contains(P))
      continue;

    Region *R = RI->getRegionFor(P);
    if (R == ParentRegion) {
      // It's a top level block in our region
      BranchInst *Term = cast<BranchInst>(P->getTerminator());
      for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) {
        BasicBlock *Succ = Term->getSuccessor(i);
        if (Succ != BB)
          continue;

        if (Visited.count(P)) {
          // Normal forward edge
          if (Term->isConditional()) {
            // Try to treat it like an ELSE block
            BasicBlock *Other = Term->getSuccessor(!i);
            if (Visited.count(Other) && !Loops.count(Other) &&
                !Pred.count(Other) && !Pred.count(P)) {

              Pred[Other] = BoolFalse;
              Pred[P] = BoolTrue;
              continue;
            }
          }
          Pred[P] = buildCondition(Term, i, false);
        } else {
          // Back edge
          LPred[P] = buildCondition(Term, i, true);
        }
      }
    } else {
      // It's an exit from a sub region
      while (R->getParent() != ParentRegion)
        R = R->getParent();

      // Edge from inside a subregion to its entry, ignore it
      if (*R == *N)
        continue;

      BasicBlock *Entry = R->getEntry();
      if (Visited.count(Entry))
        Pred[Entry] = BoolTrue;
      else
        LPred[Entry] = BoolFalse;
    }
  }
}

/// Collect various loop and predicate infos
void StructurizeCFG::collectInfos() {
  // Reset predicate
  Predicates.clear();

  // and loop infos
  Loops.clear();
  LoopPreds.clear();

  // Reset the visited nodes
  Visited.clear();

  for (RegionNode *RN : reverse(Order)) {
    LLVM_DEBUG(dbgs() << "Visiting: "
                      << (RN->isSubRegion() ? "SubRegion with entry: " : "")
                      << RN->getEntry()->getName() << "\n");

    // Analyze all the conditions leading to a node
    gatherPredicates(RN);

    // Remember that we've seen this node
    Visited.insert(RN->getEntry());

    // Find the last back edges
    analyzeLoops(RN);
  }
}

/// Insert the missing branch conditions
void StructurizeCFG::insertConditions(bool Loops) {
  BranchVector &Conds = Loops ? LoopConds : Conditions;
  Value *Default = Loops ? BoolTrue : BoolFalse;
  SSAUpdater PhiInserter;

  for (BranchInst *Term : Conds) {
    assert(Term->isConditional());

    BasicBlock *Parent = Term->getParent();
    BasicBlock *SuccTrue = Term->getSuccessor(0);
    BasicBlock *SuccFalse = Term->getSuccessor(1);

    PhiInserter.Initialize(Boolean, "");
    PhiInserter.AddAvailableValue(&Func->getEntryBlock(), Default);
    PhiInserter.AddAvailableValue(Loops ? SuccFalse : Parent, Default);

    BBPredicates &Preds = Loops ? LoopPreds[SuccFalse] : Predicates[SuccTrue];

    NearestCommonDominator Dominator(DT);
    Dominator.addBlock(Parent);

    Value *ParentValue = nullptr;
    for (std::pair<BasicBlock *, Value *> BBAndPred : Preds) {
      BasicBlock *BB = BBAndPred.first;
      Value *Pred = BBAndPred.second;

      if (BB == Parent) {
        ParentValue = Pred;
        break;
      }
      PhiInserter.AddAvailableValue(BB, Pred);
      Dominator.addAndRememberBlock(BB);
    }

    if (ParentValue) {
      Term->setCondition(ParentValue);
    } else {
      if (!Dominator.resultIsRememberedBlock())
        PhiInserter.AddAvailableValue(Dominator.result(), Default);

      Term->setCondition(PhiInserter.GetValueInMiddleOfBlock(Parent));
    }
  }
}

/// Remove all PHI values coming from "From" into "To" and remember
/// them in DeletedPhis
void StructurizeCFG::delPhiValues(BasicBlock *From, BasicBlock *To) {
  PhiMap &Map = DeletedPhis[To];
  for (PHINode &Phi : To->phis()) {
    bool Recorded = false;
    while (Phi.getBasicBlockIndex(From) != -1) {
      Value *Deleted = Phi.removeIncomingValue(From, false);
      Map[&Phi].push_back(std::make_pair(From, Deleted));
      if (!Recorded) {
        AffectedPhis.push_back(&Phi);
        Recorded = true;
      }
    }
  }
}

/// Add a dummy PHI value as soon as we knew the new predecessor
void StructurizeCFG::addPhiValues(BasicBlock *From, BasicBlock *To) {
  for (PHINode &Phi : To->phis()) {
    Value *Undef = UndefValue::get(Phi.getType());
    Phi.addIncoming(Undef, From);
  }
  AddedPhis[To].push_back(From);
}

/// Add the real PHI value as soon as everything is set up
void StructurizeCFG::setPhiValues() {
  SmallVector<PHINode *, 8> InsertedPhis;
  SSAUpdater Updater(&InsertedPhis);
  for (const auto &AddedPhi : AddedPhis) {
    BasicBlock *To = AddedPhi.first;
    const BBVector &From = AddedPhi.second;

    if (!DeletedPhis.count(To))
      continue;

    PhiMap &Map = DeletedPhis[To];
    for (const auto &PI : Map) {
      PHINode *Phi = PI.first;
      Value *Undef = UndefValue::get(Phi->getType());
      Updater.Initialize(Phi->getType(), "");
      Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
      Updater.AddAvailableValue(To, Undef);

      NearestCommonDominator Dominator(DT);
      Dominator.addBlock(To);
      for (const auto &VI : PI.second) {
        Updater.AddAvailableValue(VI.first, VI.second);
        Dominator.addAndRememberBlock(VI.first);
      }

      if (!Dominator.resultIsRememberedBlock())
        Updater.AddAvailableValue(Dominator.result(), Undef);

      for (BasicBlock *FI : From)
        Phi->setIncomingValueForBlock(FI, Updater.GetValueAtEndOfBlock(FI));
      AffectedPhis.push_back(Phi);
    }

    DeletedPhis.erase(To);
  }
  assert(DeletedPhis.empty());

  AffectedPhis.append(InsertedPhis.begin(), InsertedPhis.end());
}

void StructurizeCFG::simplifyAffectedPhis() {
  bool Changed;
  do {
    Changed = false;
    SimplifyQuery Q(Func->getParent()->getDataLayout());
    Q.DT = DT;
    for (WeakVH VH : AffectedPhis) {
      if (auto Phi = dyn_cast_or_null<PHINode>(VH)) {
        if (auto NewValue = SimplifyInstruction(Phi, Q)) {
          Phi->replaceAllUsesWith(NewValue);
          Phi->eraseFromParent();
          Changed = true;
        }
      }
    }
  } while (Changed);
}

/// Remove phi values from all successors and then remove the terminator.
void StructurizeCFG::killTerminator(BasicBlock *BB) {
  Instruction *Term = BB->getTerminator();
  if (!Term)
    return;

  for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB);
       SI != SE; ++SI)
    delPhiValues(BB, *SI);

  if (DA)
    DA->removeValue(Term);
  Term->eraseFromParent();
}

/// Let node exit(s) point to NewExit
void StructurizeCFG::changeExit(RegionNode *Node, BasicBlock *NewExit,
                                bool IncludeDominator) {
  if (Node->isSubRegion()) {
    Region *SubRegion = Node->getNodeAs<Region>();
    BasicBlock *OldExit = SubRegion->getExit();
    BasicBlock *Dominator = nullptr;

    // Find all the edges from the sub region to the exit
    for (auto BBI = pred_begin(OldExit), E = pred_end(OldExit); BBI != E;) {
      // Incrememt BBI before mucking with BB's terminator.
      BasicBlock *BB = *BBI++;

      if (!SubRegion->contains(BB))
        continue;

      // Modify the edges to point to the new exit
      delPhiValues(BB, OldExit);
      BB->getTerminator()->replaceUsesOfWith(OldExit, NewExit);
      addPhiValues(BB, NewExit);

      // Find the new dominator (if requested)
      if (IncludeDominator) {
        if (!Dominator)
          Dominator = BB;
        else
          Dominator = DT->findNearestCommonDominator(Dominator, BB);
      }
    }

    // Change the dominator (if requested)
    if (Dominator)
      DT->changeImmediateDominator(NewExit, Dominator);

    // Update the region info
    SubRegion->replaceExit(NewExit);
  } else {
    BasicBlock *BB = Node->getNodeAs<BasicBlock>();
    killTerminator(BB);
    BranchInst::Create(NewExit, BB);
    addPhiValues(BB, NewExit);
    if (IncludeDominator)
      DT->changeImmediateDominator(NewExit, BB);
  }
}

/// Create a new flow node and update dominator tree and region info
BasicBlock *StructurizeCFG::getNextFlow(BasicBlock *Dominator) {
  LLVMContext &Context = Func->getContext();
  BasicBlock *Insert = Order.empty() ? ParentRegion->getExit() :
                       Order.back()->getEntry();
  BasicBlock *Flow = BasicBlock::Create(Context, FlowBlockName,
                                        Func, Insert);
  DT->addNewBlock(Flow, Dominator);
  ParentRegion->getRegionInfo()->setRegionFor(Flow, ParentRegion);
  return Flow;
}

/// Create a new or reuse the previous node as flow node
BasicBlock *StructurizeCFG::needPrefix(bool NeedEmpty) {
  BasicBlock *Entry = PrevNode->getEntry();

  if (!PrevNode->isSubRegion()) {
    killTerminator(Entry);
    if (!NeedEmpty || Entry->getFirstInsertionPt() == Entry->end())
      return Entry;
  }

  // create a new flow node
  BasicBlock *Flow = getNextFlow(Entry);

  // and wire it up
  changeExit(PrevNode, Flow, true);
  PrevNode = ParentRegion->getBBNode(Flow);
  return Flow;
}

/// Returns the region exit if possible, otherwise just a new flow node
BasicBlock *StructurizeCFG::needPostfix(BasicBlock *Flow,
                                        bool ExitUseAllowed) {
  if (!Order.empty() || !ExitUseAllowed)
    return getNextFlow(Flow);

  BasicBlock *Exit = ParentRegion->getExit();
  DT->changeImmediateDominator(Exit, Flow);
  addPhiValues(Flow, Exit);
  return Exit;
}

/// Set the previous node
void StructurizeCFG::setPrevNode(BasicBlock *BB) {
  PrevNode = ParentRegion->contains(BB) ? ParentRegion->getBBNode(BB)
                                        : nullptr;
}

/// Does BB dominate all the predicates of Node?
bool StructurizeCFG::dominatesPredicates(BasicBlock *BB, RegionNode *Node) {
  BBPredicates &Preds = Predicates[Node->getEntry()];
  return llvm::all_of(Preds, [&](std::pair<BasicBlock *, Value *> Pred) {
    return DT->dominates(BB, Pred.first);
  });
}

/// Can we predict that this node will always be called?
bool StructurizeCFG::isPredictableTrue(RegionNode *Node) {
  BBPredicates &Preds = Predicates[Node->getEntry()];
  bool Dominated = false;

  // Regionentry is always true
  if (!PrevNode)
    return true;

  for (std::pair<BasicBlock*, Value*> Pred : Preds) {
    BasicBlock *BB = Pred.first;
    Value *V = Pred.second;

    if (V != BoolTrue)
      return false;

    if (!Dominated && DT->dominates(BB, PrevNode->getEntry()))
      Dominated = true;
  }

  // TODO: The dominator check is too strict
  return Dominated;
}

/// Take one node from the order vector and wire it up
void StructurizeCFG::wireFlow(bool ExitUseAllowed,
                              BasicBlock *LoopEnd) {
  RegionNode *Node = Order.pop_back_val();
  Visited.insert(Node->getEntry());

  if (isPredictableTrue(Node)) {
    // Just a linear flow
    if (PrevNode) {
      changeExit(PrevNode, Node->getEntry(), true);
    }
    PrevNode = Node;
  } else {
    // Insert extra prefix node (or reuse last one)
    BasicBlock *Flow = needPrefix(false);

    // Insert extra postfix node (or use exit instead)
    BasicBlock *Entry = Node->getEntry();
    BasicBlock *Next = needPostfix(Flow, ExitUseAllowed);

    // let it point to entry and next block
    Conditions.push_back(BranchInst::Create(Entry, Next, BoolUndef, Flow));
    addPhiValues(Flow, Entry);
    DT->changeImmediateDominator(Entry, Flow);

    PrevNode = Node;
    while (!Order.empty() && !Visited.count(LoopEnd) &&
           dominatesPredicates(Entry, Order.back())) {
      handleLoops(false, LoopEnd);
    }

    changeExit(PrevNode, Next, false);
    setPrevNode(Next);
  }
}

void StructurizeCFG::handleLoops(bool ExitUseAllowed,
                                 BasicBlock *LoopEnd) {
  RegionNode *Node = Order.back();
  BasicBlock *LoopStart = Node->getEntry();

  if (!Loops.count(LoopStart)) {
    wireFlow(ExitUseAllowed, LoopEnd);
    return;
  }

  if (!isPredictableTrue(Node))
    LoopStart = needPrefix(true);

  LoopEnd = Loops[Node->getEntry()];
  wireFlow(false, LoopEnd);
  while (!Visited.count(LoopEnd)) {
    handleLoops(false, LoopEnd);
  }

  // If the start of the loop is the entry block, we can't branch to it so
  // insert a new dummy entry block.
  Function *LoopFunc = LoopStart->getParent();
  if (LoopStart == &LoopFunc->getEntryBlock()) {
    LoopStart->setName("entry.orig");

    BasicBlock *NewEntry =
      BasicBlock::Create(LoopStart->getContext(),
                         "entry",
                         LoopFunc,
                         LoopStart);
    BranchInst::Create(LoopStart, NewEntry);
    DT->setNewRoot(NewEntry);
  }

  // Create an extra loop end node
  LoopEnd = needPrefix(false);
  BasicBlock *Next = needPostfix(LoopEnd, ExitUseAllowed);
  LoopConds.push_back(BranchInst::Create(Next, LoopStart,
                                         BoolUndef, LoopEnd));
  addPhiValues(LoopEnd, LoopStart);
  setPrevNode(Next);
}

/// After this function control flow looks like it should be, but
/// branches and PHI nodes only have undefined conditions.
void StructurizeCFG::createFlow() {
  BasicBlock *Exit = ParentRegion->getExit();
  bool EntryDominatesExit = DT->dominates(ParentRegion->getEntry(), Exit);

  AffectedPhis.clear();
  DeletedPhis.clear();
  AddedPhis.clear();
  Conditions.clear();
  LoopConds.clear();

  PrevNode = nullptr;
  Visited.clear();

  while (!Order.empty()) {
    handleLoops(EntryDominatesExit, nullptr);
  }

  if (PrevNode)
    changeExit(PrevNode, Exit, EntryDominatesExit);
  else
    assert(EntryDominatesExit);
}

/// Handle a rare case where the disintegrated nodes instructions
/// no longer dominate all their uses. Not sure if this is really necessary
void StructurizeCFG::rebuildSSA() {
  SSAUpdater Updater;
  for (BasicBlock *BB : ParentRegion->blocks())
    for (Instruction &I : *BB) {
      bool Initialized = false;
      // We may modify the use list as we iterate over it, so be careful to
      // compute the next element in the use list at the top of the loop.
      for (auto UI = I.use_begin(), E = I.use_end(); UI != E;) {
        Use &U = *UI++;
        Instruction *User = cast<Instruction>(U.getUser());
        if (User->getParent() == BB) {
          continue;
        } else if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
          if (UserPN->getIncomingBlock(U) == BB)
            continue;
        }

        if (DT->dominates(&I, User))
          continue;

        if (!Initialized) {
          Value *Undef = UndefValue::get(I.getType());
          Updater.Initialize(I.getType(), "");
          Updater.AddAvailableValue(&Func->getEntryBlock(), Undef);
          Updater.AddAvailableValue(BB, &I);
          Initialized = true;
        }
        Updater.RewriteUseAfterInsertions(U);
      }
    }
}

static bool hasOnlyUniformBranches(Region *R, unsigned UniformMDKindID,
                                   const LegacyDivergenceAnalysis &DA) {
  // Bool for if all sub-regions are uniform.
  bool SubRegionsAreUniform = true;
  // Count of how many direct children are conditional.
  unsigned ConditionalDirectChildren = 0;

  for (auto E : R->elements()) {
    if (!E->isSubRegion()) {
      auto Br = dyn_cast<BranchInst>(E->getEntry()->getTerminator());
      if (!Br || !Br->isConditional())
        continue;

      if (!DA.isUniform(Br))
        return false;

      // One of our direct children is conditional.
      ConditionalDirectChildren++;

      LLVM_DEBUG(dbgs() << "BB: " << Br->getParent()->getName()
                        << " has uniform terminator\n");
    } else {
      // Explicitly refuse to treat regions as uniform if they have non-uniform
      // subregions. We cannot rely on DivergenceAnalysis for branches in
      // subregions because those branches may have been removed and re-created,
      // so we look for our metadata instead.
      //
      // Warning: It would be nice to treat regions as uniform based only on
      // their direct child basic blocks' terminators, regardless of whether
      // subregions are uniform or not. However, this requires a very careful
      // look at SIAnnotateControlFlow to make sure nothing breaks there.
      for (auto BB : E->getNodeAs<Region>()->blocks()) {
        auto Br = dyn_cast<BranchInst>(BB->getTerminator());
        if (!Br || !Br->isConditional())
          continue;

        if (!Br->getMetadata(UniformMDKindID)) {
          // Early exit if we cannot have relaxed uniform regions.
          if (!RelaxedUniformRegions)
            return false;

          SubRegionsAreUniform = false;
          break;
        }
      }
    }
  }

  // Our region is uniform if:
  // 1. All conditional branches that are direct children are uniform (checked
  // above).
  // 2. And either:
  //   a. All sub-regions are uniform.
  //   b. There is one or less conditional branches among the direct children.
  return SubRegionsAreUniform || (ConditionalDirectChildren <= 1);
}

/// Run the transformation for each region found
bool StructurizeCFG::runOnRegion(Region *R, RGPassManager &RGM) {
  if (R->isTopLevelRegion())
    return false;

  DA = nullptr;

  if (SkipUniformRegions) {
    // TODO: We could probably be smarter here with how we handle sub-regions.
    // We currently rely on the fact that metadata is set by earlier invocations
    // of the pass on sub-regions, and that this metadata doesn't get lost --
    // but we shouldn't rely on metadata for correctness!
    unsigned UniformMDKindID =
        R->getEntry()->getContext().getMDKindID("structurizecfg.uniform");
    DA = &getAnalysis<LegacyDivergenceAnalysis>();

    if (hasOnlyUniformBranches(R, UniformMDKindID, *DA)) {
      LLVM_DEBUG(dbgs() << "Skipping region with uniform control flow: " << *R
                        << '\n');

      // Mark all direct child block terminators as having been treated as
      // uniform. To account for a possible future in which non-uniform
      // sub-regions are treated more cleverly, indirect children are not
      // marked as uniform.
      MDNode *MD = MDNode::get(R->getEntry()->getParent()->getContext(), {});
      for (RegionNode *E : R->elements()) {
        if (E->isSubRegion())
          continue;

        if (Instruction *Term = E->getEntry()->getTerminator())
          Term->setMetadata(UniformMDKindID, MD);
      }

      return false;
    }
  }

  Func = R->getEntry()->getParent();
  ParentRegion = R;

  DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();

  orderNodes();
  collectInfos();
  createFlow();
  insertConditions(false);
  insertConditions(true);
  setPhiValues();
  simplifyAffectedPhis();
  rebuildSSA();

  // Cleanup
  Order.clear();
  Visited.clear();
  DeletedPhis.clear();
  AddedPhis.clear();
  Predicates.clear();
  Conditions.clear();
  Loops.clear();
  LoopPreds.clear();
  LoopConds.clear();

  return true;
}

Pass *llvm::createStructurizeCFGPass(bool SkipUniformRegions) {
  return new StructurizeCFG(SkipUniformRegions);
}


/**
 * Copyright (c) 2017 - 2018, Nordic Semiconductor ASA
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form, except as embedded into a Nordic
 *    Semiconductor ASA integrated circuit in a product or a software update for
 *    such product, must reproduce the above copyright notice, this list of
 *    conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *
 * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
 *    contributors may be used to endorse or promote products derived from this
 *    software without specific prior written permission.
 *
 * 4. This software, with or without modification, must only be used with a
 *    Nordic Semiconductor ASA integrated circuit.
 *
 * 5. Any software provided in binary form under this license must not be reverse
 *    engineered, decompiled, modified and/or disassembled.
 *
 * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <nrfx.h>

#if NRFX_CHECK(NRFX_POWER_ENABLED)

#include <nrfx_power.h>

#if NRFX_CHECK(NRFX_CLOCK_ENABLED)
extern bool nrfx_clock_irq_enabled;
#endif

/**
 * @internal
 * @defgroup nrfx_power_internals POWER driver internals
 * @ingroup nrfx_power
 *
 * Internal variables, auxiliary macros and functions of POWER driver.
 * @{
 */

/**
 * This variable is used to check whether common POWER_CLOCK common interrupt
 * should be disabled or not if @ref nrfx_clock tries to disable the interrupt.
 */

bool nrfx_power_irq_enabled;

/**
 * @brief The initialization flag
 */

#define m_initialized nrfx_power_irq_enabled

/**
 * @brief The handler of power fail comparator warning event
 */
static nrfx_power_pofwarn_event_handler_t m_pofwarn_handler;

#if NRF_POWER_HAS_SLEEPEVT || defined(__NRFX_DOXYGEN__)
/**
 * @brief The handler of sleep event handler
 */
static nrfx_power_sleep_event_handler_t m_sleepevt_handler;
#endif

#if NRF_POWER_HAS_USBREG || defined(__NRFX_DOXYGEN__)
/**
 * @brief The handler of USB power events
 */
static nrfx_power_usb_event_handler_t m_usbevt_handler;
#endif

/** @} */

nrfx_power_pofwarn_event_handler_t nrfx_power_pof_handler_get(void)
{
    return m_pofwarn_handler;
}

#if NRF_POWER_HAS_USBREG
nrfx_power_usb_event_handler_t nrfx_power_usb_handler_get(void)
{
    return m_usbevt_handler;
}
#endif

nrfx_err_t nrfx_power_init(nrfx_power_config_t const * p_config)
{
    NRFX_ASSERT(p_config);
    if (m_initialized)
    {
        return NRFX_ERROR_ALREADY_INITIALIZED;
    }

#if NRF_POWER_HAS_VDDH
    nrf_power_dcdcen_vddh_set(p_config->dcdcenhv);
#endif
    nrf_power_dcdcen_set(p_config->dcdcen);

    nrfx_power_clock_irq_init();

    m_initialized = true;
    return NRFX_SUCCESS;
}

void nrfx_power_uninit(void)
{
    NRFX_ASSERT(m_initialized);

#if NRFX_CHECK(NRFX_CLOCK_ENABLED)
    if (!nrfx_clock_irq_enabled)
#endif
    {
        NRFX_IRQ_DISABLE(POWER_CLOCK_IRQn);
    }

    nrfx_power_pof_uninit();
#if NRF_POWER_HAS_SLEEPEVT || defined(__NRFX_DOXYGEN__)
    nrfx_power_sleepevt_uninit();
#endif
#if NRF_POWER_HAS_USBREG || defined(__NRFX_DOXYGEN__)
    nrfx_power_usbevt_uninit();
#endif
    m_initialized = false;
}

void nrfx_power_pof_init(nrfx_power_pofwarn_config_t const * p_config)
{
    NRFX_ASSERT(p_config != NULL);

    nrfx_power_pof_uninit();

    if (p_config->handler != NULL)
    {
        m_pofwarn_handler = p_config->handler;
    }
}

void nrfx_power_pof_enable(nrfx_power_pofwarn_config_t const * p_config)
{
    nrf_power_pofcon_set(true, p_config->thr);
#if NRF_POWER_HAS_VDDH || defined(__NRFX_DOXYGEN__)
    nrf_power_pofcon_vddh_set(p_config->thrvddh);
#endif
    if (m_pofwarn_handler != NULL)
    {
        nrf_power_int_enable(NRF_POWER_INT_POFWARN_MASK);
    }
}

void nrfx_power_pof_disable(void)
{
    nrf_power_int_disable(NRF_POWER_INT_POFWARN_MASK);
}

void nrfx_power_pof_uninit(void)
{
    m_pofwarn_handler = NULL;
}

#if NRF_POWER_HAS_SLEEPEVT || defined(__NRFX_DOXYGEN__)
void nrfx_power_sleepevt_init(nrfx_power_sleepevt_config_t const * p_config)
{
    NRFX_ASSERT(p_config != NULL);

    nrfx_power_sleepevt_uninit();
    if (p_config->handler != NULL)
    {
        m_sleepevt_handler = p_config->handler;
    }
}

void nrfx_power_sleepevt_enable(nrfx_power_sleepevt_config_t const * p_config)
{
    uint32_t enmask = 0;
    if (p_config->en_enter)
    {
        enmask |= NRF_POWER_INT_SLEEPENTER_MASK;
        nrf_power_event_clear(NRF_POWER_EVENT_SLEEPENTER);
    }
    if (p_config->en_exit)
    {
        enmask |= NRF_POWER_INT_SLEEPEXIT_MASK;
        nrf_power_event_clear(NRF_POWER_EVENT_SLEEPEXIT);
    }
    nrf_power_int_enable(enmask);
}

void nrfx_power_sleepevt_disable(void)
{
    nrf_power_int_disable(
        NRF_POWER_INT_SLEEPENTER_MASK |
        NRF_POWER_INT_SLEEPEXIT_MASK);
}

void nrfx_power_sleepevt_uninit(void)
{
    m_sleepevt_handler = NULL;
}
#endif /* NRF_POWER_HAS_SLEEPEVT */

#if NRF_POWER_HAS_USBREG || defined(__NRFX_DOXYGEN__)
void nrfx_power_usbevt_init(nrfx_power_usbevt_config_t const * p_config)
{
    nrfx_power_usbevt_uninit();
    if (p_config->handler != NULL)
    {
        m_usbevt_handler = p_config->handler;
    }
}

void nrfx_power_usbevt_enable(void)
{
    nrf_power_int_enable(
        NRF_POWER_INT_USBDETECTED_MASK |
        NRF_POWER_INT_USBREMOVED_MASK  |
        NRF_POWER_INT_USBPWRRDY_MASK);
}

void nrfx_power_usbevt_disable(void)
{
    nrf_power_int_disable(
        NRF_POWER_INT_USBDETECTED_MASK |
        NRF_POWER_INT_USBREMOVED_MASK  |
        NRF_POWER_INT_USBPWRRDY_MASK);
}

void nrfx_power_usbevt_uninit(void)
{
    m_usbevt_handler = NULL;
}
#endif /* NRF_POWER_HAS_USBREG */

void nrfx_power_irq_handler(void)
{
    uint32_t enabled = nrf_power_int_enable_get();
    if ((0 != (enabled & NRF_POWER_INT_POFWARN_MASK)) &&
        nrf_power_event_get_and_clear(NRF_POWER_EVENT_POFWARN))
    {
        /* Cannot be null if event is enabled */
        NRFX_ASSERT(m_pofwarn_handler != NULL);
        m_pofwarn_handler();
    }
#if NRF_POWER_HAS_SLEEPEVT || defined(__NRFX_DOXYGEN__)
    if ((0 != (enabled & NRF_POWER_INT_SLEEPENTER_MASK)) &&
        nrf_power_event_get_and_clear(NRF_POWER_EVENT_SLEEPENTER))
    {
        /* Cannot be null if event is enabled */
        NRFX_ASSERT(m_sleepevt_handler != NULL);
        m_sleepevt_handler(NRFX_POWER_SLEEP_EVT_ENTER);
    }
    if ((0 != (enabled & NRF_POWER_INT_SLEEPEXIT_MASK)) &&
        nrf_power_event_get_and_clear(NRF_POWER_EVENT_SLEEPEXIT))
    {
        /* Cannot be null if event is enabled */
        NRFX_ASSERT(m_sleepevt_handler != NULL);
        m_sleepevt_handler(NRFX_POWER_SLEEP_EVT_EXIT);
    }
#endif
#if NRF_POWER_HAS_USBREG || defined(__NRFX_DOXYGEN__)
    if ((0 != (enabled & NRF_POWER_INT_USBDETECTED_MASK)) &&
        nrf_power_event_get_and_clear(NRF_POWER_EVENT_USBDETECTED))
    {
        /* Cannot be null if event is enabled */
        NRFX_ASSERT(m_usbevt_handler != NULL);
        m_usbevt_handler(NRFX_POWER_USB_EVT_DETECTED);
    }
    if ((0 != (enabled & NRF_POWER_INT_USBREMOVED_MASK)) &&
        nrf_power_event_get_and_clear(NRF_POWER_EVENT_USBREMOVED))
    {
        /* Cannot be null if event is enabled */
        NRFX_ASSERT(m_usbevt_handler != NULL);
        m_usbevt_handler(NRFX_POWER_USB_EVT_REMOVED);
    }
    if ((0 != (enabled & NRF_POWER_INT_USBPWRRDY_MASK)) &&
        nrf_power_event_get_and_clear(NRF_POWER_EVENT_USBPWRRDY))
    {
        /* Cannot be null if event is enabled */
        NRFX_ASSERT(m_usbevt_handler != NULL);
        m_usbevt_handler(NRFX_POWER_USB_EVT_READY);
    }
#endif
}

#endif // NRFX_CHECK(NRFX_POWER_ENABLED)


<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Spectrum Tests</title>
  <link rel="stylesheet" href="qunit.css">
  <link rel="stylesheet" href="../spectrum.css">


<?php

// GET
$route['get']['/db/shards/:id'] = array('db/DBShardController', 'view', 'match'=> array('id'=>'/^\d+$/'));
// POST
$route['post']['/db/shards'] = array('db/DBShardController', 'create');
// PUT
$route['put']['/db/shards/:id'] = array('db/DBShardController', 'update', 'match'=> array('id'=>'/^\d+$/'));
// DELETE
$route['delete']['/db/shards/:id'] = array('db/DBShardController', 'destroy', 'match'=> array('id'=>'/^\d+$/'));

// GET
$route['get']['/db/gearman_job_servers/:id'] = array('db/DBGearman_Job_ServersController', 'view', 'match'=> array('id'=>'/^\d+$/'));
// POST
$route['post']['/db/gearman_job_servers'] = array('db/DBGearman_Job_ServersController', 'create');
// PUT
$route['put']['/db/gearman_job_servers/:id'] = array('db/DBGearman_Job_ServersController', 'update', 'match'=> array('id'=>'/^\d+$/'));
// DELETE
$route['delete']['/db/gearman_job_servers/:id'] = array('db/DBGearman_Job_ServersController', 'destroy', 'match'=> array('id'=>'/^\d+$/'));

// GET
$route['get']['/db/gearman_functions/:id'] = array('db/DBGearman_FunctionsController', 'view', 'match'=> array('id'=>'/^\d+$/'));
// POST
$route['post']['/db/gearman_functions'] = array('db/DBGearman_FunctionsController', 'create');
// PUT
$route['put']['/db/gearman_functions/:id'] = array('db/DBGearman_FunctionsController', 'update', 'match'=> array('id'=>'/^\d+$/'));
// DELETE
$route['delete']['/db/gearman_functions/:id'] = array('db/DBGearman_FunctionsController', 'destroy', 'match'=> array('id'=>'/^\d+$/'));

// GET
$route['get']['/db/schemata/:id'] = array('db/DBSchemataController', 'view', 'match'=> array('id'=>'/^\d+$/'));
// POST
$route['post']['/db/schemata'] = array('db/DBSchemataController', 'create');
// PUT
$route['put']['/db/schemata/:id'] = array('db/DBSchemataController', 'update', 'match'=> array('id'=>'/^\d+$/'));
// DELETE
$route['delete']['/db/schemata/:id'] = array('db/DBSchemataController', 'destroy', 'match'=> array('id'=>'/^\d+$/'));

// GET
$route['get']['/db/schemata_config/:id'] = array('db/DBSchemata_ConfigController', 'view', 'match'=> array('id'=>'/^\d+$/'));
// POST
$route['post']['/db/schemata_config'] = array('db/DBSchemata_ConfigController', 'create');
// PUT
$route['put']['/db/schemata_config/:id'] = array('db/DBSchemata_ConfigController', 'update', 'match'=> array('id'=>'/^\d+$/'));
// DELETE
$route['delete']['/db/schemata_config/:id'] = array('db/DBSchemata_ConfigController', 'destroy', 'match'=> array('id'=>'/^\d+$/'));

// GET
$route['get']['/db/column_sequences/:id'] = array('db/DBColumn_SequencesController', 'view', 'match'=> array('id'=>'/^\d+$/'));
// POST
$route['post']['/db/column_sequences'] = array('db/DBColumn_SequencesController', 'create');
// PUT
$route['put']['/db/column_sequences/:id'] = array('db/DBColumn_SequencesController', 'update', 'match'=> array('id'=>'/^\d+$/'));
// DELETE
$route['delete']['/db/column_sequences/:id'] = array('db/DBColumn_SequencesController', 'destroy', 'match'=> array('id'=>'/^\d+$/'));

// GET
$route['get']['/db/shard_map/:id'] = array('db/DBShard_MapController', 'view', 'match'=> array('id'=>'/^\d+$/'));
// POST
$route['post']['/db/shard_map'] = array('db/DBShard_MapController', 'create');
// PUT
//$route['put']['/db/shard_map/:id'] = array('db/DBShard_MapController', 'update', 'match'=> array('id'=>'/^\d+$/'));
// DELETE
//$route['delete']['/db/shard_map/:id'] = array('db/DBShard_MapController', 'destroy', 'match'=> array('id'=>'/^\d+$/'));

/* NOT IMPLEMENTED YET
// GET
$route['get']['/db/shard_range_map/:id'] = array('db/DBShard_Range_MapController', 'view', 'match'=> array('id'=>'/^\d+$/'));
// POST
$route['post']['/db/shard_range_map'] = array('db/DBShard_Range_MapController', 'create');
// PUT
$route['put']['/db/shard_range_map/:id'] = array('db/DBShard_Range_MapController', 'update', 'match'=> array('id'=>'/^\d+$/'));
// DELETE
$route['delete']['/db/shard_range_map/:id'] = array('db/DBShard_Range_MapController', 'destroy', 'match'=> array('id'=>'/^\d+$/'));
*/

?>


package Paws::KinesisAnalyticsV2::SqlApplicationConfigurationDescription;
  use Moose;
  has InputDescriptions => (is => 'ro', isa => 'ArrayRef[Paws::KinesisAnalyticsV2::InputDescription]');
  has OutputDescriptions => (is => 'ro', isa => 'ArrayRef[Paws::KinesisAnalyticsV2::OutputDescription]');
  has ReferenceDataSourceDescriptions => (is => 'ro', isa => 'ArrayRef[Paws::KinesisAnalyticsV2::ReferenceDataSourceDescription]');
1;

### main pod documentation begin ###

=head1 NAME

Paws::KinesisAnalyticsV2::SqlApplicationConfigurationDescription

=head1 USAGE

This class represents one of two things:

=head3 Arguments in a call to a service

Use the attributes of this class as arguments to methods. You shouldn't make instances of this class.
Each attribute should be used as a named argument in the calls that expect this type of object.

As an example, if Att1 is expected to be a Paws::KinesisAnalyticsV2::SqlApplicationConfigurationDescription object:

  $service_obj->Method(Att1 => { InputDescriptions => $value, ..., ReferenceDataSourceDescriptions => $value  });

=head3 Results returned from an API call

Use accessors for each attribute. If Att1 is expected to be an Paws::KinesisAnalyticsV2::SqlApplicationConfigurationDescription object:

  $result = $service_obj->Method(...);
  $result->Att1->InputDescriptions

=head1 DESCRIPTION

Describes the inputs, outputs, and reference data sources for an
SQL-based Kinesis Data Analytics application.

=head1 ATTRIBUTES

=head2 InputDescriptions => ArrayRef[L<Paws::KinesisAnalyticsV2::InputDescription>]

  The array of InputDescription objects describing the input streams used
by the application.

=head2 OutputDescriptions => ArrayRef[L<Paws::KinesisAnalyticsV2::OutputDescription>]

  The array of OutputDescription objects describing the destination
streams used by the application.

=head2 ReferenceDataSourceDescriptions => ArrayRef[L<Paws::KinesisAnalyticsV2::ReferenceDataSourceDescription>]

  The array of ReferenceDataSourceDescription objects describing the
reference data sources used by the application.

=head1 SEE ALSO

This class forms part of L<Paws>, describing an object used in L<Paws::KinesisAnalyticsV2>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: L<https://github.com/pplu/aws-sdk-perl>

Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues>

=cut


/*******************************************************************************
 * Copyright (c) 2000, 2019 IBM Corp. and others
 *
 * This program and the accompanying materials are made available under
 * the terms of the Eclipse Public License 2.0 which accompanies this
 * distribution and is available at https://www.eclipse.org/legal/epl-2.0/
 * or the Apache License, Version 2.0 which accompanies this distribution and
 * is available at https://www.apache.org/licenses/LICENSE-2.0.
 *
 * This Source Code may also be made available under the following
 * Secondary Licenses when the conditions for such availability set
 * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
 * General Public License, version 2 with the GNU Classpath
 * Exception [1] and GNU General Public License, version 2 with the
 * OpenJDK Assembly Exception [2].
 *
 * [1] https://www.gnu.org/software/classpath/license.html
 * [2] http://openjdk.java.net/legal/assembly-exception.html
 *
 * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
 *******************************************************************************/

#include "optimizer/J9SimplifierHelpers.hpp"
#include "optimizer/Simplifier.hpp"

#include <limits.h>
#include <math.h>
#include "compile/Compilation.hpp"
#include "env/CompilerEnv.hpp"
#include "env/IO.hpp"
#include "env/jittypes.h"
#include "il/DataTypes.hpp"
#include "il/ILOpCodes.hpp"
#include "il/Node.hpp"
#include "il/Node_inlines.hpp"
#include "il/Block.hpp"

bool propagateSignState(TR::Node *node, TR::Node *child, int32_t shiftAmount, TR::Block *block, TR::Simplifier *s)
   {
   bool changedSignState = false;
   if (!node->hasKnownOrAssumedSignCode() &&
       child->hasKnownOrAssumedSignCode() &&
       TR::Node::typeSupportedForSignCodeTracking(node->getDataType()) &&
       performTransformation(s->comp(),"%sTransfer %sSignCode 0x%x from %s [" POINTER_PRINTF_FORMAT "] to %s [" POINTER_PRINTF_FORMAT "]\n",
         s->optDetailString(),
         child->hasKnownSignCode() ? "Known":"Assumed",
         TR::DataType::getValue(child->getKnownOrAssumedSignCode()),
         child->getOpCode().getName(),
         child,
         node->getOpCode().getName(),
         node))
      {
      node->transferSignCode(child);
      changedSignState = true;
      }

   if (!node->hasKnownOrAssumedCleanSign() &&
       child->hasKnownOrAssumedCleanSign() &&
       ((node->getDecimalPrecision() >= child->getDecimalPrecision() + shiftAmount) || child->isNonNegative()) &&
         performTransformation(s->comp(), "%sSet Has%sCleanSign=true on %s [" POINTER_PRINTF_FORMAT "] due to %s already clean %schild %s [" POINTER_PRINTF_FORMAT "]\n",
            s->optDetailString(),
            child->hasKnownCleanSign()?"Known":"Assumed",
            node->getOpCode().getName(),
            node,
            !child->isNonNegative()?"a widening of":"an",
            child->isNonNegative()?">= zero ":"",
            child->getOpCode().getName(),
            child))
      {
      node->transferCleanSign(child);
      changedSignState = true;
      }

   return changedSignState;
   }

bool propagateSignStateUnaryConversion(TR::Node *node, TR::Block *block, TR::Simplifier *s)
   {
   bool validateOp = node->getType().isBCD() &&
                     ((node->getOpCode().isConversion() && node->getNumChildren()==1)
                      || (node->getOpCode().isConversion() && node->getOpCode().canHavePaddingAddress() && node->getNumChildren()==2)
                     );
   if (!validateOp)
      return false;

   TR::Node *child = node->getFirstChild();
   return propagateSignState(node, child, 0, block, s);
   }

TR::Node *removeOperandWidening(TR::Node *node, TR::Node *parent, TR::Block *block, TR::Simplifier * s)
   {
   if (s->comp()->getOption(TR_KeepBCDWidening))   // stress-testing option to force more operations through to the evaluators
      return node;

   // Many packed decimal node types (such as arithmetic/shift/stores) do not need their operands explicitly widened so simple
   // widening operations (i.e. pdshl by 0 nodes) are be removed here.
   // This cannot be done globally because other node types (such a packed node under a call) must be explicitly widened.
   if (node->isSimpleWidening())
      {
      return s->replaceNodeWithChild(node, node->getFirstChild(), s->_curTree, block, false); // correctBCDPrecision=false because node is a widening
      }
   else if ((node->getOpCodeValue() == TR::i2pd || node->getOpCodeValue() == TR::l2pd) &&
            node->hasSourcePrecision() &&
            node->getReferenceCount() == 1 && // the removal of widening may not be valid in the other contexts
            node->getDecimalPrecision() > node->getSourcePrecision() &&
            performTransformation(s->comp(), "%sReducing %s [" POINTER_PRINTF_FORMAT "] precision %d to its child integer precision of %d\n",
               s->optDetailString(), node->getOpCode().getName(), node, node->getDecimalPrecision(), node->getSourcePrecision()))
      {
      node->setDecimalPrecision(node->getSourcePrecision());
      }
   else if (node->getOpCode().isShift() &&
            node->getReferenceCount() == 1 &&
            node->getSecondChild()->getOpCode().isLoadConst())
      {
      int32_t adjust = node->getDecimalAdjust(); // adjust is < 0 for right shifts and >= 0 for left shifts
      int32_t maxShiftedPrecision = adjust+node->getFirstChild()->getDecimalPrecision();
      if (node->getOpCode().isPackedRightShift() &&
          node->getDecimalRound() != 0)
         {
         maxShiftedPrecision++; // +1 as the rounding can propagate an extra digit across
         }
      if ((maxShiftedPrecision > 0) &&
          (node->getDecimalPrecision() > maxShiftedPrecision) &&
          performTransformation(s->comp(), "%sReducing %s [" POINTER_PRINTF_FORMAT "] precision %d to the max shifted result precision of %d\n",
            s->optDetailString(), node->getOpCode().getName(), node, node->getDecimalPrecision(), maxShiftedPrecision))
         {
         bool signWasKnownClean = node->hasKnownCleanSign();
         bool signWasAssumedClean = node->hasAssumedCleanSign();

         node->setDecimalPrecision(maxShiftedPrecision);    // conservatively resets clean sign flags on a truncation -- but this truncation cannot actually dirty a sign

         if (signWasKnownClean)
            node->setHasKnownCleanSign(true);
         if (signWasAssumedClean)
            node->setHasAssumedCleanSign(true);
         }
      }
   // TODO: figure out the more global check for removing widenings - all unary operations (getNumChildren()==1), how about setSign and other shifts?
   else if ((node->getOpCodeValue() == TR::pdclean   ||
             node->getOpCodeValue() == TR::zd2zdsle  ||
             node->getOpCodeValue() == TR::zdsle2zd  ||
             node->getOpCodeValue() == TR::zd2pd     ||
             node->getOpCodeValue() == TR::pd2zd     ||
             node->getOpCodeValue() == TR::pdSetSign ||
             node->getOpCodeValue() == TR::pdclear   ||
             node->getOpCodeValue() == TR::pdclearSetSign) &&
            node->getReferenceCount() == 1 &&
            node->getDecimalPrecision() > node->getFirstChild()->getDecimalPrecision() &&
            performTransformation(s->comp(), "%sReducing %s [" POINTER_PRINTF_FORMAT "] precision %d to its child precision of %d\n",
               s->optDetailString(), node->getOpCode().getName(), node, node->getDecimalPrecision(), node->getFirstChild()->getDecimalPrecision()))
      {
      node->setDecimalPrecision(node->getFirstChild()->getDecimalPrecision());
      if (node->getOpCode().isConversion())
         propagateSignStateUnaryConversion(node, block, s);
      return s->simplify(node, block);
      }
   return node;
   }


/*************************************************************
 *
 *  MathJax/localization/ce/TeX.js
 *
 *  Copyright (c) 2009-2018 The MathJax Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
MathJax.Localization.addTranslation("ce","TeX",{
        version: "2.7.5",
        isLoaded: true,
        strings: {

        }
});

MathJax.Ajax.loadComplete("[MathJax]/localization/ce/TeX.js");


From ef1cffc526d3cf9562d50efbf8addc2aa4c06b52 Mon Sep 17 00:00:00 2001
From: Sergio Prado <sergio.prado@e-labworks.com>
Date: Sun, 30 Jul 2017 18:23:23 -0300
Subject: [PATCH 1/2] Add cross-compilation support

Signed-off-by: Sergio Prado <sergio.prado@e-labworks.com>
---
 configure | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/configure b/configure
index c2f304729651..b05321aac3da 100755
--- a/configure
+++ b/configure
@@ -499,8 +499,9 @@ if test -n "$_host"; then
 			_host_os=win32
 			;;
 		*)
-			echo "Cross-compiling to unknown target, please add your target to configure."
-			exit 1
+			echo "Cross-compiling to $_host target"
+			DEFINES="$DEFINES -DUNIX"
+			_host_os=unix
 			;;
 	esac

--
1.9.1


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>orx: OrxModule</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

orx
    1.x dev

Portable Game Engine

Main Page

Related Pages

Modules

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Enumerations |
Functions

OrxModule

Enumerations

enum  	orxMODULE_ID {

  orxMODULE_ID_ANIM = 0,
orxMODULE_ID_ANIMPOINTER,
orxMODULE_ID_ANIMSET,
orxMODULE_ID_BANK,

  orxMODULE_ID_BODY,
orxMODULE_ID_CAMERA,
orxMODULE_ID_CLOCK,
orxMODULE_ID_COMMAND,

  orxMODULE_ID_CONFIG,
orxMODULE_ID_CONSOLE,
orxMODULE_ID_DISPLAY,
orxMODULE_ID_EVENT,

  orxMODULE_ID_FILE,
orxMODULE_ID_FONT,
orxMODULE_ID_FPS,
orxMODULE_ID_FRAME,

  orxMODULE_ID_FX,
orxMODULE_ID_FXPOINTER,
orxMODULE_ID_GRAPHIC,
orxMODULE_ID_INPUT,

  orxMODULE_ID_JOYSTICK,
orxMODULE_ID_KEYBOARD,
orxMODULE_ID_LOCALE,
orxMODULE_ID_MAIN,

  orxMODULE_ID_MEMORY,
orxMODULE_ID_MOUSE,
orxMODULE_ID_OBJECT,
orxMODULE_ID_PARAM,

  orxMODULE_ID_PHYSICS,
orxMODULE_ID_PLUGIN,
orxMODULE_ID_PROFILER,
orxMODULE_ID_RENDER,

  orxMODULE_ID_RESOURCE,
orxMODULE_ID_SCREENSHOT,
orxMODULE_ID_SHADER,
orxMODULE_ID_SHADERPOINTER,

  orxMODULE_ID_SOUND,
orxMODULE_ID_SOUNDPOINTER,
orxMODULE_ID_SOUNDSYSTEM,
orxMODULE_ID_SPAWNER,

  orxMODULE_ID_STRING,
orxMODULE_ID_STRUCTURE,
orxMODULE_ID_SYSTEM,
orxMODULE_ID_TEXT,

  orxMODULE_ID_TEXTURE,
orxMODULE_ID_THREAD,
orxMODULE_ID_TIMELINE,
orxMODULE_ID_VIEWPORT,

  orxMODULE_ID_CORE_NUMBER,
orxMODULE_ID_USER_DEFINED = orxMODULE_ID_CORE_NUMBER,
orxMODULE_ID_TOTAL_NUMBER = 64,
orxMODULE_ID_NONE = orxENUM_NONE

 }

Functions

orxDLLAPI void orxFASTCALL 	orxModule_AddDependency (orxMODULE_ID _eModuleID, orxMODULE_ID _eDependID)

orxDLLAPI void orxFASTCALL 	orxModule_AddOptionalDependency (orxMODULE_ID _eModuleID, orxMODULE_ID _eDependID)

orxDLLAPI void orxFASTCALL 	orxModule_Exit (orxMODULE_ID _eModuleID)

orxDLLAPI const orxSTRING orxFASTCALL 	orxModule_GetName (orxMODULE_ID _eModuleID)

orxDLLAPI orxSTATUS orxFASTCALL 	orxModule_Init (orxMODULE_ID _eModuleID)

orxDLLAPI orxBOOL orxFASTCALL 	orxModule_IsInitialized (orxMODULE_ID _eModuleID)

orxDLLAPI void orxFASTCALL 	orxModule_Register (orxMODULE_ID _eModuleID, const orxSTRING _zModuleName, const orxMODULE_SETUP_FUNCTION _pfnSetup, const orxMODULE_INIT_FUNCTION _pfnInit, const orxMODULE_EXIT_FUNCTION _pfnExit)

typedef 	orxSTATUS (orxFASTCALL *orxMODULE_INIT_FUNCTION)()

typedef 	void (orxFASTCALL *orxMODULE_EXIT_FUNCTION)()

Detailed Description

Module file Code that handles modules and their dependencies

Enumeration Type Documentation

          enum orxMODULE_ID

Module enum

Enumerator

orxMODULE_ID_ANIM

orxMODULE_ID_ANIMPOINTER

orxMODULE_ID_ANIMSET

orxMODULE_ID_BANK

orxMODULE_ID_BODY

orxMODULE_ID_CAMERA

orxMODULE_ID_CLOCK

orxMODULE_ID_COMMAND

orxMODULE_ID_CONFIG

orxMODULE_ID_CONSOLE

orxMODULE_ID_DISPLAY

orxMODULE_ID_EVENT

orxMODULE_ID_FILE

orxMODULE_ID_FONT

orxMODULE_ID_FPS

orxMODULE_ID_FRAME

orxMODULE_ID_FX

orxMODULE_ID_FXPOINTER

orxMODULE_ID_GRAPHIC

orxMODULE_ID_INPUT

orxMODULE_ID_JOYSTICK

orxMODULE_ID_KEYBOARD

orxMODULE_ID_LOCALE

orxMODULE_ID_MAIN

orxMODULE_ID_MEMORY

orxMODULE_ID_MOUSE

orxMODULE_ID_OBJECT

orxMODULE_ID_PARAM

orxMODULE_ID_PHYSICS

orxMODULE_ID_PLUGIN

orxMODULE_ID_PROFILER

orxMODULE_ID_RENDER

orxMODULE_ID_RESOURCE

orxMODULE_ID_SCREENSHOT

orxMODULE_ID_SHADER

orxMODULE_ID_SHADERPOINTER

orxMODULE_ID_SOUND

orxMODULE_ID_SOUNDPOINTER

orxMODULE_ID_SOUNDSYSTEM

orxMODULE_ID_SPAWNER

orxMODULE_ID_STRING

orxMODULE_ID_STRUCTURE

orxMODULE_ID_SYSTEM

orxMODULE_ID_TEXT

orxMODULE_ID_TEXTURE

orxMODULE_ID_THREAD

orxMODULE_ID_TIMELINE

orxMODULE_ID_VIEWPORT

orxMODULE_ID_CORE_NUMBER

orxMODULE_ID_USER_DEFINED

orxMODULE_ID_TOTAL_NUMBER

orxMODULE_ID_NONE

Definition at line 53 of file orxModule.h.

Function Documentation

          orxDLLAPI void orxFASTCALL orxModule_AddDependency
          (
          orxMODULE_ID
          _eModuleID,

          orxMODULE_ID
          _eDependID

          )

Adds dependencies between 2 modules

Parameters

[in]	_eModuleID	Concerned module ID

[in]	_eDependID	Module ID of the needed module

          orxDLLAPI void orxFASTCALL orxModule_AddOptionalDependency
          (
          orxMODULE_ID
          _eModuleID,

          orxMODULE_ID
          _eDependID

          )

Adds optional dependencies between 2 modules

Parameters

[in]	_eModuleID	Concerned module ID

[in]	_eDependID	Module ID of the optionally needed module

          orxDLLAPI void orxFASTCALL orxModule_Exit
          (
          orxMODULE_ID
          _eModuleID	)

Exits from a module

Parameters

[in]	_eModuleID	Concerned module ID

          orxDLLAPI const orxSTRING orxFASTCALL orxModule_GetName
          (
          orxMODULE_ID
          _eModuleID	)

Gets module name

Parameters

[in]	_eModuleID	Concerned module ID

Returns

Module name / orxSTRING_EMPTY

          orxDLLAPI orxSTATUS orxFASTCALL orxModule_Init
          (
          orxMODULE_ID
          _eModuleID	)

Inits a module

Parameters

[in]	_eModuleID	Concerned module ID

Returns

orxSTATUS_SUCCESS / orxSTATUS_FAILURE

          orxDLLAPI orxBOOL orxFASTCALL orxModule_IsInitialized
          (
          orxMODULE_ID
          _eModuleID	)

Is module initialized?

Parameters

[in]	_eModuleID	Concerned module ID

Returns

orxTRUE / orxFALSE

          orxDLLAPI void orxFASTCALL orxModule_Register
          (
          orxMODULE_ID
          _eModuleID,

          const orxSTRING
          _zModuleName,

          const orxMODULE_SETUP_FUNCTION
          _pfnSetup,

          const orxMODULE_INIT_FUNCTION
          _pfnInit,

          const orxMODULE_EXIT_FUNCTION
          _pfnExit

          )

Registers a module

Parameters

[in]	_eModuleID	Concerned module ID

[in]	_zModuleName	Module name

[in]	_pfnSetup	Module setup callback

[in]	_pfnInit	Module init callback

[in]	_pfnExit	Module exit callback

          typedef orxSTATUS
          (
          orxFASTCALL *
          orxMODULE_INIT_FUNCTION	)

          typedef void
          (
          orxFASTCALL *
          orxMODULE_EXIT_FUNCTION	)

<address style="text-align: right;">
Generated for orx by  1.8.11 </address>


#-------------------------------------------------------------------------
#
# Makefile for src/test/authentication
#
# Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
# Portions Copyright (c) 1994, Regents of the University of California
#
# src/test/authentication/Makefile
#
#-------------------------------------------------------------------------

subdir = src/test/authentication
top_builddir = ../../..
include $(top_builddir)/src/Makefile.global

check:
	$(prove_check)

installcheck:
	$(prove_installcheck)

clean distclean maintainer-clean:
	rm -rf tmp_check


require 'torch'
require 'paths'
require 'optim'
require 'nn'
require 'cutorch'
require 'gnuplot'

trainName = "argx_unknown_x4"

a=torch.load("../experiment/".. trainName .. "/psnr.t7")
print(a)
b = 0
c = 0
for i =1, 300 do
    b = a[1][i].value

    if b > c then
    --if  a[i][3] > 31.37 then
        c = b
        d = i
    --end
    end
end
print(d)
print(c)