<commit_before>//===- PrintFunctionNames.cpp ---------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Example clang plugin which simply prints the names of all the top-level decls
// in the input file.
//
//===----------------------------------------------------------------------===//

#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;

namespace {
	const std::vector<std::string> endsWith = {
		"iterator",
		"iplist",
		"analysis",
		"analysisusage",
		"ref",
		"Impl",
		"Traits",
		"Pass",
		"Set",
		"iterator_range",
		"Builder",
		"Pair",
		"Map",
		"Info",
		"Entry",
		"resolver",
		"tracking",
	};
	const std::vector<std::string> startswith = {
		"__",
		"std",
		"llvm::PointerUnion",
		"llvm::sys",
		"knowledge::",
		"llvm::raw",
		"llvm::pass",
		"llvm::pm",
		"llvm::prettystack",
		"llvm::dominatortree",
	};
	const std::vector<std::string> findCalls = {
		"Allocator",
		"vector",
		"Vector",
		"Iterator",
		"iterator",
		"ilist",
		"Node",
		"Base",
		"PassManager",
		"llvm::is_integral_or_enum",
		"llvm::Optional",
		"Flags",
		"FlagIt",
	};
	const std::vector<std::string> specialValueTypes = {
		"class llvm::StringRef",
		"class std::basic_string<char>",
		"const class std::basic_string<char>",
		"const class std::basic_string<char>&",
		"class std::basic_string<char>&",
		"class std::basic_string<char>&",
		"class llvm::APInt",
		"const unsigned char*",
		"const char*",
		"char*",
		"unsigned char*",
	};
	class PrintFunctionsConsumer : public ASTConsumer {
		public:
			virtual void HandleTagDeclDefinition(TagDecl *D) {
				clang::LangOptions lo;
				lo.CPlusPlus = true;
				clang::PrintingPolicy p(lo);
				if (D->hasNameForLinkage() && D->isClass()) {
					//llvm::errs() << "Class " << D->getNameAsString() << "\n";
					if (const clang::CXXRecordDecl* x = dyn_cast<CXXRecordDecl>(D)) {
						if (!x->isInStdNamespace()) {
							// eliminate all of types taht I will _NEVER_ need
							llvm::StringRef z = x->getQualifiedNameAsString();
							for (std::vector<std::string>::const_iterator it = endsWith.cbegin(); it != endsWith.cend(); ++it) {
								if (z.endswith_lower(*it)) {
									return;
								}
							}

							for (std::vector<std::string>::const_iterator it = startswith.cbegin(); it != startswith.cend(); ++it) {
								if (z.startswith_lower(*it)) {
									return;
								}
							}

							for (std::vector<std::string>::const_iterator it = findCalls.cbegin(); it != findCalls.cend(); ++it) {
								if (z.find(*it) != llvm::StringRef::npos) {
									return;
								}
							}
							llvm::errs() << "Begin(" << x->getQualifiedNameAsString() << ")\n";
							for (clang::CXXRecordDecl::base_class_const_iterator it = x->bases_begin(); it != x->bases_end(); ++it) {
								//if (!it->getType()->isInstantiationDependentType()) {
									llvm::errs() << "\tsuper(" << it->getType().getCanonicalType().getAsString(lo) << ")\n";
								//}
							}
							std::vector<std::string> multifields;
							for (clang::CXXRecordDecl::method_iterator it = x->method_begin(); it != x->method_end(); ++it) {
								if (it->getAccess() == AS_public &&
										it->getNumParams() == 0 &&
										it->isInstance() &&
										!it->getReturnType()->isVoidType() &&
										!it->isTemplateInstantiation() &&
										!it->isCopyAssignmentOperator() &&
										//!it->isTemplateDecl() &&
										!it->isInAnonymousNamespace() &&
										!it->isOverloadedOperator() && it->isConst()) {
									std::string target,
										slotName,
										ret = it->getReturnType().getCanonicalType().getAsString(p),
										name = it->getNameInfo().getAsString();
									StringRef sr = name;
									if (sr.startswith_lower("getContext") || sr.startswith_lower("convert") || sr.startswith_lower("clone") || sr.startswith_lower("Parse") || sr.startswith_lower("strip")) {
										continue;
									} else if (sr == "rbegin" || sr == "rend" || sr.endswith("rbegin") || sr.endswith("rend") || sr == "operands") {
										continue;
#define ignore(str) \
									} else if (sr == str) { \
										continue
#define X(begin, end, size, tbeg, tend, tsize, field) \
									} else if (sr == begin) { \
										std::string tmp; \
										llvm::raw_string_ostream q(tmp); \
										q << "X(" << ret << ", \"" << field << "\", 0, Multifield, " << tbeg << ", " << tend << ", " << tsize << ", 0) // " << it->getParent()->getQualifiedNameAsString() << "\n"; \
										multifields.push_back(q.str()); \
										continue; \
										ignore(end); \
										ignore(size); \
										ignore(field)
#define Y(begin, end, size, tbeg, tend, field) X(begin, end, size, tbeg, tend, "std::distance(" << tbeg << ", " << tend << ")", field)
									X("begin", "end", "size", "t->begin()", "t->end()", "t->size()", "children");
									X("op_begin", "op_end", "getNumOperands", "t->op_begin()", "t->op_end()", "t->getNumOperands()", "operands");
									X("alias_begin", "alias_end", "alias_size", "t->alias_begin()", "t->alias_end()", "t->alias_size()", "aliases");
									X("named_metadata_begin", "named_metadata_end", "named_metadata_size", "t->named_metadata_begin()", "t->named_metadata_end()", "t->named_metadata_size()", "named_metadata");
									Y("global_begin", "global_end", "getNumGlobals", "t->global_begin()", "t->global_end()", "globals");
									X("subtype_begin", "subtype_end", "getNumContainedTypes", "t->subtype_begin()", "t->subtype_end()", "t->getNumContainedTypes()", "subtypes");
									X("param_begin", "param_end", "getNumParams", "t->param_begin()", "t->param_end()", "t->getNumParams()", "params");
									X("element_begin", "element_end", "getNumElements", "t->element_begin()", "t->element_end()", "t->getNumElements()", "elements");
									X("use_begin", "use_end", "getNumUses", "t->use_begin()", "t->use_end()", "t->getNumUses()", "uses");
									Y("user_begin", "user_end", "getNumUsers", "t->user_begin()", "t->user_end()", "users");
									X("idx_begin", "idx_end", "getNumIndices", "t->idx_begin()", "t->idx_end()", "t->getNumIndices()", "indices");
									X("arg_begin", "arg_end", "arg_size", "t->arg_begin()", "t->arg_end()", "t->arg_size()", "args");
									ignore("global_empty");
									ignore("empty");
									ignore("alias_empty");
									ignore("named_metadata_empty");
#undef Y
#undef X
#undef ignore
									} else if (sr.endswith("begin")) {
										std::string tmp, prefix = name.substr(0, name.size() - 5);
										llvm::raw_string_ostream q(tmp);
										q << "X(" << ret << ", \"" << prefix << "s\", 0, Multifield, t->" << name << "(), t->" << prefix << "end(), t->getNum" << prefix << "(), 0) // " << it->getParent()->getQualifiedNameAsString() << "\n";
										multifields.push_back(q.str());
										continue;
									} else {
										//sr = it->getNameInfo().getAsString();
										if (sr.startswith("get")) {
											slotName = name.substr(3);
										} else {
											slotName = name;
										}
									}
									bool foundMatch = false;
									for (std::vector<std::string>::const_iterator it = specialValueTypes.cbegin(); it != specialValueTypes.cend();
											++it) {
										if (ret == *it) {
											target = "Value";
											foundMatch = true;
											break;
										}
									}
									if (!foundMatch) {
										if ((it->getReturnType()->isFundamentalType() && !it->getReturnType()->isPointerType()) ||
												it->getReturnType()->isEnumeralType()) {
											target = "Value";
										} else if (it->getReturnType()->isPointerType() || it->getReturnType()->isReferenceType()) {
											target = "Reference";
										} else {
											target = "Unknown_FIXME";
											llvm::errs() << "//";
										}
									}
									llvm::errs() << "\tX(" <<
										(it->getReturnType().getCanonicalType()->isBooleanType() ? "bool" : ret) << ", "
										<< "\"" << slotName << "\", " <<
										"t->" << it->getNameInfo().getAsString() << "(), " <<
										target << " ,0) // " << it->getParent()->getQualifiedNameAsString() << "\n";
								}
							}
							for (std::vector<std::string>::const_iterator it = multifields.cbegin(); it != multifields.cend(); ++it) {
								llvm::errs() << "\t" << *it;
							}
							llvm::errs() << "End\n";
						}
					}
				}
			}
			//virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
			//  for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) {
			//    const Decl *D = *i;
			//    if (D->isInStdNamespace()) {
			//  	  continue;
			//    }
			//    if (D->isInAnonymousNamespace()) {
			//  	  continue;
			//    }
			//    if (D->isFromASTFile()) {
			//  	  continue;
			//    }
			//    if (dyn_cast<CXXConversionDecl>(D)) {
			//  	  continue;
			//    } else if (dyn_cast<CXXConstructorDecl>(D)) {
			//  	  continue;
			//    } else if (dyn_cast<CXXDestructorDecl>(D)) {
			//  	  continue;
			//    } else if (const CXXMethodDecl *ND = dyn_cast<CXXMethodDecl>(D)) {
			//  	  if (!ND->isExternallyVisible()) {
			//  		  continue;
			//  	  }
			//  	  //if (!ND->isOutOfLine()) {
			//  	  //    continue;
			//  	  //}

			//  	  if (ND->isTemplateInstantiation()) {
			//  		  continue;
			//  	  }
			//  	  if (ND->getNumParams() == 0 && ND->isInstance() && !ND->isOverloadedOperator() && !ND->getReturnType()->isVoidType()) {
			//  		  std::string target;
			//  		  if (ND->getReturnType()->isFundamentalType() && !ND->getReturnType()->isPointerType()) {
			//  			  target = "Value";
			//  		  } else if (ND->getReturnType()->isCompoundType()) {
			//  			  target = "CompoundType";
			//  		  } else {
			//  			  target = "Unknown_FIXME!";
			//  		  }
			//  		  llvm::errs() << "X(" << ND->getReturnType().getCanonicalType().getAsString() << ", "
			//  			           << "\"" << ND->getNameInfo().getAsString() << "\", " <<
			//  					   "t->" << ND->getNameInfo().getAsString() << "(), " << target <<
			//  					   " ,0) // " << ND->getParent()->getQualifiedNameAsString() << "\n";
			//
			//  			  //<< "              (class-name \"" << ND->getParent()->getNameAsString() << "\")\n"
			//  			  //<< "              (type " <<  ND->getParent()->getQualifiedNameAsString() << ")\n"
			//  			  //<< "              (function " << ND->getNameInfo().getAsString() << "))\n";
			//  	  }
			//  	  //llvm::errs() << "top-level-decl: \"" << ND->getNameAsString() << "\"\n";
			//     } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)){
			//  	   //llvm::errs() << ND->getNameAsString() << "\n";
			//     }
			//  }

			//  return true;
			//}
	};

	class PrintFunctionNamesAction : public PluginASTAction {
		protected:
			std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
					llvm::StringRef) {
				return llvm::make_unique<PrintFunctionsConsumer>();
			}

			bool ParseArgs(const CompilerInstance &CI,
					const std::vector<std::string>& args) {
				for (unsigned i = 0, e = args.size(); i != e; ++i) {
					llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";

					// Example error handling.
					if (args[i] == "-an-error") {
						DiagnosticsEngine &D = CI.getDiagnostics();
						unsigned DiagID = D.getCustomDiagID(DiagnosticsEngine::Error,
								"invalid argument '%0'");
						D.Report(DiagID) << args[i];
						return false;
					}
				}
				if (args.size() && args[0] == "help")
					PrintHelp(llvm::errs());

				return true;
			}
			void PrintHelp(llvm::raw_ostream& ros) {
				ros << "Help for PrintFunctionNames plugin goes here\n";
			}

	};

}

static FrontendPluginRegistry::Add<PrintFunctionNamesAction>
X("print-fns", "print function names");
<commit_msg>More mods<commit_after>//===- PrintFunctionNames.cpp ---------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Example clang plugin which simply prints the names of all the top-level decls
// in the input file.
//
//===----------------------------------------------------------------------===//

#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/AST.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;

