SSIZE_T parse( BYTE *data, SIZE_T /*len*/, Modules &modules, bool skipVersion/*=false*/ ) { SSIZE_T offset = 0; WORD numberOfModules = RW(data,offset); for (int mod=0; mod<numberOfModules; mod++) { Type module; module.id = RW(data,offset); module.size = RDW(data,offset); module.version = (skipVersion) ? 0 : RB(data,offset); BYTE moduleInfoLen = RB(data,offset); if (moduleInfoLen) { module.info.copy( (char *)(data+offset), moduleInfoLen ); offset += moduleInfoLen; } modules.push_back( module ); } return offset; }
int main(int argc, char **argv) { global.langPlugins.push_back(&cpp::calypso); // stack trace on signals llvm::sys::PrintStackTraceOnErrorSignal(); exe_path::initialize(argv[0], reinterpret_cast<void *>(main)); global.init(); global.version = ldc::dmd_version; global.ldc_version = ldc::ldc_version; global.llvm_version = ldc::llvm_version; // Initialize LLVM before parsing the command line so that --version shows // registered targets. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeAllAsmParsers(); initializePasses(); bool helpOnly; Strings files; parseCommandLine(argc, argv, files, helpOnly); if (files.dim == 0 && !helpOnly) { cl::PrintHelpMessage(); return EXIT_FAILURE; } if (global.errors) { fatal(); } // Set up the TargetMachine. ExplicitBitness::Type bitness = ExplicitBitness::None; if ((m32bits || m64bits) && (!mArch.empty() || !mTargetTriple.empty())) { error(Loc(), "-m32 and -m64 switches cannot be used together with -march " "and -mtriple switches"); } if (m32bits) { bitness = ExplicitBitness::M32; } if (m64bits) { if (bitness != ExplicitBitness::None) { error(Loc(), "cannot use both -m32 and -m64 options"); } bitness = ExplicitBitness::M64; } if (global.errors) { fatal(); } gTargetMachine = createTargetMachine( mTargetTriple, mArch, mCPU, mAttrs, bitness, mFloatABI, mRelocModel, mCodeModel, codeGenOptLevel(), disableFpElim, disableLinkerStripDead); #if LDC_LLVM_VER >= 308 static llvm::DataLayout DL = gTargetMachine->createDataLayout(); gDataLayout = &DL; #elif LDC_LLVM_VER >= 307 gDataLayout = gTargetMachine->getDataLayout(); #elif LDC_LLVM_VER >= 306 gDataLayout = gTargetMachine->getSubtargetImpl()->getDataLayout(); #else gDataLayout = gTargetMachine->getDataLayout(); #endif { llvm::Triple triple = llvm::Triple(gTargetMachine->getTargetTriple()); global.params.targetTriple = triple; global.params.isWindows = triple.isOSWindows(); global.params.isLP64 = gDataLayout->getPointerSizeInBits() == 64; global.params.is64bit = triple.isArch64Bit(); } // allocate the target abi gABI = TargetABI::getTarget(); // Set predefined version identifiers. registerPredefinedVersions(); dumpPredefinedVersions(); if (global.params.targetTriple.isOSWindows()) { global.dll_ext = "dll"; global.lib_ext = "lib"; } else { global.dll_ext = "so"; global.lib_ext = "a"; } // Initialization Lexer::initLexer(); Type::init(); Id::initialize(); Module::init(); Target::init(); Expression::init(); initPrecedence(); builtin_init(); initTraitsStringTable(); cpp::calypso.init(argv[0]); // CALYPSO HACK // Build import search path if (global.params.imppath) { for (unsigned i = 0; i < global.params.imppath->dim; i++) { const char *path = static_cast<const char *>(global.params.imppath->data[i]); Strings *a = FileName::splitPath(path); if (a) { if (!global.path) { global.path = new Strings(); } global.path->append(a); } } } // Build string import search path if (global.params.fileImppath) { for (unsigned i = 0; i < global.params.fileImppath->dim; i++) { const char *path = static_cast<const char *>(global.params.fileImppath->data[i]); Strings *a = FileName::splitPath(path); if (a) { if (!global.filePath) { global.filePath = new Strings(); } global.filePath->append(a); } } } if (global.params.addMain) { // a dummy name, we never actually look up this file files.push(const_cast<char *>(global.main_d)); } // Create Modules Modules modules; modules.reserve(files.dim); for (unsigned i = 0; i < files.dim; i++) { Identifier *id; const char *ext; const char *name; const char *p = files.data[i]; p = FileName::name(p); // strip path ext = FileName::ext(p); if (ext) { #if LDC_POSIX if (strcmp(ext, global.obj_ext) == 0 || strcmp(ext, global.bc_ext) == 0) #else if (Port::stricmp(ext, global.obj_ext) == 0 || Port::stricmp(ext, global.obj_ext_alt) == 0 || Port::stricmp(ext, global.bc_ext) == 0) #endif { global.params.objfiles->push(static_cast<const char *>(files.data[i])); continue; } #if LDC_POSIX if (strcmp(ext, "a") == 0) #elif __MINGW32__ if (Port::stricmp(ext, "a") == 0) #else if (Port::stricmp(ext, "lib") == 0) #endif { global.params.libfiles->push(static_cast<const char *>(files.data[i])); continue; } if (strcmp(ext, global.ddoc_ext) == 0) { global.params.ddocfiles->push(static_cast<const char *>(files.data[i])); continue; } if (FileName::equals(ext, global.json_ext)) { global.params.doJsonGeneration = 1; global.params.jsonfilename = static_cast<const char *>(files.data[i]); continue; } #if !LDC_POSIX if (Port::stricmp(ext, "res") == 0) { global.params.resfile = static_cast<const char *>(files.data[i]); continue; } if (Port::stricmp(ext, "def") == 0) { global.params.deffile = static_cast<const char *>(files.data[i]); continue; } if (Port::stricmp(ext, "exe") == 0) { global.params.exefile = static_cast<const char *>(files.data[i]); continue; } #endif if (Port::stricmp(ext, global.mars_ext) == 0 || Port::stricmp(ext, global.hdr_ext) == 0 || FileName::equals(ext, "dd")) { ext--; // skip onto '.' assert(*ext == '.'); char *tmp = static_cast<char *>(mem.xmalloc((ext - p) + 1)); memcpy(tmp, p, ext - p); tmp[ext - p] = 0; // strip extension name = tmp; if (name[0] == 0 || strcmp(name, "..") == 0 || strcmp(name, ".") == 0) { goto Linvalid; } } else { error(Loc(), "unrecognized file extension %s\n", ext); fatal(); } } else { name = p; if (!*p) { Linvalid: error(Loc(), "invalid file name '%s'", static_cast<const char *>(files.data[i])); fatal(); } name = p; } id = Identifier::idPool(name); auto m = new Module(files.data[i], id, global.params.doDocComments, global.params.doHdrGeneration); modules.push(m); } // Read files, parse them for (unsigned i = 0; i < modules.dim; i++) { Module *m = modules[i]; if (global.params.verbose) { fprintf(global.stdmsg, "parse %s\n", m->toChars()); } if (!Module::rootModule) { Module::rootModule = m; } m->importedFrom = m; if (strcmp(m->srcfile->name->str, global.main_d) == 0) { static const char buf[] = "void main(){}"; m->srcfile->setbuffer(const_cast<char *>(buf), sizeof(buf)); m->srcfile->ref = 1; } else { m->read(Loc()); } m->parse(global.params.doDocComments); m->buildTargetFiles(singleObj, createSharedLib || createStaticLib); /* m->deleteObjFile(); */ // CALYPSO: deleteObjFile moved to just before .o generation if (m->isDocFile) { gendocfile(m); // Remove m from list of modules modules.remove(i); i--; } } if (global.errors) { fatal(); } if (global.params.doHdrGeneration) { /* Generate 'header' import files. * Since 'header' import files must be independent of command * line switches and what else is imported, they are generated * before any semantic analysis. */ for (unsigned i = 0; i < modules.dim; i++) { if (global.params.verbose) { fprintf(global.stdmsg, "import %s\n", modules[i]->toChars()); } genhdrfile(modules[i]); } } if (global.errors) { fatal(); } // load all unconditional imports for better symbol resolving for (unsigned i = 0; i < modules.dim; i++) { if (global.params.verbose) { fprintf(global.stdmsg, "importall %s\n", modules[i]->toChars()); } modules[i]->importAll(nullptr); } if (global.errors) { fatal(); } // CALYPSO HACK & NOTE: this must be done after the importAll pass for D modules for modmap to kick in // Replace modmap by a monolithic header instead of twisting importAll()? for (auto m: cpp::Module::amodules) { m->importedFrom = m; m->buildTargetFiles(singleObj, createSharedLib || createStaticLib); m->importAll(0); modules.push(m); } // Do semantic analysis for (unsigned i = 0; i < modules.dim; i++) { if (global.params.verbose) { fprintf(global.stdmsg, "semantic %s\n", modules[i]->toChars()); } modules[i]->semantic(); } if (global.errors) { fatal(); } Module::dprogress = 1; Module::runDeferredSemantic(); // Do pass 2 semantic analysis for (unsigned i = 0; i < modules.dim; i++) { if (global.params.verbose) { fprintf(global.stdmsg, "semantic2 %s\n", modules[i]->toChars()); } modules[i]->semantic2(); } if (global.errors) { fatal(); } // Do pass 3 semantic analysis for (unsigned i = 0; i < modules.dim; i++) { if (global.params.verbose) { fprintf(global.stdmsg, "semantic3 %s\n", modules[i]->toChars()); } modules[i]->semantic3(); } if (global.errors) { fatal(); } Module::runDeferredSemantic3(); if (global.errors || global.warnings) { fatal(); } // Now that we analyzed all modules, write the module dependency file if // the user requested it. if (global.params.moduleDepsFile != nullptr) { File deps(global.params.moduleDepsFile); OutBuffer *ob = global.params.moduleDeps; deps.setbuffer(static_cast<void *>(ob->data), ob->offset); deps.write(); } // Generate one or more object/IR/bitcode files. if (global.params.obj && !modules.empty()) { ldc::CodeGenerator cg(llvm::getGlobalContext(), singleObj); for (unsigned i = 0; i < modules.dim; i++) { Module *const m = modules[i]; if (global.params.verbose) { fprintf(global.stdmsg, "code %s\n", m->toChars()); } auto lp = m->langPlugin(); if (lp && !singleObj && !lp->needsCodegen(m)) { // CALYPSO UGLY? global.params.objfiles->push(m->objfile->name->str); continue; } m->deleteObjFile(); // CALYPSO cg.emit(m); if (global.errors) { fatal(); } } } // Generate DDoc output files. if (global.params.doDocComments) { for (unsigned i = 0; i < modules.dim; i++) { gendocfile(modules[i]); } } // Generate the AST-describing JSON file. if (global.params.doJsonGeneration) { emitJson(modules); } freeRuntime(); llvm::llvm_shutdown(); if (global.errors) { fatal(); } // Finally, produce the final executable/archive and run it, if we are // supposed to. int status = EXIT_SUCCESS; if (!global.params.objfiles->dim) { if (global.params.link) { error(Loc(), "no object files to link"); } else if (createStaticLib) { error(Loc(), "no object files"); } } else { if (global.params.link) { status = linkObjToBinary(createSharedLib, staticFlag); } else if (createStaticLib) { status = createStaticLibrary(); } if (global.params.run && status == EXIT_SUCCESS) { status = runExecutable(); /// Delete .obj files and .exe file. for (unsigned i = 0; i < modules.dim; i++) { modules[i]->deleteObjFile(); } deleteExecutable(); } } return status; }
int ImportCommand::execute (Cmdline const & cl) { size_t argc = cl.arguments.size (); if (argc != 1 && argc != 2 && argc != 3) { throw invalid_argument ("need 1 to 3 arguments"); } Key root = cl.createKey (0); if (!root.isValid ()) { throw invalid_argument ("root key \"" + cl.arguments[0] + "\" is not a valid key name"); } KeySet originalKeys; kdb.get (originalKeys, root); KeySet base = originalKeys.cut (root); printWarnings (cerr, root); string format = cl.format; if (argc > 1) format = cl.arguments[1]; string file = "/dev/stdin"; if (argc > 2 && cl.arguments[2] != "-") file = cl.arguments[2]; Modules modules; PluginPtr plugin = modules.load (format, cl.getPluginsConfig ()); Key errorKey (root); errorKey.setString (file); KeySet importedKeys; plugin->get (importedKeys, errorKey); importedKeys = importedKeys.cut (root); printWarnings (cerr, errorKey); printError (cerr, errorKey); ThreeWayMerge merger; MergeHelper helper; helper.configureMerger (cl, merger); MergeResult result = merger.mergeKeySet ( MergeTask (BaseMergeKeys (base, root), OurMergeKeys (base, root), TheirMergeKeys (importedKeys, root), root)); helper.reportResult (cl, result, cout, cerr); int ret = -1; if (!result.hasConflicts ()) { if (cl.verbose) { cout << "The merged keyset with strategy " << cl.strategy << " is:" << endl; cout << result.getMergedKeys (); } KeySet resultKeys = result.getMergedKeys (); originalKeys.append (resultKeys); kdb.set (originalKeys, root); ret = 0; } return ret; }
Modules ModulesHandler::modules() const { Modules mods; m_model->forFirstLevelItems([&mods](ModuleItem *item) { mods.append(item->module); }); return mods; }
void Register_Function(Modules md, Students st) { Students st; Modules md; int dd,mm,yyyy; bool done=1; bool done_d=1; char string_date[15]; char ch_d,stat=2; while(done_d) { system("cls"); cout<<"\n Enter the New date (E)."; cout<<"\n Exit (Q) "; cout<<"\n Enter your choice: "; cin>> ch_d; switch(ch_d) { case 'q': case 'Q': done_d=0; stat=1; break; case 'e': case 'E': stat=0; break; } if(stat==1) break; else if(stat==2) continue; system("cls"); cout<<"Please Enter the Date(dd mm yyyy):"; cin>>dd>>mm>>yyyy; while(done) { int ID; md.Browse(); cout<<"\n Date(dd-mm-yyy):"<<dd<<"-"<<mm<<"-"<<yyyy; cout<<"\n Please Select one of Modules by ID or -1 to exit: "; cin>> ID; if (ID<=-1) {done=0;break;} if(md.Check_ID(ID)==0) {getch(); continue; } int done_m=1; while(done_m) { system("cls"); cout<<"\n Date(dd-mm-yyy):"<<dd<<"-"<<mm<<"-"<<yyyy<<" Module Name: "<<md.Get_Name(ID); cout<<"\n Enter the student ID (I)."; //cout<<"\n Undo (U)."; //cout<<"\n Search student name by ID (S)."; cout<<"\n Browse students(B)."; cout<<"\n Exit (Q) "; cout<<"\n Enter your choice: "; char IDc; int done_i=1; int IDi=0; cin>> IDc; switch(IDc) { case 'q': case 'Q': done_m=0; break; case 'i': case 'I': //system("cls") while(1){ cout<<"\n Date(dd-mm-yyy):"<<dd<<"-"<<mm<<"-"<<yyyy<<" Module Name: "<<md.Get_Name(ID); cout<<"\n Enter Student ID (-1 to exit): "; cin>>IDi; if (IDi<0) break; if (st.Check_ID(IDi)) { cout<<"\n Date(dd-mm-yyy):"<<dd<<"-"<<mm<<"-"<<yyyy<<" Module Name: "<<md.Get_Name(ID)<<" Student ID/Name: "<<IDi<<'/'<<st.Get_Name(IDi); cout<<"\n On Time (O)."; cout<<"\n Late (L)."; cout<<"\n Absent (A)."; cout<<"\n Exit (Q) "; cout<<"\n Status: "; cin>>IDc; sprintf(string_date,"%d-%d-%d",dd,mm,yyyy); Registers[Current_Reg].Date=string_date; Registers[Current_Reg].Mod_ID=ID; Registers[Current_Reg].Mod_Name=md.Get_Name(ID); Registers[Current_Reg].St_ID=IDi; switch(IDc) { case 'q': case 'Q': break; case 'o': case 'O': Registers[Current_Reg].status=+1; break; case 'L': case 'l': Registers[Current_Reg].status=0; break; case 'a': case 'A': Registers[Current_Reg].status=-1; break; } //cout<<"Record_number:("<<Current_Reg<<")"<<Registers[Current_Reg].Date<<" "<<Registers[Current_Reg].Mod_Name<<" "<<Registers[Current_Reg].St_ID; Current_Reg++; } } //Registers[Current_Reg]. break; case 'b': case 'B': st.Browse(); getch(); break; case 's': case 'S': //st.Search_Name() break; } } } }
int main(int argc, char** argv) { mem.init(); // initialize storage allocator mem.setStackBottom(&argv); #if _WIN32 && __DMC__ mem.addroots((char *)&_xi_a, (char *)&_end); #endif // stack trace on signals llvm::sys::PrintStackTraceOnErrorSignal(); Strings files; const char *p, *ext; Module *m; int status = EXIT_SUCCESS; global.init(); global.version = ldc::dmd_version; global.ldc_version = ldc::ldc_version; global.llvm_version = ldc::llvm_version; // Set some default values #if _WIN32 char buf[MAX_PATH]; GetModuleFileName(NULL, buf, MAX_PATH); global.params.argv0 = buf; #else global.params.argv0 = argv[0]; #endif global.params.useSwitchError = 1; global.params.useArrayBounds = 2; global.params.linkswitches = new Strings(); global.params.libfiles = new Strings(); global.params.objfiles = new Strings(); global.params.ddocfiles = new Strings(); global.params.moduleDeps = NULL; global.params.moduleDepsFile = NULL; // Set predefined version identifiers VersionCondition::addPredefinedGlobalIdent("LLVM"); // For backwards compatibility. VersionCondition::addPredefinedGlobalIdent("LDC"); VersionCondition::addPredefinedGlobalIdent("all"); VersionCondition::addPredefinedGlobalIdent("D_Version2"); // build complete fixed up list of command line arguments std::vector<const char*> final_args; final_args.reserve(argc); // insert command line args until -run is reached int run_argnum = 1; while (run_argnum < argc && strncmp(argv[run_argnum], "-run", 4) != 0) ++run_argnum; final_args.insert(final_args.end(), &argv[0], &argv[run_argnum]); // read the configuration file ConfigFile cfg_file; // just ignore errors for now, they are still printed cfg_file.read(global.params.argv0, (void*)main, "ldc2.conf"); // insert config file additions to the argument list final_args.insert(final_args.end(), cfg_file.switches_begin(), cfg_file.switches_end()); // insert -run and everything beyond final_args.insert(final_args.end(), &argv[run_argnum], &argv[argc]); #if 0 for (size_t i = 0; i < final_args.size(); ++i) { printf("final_args[%zu] = %s\n", i, final_args[i]); } #endif // Initialize LLVM. // Initialize targets first, so that --version shows registered targets. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeAllAsmParsers(); // Handle fixed-up arguments! cl::SetVersionPrinter(&printVersion); cl::ParseCommandLineOptions(final_args.size(), const_cast<char**>(&final_args[0]), "LDC - the LLVM D compiler\n" #if LDC_LLVM_VER < 302 , true #endif ); // Print config file path if -v was passed if (global.params.verbose) { const std::string& path = cfg_file.path(); if (!path.empty()) printf("config %s\n", path.c_str()); } bool skipModules = mCPU == "help" ||(!mAttrs.empty() && mAttrs.front() == "help"); // Negated options global.params.link = !compileOnly; global.params.obj = !dontWriteObj; global.params.useInlineAsm = !noAsm; // String options: std::string --> char* initFromString(global.params.objname, objectFile); initFromString(global.params.objdir, objectDir); initFromString(global.params.docdir, ddocDir); initFromString(global.params.docname, ddocFile); global.params.doDocComments |= global.params.docdir || global.params.docname; initFromString(global.params.xfilename, jsonFile); if (global.params.xfilename) global.params.doXGeneration = true; initFromString(global.params.hdrdir, hdrDir); initFromString(global.params.hdrname, hdrFile); global.params.doHdrGeneration |= global.params.hdrdir || global.params.hdrname; initFromString(global.params.moduleDepsFile, moduleDepsFile); if (global.params.moduleDepsFile != NULL) { global.params.moduleDeps = new OutBuffer; } processVersions(debugArgs, "debug", DebugCondition::setGlobalLevel, DebugCondition::addGlobalIdent); processVersions(versions, "version", VersionCondition::setGlobalLevel, VersionCondition::addGlobalIdent); global.params.output_o = (opts::output_o == cl::BOU_UNSET && !(opts::output_bc || opts::output_ll || opts::output_s)) ? OUTPUTFLAGdefault : opts::output_o == cl::BOU_TRUE ? OUTPUTFLAGset : OUTPUTFLAGno; global.params.output_bc = opts::output_bc ? OUTPUTFLAGset : OUTPUTFLAGno; global.params.output_ll = opts::output_ll ? OUTPUTFLAGset : OUTPUTFLAGno; global.params.output_s = opts::output_s ? OUTPUTFLAGset : OUTPUTFLAGno; templateLinkage = opts::linkonceTemplates ? LLGlobalValue::LinkOnceODRLinkage : LLGlobalValue::WeakODRLinkage; if (global.params.run || !runargs.empty()) { // FIXME: how to properly detect the presence of a PositionalEatsArgs // option without parameters? We want to emit an error in that case... // You'd think getNumOccurrences would do it, but it just returns the // number of parameters) // NOTE: Hacked around it by detecting -run in getenv_setargv(), where // we're looking for it anyway, and pre-setting the flag... global.params.run = true; if (!runargs.empty()) { char const * name = runargs[0].c_str(); char const * ext = FileName::ext(name); if (ext && FileName::equals(ext, "d") == 0 && FileName::equals(ext, "di") == 0) { error("-run must be followed by a source file, not '%s'", name); } files.push(mem.strdup(name)); runargs.erase(runargs.begin()); } else { global.params.run = false; error("Expected at least one argument to '-run'\n"); } } files.reserve(fileList.size()); typedef std::vector<std::string>::iterator It; for(It I = fileList.begin(), E = fileList.end(); I != E; ++I) if (!I->empty()) files.push(mem.strdup(I->c_str())); if (global.errors) { fatal(); } if (files.dim == 0 && !skipModules) { cl::PrintHelpMessage(); return EXIT_FAILURE; } Array* libs; if (global.params.symdebug) { libs = global.params.debuglibnames; } else libs = global.params.defaultlibnames; if (!noDefaultLib) { if (libs) { for (unsigned i = 0; i < libs->dim; i++) { char* lib = static_cast<char *>(libs->data[i]); char *arg = static_cast<char *>(mem.malloc(strlen(lib) + 3)); strcpy(arg, "-l"); strcpy(arg+2, lib); global.params.linkswitches->push(arg); } } else { global.params.linkswitches->push(mem.strdup("-ldruntime-ldc")); } } if (global.params.useUnitTests) global.params.useAssert = 1; // Bounds checking is a bit peculiar: -enable/disable-boundscheck is an // absolute decision. Only if no explicit option is specified, -release // downgrades useArrayBounds 2 to 1 (only for safe functions). if (opts::boundsChecks == cl::BOU_UNSET) global.params.useArrayBounds = opts::nonSafeBoundsChecks ? 2 : 1; else global.params.useArrayBounds = (opts::boundsChecks == cl::BOU_TRUE) ? 2 : 0; // LDC output determination // if we don't link, autodetect target from extension if(!global.params.link && !createStaticLib && global.params.objname) { ext = FileName::ext(global.params.objname); bool autofound = false; if (!ext) { // keep things as they are } else if (strcmp(ext, global.ll_ext) == 0) { global.params.output_ll = OUTPUTFLAGset; autofound = true; } else if (strcmp(ext, global.bc_ext) == 0) { global.params.output_bc = OUTPUTFLAGset; autofound = true; } else if (strcmp(ext, global.s_ext) == 0) { global.params.output_s = OUTPUTFLAGset; autofound = true; } else if (strcmp(ext, global.obj_ext) == 0 || strcmp(ext, global.obj_ext_alt) == 0) { global.params.output_o = OUTPUTFLAGset; autofound = true; } else { // append dot, so forceExt won't change existing name even if it contains dots size_t len = strlen(global.params.objname); char* s = static_cast<char *>(mem.malloc(len + 1 + 1)); memcpy(s, global.params.objname, len); s[len] = '.'; s[len+1] = 0; global.params.objname = s; } if(autofound && global.params.output_o == OUTPUTFLAGdefault) global.params.output_o = OUTPUTFLAGno; } // only link if possible if (!global.params.obj || !global.params.output_o || createStaticLib) global.params.link = 0; if (createStaticLib && createSharedLib) error("-lib and -shared switches cannot be used together"); if (createSharedLib && mRelocModel == llvm::Reloc::Default) mRelocModel = llvm::Reloc::PIC_; if (global.params.link && !createSharedLib) { global.params.exefile = global.params.objname; if (files.dim > 1) global.params.objname = NULL; } else if (global.params.run) { error("flags conflict with -run"); fatal(); } else if (global.params.objname && files.dim > 1) { if (createStaticLib || createSharedLib) { singleObj = true; } if (!singleObj) { error("multiple source files, but only one .obj name"); fatal(); } } if (soname.getNumOccurrences() > 0 && !createSharedLib) { error("-soname can be used only when building a shared library"); fatal(); } // create a proper target Ir ir; // Set up the TargetMachine. ExplicitBitness::Type bitness = ExplicitBitness::None; if ((m32bits || m64bits) && (!mArch.empty() || !mTargetTriple.empty())) error("-m32 and -m64 switches cannot be used together with -march and -mtriple switches"); if (m32bits) bitness = ExplicitBitness::M32; if (m64bits) { if (bitness != ExplicitBitness::None) { error("cannot use both -m32 and -m64 options"); } } if (global.errors) fatal(); gTargetMachine = createTargetMachine(mTargetTriple, mArch, mCPU, mAttrs, bitness, mRelocModel, mCodeModel, codeGenOptLevel(), global.params.symdebug); llvm::Triple targetTriple = llvm::Triple(gTargetMachine->getTargetTriple()); global.params.targetTriple = targetTriple; global.params.trace = false; global.params.isLinux = targetTriple.getOS() == llvm::Triple::Linux; global.params.isOSX = targetTriple.isMacOSX(); global.params.isWindows = targetTriple.isOSWindows(); global.params.isFreeBSD = targetTriple.getOS() == llvm::Triple::FreeBSD; global.params.isOpenBSD = targetTriple.getOS() == llvm::Triple::OpenBSD; global.params.isSolaris = targetTriple.getOS() == llvm::Triple::Solaris; #if LDC_LLVM_VER >= 302 gDataLayout = gTargetMachine->getDataLayout(); #else gDataLayout = gTargetMachine->getTargetData(); #endif // Starting with LLVM 3.1 we could also use global.params.targetTriple.isArch64Bit(); global.params.is64bit = gDataLayout->getPointerSizeInBits(ADDRESS_SPACE) == 64; switch (global.params.targetTriple.getArch()) { case llvm::Triple::x86: VersionCondition::addPredefinedGlobalIdent("X86"); if (global.params.useInlineAsm) { VersionCondition::addPredefinedGlobalIdent("D_InlineAsm_X86"); } VersionCondition::addPredefinedGlobalIdent("D_HardFloat"); break; case llvm::Triple::x86_64: VersionCondition::addPredefinedGlobalIdent("X86_64"); if (global.params.useInlineAsm) { VersionCondition::addPredefinedGlobalIdent("D_InlineAsm_X86_64"); } VersionCondition::addPredefinedGlobalIdent("D_HardFloat"); break; case llvm::Triple::ppc: // FIXME: Detect soft float (PPC_SoftFP/PPC_HardFP). VersionCondition::addPredefinedGlobalIdent("PPC"); break; case llvm::Triple::ppc64: VersionCondition::addPredefinedGlobalIdent("PPC64"); VersionCondition::addPredefinedGlobalIdent("D_HardFloat"); break; case llvm::Triple::arm: // FIXME: Detect various FP ABIs (ARM_Soft, ARM_SoftFP, ARM_HardFP). VersionCondition::addPredefinedGlobalIdent("ARM"); break; case llvm::Triple::thumb: VersionCondition::addPredefinedGlobalIdent("ARM"); VersionCondition::addPredefinedGlobalIdent("Thumb"); // For backwards compatibility. VersionCondition::addPredefinedGlobalIdent("ARM_Thumb"); VersionCondition::addPredefinedGlobalIdent("ARM_Soft"); VersionCondition::addPredefinedGlobalIdent("D_SoftFloat"); break; case llvm::Triple::mips: case llvm::Triple::mipsel: // FIXME: Detect O32/N32 variants (MIPS_{O32,N32}[_SoftFP,_HardFP]). VersionCondition::addPredefinedGlobalIdent("MIPS"); break; case llvm::Triple::mips64: case llvm::Triple::mips64el: // FIXME: Detect N64 variants (MIPS64_N64[_SoftFP,_HardFP]). VersionCondition::addPredefinedGlobalIdent("MIPS64"); break; case llvm::Triple::sparc: // FIXME: Detect SPARC v8+ (SPARC_V8Plus). // FIXME: Detect soft float (SPARC_SoftFP/SPARC_HardFP). VersionCondition::addPredefinedGlobalIdent("SPARC"); break; case llvm::Triple::sparcv9: VersionCondition::addPredefinedGlobalIdent("SPARC64"); VersionCondition::addPredefinedGlobalIdent("D_HardFloat"); break; default: error("invalid cpu architecture specified: %s", global.params.targetTriple.getArchName().str().c_str()); fatal(); } // endianness if (gDataLayout->isLittleEndian()) { VersionCondition::addPredefinedGlobalIdent("LittleEndian"); } else { VersionCondition::addPredefinedGlobalIdent("BigEndian"); } // a generic 64bit version if (global.params.is64bit) { VersionCondition::addPredefinedGlobalIdent("LLVM64"); // For backwards compatibility. VersionCondition::addPredefinedGlobalIdent("D_LP64"); } if (gTargetMachine->getRelocationModel() == llvm::Reloc::PIC_) { VersionCondition::addPredefinedGlobalIdent("D_PIC"); } // parse the OS out of the target triple // see http://gcc.gnu.org/install/specific.html for details // also llvm's different SubTargets have useful information switch (global.params.targetTriple.getOS()) { case llvm::Triple::Win32: VersionCondition::addPredefinedGlobalIdent("Windows"); VersionCondition::addPredefinedGlobalIdent(global.params.is64bit ? "Win64" : "Win32"); break; case llvm::Triple::MinGW32: VersionCondition::addPredefinedGlobalIdent("Windows"); VersionCondition::addPredefinedGlobalIdent(global.params.is64bit ? "Win64" : "Win32"); VersionCondition::addPredefinedGlobalIdent("mingw32"); // For backwards compatibility. VersionCondition::addPredefinedGlobalIdent("MinGW"); break; case llvm::Triple::Cygwin: error("Cygwin is not yet supported"); fatal(); VersionCondition::addPredefinedGlobalIdent("Cygwin"); break; case llvm::Triple::Linux: VersionCondition::addPredefinedGlobalIdent("linux"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::Haiku: VersionCondition::addPredefinedGlobalIdent("Haiku"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::Darwin: VersionCondition::addPredefinedGlobalIdent("OSX"); VersionCondition::addPredefinedGlobalIdent("darwin"); // For backwards compatibility. VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::FreeBSD: VersionCondition::addPredefinedGlobalIdent("freebsd"); // For backwards compatibility. VersionCondition::addPredefinedGlobalIdent("FreeBSD"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::Solaris: VersionCondition::addPredefinedGlobalIdent("solaris"); // For backwards compatibility. VersionCondition::addPredefinedGlobalIdent("Solaris"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::DragonFly: VersionCondition::addPredefinedGlobalIdent("DragonFlyBSD"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::NetBSD: VersionCondition::addPredefinedGlobalIdent("NetBSD"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::OpenBSD: VersionCondition::addPredefinedGlobalIdent("OpenBSD"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; #if LDC_LLVM_VER >= 302 case llvm::Triple::AIX: VersionCondition::addPredefinedGlobalIdent("AIX"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; #endif default: error("target '%s' is not yet supported", global.params.targetTriple.str().c_str()); fatal(); } // Expose LLVM version to runtime #define STR(x) #x #define XSTR(x) STR(x) VersionCondition::addPredefinedGlobalIdent("LDC_LLVM_" XSTR(LDC_LLVM_VER)); #undef XSTR #undef STR if (global.params.targetTriple.isOSWindows()) { global.dll_ext = "dll"; global.lib_ext = "lib"; } else { global.dll_ext = "so"; global.lib_ext = "a"; } // added in 1.039 if (global.params.doDocComments) VersionCondition::addPredefinedGlobalIdent("D_Ddoc"); // unittests? if (global.params.useUnitTests) VersionCondition::addPredefinedGlobalIdent("unittest"); if (global.params.useAssert) VersionCondition::addPredefinedGlobalIdent("assert"); if (!global.params.useArrayBounds) VersionCondition::addPredefinedGlobalIdent("D_NoBoundsChecks"); // Initialization Type::init(&ir); Id::initialize(); Module::init(); Target::init(); Expression::init(); initPrecedence(); backend_init(); //printf("%d source files\n",files.dim); // Build import search path if (global.params.imppath) { for (unsigned i = 0; i < global.params.imppath->dim; i++) { char *path = static_cast<char *>(global.params.imppath->data[i]); Strings *a = FileName::splitPath(path); if (a) { if (!global.path) global.path = new Strings(); global.path->append(a); } } } // Build string import search path if (global.params.fileImppath) { for (unsigned i = 0; i < global.params.fileImppath->dim; i++) { char *path = static_cast<char *>(global.params.fileImppath->data[i]); Strings *a = FileName::splitPath(path); if (a) { if (!global.filePath) global.filePath = new Strings(); global.filePath->append(a); } } } if (global.params.addMain) { // a dummy name, we never actually look up this file files.push(const_cast<char*>(global.main_d)); } // Create Modules Modules modules; modules.reserve(files.dim); for (unsigned i = 0; i < files.dim; i++) { Identifier *id; const char *ext; const char *name; p = static_cast<char *>(files.data[i]); p = FileName::name(p); // strip path ext = FileName::ext(p); if (ext) { #if POSIX if (strcmp(ext, global.obj_ext) == 0 || strcmp(ext, global.bc_ext) == 0) #else if (Port::stricmp(ext, global.obj_ext) == 0 || Port::stricmp(ext, global.obj_ext_alt) == 0 || Port::stricmp(ext, global.bc_ext) == 0) #endif { global.params.objfiles->push(static_cast<char *>(files.data[i])); continue; } #if POSIX if (strcmp(ext, "a") == 0) #elif __MINGW32__ if (Port::stricmp(ext, "a") == 0) #else if (Port::stricmp(ext, "lib") == 0) #endif { global.params.libfiles->push(static_cast<char *>(files.data[i])); continue; } if (strcmp(ext, global.ddoc_ext) == 0) { global.params.ddocfiles->push(static_cast<char *>(files.data[i])); continue; } if (FileName::equals(ext, global.json_ext)) { global.params.doXGeneration = 1; global.params.xfilename = static_cast<char *>(files.data[i]); continue; } #if !POSIX if (Port::stricmp(ext, "res") == 0) { global.params.resfile = static_cast<char *>(files.data[i]); continue; } if (Port::stricmp(ext, "def") == 0) { global.params.deffile = static_cast<char *>(files.data[i]); continue; } if (Port::stricmp(ext, "exe") == 0) { global.params.exefile = static_cast<char *>(files.data[i]); continue; } #endif if (Port::stricmp(ext, global.mars_ext) == 0 || Port::stricmp(ext, global.hdr_ext) == 0 || FileName::equals(ext, "dd")) { ext--; // skip onto '.' assert(*ext == '.'); char *tmp = static_cast<char *>(mem.malloc((ext - p) + 1)); memcpy(tmp, p, ext - p); tmp[ext - p] = 0; // strip extension name = tmp; if (name[0] == 0 || strcmp(name, "..") == 0 || strcmp(name, ".") == 0) { goto Linvalid; } } else { error("unrecognized file extension %s\n", ext); fatal(); } } else { name = p; if (!*p) { Linvalid: error("invalid file name '%s'", static_cast<char *>(files.data[i])); fatal(); } name = p; } id = Lexer::idPool(name); m = new Module(static_cast<char *>(files.data[i]), id, global.params.doDocComments, global.params.doHdrGeneration); m->isRoot = true; modules.push(m); } // Read files, parse them for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("parse %s\n", m->toChars()); if (!Module::rootModule) Module::rootModule = m; m->importedFrom = m; if (strcmp(m->srcfile->name->str, global.main_d) == 0) { static const char buf[] = "void main(){}"; m->srcfile->setbuffer((void *)buf, sizeof(buf)); m->srcfile->ref = 1; } else { m->read(Loc()); } m->parse(global.params.doDocComments); m->buildTargetFiles(singleObj); m->deleteObjFile(); if (m->isDocFile) { m->gendocfile(); // Remove m from list of modules modules.remove(i); i--; } } if (global.errors) fatal(); if (global.params.doHdrGeneration) { /* Generate 'header' import files. * Since 'header' import files must be independent of command * line switches and what else is imported, they are generated * before any semantic analysis. */ for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("import %s\n", m->toChars()); m->genhdrfile(); } } if (global.errors) fatal(); // load all unconditional imports for better symbol resolving for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("importall %s\n", m->toChars()); m->importAll(0); } if (global.errors) fatal(); // Do semantic analysis for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("semantic %s\n", m->toChars()); m->semantic(); } if (global.errors) fatal(); Module::dprogress = 1; Module::runDeferredSemantic(); // Do pass 2 semantic analysis for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("semantic2 %s\n", m->toChars()); m->semantic2(); } if (global.errors) fatal(); // Do pass 3 semantic analysis for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("semantic3 %s\n", m->toChars()); m->semantic3(); } if (global.errors) fatal(); // This doesn't play nice with debug info at the moment. // // Also, don't run the additional semantic3 passes when building unit tests. // This is basically a huge hack around the fact that linking against a // library is supposed to require the same compiler flags as when it was // built, but -unittest is usually not thought to behave like this from a // user perspective. // // Thus, if a library contained some functions in version(unittest), for // example the tests in std.concurrency, and we ended up inline-scannin // these functions while doing an -unittest build of a client application, // we could end up referencing functions that we think are // availableExternally, but have never been touched when the library was built. // // Alternatively, we could also amend the availableExternally detection // logic (e.g. just codegen everything on -unittest builds), but the extra // inlining is unlikely to be important for test builds anyway. if (!global.params.symdebug && willInline() && !global.params.useUnitTests) { global.inExtraInliningSemantic = true; Logger::println("Running some extra semantic3's for inlining purposes"); { // Do pass 3 semantic analysis on all imported modules, // since otherwise functions in them cannot be inlined for (unsigned i = 0; i < Module::amodules.dim; i++) { m = static_cast<Module *>(Module::amodules.data[i]); if (global.params.verbose) printf("semantic3 %s\n", m->toChars()); m->semantic2(); m->semantic3(); } if (global.errors) fatal(); } global.inExtraInliningSemantic = false; } if (global.errors || global.warnings) fatal(); // write module dependencies to file if requested if (global.params.moduleDepsFile != NULL) { assert (global.params.moduleDepsFile != NULL); File deps(global.params.moduleDepsFile); OutBuffer* ob = global.params.moduleDeps; deps.setbuffer(static_cast<void*>(ob->data), ob->offset); deps.write(); } // collects llvm modules to be linked if singleobj is passed std::vector<llvm::Module*> llvmModules; llvm::LLVMContext& context = llvm::getGlobalContext(); // Generate output files for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("code %s\n", m->toChars()); if (global.params.obj) { llvm::Module* lm = m->genLLVMModule(context, &ir); if (!singleObj) { m->deleteObjFile(); writeModule(lm, m->objfile->name->str); global.params.objfiles->push(const_cast<char*>(m->objfile->name->str)); delete lm; } else llvmModules.push_back(lm); } if (global.errors) m->deleteObjFile(); else { if (global.params.doDocComments) m->gendocfile(); } } // internal linking for singleobj if (singleObj && llvmModules.size() > 0) { Module* m = static_cast<Module*>(modules.data[0]); char* oname; const char* filename; if ((oname = global.params.exefile) || (oname = global.params.objname)) { filename = FileName::forceExt(oname, global.obj_ext); if (global.params.objdir) { filename = FileName::combine(global.params.objdir, FileName::name(filename)); } } else filename = m->objfile->name->str; #if 1 // Temporary workaround for http://llvm.org/bugs/show_bug.cgi?id=11479. char* moduleName = const_cast<char*>(filename); #else char* moduleName = m->toChars(); #endif #if LDC_LLVM_VER >= 303 llvm::Module *dest = new llvm::Module(moduleName, context); llvm::Linker linker(dest); #else llvm::Linker linker("ldc", moduleName, context); #endif std::string errormsg; for (size_t i = 0; i < llvmModules.size(); i++) { #if LDC_LLVM_VER >= 303 if (linker.linkInModule(llvmModules[i], llvm::Linker::DestroySource, &errormsg)) #else if (linker.LinkInModule(llvmModules[i], &errormsg)) #endif error("%s", errormsg.c_str()); delete llvmModules[i]; } m->deleteObjFile(); writeModule(linker.getModule(), filename); global.params.objfiles->push(const_cast<char*>(filename)); #if LDC_LLVM_VER >= 303 delete dest; #endif } // output json file if (global.params.doXGeneration) { OutBuffer buf; json_generate(&buf, &modules); // Write buf to file const char *name = global.params.xfilename; if (name && name[0] == '-' && name[1] == 0) { // Write to stdout; assume it succeeds int n = fwrite(buf.data, 1, buf.offset, stdout); assert(n == buf.offset); // keep gcc happy about return values } else { /* The filename generation code here should be harmonized with Module::setOutfile() */ const char *jsonfilename; if (name && *name) { jsonfilename = FileName::defaultExt(name, global.json_ext); } else { // Generate json file name from first obj name const char *n = (*global.params.objfiles)[0]; n = FileName::name(n); //if (!FileName::absolute(name)) //name = FileName::combine(dir, name); jsonfilename = FileName::forceExt(n, global.json_ext); } FileName::ensurePathToNameExists(jsonfilename); File *jsonfile = new File(jsonfilename); jsonfile->setbuffer(buf.data, buf.offset); jsonfile->ref = 1; jsonfile->writev(); } } backend_term(); if (global.errors) fatal(); if (!global.params.objfiles->dim) { if (global.params.link) error("no object files to link"); else if (createStaticLib) error("no object files"); } else { if (global.params.link) status = linkObjToBinary(createSharedLib); else if (createStaticLib) createStaticLibrary(); if (global.params.run) { if (!status) { status = runExecutable(); /* Delete .obj files and .exe file */ for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); m->deleteObjFile(); } deleteExecutable(); } } } return status; }
void xmlTest::testXml() { string file = "../bin/test.xml"; Data *d = Data::instance(); d->read(file); NMODE *nmode = d->specification(); Simulator *sim = nmode->simulator(); CPPUNIT_ASSERT("working directory" == sim->workingDirectory()); CPPUNIT_ASSERT("xml file" == sim->xml()); CPPUNIT_ASSERT(42 == sim->nr()); CfgMutation *mutation = nmode->mutation(); CfgMutationNode *mn = mutation->node(); CfgMutationEdge *me = mutation->edge(); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.11, mn->modifyProbability(), 0.000001); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.12, mn->modifyMaxValue(), 0.000001); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.13, mn->modifyDelta(), 0.000001); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.21, me->modifyProbability(), 0.000001); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.22, me->modifyMaxValue(), 0.000001); CPPUNIT_ASSERT_DOUBLES_EQUAL(0.23, me->modifyDelta(), 0.000001); Configuration* conf = nmode->configuration(); Modules mods = conf->modules(); CPPUNIT_ASSERT(3 == mods.size()); CPPUNIT_ASSERT("module 1" == mods[0]->name()); Nodes mod_1_nodes = mods[0]->nodes(); CPPUNIT_ASSERT(9 == mod_1_nodes.size()); CPPUNIT_ASSERT("sensor" == mod_1_nodes[0]->type()); CPPUNIT_ASSERT("sensor 1" == mod_1_nodes[0]->label()); CPPUNIT_ASSERT(P3D(0.0, 0.0, 0.0) == mod_1_nodes[0]->position()); CPPUNIT_ASSERT("id" == mod_1_nodes[0]->transferfunction()); CPPUNIT_ASSERT("sensor" == mod_1_nodes[1]->type()); CPPUNIT_ASSERT("sensor 2" == mod_1_nodes[1]->label()); CPPUNIT_ASSERT(P3D(1.0, 0.0, 0.0) == mod_1_nodes[1]->position()); CPPUNIT_ASSERT("id" == mod_1_nodes[1]->transferfunction()); CPPUNIT_ASSERT("sensor" == mod_1_nodes[2]->type()); CPPUNIT_ASSERT("sensor 3" == mod_1_nodes[2]->label()); CPPUNIT_ASSERT(P3D(2.0, 0.0, 0.0) == mod_1_nodes[2]->position()); CPPUNIT_ASSERT("id" == mod_1_nodes[2]->transferfunction()); CPPUNIT_ASSERT("actuator" == mod_1_nodes[3]->type()); CPPUNIT_ASSERT("actuator 1" == mod_1_nodes[3]->label()); CPPUNIT_ASSERT(P3D(0.5, 1.0, 0.0) == mod_1_nodes[3]->position()); CPPUNIT_ASSERT("tanh" == mod_1_nodes[3]->transferfunction()); CPPUNIT_ASSERT("actuator" == mod_1_nodes[4]->type()); CPPUNIT_ASSERT("actuator 2" == mod_1_nodes[4]->label()); CPPUNIT_ASSERT(P3D(1.5, 1.0, 0.0) == mod_1_nodes[4]->position()); CPPUNIT_ASSERT("sigm" == mod_1_nodes[4]->transferfunction()); CPPUNIT_ASSERT("module 2" == mods[1]->name()); Nodes mod_2_nodes = mods[1]->nodes(); CPPUNIT_ASSERT(3 == mod_2_nodes.size()); CPPUNIT_ASSERT("sensor" == mod_2_nodes[0]->type()); CPPUNIT_ASSERT("sensor 1" == mod_2_nodes[0]->label()); CPPUNIT_ASSERT(P3D(0.0, 0.0, 0.0) == mod_2_nodes[0]->position()); CPPUNIT_ASSERT("sigm" == mod_2_nodes[0]->transferfunction()); CPPUNIT_ASSERT("sensor" == mod_2_nodes[1]->type()); CPPUNIT_ASSERT("sensor 2" == mod_2_nodes[1]->label()); CPPUNIT_ASSERT(P3D(1.0, 0.0, 0.0) == mod_2_nodes[1]->position()); CPPUNIT_ASSERT("id" == mod_2_nodes[1]->transferfunction()); CPPUNIT_ASSERT("actuator" == mod_2_nodes[2]->type()); CPPUNIT_ASSERT("actuator 1" == mod_2_nodes[2]->label()); CPPUNIT_ASSERT(P3D(0.5, 1.0, 0.0) == mod_2_nodes[2]->position()); CPPUNIT_ASSERT("tanh" == mod_2_nodes[2]->transferfunction()); }
int main(int argc, char** argv) { mem.init(); // initialize storage allocator mem.setStackBottom(&argv); #if _WIN32 && __DMC__ mem.addroots((char *)&_xi_a, (char *)&_end); #endif // stack trace on signals llvm::sys::PrintStackTraceOnErrorSignal(); Strings files; char *p, *ext; Module *m; int status = EXIT_SUCCESS; // Set some default values #if _WIN32 char buf[MAX_PATH]; GetModuleFileName(NULL, buf, MAX_PATH); global.params.argv0 = buf; #else global.params.argv0 = argv[0]; #endif global.params.useSwitchError = 1; global.params.linkswitches = new Strings(); global.params.libfiles = new Strings(); global.params.objfiles = new Strings(); global.params.ddocfiles = new Strings(); global.params.moduleDeps = NULL; global.params.moduleDepsFile = NULL; // Set predefined version identifiers VersionCondition::addPredefinedGlobalIdent("LLVM"); VersionCondition::addPredefinedGlobalIdent("LDC"); VersionCondition::addPredefinedGlobalIdent("all"); #if DMDV2 VersionCondition::addPredefinedGlobalIdent("D_Version2"); #endif // build complete fixed up list of command line arguments std::vector<const char*> final_args; final_args.reserve(argc); // insert command line args until -run is reached int run_argnum = 1; while (run_argnum < argc && strncmp(argv[run_argnum], "-run", 4) != 0) ++run_argnum; final_args.insert(final_args.end(), &argv[0], &argv[run_argnum]); // read the configuration file ConfigFile cfg_file; // just ignore errors for now, they are still printed #if DMDV2 #define CFG_FILENAME "ldc2.conf" #else #define CFG_FILENAME "ldc.conf" #endif cfg_file.read(global.params.argv0, (void*)main, CFG_FILENAME); #undef CFG_FILENAME // insert config file additions to the argument list final_args.insert(final_args.end(), cfg_file.switches_begin(), cfg_file.switches_end()); // insert -run and everything beyond final_args.insert(final_args.end(), &argv[run_argnum], &argv[argc]); #if 0 for (size_t i = 0; i < final_args.size(); ++i) { printf("final_args[%zu] = %s\n", i, final_args[i]); } #endif // Initialize LLVM. // Initialize targets first, so that --version shows registered targets. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmPrinters(); llvm::InitializeAllAsmParsers(); // Handle fixed-up arguments! cl::SetVersionPrinter(&printVersion); cl::ParseCommandLineOptions(final_args.size(), const_cast<char**>(&final_args[0]), "LLVM-based D Compiler\n", true); // Print config file path if -v was passed if (global.params.verbose) { const std::string& path = cfg_file.path(); if (!path.empty()) printf("config %s\n", path.c_str()); } bool skipModules = mCPU == "help" ||(!mAttrs.empty() && mAttrs.front() == "help"); // Negated options global.params.link = !compileOnly; global.params.obj = !dontWriteObj; global.params.useInlineAsm = !noAsm; // String options: std::string --> char* initFromString(global.params.objname, objectFile); initFromString(global.params.objdir, objectDir); initFromString(global.params.docdir, ddocDir); initFromString(global.params.docname, ddocFile); global.params.doDocComments |= global.params.docdir || global.params.docname; initFromString(global.params.xfilename, jsonFile); if (global.params.xfilename) global.params.doXGeneration = true; initFromString(global.params.hdrdir, hdrDir); initFromString(global.params.hdrname, hdrFile); global.params.doHdrGeneration |= global.params.hdrdir || global.params.hdrname; initFromString(global.params.moduleDepsFile, moduleDepsFile); if (global.params.moduleDepsFile != NULL) { global.params.moduleDeps = new OutBuffer; } processVersions(debugArgs, "debug", DebugCondition::setGlobalLevel, DebugCondition::addGlobalIdent); processVersions(versions, "version", VersionCondition::setGlobalLevel, VersionCondition::addGlobalIdent); global.params.output_o = (opts::output_o == cl::BOU_UNSET && !(opts::output_bc || opts::output_ll || opts::output_s)) ? OUTPUTFLAGdefault : opts::output_o == cl::BOU_TRUE ? OUTPUTFLAGset : OUTPUTFLAGno; global.params.output_bc = opts::output_bc ? OUTPUTFLAGset : OUTPUTFLAGno; global.params.output_ll = opts::output_ll ? OUTPUTFLAGset : OUTPUTFLAGno; global.params.output_s = opts::output_s ? OUTPUTFLAGset : OUTPUTFLAGno; templateLinkage = opts::linkonceTemplates ? LLGlobalValue::LinkOnceODRLinkage : LLGlobalValue::WeakODRLinkage; if (global.params.run || !runargs.empty()) { // FIXME: how to properly detect the presence of a PositionalEatsArgs // option without parameters? We want to emit an error in that case... // You'd think getNumOccurrences would do it, but it just returns the // number of parameters) // NOTE: Hacked around it by detecting -run in getenv_setargv(), where // we're looking for it anyway, and pre-setting the flag... global.params.run = true; if (!runargs.empty()) { files.push(mem.strdup(runargs[0].c_str())); } else { global.params.run = false; error("Expected at least one argument to '-run'\n"); } } files.reserve(fileList.size()); typedef std::vector<std::string>::iterator It; for(It I = fileList.begin(), E = fileList.end(); I != E; ++I) if (!I->empty()) files.push(mem.strdup(I->c_str())); if (global.errors) { fatal(); } if (files.dim == 0 && !skipModules) { cl::PrintHelpMessage(); return EXIT_FAILURE; } #if LDC_LLVM_VER >= 301 llvm::TargetOptions targetOptions; #endif Array* libs; if (global.params.symdebug) { libs = global.params.debuglibnames; #if LDC_LLVM_VER == 300 llvm::NoFramePointerElim = true; #else targetOptions.NoFramePointerElim = true; #endif } else libs = global.params.defaultlibnames; if (!noDefaultLib) { if (libs) { for (unsigned i = 0; i < libs->dim; i++) { char* lib = static_cast<char *>(libs->data[i]); char *arg = static_cast<char *>(mem.malloc(strlen(lib) + 3)); strcpy(arg, "-l"); strcpy(arg+2, lib); global.params.linkswitches->push(arg); } } else { #if DMDV2 global.params.linkswitches->push(mem.strdup("-ldruntime-ldc")); #else global.params.linkswitches->push(mem.strdup("-lldc-runtime")); global.params.linkswitches->push(mem.strdup("-ltango-cc-tango")); global.params.linkswitches->push(mem.strdup("-ltango-gc-basic")); // pass the runtime again to resolve issues // with linking order global.params.linkswitches->push(mem.strdup("-lldc-runtime")); #endif } } if (global.params.run) quiet = 1; if (global.params.useUnitTests) global.params.useAssert = 1; // LDC output determination // if we don't link, autodetect target from extension if(!global.params.link && global.params.objname) { ext = FileName::ext(global.params.objname); bool autofound = false; if (!ext) { // keep things as they are } else if (strcmp(ext, global.ll_ext) == 0) { global.params.output_ll = OUTPUTFLAGset; autofound = true; } else if (strcmp(ext, global.bc_ext) == 0) { global.params.output_bc = OUTPUTFLAGset; autofound = true; } else if (strcmp(ext, global.s_ext) == 0) { global.params.output_s = OUTPUTFLAGset; autofound = true; } else if (strcmp(ext, global.obj_ext) == 0) { global.params.output_o = OUTPUTFLAGset; autofound = true; } else { // append dot, so forceExt won't change existing name even if it contains dots size_t len = strlen(global.params.objname); size_t extlen = strlen("."); char* s = static_cast<char *>(mem.malloc(len + 1 + extlen + 1)); memcpy(s, global.params.objname, len); s[len] = '.'; s[len+1+extlen] = 0; global.params.objname = s; } if(autofound && global.params.output_o == OUTPUTFLAGdefault) global.params.output_o = OUTPUTFLAGno; } // only link if possible if (!global.params.obj || !global.params.output_o || createStaticLib) global.params.link = 0; if (createStaticLib && createSharedLib) error("-lib and -shared switches cannot be used together"); if (createSharedLib && mRelocModel == llvm::Reloc::Default) mRelocModel = llvm::Reloc::PIC_; if (global.params.link && !createSharedLib) { global.params.exefile = global.params.objname; if (files.dim > 1) global.params.objname = NULL; } else if (global.params.run) { error("flags conflict with -run"); fatal(); } else if (global.params.objname && files.dim > 1) { if (createStaticLib || createSharedLib) { singleObj = true; } if (!singleObj) { error("multiple source files, but only one .obj name"); fatal(); } } if (soname.getNumOccurrences() > 0 && !createSharedLib) { error("-soname can be used only when building a shared library"); fatal(); } // create a proper target Ir ir; // check -m32/64 sanity if (m32bits && m64bits) error("cannot use both -m32 and -m64 options"); else if ((m32bits || m64bits) && (!mArch.empty() || !mTargetTriple.empty())) error("-m32 and -m64 switches cannot be used together with -march and -mtriple switches"); if (global.errors) fatal(); // override triple if needed std::string defaultTriple = llvm::sys::getDefaultTargetTriple(); if (sizeof(void*) == 4 && m64bits) { #if LDC_LLVM_VER >= 301 defaultTriple = llvm::Triple(defaultTriple).get64BitArchVariant().str(); #else defaultTriple = llvm::Triple__get64BitArchVariant(defaultTriple).str(); #endif } else if (sizeof(void*) == 8 && m32bits) { #if LDC_LLVM_VER >= 301 defaultTriple = llvm::Triple(defaultTriple).get32BitArchVariant().str(); #else defaultTriple = llvm::Triple__get32BitArchVariant(defaultTriple).str(); #endif } // did the user override the target triple? if (mTargetTriple.empty()) { if (!mArch.empty()) { error("you must specify a target triple as well with -mtriple when using the -march option"); fatal(); } global.params.targetTriple = defaultTriple.c_str(); } else { global.params.targetTriple = llvm::Triple::normalize(mTargetTriple).c_str(); } std::string triple = global.params.targetTriple; // Allocate target machine. const llvm::Target *theTarget = NULL; // Check whether the user has explicitly specified an architecture to compile for. if (mArch.empty()) { std::string Err; theTarget = llvm::TargetRegistry::lookupTarget(triple, Err); if (theTarget == 0) { error("%s Please use the -march option.", Err.c_str()); fatal(); } } else { for (llvm::TargetRegistry::iterator it = llvm::TargetRegistry::begin(), ie = llvm::TargetRegistry::end(); it != ie; ++it) { if (mArch == it->getName()) { theTarget = &*it; break; } } if (!theTarget) { error("invalid target '%s'", mArch.c_str()); fatal(); } } // Package up features to be passed to target/subtarget std::string FeaturesStr; if (mCPU.size() || mAttrs.size()) { llvm::SubtargetFeatures Features; for (unsigned i = 0; i != mAttrs.size(); ++i) Features.AddFeature(mAttrs[i]); FeaturesStr = Features.getString(); } // FIXME //std::auto_ptr<llvm::TargetMachine> target(theTarget->createTargetMachine(triple, FeaturesStr)); //assert(target.get() && "Could not allocate target machine!"); //gTargetMachine = target.get(); #if LDC_LLVM_VER == 300 llvm::TargetMachine* target = theTarget->createTargetMachine(triple, mCPU, FeaturesStr, mRelocModel, mCodeModel); #else llvm::TargetMachine * target = theTarget->createTargetMachine( llvm::StringRef(triple), llvm::StringRef(mCPU), llvm::StringRef(FeaturesStr), targetOptions, mRelocModel, mCodeModel, codeGenOptLevel() ); #endif gTargetMachine = target; gTargetData = target->getTargetData(); // get final data layout std::string datalayout = gTargetData->getStringRepresentation(); global.params.dataLayout = datalayout.c_str(); global.params.llvmArch = theTarget->getName(); if (strcmp(global.params.llvmArch,"x86")==0) { VersionCondition::addPredefinedGlobalIdent("X86"); global.params.isLE = true; global.params.is64bit = false; global.params.cpu = ARCHx86; if (global.params.useInlineAsm) { VersionCondition::addPredefinedGlobalIdent("D_InlineAsm_X86"); } } else if (strcmp(global.params.llvmArch,"x86-64")==0) { VersionCondition::addPredefinedGlobalIdent("X86_64"); global.params.isLE = true; global.params.is64bit = true; global.params.cpu = ARCHx86_64; if (global.params.useInlineAsm) { VersionCondition::addPredefinedGlobalIdent("D_InlineAsm_X86_64"); } } else if (strcmp(global.params.llvmArch,"ppc32")==0) { VersionCondition::addPredefinedGlobalIdent("PPC"); global.params.isLE = false; global.params.is64bit = false; global.params.cpu = ARCHppc; } else if (strcmp(global.params.llvmArch,"ppc64")==0) { VersionCondition::addPredefinedGlobalIdent("PPC64"); global.params.isLE = false; global.params.is64bit = true; global.params.cpu = ARCHppc_64; } else if (strcmp(global.params.llvmArch,"arm")==0) { VersionCondition::addPredefinedGlobalIdent("ARM"); global.params.isLE = true; global.params.is64bit = false; global.params.cpu = ARCHarm; } else if (strcmp(global.params.llvmArch,"thumb")==0) { VersionCondition::addPredefinedGlobalIdent("ARM"); VersionCondition::addPredefinedGlobalIdent("Thumb"); global.params.isLE = true; global.params.is64bit = false; global.params.cpu = ARCHthumb; } else { error("invalid cpu architecture specified: %s", global.params.llvmArch); fatal(); } // endianness if (global.params.isLE) { VersionCondition::addPredefinedGlobalIdent("LittleEndian"); } else { VersionCondition::addPredefinedGlobalIdent("BigEndian"); } // a generic 64bit version if (global.params.is64bit) { VersionCondition::addPredefinedGlobalIdent("LLVM64"); // FIXME: is this always correct? VersionCondition::addPredefinedGlobalIdent("D_LP64"); } if (mRelocModel == llvm::Reloc::PIC_) { VersionCondition::addPredefinedGlobalIdent("D_PIC"); } // parse the OS out of the target triple // see http://gcc.gnu.org/install/specific.html for details // also llvm's different SubTargets have useful information switch (llvm::Triple(triple).getOS()) { case llvm::Triple::Win32: global.params.os = OSWindows; VersionCondition::addPredefinedGlobalIdent("Windows"); VersionCondition::addPredefinedGlobalIdent("Win32"); if (global.params.is64bit) { VersionCondition::addPredefinedGlobalIdent("Win64"); } break; case llvm::Triple::MinGW32: global.params.os = OSWindows; VersionCondition::addPredefinedGlobalIdent("Windows"); VersionCondition::addPredefinedGlobalIdent("Win32"); VersionCondition::addPredefinedGlobalIdent("mingw32"); VersionCondition::addPredefinedGlobalIdent("MinGW"); if (global.params.is64bit) { VersionCondition::addPredefinedGlobalIdent("Win64"); } break; case llvm::Triple::Cygwin: error("CygWin is not yet supported"); fatal(); break; case llvm::Triple::Linux: global.params.os = OSLinux; VersionCondition::addPredefinedGlobalIdent("linux"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::Haiku: global.params.os = OSHaiku; VersionCondition::addPredefinedGlobalIdent("Haiku"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::Darwin: global.params.os = OSMacOSX; VersionCondition::addPredefinedGlobalIdent("OSX"); VersionCondition::addPredefinedGlobalIdent("darwin"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::FreeBSD: global.params.os = OSFreeBSD; VersionCondition::addPredefinedGlobalIdent("freebsd"); VersionCondition::addPredefinedGlobalIdent("FreeBSD"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; case llvm::Triple::Solaris: global.params.os = OSSolaris; VersionCondition::addPredefinedGlobalIdent("solaris"); VersionCondition::addPredefinedGlobalIdent("Solaris"); VersionCondition::addPredefinedGlobalIdent("Posix"); break; default: error("target '%s' is not yet supported", global.params.targetTriple); fatal(); } // Expose LLVM version to runtime #define STR(x) #x #define XSTR(x) STR(x) VersionCondition::addPredefinedGlobalIdent("LDC_LLVM_"XSTR(LDC_LLVM_VER)); #undef XSTR #undef STR if (global.params.os == OSWindows) { global.dll_ext = "dll"; global.lib_ext = "lib"; } else { global.dll_ext = "so"; global.lib_ext = "a"; } // added in 1.039 if (global.params.doDocComments) VersionCondition::addPredefinedGlobalIdent("D_Ddoc"); #if DMDV2 // unittests? if (global.params.useUnitTests) VersionCondition::addPredefinedGlobalIdent("unittest"); #endif // Initialization Type::init(&ir); Id::initialize(); Module::init(); initPrecedence(); backend_init(); //printf("%d source files\n",files.dim); // Build import search path if (global.params.imppath) { for (unsigned i = 0; i < global.params.imppath->dim; i++) { char *path = static_cast<char *>(global.params.imppath->data[i]); Strings *a = FileName::splitPath(path); if (a) { if (!global.path) global.path = new Strings(); global.path->append(a); } } } // Build string import search path if (global.params.fileImppath) { for (unsigned i = 0; i < global.params.fileImppath->dim; i++) { char *path = static_cast<char *>(global.params.fileImppath->data[i]); Strings *a = FileName::splitPath(path); if (a) { if (!global.filePath) global.filePath = new Strings(); global.filePath->append(a); } } } // Create Modules Modules modules; modules.reserve(files.dim); for (unsigned i = 0; i < files.dim; i++) { Identifier *id; char *ext; char *name; p = static_cast<char *>(files.data[i]); p = FileName::name(p); // strip path ext = FileName::ext(p); if (ext) { #if POSIX if (strcmp(ext, global.obj_ext) == 0 || strcmp(ext, global.bc_ext) == 0) #else if (stricmp(ext, global.obj_ext) == 0 || stricmp(ext, global.bc_ext) == 0) #endif { global.params.objfiles->push(static_cast<char *>(files.data[i])); continue; } #if POSIX if (strcmp(ext, "a") == 0) #elif __MINGW32__ if (stricmp(ext, "a") == 0) #else if (stricmp(ext, "lib") == 0) #endif { global.params.libfiles->push(static_cast<char *>(files.data[i])); continue; } if (strcmp(ext, global.ddoc_ext) == 0) { global.params.ddocfiles->push(static_cast<char *>(files.data[i])); continue; } if (FileName::equals(ext, global.json_ext)) { global.params.doXGeneration = 1; global.params.xfilename = static_cast<char *>(files.data[i]); continue; } #if !POSIX if (stricmp(ext, "res") == 0) { global.params.resfile = static_cast<char *>(files.data[i]); continue; } if (stricmp(ext, "def") == 0) { global.params.deffile = static_cast<char *>(files.data[i]); continue; } if (stricmp(ext, "exe") == 0) { global.params.exefile = static_cast<char *>(files.data[i]); continue; } #endif if (stricmp(ext, global.mars_ext) == 0 || stricmp(ext, global.hdr_ext) == 0 || stricmp(ext, "htm") == 0 || stricmp(ext, "html") == 0 || stricmp(ext, "xhtml") == 0) { ext--; // skip onto '.' assert(*ext == '.'); name = static_cast<char *>(mem.malloc((ext - p) + 1)); memcpy(name, p, ext - p); name[ext - p] = 0; // strip extension if (name[0] == 0 || strcmp(name, "..") == 0 || strcmp(name, ".") == 0) { Linvalid: error("invalid file name '%s'", static_cast<char *>(files.data[i])); fatal(); } } else { error("unrecognized file extension %s\n", ext); fatal(); } } else { name = p; if (!*name) goto Linvalid; } id = Lexer::idPool(name); m = new Module(static_cast<char *>(files.data[i]), id, global.params.doDocComments, global.params.doHdrGeneration); m->isRoot = true; modules.push(m); } // Read files, parse them for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("parse %s\n", m->toChars()); if (!Module::rootModule) Module::rootModule = m; m->importedFrom = m; m->read(0); m->parse(global.params.doDocComments); m->buildTargetFiles(singleObj); m->deleteObjFile(); if (m->isDocFile) { m->gendocfile(); // Remove m from list of modules modules.remove(i); i--; } } if (global.errors) fatal(); if (global.params.doHdrGeneration) { /* Generate 'header' import files. * Since 'header' import files must be independent of command * line switches and what else is imported, they are generated * before any semantic analysis. */ for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("import %s\n", m->toChars()); m->genhdrfile(); } } if (global.errors) fatal(); // load all unconditional imports for better symbol resolving for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("importall %s\n", m->toChars()); m->importAll(0); } if (global.errors) fatal(); // Do semantic analysis for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("semantic %s\n", m->toChars()); m->semantic(); } if (global.errors) fatal(); Module::dprogress = 1; Module::runDeferredSemantic(); // Do pass 2 semantic analysis for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("semantic2 %s\n", m->toChars()); m->semantic2(); } if (global.errors) fatal(); // Do pass 3 semantic analysis for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("semantic3 %s\n", m->toChars()); m->semantic3(); } if (global.errors) fatal(); #if !IN_LLVM // Scan for functions to inline if (global.params.useInline) { /* The problem with useArrayBounds and useAssert is that the * module being linked to may not have generated them, so if * we inline functions from those modules, the symbols for them will * not be found at link time. */ if (!global.params.useArrayBounds && !global.params.useAssert) #else // This doesn't play nice with debug info at the moment if (!global.params.symdebug && willInline()) { global.params.useAvailableExternally = true; Logger::println("Running some extra semantic3's for inlining purposes"); #endif { // Do pass 3 semantic analysis on all imported modules, // since otherwise functions in them cannot be inlined for (unsigned i = 0; i < Module::amodules.dim; i++) { m = static_cast<Module *>(Module::amodules.data[i]); if (global.params.verbose) printf("semantic3 %s\n", m->toChars()); m->semantic2(); m->semantic3(); } if (global.errors) fatal(); } #if !IN_LLVM for (int i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("inline scan %s\n", m->toChars()); m->inlineScan(); } #endif } if (global.errors || global.warnings) fatal(); // write module dependencies to file if requested if (global.params.moduleDepsFile != NULL) { assert (global.params.moduleDepsFile != NULL); File deps(global.params.moduleDepsFile); OutBuffer* ob = global.params.moduleDeps; deps.setbuffer(static_cast<void*>(ob->data), ob->offset); deps.write(); } // collects llvm modules to be linked if singleobj is passed std::vector<llvm::Module*> llvmModules; llvm::LLVMContext& context = llvm::getGlobalContext(); // Generate output files for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); if (global.params.verbose) printf("code %s\n", m->toChars()); if (global.params.obj) { llvm::Module* lm = m->genLLVMModule(context, &ir); if (!singleObj) { m->deleteObjFile(); writeModule(lm, m->objfile->name->str); global.params.objfiles->push(m->objfile->name->str); delete lm; } else llvmModules.push_back(lm); } if (global.errors) m->deleteObjFile(); else { if (global.params.doDocComments) m->gendocfile(); } } // internal linking for singleobj if (singleObj && llvmModules.size() > 0) { Module* m = static_cast<Module*>(modules.data[0]); char* name = m->toChars(); char* filename = m->objfile->name->str; llvm::Linker linker(name, name, context); std::string errormsg; for (int i = 0; i < llvmModules.size(); i++) { if(linker.LinkInModule(llvmModules[i], &errormsg)) error("%s", errormsg.c_str()); delete llvmModules[i]; } m->deleteObjFile(); writeModule(linker.getModule(), filename); global.params.objfiles->push(filename); } // output json file if (global.params.doXGeneration) json_generate(&modules); backend_term(); if (global.errors) fatal(); if (!global.params.objfiles->dim) { if (global.params.link) error("no object files to link"); else if (createStaticLib) error("no object files"); } else { if (global.params.link) status = linkObjToBinary(createSharedLib); else if (createStaticLib) createStaticLibrary(); if (global.params.run) { if (!status) { status = runExecutable(); /* Delete .obj files and .exe file */ for (unsigned i = 0; i < modules.dim; i++) { m = static_cast<Module *>(modules.data[i]); m->deleteObjFile(); } deleteExecutable(); } } } return status; }
int EditorCommand::execute(Cmdline const& cl) { #ifdef _WIN32 throw EditorNotAvailable(); #endif int argc = cl.arguments.size (); if (argc < 1) { throw invalid_argument ("wrong number of arguments, 1 needed"); } Key root = cl.createKey(0); KeySet ours; KDB kdb; kdb.get (ours, root); KeySet oursToEdit = ours.cut (root); // export it to file string format = cl.format; if (argc > 1) format = cl.arguments[1]; Modules modules; PluginPtr plugin = modules.load(format); tmpFile(); if (cl.verbose) std::cout << "filename set to " << filename << std::endl; Key errorKey(root); errorKey.setString(filename); if (plugin->set(oursToEdit, errorKey) == -1) { printWarnings(cerr, errorKey); printError(cerr, errorKey); return 11; } printWarnings(cerr, errorKey); // start editor if (cl.verbose) std::cout << "running editor with " << filename << std::endl; if (!cl.editor.empty()) { if (!runEditor (cl.editor, filename)) { std::cerr << "Could not run editor " << cl.editor << std::endl; return 12; } } else { if (!runAllEditors(filename)) { std::cerr << "Could not run any editor, please change /sw/elektra/kdb/#0/current/editor" << std::endl; return 12; } } // import from the file KeySet importedKeys; plugin->get(importedKeys, errorKey); importedKeys = importedKeys.cut(root); printWarnings (cerr, errorKey); printError (cerr, errorKey); ThreeWayMerge merger; MergeHelper helper; helper.configureMerger (cl, merger); MergeResult result = merger.mergeKeySet ( MergeTask (BaseMergeKeys (oursToEdit, root), OurMergeKeys (oursToEdit, root), TheirMergeKeys (importedKeys, root), root)); helper.reportResult (cl, result, cout, cerr); int ret = 13; if (!result.hasConflicts ()) { if (cl.verbose) { cout << "The merged keyset with strategy " << cl.strategy << " is:" << endl; cout << result.getMergedKeys(); } KeySet resultKeys = result.getMergedKeys(); if (cl.verbose) std::cout << "about to write result keys " << resultKeys << std::endl; ours.append(resultKeys); kdb.set (ours, root); if (cl.verbose) std::cout << "successful, cleaning up " << filename << std::endl; unlink(filename.c_str()); ret = 0; } else { std::cout << "Import not successful, please import and remove \"" << filename << '"' << std::endl; } return ret; }
void mbbarplot() { const Int_t nx = 207; const Int_t np = 26; char *collections[nx+1]; collections[np-1]="All Other Modules"; double sum = 0.; double sum25 = 0.; double collectionV[nx+1]; collectionV[np-1]=sum-sum25; Modules modules; char ch; string line[nx]; string stringcoll[nx]; char collv1[nx+1][200]; char collv2[nx+1][200]; char collv3[nx+1][200]; char collv4[nx+1][200]; double vcollv1[nx+1]; double vcollv2[nx+1]; ifstream myfile ("timingmb.txt"); if (myfile.is_open()){ for(int i=0; i<nx; i++){ int ich=0; int icoll=0; int icollv1=0; int icollv2=0; int icollv3=0; int icollv4=0; int ispace=0; getline(myfile, line[i]); collections[i]=line[i].c_str(); cout<<collections[i]<<endl; while (collections[i][ich]){ ch=collections[i][ich]; if(isspace(ch)) { ch='\n'; ispace++; } if(ispace==0){ collv1[i][icollv1]=collections[i][ich]; icollv1++; } if(ispace==3){ collv2[i][icollv2]=collections[i][ich+1]; icollv2++; } if(ispace==8){ collv3[i][icollv3]=collections[i][ich+1]; icollv3++; } if(ispace==10){ collv4[i][icollv4]=collections[i][ich+1]; icollv4++; } //putchar(ch); ich++; } //coll[i][icoll-1]='\0'; //collv1[i][icollv1-1]='\0'; //collv2[i][icollv2-1]='\0'; cout<<collv1[i]<<" "<<atof(collv2[i])<<" "<<atof(collv3[i])<<" "<<collv4[i]<<endl; modules.SetReportName(string(collv1[i])); modules.SetPerEventTiming(atof(collv2[i])); modules.SetPerVisitTiming(atof(collv3[i])); modules.SetModuleName(string(collv4[i])); //modules[i].(); //cout<<modules[i].GetReportName()<<", "<<modules[i].GetPerEventTiming()<<", "<<modules[i].GetPerVisitTiming()<<", "<<modules[i].GetModuleName()<<endl; cout<<modules.GetReportName()<<", "<<modules.GetPerEventTiming()<<", "<<modules.GetPerVisitTiming()<<", "<<modules.GetModuleName()<<endl; /* stringcoll[i]=string(coll[i]); if(i<np-1)cout<<"stringcoll="<<stringcoll[i]<<endl; vcollv1[i]=atof(collv1[i]); vcollv2[i]=atof(collv2[i]); if(i<np-1) sum25+=vcollv2[i]; sum+=vcollv2[i]; */ } } //cout<<"sum = "<<sum25<<", "<<sum<<endl; //cout<<endl; //stringcoll[np-1]="All Other Modules"; //vcollv2[np-1]=sum-sum25; /* double percent[nx]; TH1D *h0 = new TH1D("h0","",26,0,26); for (int i=0; i<nx; i++) { percent[i]=collectionV[i]*100.0/sum; //h0->Fill(collections[i], collectionV[i]); h0->Fill(collections[i], percent[i]); } h0->SetStats(0); h0->SetFillColor(2); h0->SetBarWidth(0.8); h0->SetBarOffset(0.1); h0->GetYaxis()->SetTitle("Time in percent (%)"); h0->GetYaxis()->SetTitleOffset(1.1); h0->GetYaxis()->CenterTitle(); h0->SetTickLength(0.01); h0->SetMaximum(16); //h0->GetXaxis()->SetUserRange(-0.5, 29.5); TCanvas *c1 = new TCanvas("c1","c1",880,660); gPad->SetGrid(); //gPad->SetLogx(); gPad->SetTicks(); gPad->SetBottomMargin(0.09); gPad->SetLeftMargin(0.30); gPad->SetRightMargin(0.02); gPad->SetTopMargin(0.05); h0->Draw("hbar0"); TLatex tex(0.5,0.5,"u"); tex.SetTextFont(42); tex.SetTextSize(0.04); tex.SetNDC(); tex.DrawLatex(0.555, 0.72, "Timing in the reconstruction step"); tex.DrawLatex(0.555, 0.655, "MiniBias AOD"); c1->SaveAs("timingMBAOD_300events.png"); */ }
int InfoCommand::execute (Cmdline const & cl) { std::string subkey; if (cl.arguments.size () == 1) { } else if (cl.arguments.size () == 2) { subkey = cl.arguments[1]; } else { throw invalid_argument ("Need at 1 or 2 argument(s)"); } std::string name = cl.arguments[0]; KeySet conf; Key parentKey (std::string ("system/elektra/modules/") + name, KEY_END); if (!cl.load) { kdb.get (conf, parentKey); } if (!conf.lookup (parentKey)) { if (!cl.load) { cerr << "Module does not seem to be loaded." << endl; cerr << "Now in fallback code. Will directly load config from plugin." << endl; } Modules modules; KeySet ks = cl.getPluginsConfig (); PluginPtr plugin; if (ks.size () == 0) { plugin = modules.load (name); } else { plugin = modules.load (name, ks); } conf.append (plugin->getInfo ()); } Key root (std::string ("system/elektra/modules/") + name + "/exports", KEY_END); if (!subkey.empty ()) { root.setName (std::string ("system/elektra/modules/") + name + "/infos/" + subkey); Key k = conf.lookup (root); if (k) { cout << k.getString () << std::endl; return 0; } else { cerr << "clause not found" << std::endl; return 1; } } root.setName (std::string ("system/elektra/modules/") + name + "/exports"); Key k = conf.lookup (root); if (k) { cout << "Exported symbols: "; while ((k = conf.next ()) && k.isBelow (root)) { cout << k.getBaseName () << " "; } cout << endl; } else cout << "no exported symbols found" << endl; root.setName (std::string ("system/elektra/modules/") + name + "/infos"); k = conf.lookup (root); if (k) { while ((k = conf.next ()) && k.isBelow (root)) { cout << k.getBaseName () << ": " << k.getString () << endl; } } else cout << "no information found" << endl; return 0; }
Try<Nothing> ModuleManager::load(const Modules& modules) { Lock lock(&mutex); initialize(); foreach (const Modules::Library& library, modules.libraries()) { string libraryName; if (library.has_file()) { libraryName = library.file(); } else if (library.has_name()) { libraryName = os::libraries::expandName(library.name()); } else { return Error("Library name or path not provided"); } if (!dynamicLibraries.contains(libraryName)) { Owned<DynamicLibrary> dynamicLibrary(new DynamicLibrary()); Try<Nothing> result = dynamicLibrary->open(libraryName); if (!result.isSome()) { return Error( "Error opening library: '" + libraryName + "': " + result.error()); } dynamicLibraries[libraryName] = dynamicLibrary; } // Load module manifests. foreach (const Modules::Library::Module& module, library.modules()) { if (!module.has_name()) { return Error( "Error: module name not provided with library '" + libraryName + "'"); } // Check for possible duplicate module names. const std::string moduleName = module.name(); if (moduleBases.contains(moduleName)) { return Error("Error loading duplicate module '" + moduleName + "'"); } // Load ModuleBase. Try<void*> symbol = dynamicLibraries[libraryName]->loadSymbol(moduleName); if (symbol.isError()) { return Error( "Error loading module '" + moduleName + "': " + symbol.error()); } ModuleBase* moduleBase = (ModuleBase*) symbol.get(); // Verify module compatibility including version, etc. Try<Nothing> result = verifyModule(moduleName, moduleBase); if (result.isError()) { return Error( "Error verifying module '" + moduleName + "': " + result.error()); } moduleBases[moduleName] = (ModuleBase*) symbol.get(); // Now copy the supplied module-specific parameters. moduleParameters[moduleName].mutable_parameter()->CopyFrom( module.parameters()); } } return Nothing(); }
MvcBuilder() { _container = ObjectContainer::createContainer(); _modules.setContainer(_container); }
void _prepare() { ObjectContainer* container = _container; _modules.prepare(); _mainModule->onDestroy([=]() {ObjectContainer::releaseContainer(container);}); }