namespace {
	const std::vector<std::string> endsWith = {
		"iterator",
		"iplist",
		"analysis",
		"analysisusage",
		"ref",
		"Impl",
		"Traits",
		"Pass",
		"Set",
		"iterator_range",
		"Builder",
		"Pair",
		"Map",
		"Info",
		"Entry",
		"resolver",
		"tracking",
	};
	const std::vector<std::string> startswith = {
		"__",
		"std",
		"llvm::PointerUnion",
		"llvm::sys",
		"knowledge::",
		"llvm::raw",
		"llvm::pass",
		"llvm::pm",
		"llvm::prettystack",
		"llvm::dominatortree",
	};
	const std::vector<std::string> findCalls = {
		"Allocator",
		"vector",
		"Vector",
		"Iterator",
		"iterator",
		"ilist",
		"Node",
		"Base",
		"PassManager",
		"llvm::is_integral_or_enum",
		"llvm::Optional",
		"Flags",
		"FlagIt",
	};
	const std::vector<std::string> specialValueTypes = {
		"class llvm::StringRef",
		"class std::basic_string<char>",
		"const class std::basic_string<char>",
		"const class std::basic_string<char>&",
		"class std::basic_string<char>&",
		"class llvm::APInt",
		"const unsigned char*",
		"const char*",
		"char*",
		"unsigned char*",
		"llvm::StringRef",
		"llvm::APInt",
		"std::basic_string<char>",
		"const std::basic_string<char>",
		"const std::basic_string<char>&",
		"std::basic_string<char>&",
		"const std::string &",
		"std::string &",
		"const std::string",
		"std::string",
	};
	class PrintFunctionsConsumer : public ASTConsumer {
		public:
			virtual void HandleTagDeclDefinition(TagDecl *D) {
				clang::LangOptions lo;
				lo.CPlusPlus = true;
				clang::PrintingPolicy p(lo);
				if (D->hasNameForLinkage() && D->isClass()) {
					//llvm::errs() << "Class " << D->getNameAsString() << "\n";
					if (const clang::CXXRecordDecl* x = dyn_cast<CXXRecordDecl>(D)) {
						if (!x->isInStdNamespace()) {
							// eliminate all of types taht I will _NEVER_ need
							llvm::StringRef z = x->getQualifiedNameAsString();
							for (std::vector<std::string>::const_iterator it = endsWith.cbegin(); it != endsWith.cend(); ++it) {
								if (z.endswith_lower(*it)) {
									return;
								}
							}

							for (std::vector<std::string>::const_iterator it = startswith.cbegin(); it != startswith.cend(); ++it) {
								if (z.startswith_lower(*it)) {
									return;
								}
							}

							for (std::vector<std::string>::const_iterator it = findCalls.cbegin(); it != findCalls.cend(); ++it) {
								if (z.find(*it) != llvm::StringRef::npos) {
									return;
								}
							}
							llvm::errs() << "Begin(" << x->getQualifiedNameAsString() << ")\n";
							for (clang::CXXRecordDecl::base_class_const_iterator it = x->bases_begin(); it != x->bases_end(); ++it) {
								//if (!it->getType()->isInstantiationDependentType()) {
								llvm::errs() << "\tsuper(" << it->getType().getAsString(lo) << ")\n";
								//}
							}
							std::vector<std::string> multifields;
							for (clang::CXXRecordDecl::method_iterator it = x->method_begin(); it != x->method_end(); ++it) {
								if (it->getAccess() == AS_public &&
										it->getNumParams() == 0 &&
										it->isInstance() &&
										!it->getReturnType()->isVoidType() &&
										!it->isTemplateInstantiation() &&
										!it->isCopyAssignmentOperator() &&
										//!it->isTemplateDecl() &&
										!it->isInAnonymousNamespace() &&
										!it->isOverloadedOperator() && it->isConst()) {
									//llvm::errs() << " // hasQualifiers = " << it->getReturnType().hasQualifiers() << "\n";
									//llvm::errs() << " // hasLocalQualifiers = " << it->getReturnType().hasLocalQualifiers() << "\n";
									//llvm::errs() << " // isCanonical = " << it->getReturnType().isCanonical() << "\n";
									std::string target,
										slotName,
										ret = it->getReturnType().getAsString(p),
										name = it->getNameInfo().getAsString();
									StringRef sr = name;
									if (sr.startswith_lower("getContext") || sr.startswith_lower("convert") || sr.startswith_lower("clone") || sr.startswith_lower("Parse") || sr.startswith_lower("strip")) {
										continue;
									} else if (sr == "rbegin" || sr == "rend" || sr.endswith("rbegin") || sr.endswith("rend") || sr == "operands") {
										continue;
#define ignore(str) \
									} else if (sr == str) { \
										continue
#define X(begin, end, size, tbeg, tend, tsize, field) \
									} else if (sr == begin) { \
										std::string tmp; \
										llvm::raw_string_ostream q(tmp); \
										q << "X("; \
										if (!it->getReturnType().isCanonical()) { \
											q << x->getQualifiedNameAsString() << "::"; \
										} \
										q << ret << ", \"" << field << "\", 0, Multifield, " << tbeg << ", " << tend << ", " << tsize << ", 0) // " << it->getParent()->getQualifiedNameAsString() << "\n"; \
										multifields.push_back(q.str()); \
										continue; \
										ignore(end); \
										ignore(size); \
										ignore(field)
#define Y(begin, end, size, tbeg, tend, field) X(begin, end, size, tbeg, tend, "std::distance(" << tbeg << ", " << tend << ")", field)
									X("begin", "end", "size", "t->begin()", "t->end()", "t->size()", "children");
									X("op_begin", "op_end", "getNumOperands", "t->op_begin()", "t->op_end()", "t->getNumOperands()", "operands");
									X("alias_begin", "alias_end", "alias_size", "t->alias_begin()", "t->alias_end()", "t->alias_size()", "aliases");
									X("named_metadata_begin", "named_metadata_end", "named_metadata_size", "t->named_metadata_begin()", "t->named_metadata_end()", "t->named_metadata_size()", "named_metadata");
									Y("global_begin", "global_end", "getNumGlobals", "t->global_begin()", "t->global_end()", "globals");
									X("subtype_begin", "subtype_end", "getNumContainedTypes", "t->subtype_begin()", "t->subtype_end()", "t->getNumContainedTypes()", "subtypes");
									X("param_begin", "param_end", "getNumParams", "t->param_begin()", "t->param_end()", "t->getNumParams()", "params");
									X("element_begin", "element_end", "getNumElements", "t->element_begin()", "t->element_end()", "t->getNumElements()", "elements");
									X("use_begin", "use_end", "getNumUses", "t->use_begin()", "t->use_end()", "t->getNumUses()", "uses");
									Y("user_begin", "user_end", "getNumUsers", "t->user_begin()", "t->user_end()", "users");
									X("idx_begin", "idx_end", "getNumIndices", "t->idx_begin()", "t->idx_end()", "t->getNumIndices()", "indices");
									X("arg_begin", "arg_end", "arg_size", "t->arg_begin()", "t->arg_end()", "t->arg_size()", "args");
									ignore("global_empty");
									ignore("empty");
									ignore("alias_empty");
									ignore("named_metadata_empty");
#undef Y
#undef X
#undef ignore
									} else if (sr.endswith("begin")) {
										std::string tmp, prefix = name.substr(0, name.size() - 5);
										llvm::raw_string_ostream q(tmp);
										q << "X(" << ret << ", \"" << prefix << "s\", 0, Multifield, t->" << name << "(), t->" << prefix << "end(), t->getNum" << prefix << "(), 0) // " << it->getParent()->getQualifiedNameAsString() << "\n";
										multifields.push_back(q.str());
										continue;
									} else {
										//sr = it->getNameInfo().getAsString();
										if (sr.startswith("get")) {
											slotName = name.substr(3);
										} else {
											slotName = name;
										}
									}
									bool foundMatch = false;
									for (std::vector<std::string>::const_iterator it = specialValueTypes.cbegin(); it != specialValueTypes.cend();
											++it) {
										if (ret == *it) {
											target = "Value";
											foundMatch = true;
											break;
										}
									}
									if (!foundMatch) {
										if ((it->getReturnType()->isFundamentalType() && !it->getReturnType()->isPointerType()) ||
												it->getReturnType()->isEnumeralType()) {
											target = "Value";
										} else if (it->getReturnType()->isPointerType() || it->getReturnType()->isReferenceType()) {
											target = "Reference";
										} else {
											target = "Unknown_FIXME";
											llvm::errs() << "//";
										}
									}
									llvm::errs() << "\tX(" <<
										(it->getReturnType().getCanonicalType()->isBooleanType() ? "bool" : ret) << ", "
										<< "\"" << slotName << "\", " <<
										"t->" << it->getNameInfo().getAsString() << "(), " <<
										target << " ,0) // " << it->getParent()->getQualifiedNameAsString() << "\n";
								}
							}
							for (std::vector<std::string>::const_iterator it = multifields.cbegin(); it != multifields.cend(); ++it) {
								llvm::errs() << "\t" << *it;
							}
							llvm::errs() << "End\n";
						}
					}
				}
			}
			//virtual bool HandleTopLevelDecl(DeclGroupRef DG) {
			//  for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i) {
			//    const Decl *D = *i;
			//    if (D->isInStdNamespace()) {
			//  	  continue;
			//    }
			//    if (D->isInAnonymousNamespace()) {
			//  	  continue;
			//    }
			//    if (D->isFromASTFile()) {
			//  	  continue;
			//    }
			//    if (dyn_cast<CXXConversionDecl>(D)) {
			//  	  continue;
			//    } else if (dyn_cast<CXXConstructorDecl>(D)) {
			//  	  continue;
			//    } else if (dyn_cast<CXXDestructorDecl>(D)) {
			//  	  continue;
			//    } else if (const CXXMethodDecl *ND = dyn_cast<CXXMethodDecl>(D)) {
			//  	  if (!ND->isExternallyVisible()) {
			//  		  continue;
			//  	  }
			//  	  //if (!ND->isOutOfLine()) {
			//  	  //    continue;
			//  	  //}

			//  	  if (ND->isTemplateInstantiation()) {
			//  		  continue;
			//  	  }
			//  	  if (ND->getNumParams() == 0 && ND->isInstance() && !ND->isOverloadedOperator() && !ND->getReturnType()->isVoidType()) {
			//  		  std::string target;
			//  		  if (ND->getReturnType()->isFundamentalType() && !ND->getReturnType()->isPointerType()) {
			//  			  target = "Value";
			//  		  } else if (ND->getReturnType()->isCompoundType()) {
			//  			  target = "CompoundType";
			//  		  } else {
			//  			  target = "Unknown_FIXME!";
			//  		  }
			//  		  llvm::errs() << "X(" << ND->getReturnType().getCanonicalType().getAsString() << ", "
			//  			           << "\"" << ND->getNameInfo().getAsString() << "\", " <<
			//  					   "t->" << ND->getNameInfo().getAsString() << "(), " << target <<
			//  					   " ,0) // " << ND->getParent()->getQualifiedNameAsString() << "\n";
			//
			//  			  //<< "              (class-name \"" << ND->getParent()->getNameAsString() << "\")\n"
			//  			  //<< "              (type " <<  ND->getParent()->getQualifiedNameAsString() << ")\n"
			//  			  //<< "              (function " << ND->getNameInfo().getAsString() << "))\n";
			//  	  }
			//  	  //llvm::errs() << "top-level-decl: \"" << ND->getNameAsString() << "\"\n";
			//     } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)){
			//  	   //llvm::errs() << ND->getNameAsString() << "\n";
			//     }
			//  }

			//  return true;
			//}
	};

	class PrintFunctionNamesAction : public PluginASTAction {
		protected:
			std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
					llvm::StringRef) {
				return llvm::make_unique<PrintFunctionsConsumer>();
			}

			bool ParseArgs(const CompilerInstance &CI,
					const std::vector<std::string>& args) {
				for (unsigned i = 0, e = args.size(); i != e; ++i) {
					llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";

					// Example error handling.
					if (args[i] == "-an-error") {
						DiagnosticsEngine &D = CI.getDiagnostics();
						unsigned DiagID = D.getCustomDiagID(DiagnosticsEngine::Error,
								"invalid argument '%0'");
						D.Report(DiagID) << args[i];
						return false;
					}
				}
				if (args.size() && args[0] == "help")
					PrintHelp(llvm::errs());

				return true;
			}
			void PrintHelp(llvm::raw_ostream& ros) {
				ros << "Help for PrintFunctionNames plugin goes here\n";
			}

	};

}

static FrontendPluginRegistry::Add<PrintFunctionNamesAction>
X("print-fns", "print function names");
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: liangbarsky.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:05:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"

#include "basegfx/tools/tools.hxx"
#include "basegfx/numeric/ftools.hxx"
#include "basegfx/range/b2drange.hxx"

namespace basegfx
{
    namespace tools
    {
        namespace
        {
            // see Foley/vanDam, pp. 122 for the Liang-Barsky line
            // clipping algorithm
            inline bool liangBarskyClipT( double  nDenom,
                                          double  nNumerator,
                                          double& io_rTE,
                                          double& io_rTL )
            {
                double t;
                if( nDenom > 0 )
                {
                    t = nNumerator / nDenom;
                    if( t > io_rTL )
                        return false;
                    else if( t > io_rTE )
                        io_rTE = t;
                }
                else if( nDenom < 0 )
                {
                    t = nNumerator / nDenom;
                    if( t < io_rTE )
                        return false;
                    else
                        io_rTL = t;
                }
                else if( nNumerator > 0 )
                {
                    return false;
                }

                return true;
            }
        }

        // see Foley/vanDam, pp. 122 for the Liang-Barsky line
        // clipping algorithm
        bool liangBarskyClip2D( ::basegfx::B2DPoint&        io_rStart,
                                ::basegfx::B2DPoint&        io_rEnd,
                                const ::basegfx::B2DRange&  rClipRect )
        {
            const double nDX( io_rEnd.getX() - io_rStart.getX() );
            const double nDY( io_rEnd.getY() - io_rStart.getY() );

            if( ::basegfx::fTools::equalZero( nDX ) &&
                ::basegfx::fTools::equalZero( nDY ) )
            {
                return rClipRect.isInside( io_rStart );
            }
            else
            {
                double nTE( 0.0 );
                double nTL( 1.0 );
                if( liangBarskyClipT(nDX, rClipRect.getMinX() - io_rStart.getX(),
                                     nTE, nTL ) )                   // inside wrt. left edge
                {
                    if( liangBarskyClipT(-nDX, io_rStart.getX() - rClipRect.getMaxX(),
                                         nTE, nTL ) )               // inside wrt. right edge
                    {
                        if( liangBarskyClipT(nDY, rClipRect.getMinY() - io_rStart.getY(),
                                             nTE, nTL ) )           // inside wrt. bottom edge
                        {
                            if( liangBarskyClipT(-nDY, io_rStart.getY() - rClipRect.getMaxY(),
                                                 nTE, nTL ) )       // inside wrt. top edge
                            {
                                // compute actual intersection points,
                                // if nTL has changed
                                if( nTL < 1.0 )
                                {
                                    io_rEnd.setX( io_rStart.getX() + nTL*nDX );
                                    io_rEnd.setY( io_rStart.getY() + nTL*nDY );
                                }

                                // compute actual intersection points,
                                // if nTE has changed
                                if( nTE > 0.0 )
                                {
                                    io_rStart.setX( io_rStart.getX() + nTE*nDX );
                                    io_rStart.setY( io_rStart.getY() + nTE*nDY );
                                }

                                // line is (at least partially) visible
                                return true;
                            }
                        }
                    }
                }
            }

            return false;
        }
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.4.60); FILE MERGED 2008/03/28 16:05:56 rt 1.4.60.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: liangbarsky.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"

#include "basegfx/tools/tools.hxx"
#include "basegfx/numeric/ftools.hxx"
#include "basegfx/range/b2drange.hxx"

namespace basegfx
{
    namespace tools
    {
        namespace
        {
            // see Foley/vanDam, pp. 122 for the Liang-Barsky line
            // clipping algorithm
            inline bool liangBarskyClipT( double  nDenom,
                                          double  nNumerator,
                                          double& io_rTE,
                                          double& io_rTL )
            {
                double t;
                if( nDenom > 0 )
                {
                    t = nNumerator / nDenom;
                    if( t > io_rTL )
                        return false;
                    else if( t > io_rTE )
                        io_rTE = t;
                }
                else if( nDenom < 0 )
                {
                    t = nNumerator / nDenom;
                    if( t < io_rTE )
                        return false;
                    else
                        io_rTL = t;
                }
                else if( nNumerator > 0 )
                {
                    return false;
                }

                return true;
            }
        }

        // see Foley/vanDam, pp. 122 for the Liang-Barsky line
        // clipping algorithm
        bool liangBarskyClip2D( ::basegfx::B2DPoint&        io_rStart,
                                ::basegfx::B2DPoint&        io_rEnd,
                                const ::basegfx::B2DRange&  rClipRect )
        {
            const double nDX( io_rEnd.getX() - io_rStart.getX() );
            const double nDY( io_rEnd.getY() - io_rStart.getY() );

            if( ::basegfx::fTools::equalZero( nDX ) &&
                ::basegfx::fTools::equalZero( nDY ) )
            {
                return rClipRect.isInside( io_rStart );
            }
            else
            {
                double nTE( 0.0 );
                double nTL( 1.0 );
                if( liangBarskyClipT(nDX, rClipRect.getMinX() - io_rStart.getX(),
                                     nTE, nTL ) )                   // inside wrt. left edge
                {
                    if( liangBarskyClipT(-nDX, io_rStart.getX() - rClipRect.getMaxX(),
                                         nTE, nTL ) )               // inside wrt. right edge
                    {
                        if( liangBarskyClipT(nDY, rClipRect.getMinY() - io_rStart.getY(),
                                             nTE, nTL ) )           // inside wrt. bottom edge
                        {
                            if( liangBarskyClipT(-nDY, io_rStart.getY() - rClipRect.getMaxY(),
                                                 nTE, nTL ) )       // inside wrt. top edge
                            {
                                // compute actual intersection points,
                                // if nTL has changed
                                if( nTL < 1.0 )
                                {
                                    io_rEnd.setX( io_rStart.getX() + nTL*nDX );
                                    io_rEnd.setY( io_rStart.getY() + nTL*nDY );
                                }

                                // compute actual intersection points,
                                // if nTE has changed
                                if( nTE > 0.0 )
                                {
                                    io_rStart.setX( io_rStart.getX() + nTE*nDX );
                                    io_rStart.setY( io_rStart.getY() + nTE*nDY );
                                }

                                // line is (at least partially) visible
                                return true;
                            }
                        }
                    }
                }
            }

            return false;
        }
    }
}
<|endoftext|>


<commit_before>#pragma once
#include <cstdint>
#include <iostream>
#include <iomanip>

#include "instruction_procedures.h"
#include "decoder.h"
#include "memory.h"
#include "global_registers.h"
#include "register_procedures.h"

using namespace std;

void Format(AddressingMode addressingMode)
{
	switch (addressingMode)
	{
	case Immediate:
		cout << "#$" << setw(2) << setfill('0') << uppercase << hex;
		break;
	case ZeroPage:
	case ZeroPageX:
	case ZeroPageY:
	case Relative:
		cout << "$" << setw(2) << setfill('0') << uppercase << hex;
		break;
	case Absolute:
	case AbsoluteX:
	case AbsoluteY:
		cout << "$" << setw(4) << setfill('0') << uppercase << hex;
		break;
	case ZeroPageIndirectX:
	case ZeroPageIndirectY:
		cout << '(' << '$' << setw(4) << setfill('0') << uppercase << hex;
		break;
	}

	//Anything else does not need special formatting
}

void PrintOperands(AddressingMode addressingMode, uint8_t operands[])
{
	Format(addressingMode);

	uint16_t operand;
	switch (addressingMode)
	{
	case Immediate:
		cout << (int)operands[0];
		break;
	case ZeroPage:
		cout << (int)operands[0];
		break;
	case ZeroPageX:
		cout << (int)operands[0] << ",X";
		break;
	case ZeroPageY:
		cout << (int)operands[0] << ",Y";
	case Relative:
		cout << (int)operands[0];
		break;
	case Absolute:
		operand = (uint16_t)operands[1] << 8 | operands[0];
		cout << operand;
		break;
	case AbsoluteX:
		operand = (uint16_t)operands[1] << 8 | operands[0];
		cout << operand << ",X";
		break;
	case AbsoluteY:
		operand = (uint16_t)operands[1] << 8 | operands[0];
		cout << operand << ",Y";
		break;
	case ZeroPageIndirectX:
		cout << (int)operands[0] << ",X)";
		break;
	case ZeroPageIndirectY:
		cout << (int)operands[0] << "),Y";
		break;
	}

	cout << endl;

}

uint16_t _8_to_16(uint8_t high, uint8_t low)
{
	return (uint16_t)high << 8 | low;
}

uint16_t _calculate_address(AddressingMode addressingMode, uint8_t operands[])
{
	switch (addressingMode)
	{
	case Absolute:
		return _8_to_16(operands[1], operands[0]);
	case ZeroPage:
		return operands[0];
	case Relative:
		return _8_to_16(reg::PCH, reg::PCL) + (int8_t)operands[0];
	case AbsoluteX:
		return reg::X + (int16_t)_8_to_16(operands[1], operands[0]);
	case AbsoluteY:
		return reg::Y + (int16_t)_8_to_16(operands[1], operands[0]);
	case ZeroPageX:
		return (uint16_t)((reg::X + operands[0]) % 0xFF);
	case ZeroPageY:
		return (uint16_t)((reg::Y + operands[0]) % 0xFF);
	case ZeroPageIndirectX:
		return _8_to_16(mem[reg::X + operands[0] + 1], mem[reg::X + operands[0]]);
	case ZeroPageIndirectY:
		return _8_to_16(mem[reg::Y + operands[0] + 1], mem[reg::Y + operands[0]]);
	default:
		return 0;
	}
}

// Should not be used with addressing modes Accumulator and Implied.
uint8_t& _fetch_operand(AddressingMode addressingMode, uint8_t operands[])
{
	switch (addressingMode)
	{
	case Immediate:
		return operands[0];
	default:
		return mem[_calculate_address(addressingMode, operands)];
	}
}

void ProcADC(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	if (!GetFlagD())
	{
		bool bit7 = (reg::Accumulator & (1 << 7)) != 0;
		uint8_t oldAcc = reg::Accumulator;
		if (reg::Accumulator + operand > 255)
			SetFlagC(true);
		else
			SetFlagC(false);

		reg::Accumulator += operand;

		SetFlagN((reg::Accumulator & (1 << 7)) != 0); // Put bit 7 in S flag
		SetFlagZ(!reg::Accumulator);
		//TODO: Implement overflow flag setting
	}
}

void ProcAND(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::Accumulator = reg::Accumulator & operand;
	SetFlagZ(reg::Accumulator == 0);
	SetFlagN((reg::Accumulator & (1 << 7)) != 0);
}

void ProcASL(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = (addressingMode == Accumulator) ? reg::Accumulator : _fetch_operand(addressingMode, operands);

	SetFlagC((operand & (1 << 7)) != 0);
	SetFlagN((operand & (1 << 6)) != 0);

	operand <<= 1;

	SetFlagZ(operand == 0);
}

void ProcBCC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BCC ";
	PrintOperands(addressingMode, operands);
}

void ProcBCS(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BCS ";
	PrintOperands(addressingMode, operands);
}

void ProcBEQ(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BEQ ";
	PrintOperands(addressingMode, operands);
}

void ProcBIT(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BIT ";
	PrintOperands(addressingMode, operands);
}

void ProcBMI(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BMI ";
	PrintOperands(addressingMode, operands);
}

void ProcBNE(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BNE ";
	PrintOperands(addressingMode, operands);
}

void ProcBPL(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BPL ";
	PrintOperands(addressingMode, operands);
}

void ProcBRK(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BRK ";
	PrintOperands(addressingMode, operands);
}

void ProcBVC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BVC ";
	PrintOperands(addressingMode, operands);
}

void ProcBVS(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BVS ";
	PrintOperands(addressingMode, operands);
}

void ProcCLC(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagC(false);
}

void ProcCLD(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagD(false);
}

void ProcCLI(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagI(false);
}

void ProcCLV(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagV(false);
}

void ProcCMP(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t &operand = _fetch_operand(addressingMode, operands);
	SetFlagZ(operand == reg::Accumulator);
	SetFlagN(reg::Accumulator < operand);
	SetFlagC(reg::Accumulator >= operand);
}

void ProcCPX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "CPX ";
	PrintOperands(addressingMode, operands);
}

void ProcCPY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "CPY ";
	PrintOperands(addressingMode, operands);
}

void ProcDEC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "DEC ";
	PrintOperands(addressingMode, operands);
}

void ProcDEX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "DEX ";
	PrintOperands(addressingMode, operands);
}

void ProcDEY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "DEY ";
	PrintOperands(addressingMode, operands);
}

void ProcEOR(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "EOR ";
	PrintOperands(addressingMode, operands);
}

void ProcINC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "INC ";
	PrintOperands(addressingMode, operands);
}

void ProcINX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "INX ";
	PrintOperands(addressingMode, operands);
}

void ProcINY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "INY ";
	PrintOperands(addressingMode, operands);
}

void ProcJMP(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "JMP ";
	PrintOperands(addressingMode, operands);
}

void ProcJSR(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "JSR ";
	PrintOperands(addressingMode, operands);
}

void ProcLDA(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::Accumulator = operand;
	SetFlagZ(reg::Accumulator == 0);
	SetFlagN(reg::Accumulator & (1 << 7) != 0);
}

void ProcLDX(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::X = operand;
	SetFlagZ(reg::X == 0);
	SetFlagN(reg::X & (1 << 7) != 0);
}

void ProcLDY(AddressingMode addressingMode, uint8_t operands[])
{
    uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::Y= operand;
	SetFlagN(reg::Y & (1 << 7) != 0);
	SetFlagZ(reg::Y == 0);
}

void ProcLSR(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "LSR ";
	PrintOperands(addressingMode, operands);
}

void ProcNOP(AddressingMode addressingMode, uint8_t operands[])
{
}

void ProcORA(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::Accumulator = reg::Accumulator | operand;
	SetFlagZ(reg::Accumulator == 0);
	SetFlagN(reg::Accumulator & (1 << 7) != 0);

}

void ProcPHA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "PHA ";
	PrintOperands(addressingMode, operands);
}

void ProcPHP(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "PHP ";
	PrintOperands(addressingMode, operands);
}

void ProcPLA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "PLA ";
	PrintOperands(addressingMode, operands);
}

void ProcPLP(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "PLP ";
	PrintOperands(addressingMode, operands);
}

void ProcROL(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "ROL ";
	PrintOperands(addressingMode, operands);
}

void ProcROR(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "ROR ";
	PrintOperands(addressingMode, operands);
}

void ProcRTI(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "RTI ";
	PrintOperands(addressingMode, operands);
}

void ProcRTS(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "RTS ";
	PrintOperands(addressingMode, operands);
}

void ProcSBC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "SBC ";
	PrintOperands(addressingMode, operands);
}

void ProcSEC(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagC(true);
}

void ProcSED(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagD(true);
}

void ProcSEI(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "SEI ";
	PrintOperands(addressingMode, operands);
}

void ProcSTA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "STA ";
	PrintOperands(addressingMode, operands);
}

void ProcSTX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "STX ";
	PrintOperands(addressingMode, operands);
}

void ProcSTY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "STY ";
	PrintOperands(addressingMode, operands);
}

void ProcTAX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TAX ";
	PrintOperands(addressingMode, operands);
}

void ProcTAY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TAY ";
	PrintOperands(addressingMode, operands);
}

void ProcTSX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TSX ";
	PrintOperands(addressingMode, operands);
}

void ProcTXA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TXA ";
	PrintOperands(addressingMode, operands);
}

void ProcTXS(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TXS ";
	PrintOperands(addressingMode, operands);
}

void ProcTYA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TYA ";
	PrintOperands(addressingMode, operands);
}
<commit_msg>suppressed more warnings<commit_after>#pragma once
#include <cstdint>
#include <iostream>
#include <iomanip>

#include "instruction_procedures.h"
#include "decoder.h"
#include "memory.h"
#include "global_registers.h"
#include "register_procedures.h"

using namespace std;

void Format(AddressingMode addressingMode)
{
	switch (addressingMode)
	{
	case Immediate:
		cout << "#$" << setw(2) << setfill('0') << uppercase << hex;
		break;
	case ZeroPage:
	case ZeroPageX:
	case ZeroPageY:
	case Relative:
		cout << "$" << setw(2) << setfill('0') << uppercase << hex;
		break;
	case Absolute:
	case AbsoluteX:
	case AbsoluteY:
		cout << "$" << setw(4) << setfill('0') << uppercase << hex;
		break;
	case ZeroPageIndirectX:
	case ZeroPageIndirectY:
		cout << '(' << '$' << setw(4) << setfill('0') << uppercase << hex;
		break;
	}

	//Anything else does not need special formatting
}

void PrintOperands(AddressingMode addressingMode, uint8_t operands[])
{
	Format(addressingMode);

	uint16_t operand;
	switch (addressingMode)
	{
	case Immediate:
		cout << (int)operands[0];
		break;
	case ZeroPage:
		cout << (int)operands[0];
		break;
	case ZeroPageX:
		cout << (int)operands[0] << ",X";
		break;
	case ZeroPageY:
		cout << (int)operands[0] << ",Y";
	case Relative:
		cout << (int)operands[0];
		break;
	case Absolute:
		operand = (uint16_t)operands[1] << 8 | operands[0];
		cout << operand;
		break;
	case AbsoluteX:
		operand = (uint16_t)operands[1] << 8 | operands[0];
		cout << operand << ",X";
		break;
	case AbsoluteY:
		operand = (uint16_t)operands[1] << 8 | operands[0];
		cout << operand << ",Y";
		break;
	case ZeroPageIndirectX:
		cout << (int)operands[0] << ",X)";
		break;
	case ZeroPageIndirectY:
		cout << (int)operands[0] << "),Y";
		break;
	}

	cout << endl;

}

uint16_t _8_to_16(uint8_t high, uint8_t low)
{
	return (uint16_t)high << 8 | low;
}

uint16_t _calculate_address(AddressingMode addressingMode, uint8_t operands[])
{
	switch (addressingMode)
	{
	case Absolute:
		return _8_to_16(operands[1], operands[0]);
	case ZeroPage:
		return operands[0];
	case Relative:
		return _8_to_16(reg::PCH, reg::PCL) + (int8_t)operands[0];
	case AbsoluteX:
		return reg::X + (int16_t)_8_to_16(operands[1], operands[0]);
	case AbsoluteY:
		return reg::Y + (int16_t)_8_to_16(operands[1], operands[0]);
	case ZeroPageX:
		return (uint16_t)((reg::X + operands[0]) % 0xFF);
	case ZeroPageY:
		return (uint16_t)((reg::Y + operands[0]) % 0xFF);
	case ZeroPageIndirectX:
		return _8_to_16(mem[reg::X + operands[0] + 1], mem[reg::X + operands[0]]);
	case ZeroPageIndirectY:
		return _8_to_16(mem[reg::Y + operands[0] + 1], mem[reg::Y + operands[0]]);
	default:
		return 0;
	}
}

// Should not be used with addressing modes Accumulator and Implied.
uint8_t& _fetch_operand(AddressingMode addressingMode, uint8_t operands[])
{
	switch (addressingMode)
	{
	case Immediate:
		return operands[0];
	default:
		return mem[_calculate_address(addressingMode, operands)];
	}
}

void ProcADC(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	if (!GetFlagD())
	{
		bool bit7 = (reg::Accumulator & (1 << 7)) != 0;
		uint8_t oldAcc = reg::Accumulator;
		if (reg::Accumulator + operand > 255)
			SetFlagC(true);
		else
			SetFlagC(false);

		reg::Accumulator += operand;

		SetFlagN((reg::Accumulator & (1 << 7)) != 0); // Put bit 7 in S flag
		SetFlagZ(!reg::Accumulator);
		//TODO: Implement overflow flag setting
	}
}

void ProcAND(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::Accumulator = reg::Accumulator & operand;
	SetFlagZ(reg::Accumulator == 0);
	SetFlagN((reg::Accumulator & (1 << 7)) != 0);
}

void ProcASL(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = (addressingMode == Accumulator) ? reg::Accumulator : _fetch_operand(addressingMode, operands);

	SetFlagC((operand & (1 << 7)) != 0);
	SetFlagN((operand & (1 << 6)) != 0);

	operand <<= 1;

	SetFlagZ(operand == 0);
}

void ProcBCC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BCC ";
	PrintOperands(addressingMode, operands);
}

void ProcBCS(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BCS ";
	PrintOperands(addressingMode, operands);
}

void ProcBEQ(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BEQ ";
	PrintOperands(addressingMode, operands);
}

void ProcBIT(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BIT ";
	PrintOperands(addressingMode, operands);
}

void ProcBMI(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BMI ";
	PrintOperands(addressingMode, operands);
}

void ProcBNE(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BNE ";
	PrintOperands(addressingMode, operands);
}

void ProcBPL(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BPL ";
	PrintOperands(addressingMode, operands);
}

void ProcBRK(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BRK ";
	PrintOperands(addressingMode, operands);
}

void ProcBVC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BVC ";
	PrintOperands(addressingMode, operands);
}

void ProcBVS(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "BVS ";
	PrintOperands(addressingMode, operands);
}

void ProcCLC(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagC(false);
}

void ProcCLD(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagD(false);
}

void ProcCLI(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagI(false);
}

void ProcCLV(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagV(false);
}

void ProcCMP(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t &operand = _fetch_operand(addressingMode, operands);
	SetFlagZ(operand == reg::Accumulator);
	SetFlagN(reg::Accumulator < operand);
	SetFlagC(reg::Accumulator >= operand);
}

void ProcCPX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "CPX ";
	PrintOperands(addressingMode, operands);
}

void ProcCPY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "CPY ";
	PrintOperands(addressingMode, operands);
}

void ProcDEC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "DEC ";
	PrintOperands(addressingMode, operands);
}

void ProcDEX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "DEX ";
	PrintOperands(addressingMode, operands);
}

void ProcDEY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "DEY ";
	PrintOperands(addressingMode, operands);
}

void ProcEOR(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "EOR ";
	PrintOperands(addressingMode, operands);
}

void ProcINC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "INC ";
	PrintOperands(addressingMode, operands);
}

void ProcINX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "INX ";
	PrintOperands(addressingMode, operands);
}

void ProcINY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "INY ";
	PrintOperands(addressingMode, operands);
}

void ProcJMP(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "JMP ";
	PrintOperands(addressingMode, operands);
}

void ProcJSR(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "JSR ";
	PrintOperands(addressingMode, operands);
}

void ProcLDA(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::Accumulator = operand;
	SetFlagZ(reg::Accumulator == 0);
	SetFlagN((reg::Accumulator & (1 << 7)) != 0);
}

void ProcLDX(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::X = operand;
	SetFlagZ(reg::X == 0);
	SetFlagN((reg::X & (1 << 7)) != 0);
}

void ProcLDY(AddressingMode addressingMode, uint8_t operands[])
{
    uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::Y= operand;
	SetFlagN((reg::Y & (1 << 7)) != 0);
	SetFlagZ(reg::Y == 0);
}

void ProcLSR(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "LSR ";
	PrintOperands(addressingMode, operands);
}

void ProcNOP(AddressingMode addressingMode, uint8_t operands[])
{
}

void ProcORA(AddressingMode addressingMode, uint8_t operands[])
{
	uint8_t& operand = _fetch_operand(addressingMode, operands);
	reg::Accumulator = reg::Accumulator | operand;
	SetFlagZ(reg::Accumulator == 0);
	SetFlagN((reg::Accumulator & (1 << 7)) != 0);

}

void ProcPHA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "PHA ";
	PrintOperands(addressingMode, operands);
}

void ProcPHP(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "PHP ";
	PrintOperands(addressingMode, operands);
}

void ProcPLA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "PLA ";
	PrintOperands(addressingMode, operands);
}

void ProcPLP(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "PLP ";
	PrintOperands(addressingMode, operands);
}

void ProcROL(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "ROL ";
	PrintOperands(addressingMode, operands);
}

void ProcROR(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "ROR ";
	PrintOperands(addressingMode, operands);
}

void ProcRTI(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "RTI ";
	PrintOperands(addressingMode, operands);
}

void ProcRTS(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "RTS ";
	PrintOperands(addressingMode, operands);
}

void ProcSBC(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "SBC ";
	PrintOperands(addressingMode, operands);
}

void ProcSEC(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagC(true);
}

void ProcSED(AddressingMode addressingMode, uint8_t operands[])
{
	SetFlagD(true);
}

void ProcSEI(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "SEI ";
	PrintOperands(addressingMode, operands);
}

void ProcSTA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "STA ";
	PrintOperands(addressingMode, operands);
}

void ProcSTX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "STX ";
	PrintOperands(addressingMode, operands);
}

void ProcSTY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "STY ";
	PrintOperands(addressingMode, operands);
}

void ProcTAX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TAX ";
	PrintOperands(addressingMode, operands);
}

void ProcTAY(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TAY ";
	PrintOperands(addressingMode, operands);
}

void ProcTSX(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TSX ";
	PrintOperands(addressingMode, operands);
}

void ProcTXA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TXA ";
	PrintOperands(addressingMode, operands);
}

void ProcTXS(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TXS ";
	PrintOperands(addressingMode, operands);
}

void ProcTYA(AddressingMode addressingMode, uint8_t operands[])
{
	cout << "TYA ";
	PrintOperands(addressingMode, operands);
}
<|endoftext|>


<commit_before>#include <audio/format/OGG.h>
#include <system/System.h>
#include <vorbis/vorbisfile.h>

namespace lime {

	typedef struct {

		unsigned char* data;
		ogg_int64_t size;
		ogg_int64_t pos;

	} OAL_OggMemoryFile;

	static size_t OAL_OggBufferRead (void* dest, size_t eltSize, size_t nelts, OAL_OggMemoryFile* src) {

		size_t len = eltSize * nelts;

		if ((src->pos + len) > src->size) {

			len = src->size - src->pos;

		}

		if (len > 0) {

			memcpy (dest, (src->data + src->pos), len);
			src->pos += len;

		}

		return len;

	}

	static int OAL_OggBufferSeek (OAL_OggMemoryFile* src, ogg_int64_t pos, int whence) {

		switch (whence) {

			case SEEK_CUR:

				src->pos += pos;
				break;

			case SEEK_END:

				src->pos = src->size - pos;
				break;

			case SEEK_SET:

				src->pos = pos;
				break;

			default:

				return -1;

		}

		if (src->pos < 0) {

			src->pos = 0;
			return -1;

		}

		if (src->pos > src->size) {

			return -1;

		}

		return 0;

	}

	static int OAL_OggBufferClose (OAL_OggMemoryFile* src) {

		return 0;

	}

	static long OAL_OggBufferTell (OAL_OggMemoryFile *src) {

		return src->pos;

	}

	static ov_callbacks OAL_CALLBACKS_BUFFER = {

		(size_t (*)(void *, size_t, size_t, void *)) OAL_OggBufferRead,
		(int (*)(void *, ogg_int64_t, int)) OAL_OggBufferSeek,
		(int (*)(void *)) OAL_OggBufferClose,
		(long (*)(void *)) OAL_OggBufferTell

	};

	bool OGG::Decode (Resource *resource, AudioBuffer *audioBuffer) {

		OggVorbis_File oggFile;

		if (resource->path) {

			FILE_HANDLE *file;

			//#ifdef ANDROID
			//FileInfo info = AndroidGetAssetFD (resource->path);
			//file = lime::fdopen (info.fd, "rb");
			//lime::fseek (file, info.offset, 0);
			//#else
			file = lime::fopen (resource->path, "rb");
			//#endif

			if (!file) {

				//LOG_SOUND("FAILED to read audio file, file pointer as null?\n");
				return false;

			}

			//#ifdef ANDROID
			//ov_open (file, &oggFile, NULL, info.length);
			//#else
			ov_open (file->getFile (), &oggFile, NULL, file->getLength ());
			//#endif

		} else {

			OAL_OggMemoryFile fakeFile = { resource->data->Bytes (), resource->data->Size (), 0 };

			if (ov_open_callbacks (&fakeFile, &oggFile, NULL, 0, OAL_CALLBACKS_BUFFER) != 0) {

				return false;

			}

		}

		// 0 for Little-Endian, 1 for Big-Endian
		#ifdef HXCPP_BIG_ENDIAN
		#define BUFFER_READ_TYPE 1
		#else
		#define BUFFER_READ_TYPE 0
		#endif

		int bitStream;
		long bytes = 1;
		int totalBytes = 0;

		#define BUFFER_SIZE 32768

		vorbis_info *pInfo = ov_info (&oggFile, -1);

		if (pInfo == NULL) {

			//LOG_SOUND("FAILED TO READ OGG SOUND INFO, IS THIS EVEN AN OGG FILE?\n");
			return false;

		}

		audioBuffer->channels = pInfo->channels;
		audioBuffer->sampleRate = pInfo->rate;

		//default to 16? todo
		audioBuffer->bitsPerSample = 16;

		// Seem to need four times the read PCM total
		audioBuffer->data->Resize (ov_pcm_total (&oggFile, -1) * 4);

		while (bytes > 0) {

			if (audioBuffer->data->Size () < totalBytes + BUFFER_SIZE) {

				audioBuffer->data->Resize (totalBytes + BUFFER_SIZE);

			}

			bytes = ov_read (&oggFile, (char *)audioBuffer->data->Bytes () + totalBytes, BUFFER_SIZE, BUFFER_READ_TYPE, 2, 1, &bitStream);
			totalBytes += bytes;

		}

		audioBuffer->data->Resize (totalBytes);
		ov_clear (&oggFile);

		#undef BUFFER_SIZE
		#undef BUFFER_READ_TYPE

		return true;

	}

}<commit_msg>Make sure OGG file is readable<commit_after>#include <audio/format/OGG.h>
#include <system/System.h>
#include <vorbis/vorbisfile.h>

namespace lime {

	typedef struct {

		unsigned char* data;
		ogg_int64_t size;
		ogg_int64_t pos;

	} OAL_OggMemoryFile;

	static size_t OAL_OggBufferRead (void* dest, size_t eltSize, size_t nelts, OAL_OggMemoryFile* src) {

		size_t len = eltSize * nelts;

		if ((src->pos + len) > src->size) {

			len = src->size - src->pos;

		}

		if (len > 0) {

			memcpy (dest, (src->data + src->pos), len);
			src->pos += len;

		}

		return len;

	}

	static int OAL_OggBufferSeek (OAL_OggMemoryFile* src, ogg_int64_t pos, int whence) {

		switch (whence) {

			case SEEK_CUR:

				src->pos += pos;
				break;

			case SEEK_END:

				src->pos = src->size - pos;
				break;

			case SEEK_SET:

				src->pos = pos;
				break;

			default:

				return -1;

		}

		if (src->pos < 0) {

			src->pos = 0;
			return -1;

		}

		if (src->pos > src->size) {

			return -1;

		}

		return 0;

	}

	static int OAL_OggBufferClose (OAL_OggMemoryFile* src) {

		return 0;

	}

	static long OAL_OggBufferTell (OAL_OggMemoryFile *src) {

		return src->pos;

	}

	static ov_callbacks OAL_CALLBACKS_BUFFER = {

		(size_t (*)(void *, size_t, size_t, void *)) OAL_OggBufferRead,
		(int (*)(void *, ogg_int64_t, int)) OAL_OggBufferSeek,
		(int (*)(void *)) OAL_OggBufferClose,
		(long (*)(void *)) OAL_OggBufferTell

	};

	bool OGG::Decode (Resource *resource, AudioBuffer *audioBuffer) {

		OggVorbis_File oggFile;

		if (resource->path) {

			FILE_HANDLE *file;

			//#ifdef ANDROID
			//FileInfo info = AndroidGetAssetFD (resource->path);
			//file = lime::fdopen (info.fd, "rb");
			//lime::fseek (file, info.offset, 0);
			//#else
			file = lime::fopen (resource->path, "rb");
			//#endif

			if (!file || !file->isFile ()) {

				//LOG_SOUND("FAILED to read audio file, file pointer as null?\n");
				return false;

			}

			//#ifdef ANDROID
			//ov_open (file, &oggFile, NULL, info.length);
			//#else
			ov_open (file->getFile (), &oggFile, NULL, file->getLength ());
			//#endif

		} else {

			OAL_OggMemoryFile fakeFile = { resource->data->Bytes (), resource->data->Size (), 0 };

			if (ov_open_callbacks (&fakeFile, &oggFile, NULL, 0, OAL_CALLBACKS_BUFFER) != 0) {

				return false;

			}

		}

		// 0 for Little-Endian, 1 for Big-Endian
		#ifdef HXCPP_BIG_ENDIAN
		#define BUFFER_READ_TYPE 1
		#else
		#define BUFFER_READ_TYPE 0
		#endif

		int bitStream;
		long bytes = 1;
		int totalBytes = 0;

		#define BUFFER_SIZE 32768

		vorbis_info *pInfo = ov_info (&oggFile, -1);

		if (pInfo == NULL) {

			//LOG_SOUND("FAILED TO READ OGG SOUND INFO, IS THIS EVEN AN OGG FILE?\n");
			return false;

		}

		audioBuffer->channels = pInfo->channels;
		audioBuffer->sampleRate = pInfo->rate;

		//default to 16? todo
		audioBuffer->bitsPerSample = 16;

		// Seem to need four times the read PCM total
		audioBuffer->data->Resize (ov_pcm_total (&oggFile, -1) * 4);

		while (bytes > 0) {

			if (audioBuffer->data->Size () < totalBytes + BUFFER_SIZE) {

				audioBuffer->data->Resize (totalBytes + BUFFER_SIZE);

			}

			bytes = ov_read (&oggFile, (char *)audioBuffer->data->Bytes () + totalBytes, BUFFER_SIZE, BUFFER_READ_TYPE, 2, 1, &bitStream);
			totalBytes += bytes;

		}

		audioBuffer->data->Resize (totalBytes);
		ov_clear (&oggFile);

		#undef BUFFER_SIZE
		#undef BUFFER_READ_TYPE

		return true;

	}

}<|endoftext|>


<commit_before>// Copyright 2021 The CFU-Playground Authors
//
// 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.

#include "tflite.h"

#include "perf.h"
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/micro_profiler.h"
#include "tensorflow/lite/schema/schema_generated.h"

#ifdef SHOW_MEMORY_USE
#include "tensorflow/lite/micro/recording_micro_interpreter.h"
#define INTERPRETER_TYPE RecordingMicroInterpreter
#else
#define INTERPRETER_TYPE MicroInterpreter
#endif

//
// Unit test prototypes. Because of the way these names are generated, they are
// not defined in any include file. The actual tests are in test_name.cc - e.g
// conv_test is defined in conv_test.cc.
extern int conv_test(int argc, char** argv);
extern int depthwise_conv_test(int argc, char** argv);

// Run tflite unit tests
void tflite_do_tests() {
  // conv test from conv_test.cc
  puts("\nCONV TEST:");
  conv_test(0, NULL);
  // depthwise conv test from depthwise_conv_test.cc
  puts("DEPTHWISE_CONV TEST:");
  depthwise_conv_test(0, NULL);
}

// For C++ exceptions
void* __dso_handle = &__dso_handle;

//
// TfLM global objects
namespace {
tflite::ErrorReporter* error_reporter = nullptr;
tflite::MicroOpResolver* op_resolver = nullptr;
tflite::MicroProfiler* profiler = nullptr;

const tflite::Model* model = nullptr;
tflite::INTERPRETER_TYPE* interpreter = nullptr;

// An area of memory to use for input, output, and intermediate arrays.
// constexpr int kTensorArenaSize = 136 * 1024;
#if defined(INCLUDE_MODEL_MNV2) || defined(INLCUDE_MODEL_MLCOMMONS_TINY_V01_VWW)
constexpr int kTensorArenaSize = 800 * 1024;
#else
constexpr int kTensorArenaSize = 81 * 1024;
#endif
static uint8_t tensor_arena[kTensorArenaSize];
}  // namespace

static void tflite_init() {
  static bool initialized = false;
  if (initialized) {
    return;
  }
  initialized = true;

  // Sets up error reporting etc
  static tflite::MicroErrorReporter micro_error_reporter;
  error_reporter = &micro_error_reporter;
  TF_LITE_REPORT_ERROR(error_reporter, "Error_reporter OK!");

  // Pull in only the operation implementations we need.
  // This relies on a complete list of all the ops needed by this graph.
  // An easier approach is to just use the AllOpsResolver, but this will
  // incur some penalty in code space for op implementations that are not
  // needed by this graph.
  //
  static tflite::AllOpsResolver resolver;
  op_resolver = &resolver;
  // // NOLINTNEXTLINE(runtime-global-variables)
  // static tflite::MicroMutableOpResolver<8> micro_op_resolver;
  // micro_op_resolver.AddAveragePool2D();
  // micro_op_resolver.AddConv2D();
  // micro_op_resolver.AddDepthwiseConv2D();
  // micro_op_resolver.AddReshape();
  // micro_op_resolver.AddSoftmax();

  // // needed for jon's model conv2d/relu, maxpool2d, reshape, fullyconnected,
  // logistic micro_op_resolver.AddMaxPool2D();
  // micro_op_resolver.AddFullyConnected();
  // micro_op_resolver.AddLogistic();

  // // needed for MODEL=magic_wand_full_i8
  // // micro_op_resolver.AddQuantize();
  // op_resolver = &micro_op_resolver;

  // profiler
  static tflite::MicroProfiler micro_profiler;
  profiler = &micro_profiler;
}

void tflite_load_model(const unsigned char* model_data) {
  tflite_init();
  if (interpreter) {
    interpreter->~INTERPRETER_TYPE();
    interpreter = nullptr;
  }

  // Map the model into a usable data structure. This doesn't involve any
  // copying or parsing, it's a very lightweight operation.
  model = tflite::GetModel(model_data);

  // Build an interpreter to run the model with.
  // NOLINTNEXTLINE(runtime-global-variables)
  alignas(tflite::INTERPRETER_TYPE) static unsigned char
      buf[sizeof(tflite::INTERPRETER_TYPE)];
  interpreter = new (buf)
      tflite::INTERPRETER_TYPE(model, *op_resolver, tensor_arena,
                               kTensorArenaSize, error_reporter, profiler);

  // Allocate memory from the tensor_arena for the model's tensors.
  TfLiteStatus allocate_status = interpreter->AllocateTensors();
  if (allocate_status != kTfLiteOk) {
    TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors() failed");
    return;
  }

  // Get information about the memory area to use for the model's input.
  auto input = interpreter->input(0);
  auto dims = input->dims;
  printf("Input: %d bytes, %d dims:", input->bytes, dims->size);
  for (int ii = 0; ii < dims->size; ++ii) {
    printf(" %d", dims->data[ii]);
  }
  puts("\n");
}

void tflite_set_input_zeros() {
  auto input = interpreter->input(0);
  memset(input->data.int8, 0, input->bytes);
  printf("Zeroed %d bytes at 0x%p\n", input->bytes, input->data.int8);
}

void tflite_set_input_zeros_float() {
  auto input = interpreter->input(0);
  memset(input->data.f, 0, input->bytes);
  printf("Zeroed %d bytes at 0x%p\n", input->bytes, input->data.f);
}

void tflite_set_input(const void* data) {
  auto input = interpreter->input(0);
  memcpy(input->data.int8, data, input->bytes);
  printf("Copied %d bytes at 0x%p\n", input->bytes, input->data.int8);
}

void tflite_set_input_unsigned(const unsigned char* data) {
  auto input = interpreter->input(0);
  for (size_t i = 0; i < input->bytes; i++) {
    input->data.int8[i] = (int)data[i] - 127;
  }
  printf("Set %d bytes at 0x%p\n", input->bytes, input->data.int8);
}

void tflite_set_input_float(const float* data) {
  auto input = interpreter->input(0);
  memcpy(input->data.f, data, input->bytes);
  printf("Copied %d bytes at 0x%p\n", input->bytes, input->data.f);
}

int8_t* tflite_get_output() { return interpreter->output(0)->data.int8; }

float* tflite_get_output_float() { return interpreter->output(0)->data.f; }

void tflite_classify() {
  // Run the model on this input and make sure it succeeds.
  perf_reset_all_counters();
  perf_set_mcycle(0);
  if (kTfLiteOk != interpreter->Invoke()) {
    TF_LITE_REPORT_ERROR(error_reporter, "Invoke failed.");
  }
  unsigned int cyc = perf_get_mcycle();
  perf_print_all_counters();
  perf_print_value(cyc);
  printf(" cycles total\n");

  // Uncomment to see how large the arena needs to be.

#ifdef SHOW_MEMORY_USE
  interpreter->GetMicroAllocator().PrintAllocations();
#endif
  printf("Arena used bytes: %llu\n",
         (long long unsigned)(interpreter->arena_used_bytes()));
}

int8_t* get_input() { return interpreter->input(0)->data.int8; }
<commit_msg>Determine smallest possible tensor arena at compile time.<commit_after>// Copyright 2021 The CFU-Playground Authors
//
// 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.

#include "tflite.h"

#include "perf.h"
#include "tensorflow/lite/micro/all_ops_resolver.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"
#include "tensorflow/lite/micro/micro_interpreter.h"
#include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
#include "tensorflow/lite/micro/micro_profiler.h"
#include "tensorflow/lite/schema/schema_generated.h"

#ifdef SHOW_MEMORY_USE
#include "tensorflow/lite/micro/recording_micro_interpreter.h"
#define INTERPRETER_TYPE RecordingMicroInterpreter
#else
#define INTERPRETER_TYPE MicroInterpreter
#endif

//
// Unit test prototypes. Because of the way these names are generated, they are
// not defined in any include file. The actual tests are in test_name.cc - e.g
// conv_test is defined in conv_test.cc.
extern int conv_test(int argc, char** argv);
extern int depthwise_conv_test(int argc, char** argv);

// Run tflite unit tests
void tflite_do_tests() {
  // conv test from conv_test.cc
  puts("\nCONV TEST:");
  conv_test(0, NULL);
  // depthwise conv test from depthwise_conv_test.cc
  puts("DEPTHWISE_CONV TEST:");
  depthwise_conv_test(0, NULL);
}

// For C++ exceptions
void* __dso_handle = &__dso_handle;

//
// TfLM global objects
namespace {
tflite::ErrorReporter* error_reporter = nullptr;
tflite::MicroOpResolver* op_resolver = nullptr;
tflite::MicroProfiler* profiler = nullptr;

const tflite::Model* model = nullptr;
tflite::INTERPRETER_TYPE* interpreter = nullptr;

// C++ 11 does not have a constexpr std::max.
// For this reason, a small implementation is written.
template <typename T>
constexpr T const& const_max(const T& x) {
  return x;
}

template <typename T, typename... Args>
constexpr T const& const_max(const T& x, const T& y, const Args&... rest) {
  return const_max(x > y ? x : y, rest...);
}

// Get the smallest kTensorArenaSize possible.
constexpr int kTensorArenaSize = const_max<int>(
#ifdef INCLUDE_MODEL_PDTI8
    81 * 1024,
#endif
#ifdef INCLUDE_MODEL_MICRO_SPEECH
    7 * 1024,
#endif
#ifdef INCLUDE_MODEL_MAGIC_WAND
    5 * 1024,
#endif
#ifdef INCLUDE_MODEL_MNV2
    800 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_ANOMD
    3 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_IMGC
    53 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_KWS
    23 * 1024,
#endif
#ifdef INLCUDE_MODEL_MLCOMMONS_TINY_V01_VWW
    99 * 1024,
#endif
    0 /* When no models defined, we don't need a tensor arena. */
);

static uint8_t tensor_arena[kTensorArenaSize];
}  // namespace

static void tflite_init() {
  static bool initialized = false;
  if (initialized) {
    return;
  }
  initialized = true;

  // Sets up error reporting etc
  static tflite::MicroErrorReporter micro_error_reporter;
  error_reporter = &micro_error_reporter;
  TF_LITE_REPORT_ERROR(error_reporter, "Error_reporter OK!");

  // Pull in only the operation implementations we need.
  // This relies on a complete list of all the ops needed by this graph.
  // An easier approach is to just use the AllOpsResolver, but this will
  // incur some penalty in code space for op implementations that are not
  // needed by this graph.
  //
  static tflite::AllOpsResolver resolver;
  op_resolver = &resolver;
  // // NOLINTNEXTLINE(runtime-global-variables)
  // static tflite::MicroMutableOpResolver<8> micro_op_resolver;
  // micro_op_resolver.AddAveragePool2D();
  // micro_op_resolver.AddConv2D();
  // micro_op_resolver.AddDepthwiseConv2D();
  // micro_op_resolver.AddReshape();
  // micro_op_resolver.AddSoftmax();

  // // needed for jon's model conv2d/relu, maxpool2d, reshape, fullyconnected,
  // logistic micro_op_resolver.AddMaxPool2D();
  // micro_op_resolver.AddFullyConnected();
  // micro_op_resolver.AddLogistic();

  // // needed for MODEL=magic_wand_full_i8
  // // micro_op_resolver.AddQuantize();
  // op_resolver = &micro_op_resolver;

  // profiler
  static tflite::MicroProfiler micro_profiler;
  profiler = &micro_profiler;
}

void tflite_load_model(const unsigned char* model_data) {
  tflite_init();
  if (interpreter) {
    interpreter->~INTERPRETER_TYPE();
    interpreter = nullptr;
  }

  // Map the model into a usable data structure. This doesn't involve any
  // copying or parsing, it's a very lightweight operation.
  model = tflite::GetModel(model_data);

  // Build an interpreter to run the model with.
  // NOLINTNEXTLINE(runtime-global-variables)
  alignas(tflite::INTERPRETER_TYPE) static unsigned char
      buf[sizeof(tflite::INTERPRETER_TYPE)];
  interpreter = new (buf)
      tflite::INTERPRETER_TYPE(model, *op_resolver, tensor_arena,
                               kTensorArenaSize, error_reporter, profiler);

  // Allocate memory from the tensor_arena for the model's tensors.
  TfLiteStatus allocate_status = interpreter->AllocateTensors();
  if (allocate_status != kTfLiteOk) {
    TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors() failed");
    return;
  }

  // Get information about the memory area to use for the model's input.
  auto input = interpreter->input(0);
  auto dims = input->dims;
  printf("Input: %d bytes, %d dims:", input->bytes, dims->size);
  for (int ii = 0; ii < dims->size; ++ii) {
    printf(" %d", dims->data[ii]);
  }
  puts("\n");
}

void tflite_set_input_zeros() {
  auto input = interpreter->input(0);
  memset(input->data.int8, 0, input->bytes);
  printf("Zeroed %d bytes at 0x%p\n", input->bytes, input->data.int8);
}

void tflite_set_input_zeros_float() {
  auto input = interpreter->input(0);
  memset(input->data.f, 0, input->bytes);
  printf("Zeroed %d bytes at 0x%p\n", input->bytes, input->data.f);
}

void tflite_set_input(const void* data) {
  auto input = interpreter->input(0);
  memcpy(input->data.int8, data, input->bytes);
  printf("Copied %d bytes at 0x%p\n", input->bytes, input->data.int8);
}

void tflite_set_input_unsigned(const unsigned char* data) {
  auto input = interpreter->input(0);
  for (size_t i = 0; i < input->bytes; i++) {
    input->data.int8[i] = (int)data[i] - 127;
  }
  printf("Set %d bytes at 0x%p\n", input->bytes, input->data.int8);
}

void tflite_set_input_float(const float* data) {
  auto input = interpreter->input(0);
  memcpy(input->data.f, data, input->bytes);
  printf("Copied %d bytes at 0x%p\n", input->bytes, input->data.f);
}

int8_t* tflite_get_output() { return interpreter->output(0)->data.int8; }

float* tflite_get_output_float() { return interpreter->output(0)->data.f; }

void tflite_classify() {
  // Run the model on this input and make sure it succeeds.
  perf_reset_all_counters();
  perf_set_mcycle(0);
  if (kTfLiteOk != interpreter->Invoke()) {
    TF_LITE_REPORT_ERROR(error_reporter, "Invoke failed.");
  }
  unsigned int cyc = perf_get_mcycle();
  perf_print_all_counters();
  perf_print_value(cyc);
  printf(" cycles total\n");

  // Uncomment to see how large the arena needs to be.

#ifdef SHOW_MEMORY_USE
  interpreter->GetMicroAllocator().PrintAllocations();
#endif
  printf("Arena used bytes: %llu\n",
         (long long unsigned)(interpreter->arena_used_bytes()));
}

int8_t* get_input() { return interpreter->input(0)->data.int8; }
<|endoftext|>


<commit_before>//=============================================================================
//File Name: AutonMotionProfile.cpp
//Description: Drives set distance with motion profiles
//Author: FRC Team 3512, Spartatroniks
//=============================================================================

#include "../Robot.hpp"
#include <Timer.h>

bool Robot::checkReflectiveStrips() {

	return true;
}

void Robot::RightLeftAuton() {
	float targetValue;
	const float targetDistance = 360.0;
	Timer *timer = new Timer;
	timer->Reset();
	robotDrive->resetEncoders();
	timer->Start();
	bool state = checkReflectiveStrips();
	claw->SetAngle(88.0);
	Wait (0.5);
	while ((robotDrive->getRightDist())<targetDistance && IsEnabled() && robotDrive->getRightDist() > -5.0){
		targetValue = (((targetDistance - (robotDrive->getRightDist()))/targetDistance)*-0.6);
		std::cout << "right distance: " << (robotDrive->getRightDist())<< std::endl;
		std::cout << "left distance: " << (robotDrive->getLeftDist()) << std::endl;
		std::cout << "targetValue: " << targetValue << std::endl;
		robotDrive->drive (targetValue , 0);
		Wait (0.1);
	}
	robotDrive->drive(-0.1,0);
	Wait (0.1);
	robotDrive->drive(0,0);
	std::cout << "final right distance: " << (robotDrive->getRightDist()) << std::endl;
	std::cout << "final left distance: " << (robotDrive->getLeftDist()) << std::endl;
	if (state == true){
		claw->Shoot();
	}
	else{
		while (timer->HasPeriodPassed(5) == false){
			Wait (0.01);
		}
		claw->Shoot();
	}
	while (IsEnabled() && IsAutonomous()){
		claw->Update();
	}
}
<commit_msg>    boocheckReflectiveStrips();<commit_after>//=============================================================================
//File Name: AutonMotionProfile.cpp
//Description: Drives set distance with motion profiles
//Author: FRC Team 3512, Spartatroniks
//=============================================================================

#include "../Robot.hpp"
#include <Timer.h>

bool Robot::checkReflectiveStrips() {

	return true;
}

void Robot::RightLeftAuton() {
	float targetValue;
	const float targetDistance = 370.0;
	Timer *timer = new Timer;
	timer->Reset();
	robotDrive->resetEncoders();
	timer->Start();
	bool state = checkReflectiveStrips();
	claw->SetAngle(103.0 - 37.0);
	Wait (0.5);
	while ((robotDrive->getRightDist())<targetDistance && IsEnabled() && robotDrive->getRightDist() > -5.0){
		targetValue = (((targetDistance - (robotDrive->getRightDist()))/targetDistance)*-0.6);
		std::cout << "right distance: " << (robotDrive->getRightDist())<< std::endl;
		std::cout << "left distance: " << (robotDrive->getLeftDist()) << std::endl;
		std::cout << "targetValue: " << targetValue << std::endl;
		robotDrive->drive (targetValue , 0);
		Wait (0.1);
	}
	robotDrive->drive(-0.1,0);
	Wait (0.1);
	robotDrive->drive(0,0);
	std::cout << "final right distance: " << (robotDrive->getRightDist()) << std::endl;
	std::cout << "final left distance: " << (robotDrive->getLeftDist()) << std::endl;
	if (state == true){
		claw->Shoot();
	}
	else{
		while (timer->HasPeriodPassed(5) == false){
			Wait (0.01);
		}
		claw->Shoot();
	}
	while (IsEnabled() && IsAutonomous()){
		claw->Update();
	}
}
<|endoftext|>


<commit_before>#include "dynet/param-init.h"
#include "dynet/tensor.h"

using namespace dynet;
using namespace std;

#include <fstream>

void ParameterInitNormal::initialize_params(Tensor & values) const {
  TensorTools::randomize_normal(values, mean, sqrt(var));
}

void ParameterInitUniform::initialize_params(Tensor & values) const {
  TensorTools::randomize_uniform(values, left, right);
}

void ParameterInitConst::initialize_params(Tensor & values) const {
  TensorTools::constant(values, cnst);
}

void ParameterInitIdentity::initialize_params(Tensor & values) const {
  TensorTools::identity(values);
}

void ParameterInitGlorot::initialize_params(Tensor & values) const {
  int dims = 0, dim_len = values.d.nd - (lookup ? 1 : 0);
  for (int i = 0; i < dim_len; ++i) dims += values.d[i];
  float my_scale = gain * sqrt(6) / sqrt(dims);
  TensorTools::randomize_uniform(values, -my_scale, my_scale);
}

void ParameterInitSaxe::initialize_params(Tensor & values) const {
  if (values.device->type == DeviceType::GPU)
    throw std::runtime_error("Saxe initialization not implemented for CUDA (we welcome pull requests)");
  else
    TensorTools::randomize_orthonormal(values, gain);
}

void ParameterInitFromVector::initialize_params(Tensor & values) const {
  TensorTools::set_elements(values, vec);
}

void ParameterInitFromFile::initialize_params(Tensor & values) const {
  ifstream is(filename);
  istream_iterator<float> start(is), end;
  vector<float> param_vector(start, end);
  TensorTools::set_elements(values, param_vector);
}
<commit_msg>restore glorot init fix<commit_after>#include "dynet/param-init.h"
#include "dynet/tensor.h"

using namespace dynet;
using namespace std;

#include <fstream>

void ParameterInitNormal::initialize_params(Tensor & values) const {
  TensorTools::randomize_normal(values, mean, sqrt(var));
}

void ParameterInitUniform::initialize_params(Tensor & values) const {
  TensorTools::randomize_uniform(values, left, right);
}

void ParameterInitConst::initialize_params(Tensor & values) const {
  TensorTools::constant(values, cnst);
}

void ParameterInitIdentity::initialize_params(Tensor & values) const {
  TensorTools::identity(values);
}

void ParameterInitGlorot::initialize_params(Tensor & values) const {
  int dims = 0, dim_len = values.d.nd - (lookup ? 1 : 0);
  for (int i = 0; i < dim_len; ++i) dims += values.d[i];
  float my_scale = gain * sqrt(3 * dim_len) / sqrt(dims);
  TensorTools::randomize_uniform(values, -my_scale, my_scale);
}

void ParameterInitSaxe::initialize_params(Tensor & values) const {
  if (values.device->type == DeviceType::GPU)
    throw std::runtime_error("Saxe initialization not implemented for CUDA (we welcome pull requests)");
  else
    TensorTools::randomize_orthonormal(values, gain);
}

void ParameterInitFromVector::initialize_params(Tensor & values) const {
  TensorTools::set_elements(values, vec);
}

void ParameterInitFromFile::initialize_params(Tensor & values) const {
  ifstream is(filename);
  istream_iterator<float> start(is), end;
  vector<float> param_vector(start, end);
  TensorTools::set_elements(values, param_vector);
}
<|endoftext|>


<commit_before>#include<stdio.h>
#include<stdlib.h>
#include<math.h>

#define LM (1)		//memory unit
#define L1 (LM+2)	//layer 1 unit
#define L2 (5)		//layer 2 unti
#define L3 (LM+3)	//layer 3 unit
#define LL (L1 * L2 + L2 * L3)
#define PARENT (20)	//best parent
#define SON (5)	//son per unit
#define STEP (1000)	// test step
#define MG (1000)	//goal unit

#define VR (1)		// speed range
#define WR (0.5)	// degree speed range

#define PI (3.1415926)
#define RAND(MAX) (random() * (double)(MAX) / RAND_MAX)

//#define DEBUG

double active_function(double t){
	return 1/(1+exp(-t));
}

struct car{
	float gene[LL];
	int point;
};

struct goal{
	float x,y;	//goal always at (0,0) (x,y) is the start point of car
	float *wall;
	int n = 0;
};

int direction(float x1,float y1,float x2,float y2,float x3,float y3){

}
int intersect(float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4){
	return 0;
}

void init_car(car* c){
	c->point = 0;
	int i;
	for(i = 0;i < LL;i++)
		c->gene[i] = RAND(1) - 0.5;
}

void init_goal(goal* g){
	int i;
	float cx,cy;
	if(g->n)
		free(g->wall);
	g->n = random() % 5;
	g->wall = (float*)malloc(4*g->n*sizeof(float));
	for(i = 0;i < g->n ;i++){
		cx = RAND(30);
		cy = RAND(30);
		g->wall[i*4+0] = cx + RAND(5);
		g->wall[i*4+1] = cy + RAND(5);
		g->wall[i*4+2] = cx + RAND(5);
		g->wall[i*4+3] = cy + RAND(5);
	}
	g->x = RAND(50);
	g->y = RAND(50);
}

int main(){
	int i,j,k,l,I,generation;
	float memory_t[2][20];
	float v,w,x,y,dx,dy,dv,dw;
	float hit;
	car best[2][PARENT],t;
	goal g[MG];
	for(i = 0;i < PARENT;i++)
		init_car(best[0]+i);

	for(generation = 0; generation < 100;generation++){
		for(i = 0;i < PARENT;i++){
			best[(generation + 1) & 1][i].point = -1;
		}
		for(i = 0;i < MG;i++)
			init_goal(g+i);
		for(I = 0;I < SON;I++)
			for(i = 0;i < PARENT;i++){
			t = best[generation & 1][i];
			t.gene[random()%LL] = RAND(1) - 0.5;
			t.point = 0;
			l = STEP;
			for(j = 0;j < LM;j++)
				memory_t[0][j] = RAND(0.01);
			//inti memory
			x = g[0].x;
			y = g[0].y;
			v = 0;
			w = 0;
#ifdef DEBUG
					printf("(%f,%f)",x,y);
#endif
			while(l--){
				//init input
				memory_t[0][LM+0] = - x * cos(w) - y * sin(w);
				memory_t[0][LM+1] = x * sin(w) - y * cos(w);
				//calc output
				for(j = 0;j < L2;j++){
					memory_t[1][j] = 0;
					for(k = 0;k < L1;k++){
						memory_t[1][j] += t.gene[j*L1+k] * memory_t[0][k];
					}
					memory_t[1][j] = active_function(memory_t[1][j]);
				}
				for(j = 0;j < L3;j++){
					memory_t[0][j] = 0;
					for(k = 0;k < L2;k++){
						memory_t[0][j] += t.gene[j*L2+k] * memory_t[1][k];
					}
					memory_t[0][j] = active_function(memory_t[0][j]);
				}
				dv = VR * (memory_t[0][LM+0] - 0.5);
				dw = WR * (memory_t[0][LM+1] - memory_t[0][LM+2]);
				v = sqrt((v + dv)*(v+dv) + dw * dw);
				w += asin(dw/v);
				if(v == 0)
					w = VR;
				if(w > PI)
					w -= 2 * PI;
				if(w <= -PI)
					w += 2 * PI;
				dx = x + v * cos(w);
				dy = y + v * sin(w);
				//if hit wall
				hit = 0;
				for(j = 0;j < g[t.point].n;j++)
					if(intersect(x,y,dx,dy,g[t.point].wall[0],g[t.point].wall[1],g[t.point].wall[2],g[t.point].wall[3]))
						hit = 1;
				//go
				x = dx;
				y = dy;
#ifdef DEBUG
					printf("\n\t-><%f,%f>[%f,%f](%f,%f)",dv,dw,v,w,x,y);
#endif
				//if finish
				if(abs(x)+abs(y) < 0.1){
					t.point++;
					x = g[t.point].x;
					y = g[t.point].y;
#ifdef DEBUG
					printf("\n(%f,%f)",x,y);
#endif
				}
			}
#ifdef DEBUG
			putchar(10);
#endif
			//if better
			j = -1;k = t.point;
			for(l = 0;l < PARENT;l++){
				if(best[(generation + 1) & 1][l].point < k) {
					j = l;
					k = best[(generation + 1) & 1][l].point;
				}
			}
			if(j != -1)
				best[(generation + 1) & 1][j] = t;
		}
		//print score board
		printf("%d:",generation);
		for(i = 0;i < PARENT;i++)
			printf("%5d",best[(generation  + 1) &1][i].point);
		putchar(10);
	}
	return 0;
}
<commit_msg>包含撞墙检测的测试版<commit_after>#include<stdio.h>
#include<stdlib.h>
#include<math.h>

#define LM (1)		//memory unit
#define L1 (LM+6)	//layer 1 unit
#define L2 (5)		//layer 2 unti
#define L3 (LM+3)	//layer 3 unit
#define LL (L1 * L2 + L2 * L3)
#define PARENT (20)	//best parent
#define SON (5)	//son per unit
#define STEP (1000)	// test step
#define MG (1000)	//goal unit

#define VR (1)		// speed range
#define WR (0.5)	// degree speed range
#define SENSOR (1)

#define PI (3.1415926)
#define RAND(MAX) (random() * (double)(MAX) / RAND_MAX)

//#define DEBUG

double active_function(double t){
	return 1/(1+exp(-t));
}

struct car{
	float gene[LL];
	int point;
};

struct goal{
	float x,y;	//goal always at (0,0) (x,y) is the start point of car
	float *wall;
	int n = 0;
};

int CrossProduct(float v1[],float v2[]){
	return v1[0] * v2[1] - v1[1] * v2[0];
}
int intersect(float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4){
	float tab[4][2];
	tab[0][0] = x3 - x1;
	tab[0][1] = y3 - y1;
	tab[1][0] = x2 - x3;
	tab[1][1] = y2 - y3;
	tab[2][0] = x4 - x2;
	tab[2][1] = y4 - y2;
	tab[3][0] = x1 - x4;
	tab[4][1] = y1 - y4;

	float res;
	int i;
	res = CrossProduct(tab[3],tab[0]);
	for(i = 0;i < 3;i++)
		if(res * CrossProduct(tab[i],tab[i+1]) < 0)
			return 0;

	//printf("%f,%f %f,%f %f,%f %f,%f hit\n",x1,y1,x2,y2,x3,y3,x4,y4);

	return 1;
}

int hit_wall(float x1,float y1,float x2,float y2,goal g){
	int i;
	for(i = 0;i < g.n;i++)
		if(intersect(x1,y1,x2,y2,g.wall[i*4+0],g.wall[i*4+1],g.wall[i*4+2],g.wall[i*4+3]))
			return 1;
	return 0;
}

void init_car(car* c){
	c->point = 0;
	int i;
	for(i = 0;i < LL;i++)
		c->gene[i] = RAND(1) - 0.5;
}

void init_goal(goal* g){
	int i;
	float cx,cy;
	if(g->n)
		free(g->wall);
	g->x = RAND(50) - 25;
	g->y = RAND(50) - 25;

	//
	g->n = 1;
	g->wall = (float*)malloc(4*g->n*sizeof(float));
	g->wall[0] = g->x / 2 - 1;
	g->wall[1] = g->y / 2;
	g->wall[2] = g->x / 2 + 1;
	g->wall[3] = g->y / 2;

	/*
	g->n = random() % 5;
	g->wall = (float*)malloc(4*g->n*sizeof(float));
	for(i = 0;i < g->n ;i++){
		cx = RAND(30);
		cy = RAND(30);
		g->wall[i*4+0] = cx + RAND(5);
		g->wall[i*4+1] = cy + RAND(5);
		g->wall[i*4+2] = cx + RAND(5);
		g->wall[i*4+3] = cy + RAND(5);
	}
	*/
}

int main(){
	int i,j,k,l,I,generation;
	float memory_t[2][20];
	float v,w,x,y,dx,dy,dv,dw;
	float hit;
	car best[2][PARENT],t;
	goal g[MG];
	for(i = 0;i < PARENT;i++)
		init_car(best[0]+i);

	for(generation = 0; generation < 100;generation++){
		for(i = 0;i < PARENT;i++){
			best[(generation + 1) & 1][i].point = -1;
		}
		for(i = 0;i < MG;i++)
			init_goal(g+i);
		for(I = 0;I < SON;I++)
			for(i = 0;i < PARENT;i++){
			t = best[generation & 1][i];
			t.gene[random()%LL] = RAND(1) - 0.5;
			t.point = 0;
			l = STEP;
			for(j = 0;j < LM;j++)
				memory_t[0][j] = RAND(0.01);
			//inti memory
			x = g[0].x;
			y = g[0].y;
			v = 0;
			w = 0;
#ifdef DEBUG
					printf("(%f,%f)",x,y);
#endif
			while(l--){
				//init input
				memory_t[0][LM+0] = - x * cos(w) - y * sin(w);
				memory_t[0][LM+1] = x * sin(w) - y * cos(w);
				memory_t[0][LM+2] = hit;
				memory_t[0][LM+3] = hit_wall(x,y,x+SENSOR*cos(w),y+SENSOR*sin(w),g[t.point]);
				memory_t[0][LM+4] = hit_wall(x,y,x+SENSOR*cos(w - PI / 2),y+SENSOR*sin(w - PI / 2),g[t.point]);
				memory_t[0][LM+5] = hit_wall(x,y,x+SENSOR*cos(w + PI / 2),y+SENSOR*sin(w + PI / 2),g[t.point]);

				//calc output
				for(j = 0;j < L2;j++){
					memory_t[1][j] = 0;
					for(k = 0;k < L1;k++){
						memory_t[1][j] += t.gene[j*L1+k] * memory_t[0][k];
					}
					memory_t[1][j] = active_function(memory_t[1][j]);
				}
				for(j = 0;j < L3;j++){
					memory_t[0][j] = 0;
					for(k = 0;k < L2;k++){
						memory_t[0][j] += t.gene[j*L2+k] * memory_t[1][k];
					}
					memory_t[0][j] = active_function(memory_t[0][j]);
				}
				dv = VR * (memory_t[0][LM+0] - 0.5);
				dw = WR * (memory_t[0][LM+1] - memory_t[0][LM+2]);
				v = sqrt((v + dv)*(v+dv) + dw * dw);
				w += asin(dw/v);
				if(v == 0)
					w = VR;
				if(w > PI)
					w -= 2 * PI;
				if(w <= -PI)
					w += 2 * PI;
				dx = x + v * cos(w);
				dy = y + v * sin(w);
				//if hit wall
				if(hit_wall(x,y,dx,dy,g[t.point])){
					hit = 1;
					v = 0;
				}
				else{
					//go
					hit = 0;
					x = dx;
					y = dy;
				}
#ifdef DEBUG
				printf("\n\t-><%f,%f>[%f,%f](%f,%f)",dv,dw,v,w,x,y);
#endif
				//if finish
				if(abs(x)+abs(y) < 0.1){
					t.point++;
					x = g[t.point].x;
					y = g[t.point].y;
#ifdef DEBUG
					printf("\n(%f,%f)",x,y);
#endif
				}
			}
#ifdef DEBUG
			putchar(10);
#endif
			//if better
			j = -1;k = t.point;
			for(l = 0;l < PARENT;l++){
				if(best[(generation + 1) & 1][l].point < k) {
					j = l;
					k = best[(generation + 1) & 1][l].point;
				}
			}
			if(j != -1)
				best[(generation + 1) & 1][j] = t;
			}
		//print score board
		printf("%d:",generation);
		for(i = 0;i < PARENT;i++)
			printf("%5d",best[(generation  + 1) &1][i].point);
		putchar(10);
	}
	return 0;
}
<|endoftext|>


<commit_before>#define CYBOZU_TEST_DISABLE_AUTO_RUN
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <cybozu/option.hpp>
#include <cybozu/xorshift.hpp>
#include <mcl/bn384.hpp>
#include <mcl/bn.hpp>

using namespace mcl::bn384;

mcl::fp::Mode g_mode;

#include "bench.hpp"

#include "common_test.hpp"

void testCurve(const mcl::CurveParam& cp)
{
	initPairing(cp, g_mode);
	G1 P;
	G2 Q;
	mapToG1(P, 1);
	mapToG2(Q, 1);
	GT e1, e2;
#ifdef ONLY_BENCH
	cybozu::CpuClock clk;
	for (int i = 0; i < 10000; i++) { clk.begin(); pairing(e1, P, Q); clk.end(); }
	clk.put();
	return;
#endif
	pairing(e1, P, Q);
	{
		GT e;
		pairing(e, P + P, Q);
		CYBOZU_TEST_EQUAL(e1 * e1, e);
		pairing(e, P, Q + Q);
		CYBOZU_TEST_EQUAL(e1 * e1, e);
	}
	cybozu::XorShift rg;
	mpz_class a, b;
	Fr r;
	G1 aP;
	G2 bQ;
	r.setRand(rg); a = r.getMpz();
	r.setRand(rg); b = r.getMpz();
	G1::mul(aP, P, a);
	G2::mul(bQ, Q, b);
	pairing(e2, aP, bQ);
	GT::pow(e1, e1, a * b);
	CYBOZU_TEST_EQUAL(e1, e2);
	testCommon(P, Q);
	testBench(P, Q);
	testSquareRoot();
	testLagrange();
}

CYBOZU_TEST_AUTO(pairing)
{
//	puts("BN160");
//	testCurve(mcl::BN160);
//	puts("BLS12_377");
//	testCurve(mcl::BLS12_377);
//	puts("BN_P256");
//	testCurve(mcl::BN_P256);
	puts("BN254");
	testCurve(mcl::BN254);
	puts("BN381_1");
	testCurve(mcl::BN381_1);
	puts("BN381_2");
	testCurve(mcl::BN381_2);
	puts("BLS12_381");
	testCurve(mcl::BLS12_381);
	// Q is not on EcT, but bad order
	{
		const char *s = "1 18d3d8c085a5a5e7553c3a4eb628e88b8465bf4de2612e35a0a4eb018fb0c82e9698896031e62fd7633ffd824a859474 1dc6edfcf33e29575d4791faed8e7203832217423bf7f7fbf1f6b36625b12e7132c15fbc15562ce93362a322fb83dd0d 65836963b1f7b6959030ddfa15ab38ce056097e91dedffd996c1808624fa7e2644a77be606290aa555cda8481cfb3cb 1b77b708d3d4f65aeedf54b58393463a42f0dc5856baadb5ce608036baeca398c5d9e6b169473a8838098fd72fd28b50";
		G2 Q;
		CYBOZU_TEST_EXCEPTION(Q.setStr(s, 16), std::exception);
	}
}

int main(int argc, char *argv[])
	try
{
	cybozu::Option opt;
	std::string mode;
	opt.appendOpt(&mode, "auto", "m", ": mode(gmp/gmp_mont/llvm/llvm_mont/xbyak)");
	if (!opt.parse(argc, argv)) {
		opt.usage();
		return 1;
	}
	g_mode = mcl::fp::StrToMode(mode);
	return cybozu::test::autoRun.run(argc, argv);
} catch (std::exception& e) {
	printf("ERR %s\n", e.what());
	return 1;
}
<commit_msg>bilinear test runs well for BN_P256<commit_after>#define CYBOZU_TEST_DISABLE_AUTO_RUN
#include <cybozu/test.hpp>
#include <cybozu/benchmark.hpp>
#include <cybozu/option.hpp>
#include <cybozu/xorshift.hpp>
#include <mcl/bn384.hpp>
#include <mcl/bn.hpp>

using namespace mcl::bn384;

mcl::fp::Mode g_mode;

#include "bench.hpp"

#include "common_test.hpp"

void testCurve(const mcl::CurveParam& cp)
{
	initPairing(cp, g_mode);
	G1 P;
	G2 Q;
	mapToG1(P, 1);
	mapToG2(Q, 1);
	GT e1, e2;
#ifdef ONLY_BENCH
	cybozu::CpuClock clk;
	for (int i = 0; i < 10000; i++) { clk.begin(); pairing(e1, P, Q); clk.end(); }
	clk.put();
	return;
#endif
	pairing(e1, P, Q);
	{
		GT e;
		pairing(e, P + P, Q);
		CYBOZU_TEST_EQUAL(e1 * e1, e);
		pairing(e, P, Q + Q);
		CYBOZU_TEST_EQUAL(e1 * e1, e);
	}
	cybozu::XorShift rg;
	for (int i = 0; i < 100; i++) {
		Fr a, b;
		G1 aP;
		G2 bQ;
		GT e;
		a.setRand(rg);
		b.setRand(rg);
		aP = P * a;
		bQ = Q * b;
		pairing(e2, aP, bQ);
		GT::pow(e, e1, a * b);
		CYBOZU_TEST_EQUAL(e2, e);
	}
	testCommon(P, Q);
	testBench(P, Q);
	testSquareRoot();
	testLagrange();
}

CYBOZU_TEST_AUTO(pairing)
{
//	puts("BN160");
//	testCurve(mcl::BN160);
//	puts("BLS12_377");
//	testCurve(mcl::BLS12_377);
	puts("BN_P256");
	testCurve(mcl::BN_P256);
	puts("BN254");
	testCurve(mcl::BN254);
	puts("BN381_1");
	testCurve(mcl::BN381_1);
	puts("BN381_2");
	testCurve(mcl::BN381_2);
	puts("BLS12_381");
	testCurve(mcl::BLS12_381);
	// Q is not on EcT, but bad order
	{
		const char *s = "1 18d3d8c085a5a5e7553c3a4eb628e88b8465bf4de2612e35a0a4eb018fb0c82e9698896031e62fd7633ffd824a859474 1dc6edfcf33e29575d4791faed8e7203832217423bf7f7fbf1f6b36625b12e7132c15fbc15562ce93362a322fb83dd0d 65836963b1f7b6959030ddfa15ab38ce056097e91dedffd996c1808624fa7e2644a77be606290aa555cda8481cfb3cb 1b77b708d3d4f65aeedf54b58393463a42f0dc5856baadb5ce608036baeca398c5d9e6b169473a8838098fd72fd28b50";
		G2 Q;
		CYBOZU_TEST_EXCEPTION(Q.setStr(s, 16), std::exception);
	}
}

int main(int argc, char *argv[])
	try
{
	cybozu::Option opt;
	std::string mode;
	opt.appendOpt(&mode, "auto", "m", ": mode(gmp/gmp_mont/llvm/llvm_mont/xbyak)");
	if (!opt.parse(argc, argv)) {
		opt.usage();
		return 1;
	}
	g_mode = mcl::fp::StrToMode(mode);
	return cybozu::test::autoRun.run(argc, argv);
} catch (std::exception& e) {
	printf("ERR %s\n", e.what());
	return 1;
}
<|endoftext|>