Exemple #1
0
        static TestProcess()
        {
            var descriptor = ProcessDescriptor.CreateDescriptor <TestProcess, TestProcessState>();

            descriptor.AddAcceptedMessage(typeof(TestEvent));
            Descriptor = descriptor;
        }
Exemple #2
0
 private void SetLocalProperties(string organizationName, string applicationName, string hostName, int port)
 {
     LocalCoreRegistryRepository          = new ApplicationRegistrationRepository();
     LocalCoreRegistryRepository.Database = new SQLiteDatabase(WorkspaceDirectory, nameof(CoreClient));
     CoreServiceRegistryContainer.GetServiceRegistry().Get <IStorableTypesProvider>().AddTypes(LocalCoreRegistryRepository);
     ProcessDescriptor = ProcessDescriptor.ForApplicationRegistration(LocalCoreRegistryRepository, hostName, port, applicationName, organizationName);
 }
Exemple #3
0
        private void InitializeCoFSMs()
        {
            ProcessDescriptor pd = _code as ProcessDescriptor;

            if (pd != null)
            {
                TransactingComponent.TATarget[] coFSMs = pd.Instance.GetCoFSMs();
                if (coFSMs != null)
                {
                    foreach (TransactingComponent.TATarget target in coFSMs)
                    {
                        CoFSMInfo cfi = new CoFSMInfo();
                        _coFSMs[target.Target] = cfi;
                        if (target.NeutralTA != null)
                        {
                            cfi.HasNeutralTA = true;
                            AddCoStates(-1, LocalVariableState.Empty, target.NeutralTA);
                        }
                        else
                        {
                            cfi.HasNeutralTA = false;
                        }
                    }
                }
            }
        }
        public override CoreServiceResponse <ApplicationRegistration.Application> LimitNotReachedAction()
        {
            string       ApplicationName = ProcessDescriptor.Application.Name;
            Organization org             = User.Organizations.Where(o => o.Name.Equals(OrganizationName)).FirstOrDefault();

            ApplicationRegistration.Application app = CoreRegistryRepository.OneApplicationWhere(c => c.Name == ApplicationName && c.OrganizationId == org.Id);
            if (app == null)
            {
                app = new ApplicationRegistration.Application {
                    Name = ApplicationName, OrganizationId = org.Id
                };
                app = CoreRegistryRepository.Save(app);
                ProcessDescriptor instance = new ProcessDescriptor {
                    InstanceIdentifier = $"{ClientIpAddress}-{app.Name}-{app.Cuid}"
                };
                app.Instances.Add(instance);
                app.Machines.Add(new Machine {
                    Name = HostName
                });
                app = CoreApplicationRegistryService.AddApiKey(CoreRegistryRepository, app);
                return(new CoreServiceResponse <ApplicationRegistration.Application>(app)
                {
                    Success = true, Message = $"Application {ApplicationName} created"
                });
            }
            else
            {
                return(new CoreServiceResponse <ApplicationRegistration.Application>(app)
                {
                    Success = true, Message = $"Application {ApplicationName} already registered for the organization {OrganizationName}"
                });
            }
        }
Exemple #5
0
        public virtual CoreServiceResponse RegisterApplicationProcess(ProcessDescriptor descriptor)
        {
            try
            {
                Args.ThrowIfNull(descriptor?.Application?.Name, "descriptor.Application.Name");
                Args.ThrowIfNull(descriptor?.Application?.Organization?.Name, "descriptor.Application.Organization.Name");

                if (CurrentUser.Equals(UserAccounts.Data.User.Anonymous))
                {
                    return(new CoreServiceResponse <ApplicationRegistrationResult> {
                        Success = false, Message = "You must be logged in to do that", Data = new ApplicationRegistrationResult {
                            Status = ApplicationRegistrationStatus.Unauthorized
                        }
                    });
                }
                User user = GetApplicationRegistrationRepositoryUser();

                string organizationName = descriptor.Application.Organization.Name;
                CoreServiceResponse <Organization> response = AssociateUserToOrganization(user, organizationName);
                if (!response.Success)
                {
                    return(response);
                }

                ClientApplicationFactory appFactory = new ClientApplicationFactory(this, user, organizationName, descriptor);
                return(GetApplicationRegistrationResponse(appFactory));
            }
            catch (Exception ex)
            {
                Logger.AddEntry("Exception occurred in {0}", ex, nameof(ApplicationRegistrationService.RegisterApplicationProcess));
                return(new CoreServiceResponse {
                    Success = false, Message = ex.Message
                });
            }
        }
Exemple #6
0
        static void Main(string[] args)
        {
            Testbench tb = new Testbench();

            DesignContext.Instance.Elaborate();
            DesignContext.Instance.Simulate(101 * Testbench.ClockPeriod);

            // Now convert the design to VHDL and embed it into a Xilinx ISE project
            XilinxProject project_SC = new XilinxProject(@".\SystemC_output", "SimpleCounter");

            project_SC.PutProperty(EXilinxProjectProperties.DeviceFamily, EDeviceFamily.Spartan3);
            project_SC.PutProperty(EXilinxProjectProperties.Device, EDevice.xc3s1500l);
            project_SC.PutProperty(EXilinxProjectProperties.Package, EPackage.fg676);
            project_SC.PutProperty(EXilinxProjectProperties.SpeedGrade, ESpeedGrade._4);
            project_SC.PutProperty(EXilinxProjectProperties.PreferredLanguage, EHDL.VHDL);

            SystemCGenerator codeGen_SC = new SystemCGenerator();

            SynthesisEngine.Create(DesignContext.Instance, project_SC).Synthesize(codeGen_SC);
            project_SC.Save();

            DesignContext.Instance.CompleteAnalysis();

            // The actual compilation steps start here.
            ProcessDescriptor euclid = tb.Descriptor.FindComponent("_gcd").FindProcess("Euclid");
            XIL3Function      asm    = euclid.Implementation.Compile(DefaultInstructionSet.Instance).ToXIL3();

            Console.WriteLine(asm);
        }
Exemple #7
0
        private void DecompileStates()
        {
            ProcessDescriptor pd = (ProcessDescriptor)_code;

            _templ = new MSILDecompilerTemplate()
            {
                Instance                 = pd.Instance.Owner,
                ArgumentValues           = new object[0],
                Decompilee               = _code,
                Method                   = _code.Method,
                Code                     = MethodCode.Create(_code.Method),
                DisallowReturnStatements = true,
                NestLoopsDeeply          = true,
                TryToEliminateLoops      = true,
                DisallowConditionals     = true
            };
            LocalVariableState initialState = _templ.ExportLocalVariableState();

            GetStateInfo(_dissectionPoints[0], initialState);

            while (_stateWorkQueue.Any())
            {
                StateInfo      si     = _stateWorkQueue.Dequeue();
                MSILDecompiler decomp = new MSILDecompiler(_code, si.CFG, _instance)
                {
                    Template = _templ
                };
                _templ.AddAttribute(this);
                _templ.ImportLocalVariableState(si.LVState);
                IDecompilationResult result = decomp.Decompile();
                si.StateFun = result.Decompiled;
                _calledMethods.AddRange(result.CalledMethods);
                _referencedFields.AddRange(result.ReferencedFields);
            }
        }
Exemple #8
0
        public IDecompilationResult Transform()
        {
            ProcessDescriptor      pd    = _code as ProcessDescriptor;
            FSMTransformerTemplate templ =
                new FSMTransformerTemplate(_context, _code, _instance, _arguments);
            Function body = templ.GetAlgorithm();

            _code.Implementation = body;
            foreach (var tup in templ.CoFSMs)
            {
                CoFSMInfo cfi = tup.Item2;
                cfi.Sensitivity.Add(cfi.CoStateSignal.Desc);
                FSMCombTemplate   cotempl = new FSMCombTemplate(cfi);
                Function          comb    = cotempl.GetAlgorithm();
                string            name    = _code.Name + "$comb";
                ProcessDescriptor pdcomb  = new ProcessDescriptor(name)
                {
                    Kind                  = Process.EProcessKind.Triggered,
                    Implementation        = comb,
                    GenuineImplementation = body,
                    Sensitivity           = cfi.Sensitivity.ToArray()
                };
                _code.Owner.AddChild(pdcomb, name);
            }
            return(templ);
        }
Exemple #9
0
        protected ConventionProcess()
        {
            var processType = GetType();

            _transitionRouter = new ConventionProcessMessageRouter <TState>(processType);
            _descriptor       = ProcessDescriptor.ScanByConvention(processType);
        }
Exemple #10
0
        public virtual CoreServiceResponse RegisterApplication(ProcessDescriptor descriptor)
        {
            try
            {
                Args.ThrowIfNull(descriptor?.Application?.Name, "descriptor.Application.Name");
                Args.ThrowIfNull(descriptor?.Application?.Organization?.Name, "descriptor.Application.Organization.Name");

                string organizationName = descriptor.Application.Organization.Name;
                if (CurrentUser.Equals(UserAccounts.Data.User.Anonymous))
                {
                    return(new CoreServiceResponse <ApplicationRegistrationResult> {
                        Success = false, Message = "You must be logged in to do that", Data = new ApplicationRegistrationResult {
                            Status = ApplicationRegistrationStatus.Unauthorized
                        }
                    });
                }
                User user = CoreRegistryRepository.OneUserWhere(c => c.UserName == CurrentUser.UserName);
                if (user == null)
                {
                    user = new User()
                    {
                        UserName = CurrentUser.UserName,
                        Email    = CurrentUser.Email
                    };
                    user = CoreRegistryRepository.Save(user);
                }
                OrganizationFactory orgEnforcer             = new OrganizationFactory(CoreRegistryRepository, user, organizationName);
                CoreServiceResponse <Organization> response = orgEnforcer.Execute();
                if (!response.Success)
                {
                    return(response);
                }
                Organization             org         = response.TypedData();
                ClientApplicationFactory appEnforcer = new ClientApplicationFactory(this, user, organizationName, descriptor);
                CoreServiceResponse <ApplicationRegistration.Application> appResponse = appEnforcer.Execute();
                if (appResponse.Success)
                {
                    ApplicationRegistration.Application app = appResponse.TypedData();
                    return(new CoreServiceResponse <ApplicationRegistrationResult>(
                               new ApplicationRegistrationResult
                    {
                        Status = ApplicationRegistrationStatus.Success,
                        ClientId = app.Cuid,
                        ApiKey = app.ApiKeys.First().SharedSecret
                    })
                    {
                        Success = true
                    });
                }
                return(appResponse);
            }
            catch (Exception ex)
            {
                Logger.AddEntry("Exception occurred in {0}", ex, nameof(CoreApplicationRegistrationService.RegisterApplication));
                return(new CoreServiceResponse {
                    Success = false, Message = ex.Message
                });
            }
        }
Exemple #11
0
 public HLSState(HLSPlan plan, DesignContext design, Component host, ProcessDescriptor proc, IProject proj)
 {
     _plan   = plan;
     _design = design;
     _host   = host;
     _proc   = proc;
     _proj   = proj;
 }
Exemple #12
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="processId"></param>
 /// <param name="process"></param>
 /// <returns></returns>
 public bool TryGetProcess(Guid processId, out ProcessDescriptor process)
 {
     if (!_initialized)
     {
         Init();
     }
     return(_dic.TryGetValue(processId, out process));
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="process"></param>
 public DefaultExecutor(ProcessDescriptor process)
 {
     if (process == null)
     {
         throw new ArgumentNullException("process");
     }
     this.Process  = process;
     this.Ontology = Process.Ontology;
 }
Exemple #14
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="process"></param>
 public DefaultExecutor(ProcessDescriptor process)
 {
     if (process == null)
     {
         throw new ArgumentNullException("process");
     }
     this.Process = process;
     this.Ontology = Process.Ontology;
 }
Exemple #15
0
        public override IDecompilationResult Rewrite(DesignContext ctx, CodeDescriptor code, object instance, object[] arguments)
        {
            ProcessDescriptor pd = (ProcessDescriptor)code;

            pd.Kind = Process.EProcessKind.Triggered;
            FSMTransformer trans = new FSMTransformer(ctx, code, instance, arguments);

            return(trans.Transform());
        }
 public ClientApplicationFactory(CoreApplicationRegistrationService service, ApplicationRegistration.User user, string organizationName, ProcessDescriptor processDescriptor)
 {
     CoreApplicationRegistryService = service;
     User = user;
     CoreRegistryRepository = service.CoreRegistryRepository;
     OrganizationName       = organizationName;
     ProcessDescriptor      = processDescriptor;
     ClientIpAddress        = service.ClientIpAddress;
     HostName = service.HostName;
 }
Exemple #17
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="process"></param>
 public DefaultDispatcher(ProcessDescriptor process)
 {
     if (process == null)
     {
         throw new ArgumentNullException("process");
     }
     this._acDomain = process.AcDomain;
     this.Process   = process;
     this.Ontology  = process.Ontology;
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="process"></param>
 public DefaultDispatcher(ProcessDescriptor process)
 {
     if (process == null)
     {
         throw new ArgumentNullException("process");
     }
     this._acDomain = process.AcDomain;
     this.Process = process;
     this.Ontology = process.Ontology;
 }
Exemple #19
0
        public void CoreApplicationRegistryServiceMustBeLoggedInToRegister()
        {
            CoreApplicationRegistrationService svc = GetTestService();
            string              orgName            = 5.RandomLetters();
            string              appName            = 8.RandomLetters();
            ProcessDescriptor   descriptor         = ProcessDescriptor.ForApplicationRegistration(svc.CoreRegistryRepository, "localhost", 8080, appName, orgName);
            CoreServiceResponse response           = svc.RegisterApplication(descriptor);

            Expect.IsFalse(response.Success);
            Expect.IsNotNull(response.Data);
            Expect.IsInstanceOfType <ApplicationRegistrationResult>(response.Data);
            Expect.AreEqual(ApplicationRegistrationStatus.Unauthorized, ((ApplicationRegistrationResult)response.Data).Status);
        }
Exemple #20
0
            public void Handle(UpdateProcessCommand message)
            {
                var acDomain          = _set._acDomain;
                var processRepository = _set._acDomain.RetrieveRequiredService <IRepository <Process, Guid> >();

                if (!acDomain.NodeHost.Processs.ContainsProcess(message.Input.Id))
                {
                    throw new NotExistException();
                }
                var entity = processRepository.GetByKey(message.Input.Id);

                if (entity == null)
                {
                    throw new NotExistException();
                }
                var bkState = _set._dic[entity.Id];

                entity.Update(message.Input);

                var  newState     = new ProcessDescriptor(acDomain, ProcessState.Create(entity), entity.Id);
                bool stateChanged = newState != bkState;

                lock (Locker)
                {
                    if (stateChanged)
                    {
                        Update(newState);
                    }
                }
                try
                {
                    processRepository.Update(entity);
                    processRepository.Context.Commit();
                }
                catch
                {
                    if (stateChanged)
                    {
                        Update(bkState);
                    }
                    processRepository.Context.Rollback();
                    throw;
                }
                if (stateChanged)
                {
                    _set._acDomain.PublishEvent(new ProcessUpdatedEvent(message.AcSession, entity));
                    _set._acDomain.CommitEventBus();
                }
            }
Exemple #21
0
 public static ProcessTr Create(ProcessDescriptor process)
 {
     return(new ProcessTr(process.AcDomain)
     {
         CreateOn = process.Process.CreateOn,
         Id = process.Process.Id,
         IsEnabled = process.Process.IsEnabled,
         Name = process.Process.Name,
         NetPort = process.Process.NetPort,
         OntologyId = process.Process.OntologyId,
         CatalogCode = process.Process.CatalogCode,
         Type = process.Process.Type,
         WebApiBaseAddress = process.WebApiBaseAddress
     });
 }
Exemple #22
0
 public ServiceSelfHost(Anycmd.IAcDomain acDomain, ProcessDescriptor process)
     : base("Self-Host", typeof(MessageService).Assembly)
 {
     if (acDomain == null)
     {
         throw new ArgumentNullException("acDomain");
     }
     if (process == null)
     {
         throw new ArgumentNullException("process");
     }
     this._acDomain   = acDomain;
     this._process    = process;
     this.ServiceName = process.ProcessType.ToName() + " - " + process.Process.Name;
 }
Exemple #23
0
 public ServiceSelfHost(Anycmd.IAcDomain acDomain, ProcessDescriptor process)
     : base("Self-Host", typeof(MessageService).Assembly)
 {
     if (acDomain == null)
     {
         throw new ArgumentNullException("acDomain");
     }
     if (process == null)
     {
         throw new ArgumentNullException("process");
     }
     this._acDomain = acDomain;
     this._process = process;
     this.ServiceName = process.ProcessType.ToName() + " - " + process.Process.Name;
 }
Exemple #24
0
        public int CompleteExecution(Guid procElUId, List <CompleteParameter> parameters)
        {
            UserConnection userConnection = UserConnection;
            IProcessEngine processEngine  = userConnection.ProcessEngine;

            try {
                BaseProcessSchemaElement    schemaElement = processEngine.GetSchemaElement(procElUId);
                Dictionary <string, object> nameValues    = GetSchemaParameterValues(userConnection, schemaElement, parameters);
                ProcessDescriptor           descriptor    = processEngine.CompleteExecuting(procElUId, nameValues);
                return(descriptor.WaitingUserTasksCount);
            } catch (Terrasoft.Common.ItemNotFoundException) {
                _log.Warn($"Attempt to complete the process element with Id '{procElUId}', but that element was not found.");
                return(-1);
            }
        }
        private void AnalyzeProcess(Process process)
        {
            Action     func   = process.InitialAction;
            MethodInfo method = func.Method;
            List <ISignalOrPortDescriptor> sens = new List <ISignalOrPortDescriptor>();

            if (process.Sensitivity != null)
            {
                foreach (EventSource e in process.Sensitivity)
                {
                    DesignObject owner = e.Owner;
                    if (!(owner is SignalBase))
                    {
                        _context.Report(EIssueClass.Error,
                                        "Process " + method.Name + " is sensitive to an event which is not owned by " +
                                        "a signal. This is currently not supported by the behavioral model.");
                    }
                    else
                    {
                        var signal = (SignalBase)owner;
                        var spdesc = signal.Descriptor;
                        if (spdesc == null)
                        {
                            throw new InvalidOperationException();
                        }
                        var sref = spdesc.AsSignalRef(SignalRef.EReferencedProperty.Instance)
                                   .RelateToComponent(process.Owner.Descriptor);
                        if (sref == null)
                        {
                            ReportError("Did not find a matching port for signal " + signal.Descriptor.Name);
                        }
                        else
                        {
                            sens.Add(sref.Desc);
                        }
                    }
                }
            }
            ProcessDescriptor pd = new ProcessDescriptor(method, process)
            {
                Sensitivity = sens.ToArray(),
                Owner       = process.Owner.Descriptor
            };

            //DecompileAndEnqueueCallees(pd, process.Owner, new object[] { process.Owner });
            DecompileAndEnqueueCallees(pd, func.Target, new object[] { process.Owner });
            process.Owner.Descriptor.AddChild(pd, method.Name);
        }
Exemple #26
0
        /// <summary>
        /// Creates and adds a new symbolic process (i.e. without specification of behavior).
        /// </summary>
        /// <param name="me">component descriptor to host the new process</param>
        /// <param name="kind">kind of process</param>
        /// <param name="name">name of the new process</param>
        /// <param name="sensitivity">sensitivity list of the new process</param>
        /// <returns>the descriptor of the new process</returns>
        public static ProcessDescriptor CreateProcess(this IComponentDescriptor me,
                                                      Process.EProcessKind kind, string name, params ISignalOrPortDescriptor[] sensitivity)
        {
            Contract.Requires <ArgumentNullException>(me != null);
            Contract.Requires <ArgumentNullException>(name != null);
            Contract.Requires <ArgumentNullException>(sensitivity != null);

            ProcessDescriptor pd = new ProcessDescriptor(name)
            {
                Kind        = kind,
                Sensitivity = sensitivity
            };

            me.AddChild(pd, pd.Name);
            return(pd);
        }
Exemple #27
0
        public void OrganizationGetsCreated()
        {
            Log.Default = new ConsoleLogger();
            Log.Default.StartLoggingThread();
            string userName = 4.RandomLetters();
            string orgName  = 5.RandomLetters();
            string appName  = 8.RandomLetters();
            CoreApplicationRegistrationService svc = GetTestServiceWithUser(userName);
            ProcessDescriptor   descriptor         = ProcessDescriptor.ForApplicationRegistration(svc.CoreRegistryRepository, "localhost", 8080, appName, orgName);
            CoreServiceResponse response           = svc.RegisterApplication(descriptor);

            Expect.IsTrue(response.Success);
            var user = svc.CoreRegistryRepository.OneUserWhere(c => c.UserName == userName);

            user = svc.CoreRegistryRepository.Retrieve <ApplicationRegistration.User>(user.Id);
            Expect.IsNotNull(user);
            Expect.AreEqual(1, user.Organizations.Count);
            Thread.Sleep(1000);
            Pass($"{nameof(OrganizationGetsCreated)} Test Passed");
        }
 public IRemoteServerProcess StartProcess(ProcessInfo processInfo, out int processID)
 {
     try
     {
         var          channel = GetServiceInterface();
         IAsyncResult result  = channel.BeginStartProcess(_sessionDescriptor.Handle, processInfo, null, null);
         result.AsyncWaitHandle.WaitOne();
         ProcessDescriptor processDescriptor = channel.EndStartProcess(result);
         processID = processDescriptor.ID;
         return(new ClientProcess(this, processInfo, processDescriptor));
     }
     catch (FaultException <DataphorFault> fault)
     {
         throw DataphorFaultUtility.FaultToException(fault.Detail);
     }
     catch (CommunicationException ce)
     {
         ReportCommunicationError();
         throw new ServerException(ServerException.Codes.CommunicationFailure, ErrorSeverity.Environment, ce);
     }
 }
Exemple #29
0
 public void MustBeLoggedInToRegister()
 {
     After.Setup((Action <SetupContext>)(ctx =>
     {
         ctx.CopyFrom((Incubation.Incubator)CoreServiceRegistryContainer.GetServiceRegistry());
     }))
     .WhenA <CoreApplicationRegistrationService>("tries to register application when not logged in", cars =>
     {
         ProcessDescriptor descriptor = ProcessDescriptor.ForApplicationRegistration(cars.CoreRegistryRepository, "localhost", 8080, "testApp", "testOrg");
         return(cars.RegisterApplication(descriptor));
     })
     .TheTest
     .ShouldPass(because =>
     {
         CoreServiceResponse result = because.ResultAs <CoreServiceResponse>();
         because.ItsTrue("the response was not successful", !result.Success, "request should have failed");
         because.ItsTrue("the message says 'You must be logged in to do that'", result.Message.Equals("You must be logged in to do that"));
         because.IllLookAtIt(result.Message);
     })
     .SoBeHappy()
     .UnlessItFailed();
 }
Exemple #30
0
        public virtual void OnDecompilation(MSILDecompilerTemplate decomp)
        {
            ProcessDescriptor pd = decomp.Decompilee as ProcessDescriptor;

            if (pd == null)
            {
                throw new InvalidOperationException("HLS for " + decomp.Decompilee.Name + " not possible: ain't a process");
            }

            PropertyInfo planProp = null;

            if (_planPropName != null)
            {
                planProp = pd.Method.DeclaringType.GetProperty(_planPropName);
                if (planProp == null && pd.AsyncMethod != null)
                {
                    planProp = pd.AsyncMethod.DeclaringType.GetProperty(_planPropName);
                }
                if (planProp == null)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendFormat("HLS error: declaring type {0} does not define property {1} defining the HLS plan",
                                    pd.Method.DeclaringType.Name, _planPropName);
                    throw new InvalidOperationException(sb.ToString());
                }
            }
            DesignContext.Instance.QueueRefinement(new Refinement(pd, planProp));

            decomp.AddAttribute(this);
            decomp.DisallowConditionals = false;

            // FIXME: Does it always make sense? Currently just a hack to get PhysicalModels working...
            // Answer: No, it doesn't make sense. To many loops need to be instrumented by ProgramFlow.DoNotUnroll()
            // ==> very error-prone...
            // decomp.TryToEliminateLoops = true;
        }
Exemple #31
0
 public ClientProcess(ClientSession clientSession, ProcessInfo processInfo, ProcessDescriptor processDescriptor)
 {
     _clientSession     = clientSession;
     _processInfo       = processInfo;
     _processDescriptor = processDescriptor;
 }
Exemple #32
0
 public HLSState(HLSPlan plan, DesignContext design, Component host, ProcessDescriptor proc, IProject proj)
 {
     _plan = plan;
     _design = design;
     _host = host;
     _proc = proc;
     _proj = proj;
 }
Exemple #33
0
        private void DeclareProcess(ProcessDescriptor pd, IndentedTextWriter tw)
        {
            bool simuOnly = pd.HasAttribute<SimulationOnly>();
            if (simuOnly)
                SwitchOffSynthesis(tw);

            string pname = MakeIDName(pd.Name, pd);
            tw.WriteLine("void " + pname + "()");
            tw.WriteLine("{");

            for (int i = 0; i < pd.Implementation.LocalVariables.Count; i++)
            {
                var local = pd.Implementation.LocalVariables[i];
                string typestr = GetTypeDescriptorCompletedName(local.Type);
                string varname = MakeIDName(local.Name, local);
                //if(typestr == "int")
                //    tw.Write("static const " + typestr + " " + varname + "// initialization missing!!!");
                //else
                    tw.Write("static " + typestr + " " + varname);
                if (pd.ValueRangeConstraints[i].IsConstrained)
                {
                    CodeDescriptor.ValueRangeConstraint vrc = pd.ValueRangeConstraints[i];
                    tw.Write("<" + (Math.Log(Math.Max(Math.Abs(vrc.MaxValue), Math.Abs(vrc.MinValue))) / Math.Log(2) + 1) + ">");
                }
                else
                {
                    TypeInfo ti;
                    if (LookupType(local.Type.CILType, out ti) &&
                        ti.RangeSpec == TypeInfo.ERangeSpec.ByRange &&
                        ti.ShowDefaultRange)
                    {
                        //tw.Write(" <" + (ti.DefaultRange.SecondBound - ti.DefaultRange.FirstBound + 1) + ">");
                        tw.Write(" [" + (ti.DefaultRange.SecondBound - ti.DefaultRange.FirstBound + 1) + "]");
                    }
                }
                tw.WriteLine(";");
            }

            if (pd.Kind == Components.Process.EProcessKind.Threaded)
            {
                tw.Indent++;
                tw.WriteLine("while(true)");
                tw.WriteLine("{");
                GenerateMethodBody(pd, tw);
                tw.WriteLine("}");
                tw.Indent--;
            }
            else
                GenerateMethodBody(pd, tw);

            tw.WriteLine("}");

            if (simuOnly)
                SwitchOnSynthesis(tw);
        }
Exemple #34
0
        private void GenerateMethodBody(ProcessDescriptor cd, IndentedTextWriter tw)
        {
            _sim.PushScope();
            //tw.WriteLine("// Local Variables");
            //tw.Indent++;
            //for (int i = 0; i < cd.Implementation.LocalVariables.Count; i++)
            //{
            //    var local = cd.Implementation.LocalVariables[i];
            //    string typestr = GetTypeDescriptorCompletedName(local.Type);
            //    string varname = MakeIDName(local.Name, local);
            //    tw.Write(typestr + " " + varname);
            //    if (cd.ValueRangeConstraints[i].IsConstrained)
            //    {
            //        CodeDescriptor.ValueRangeConstraint vrc = cd.ValueRangeConstraints[i];
            //        tw.Write("<" + (Math.Log(Math.Max(Math.Abs(vrc.MaxValue), Math.Abs(vrc.MinValue))) / Math.Log(2) + 1) + ">");
            //    }
            //    else
            //    {
            //        TypeInfo ti;
            //        if (LookupType(local.Type.CILType, out ti) &&
            //            ti.RangeSpec == TypeInfo.ERangeSpec.ByRange &&
            //            ti.ShowDefaultRange)
            //        {
            //            tw.Write(" <" + (ti.DefaultRange.SecondBound - ti.DefaultRange.FirstBound + 1) + ">");
            //        }
            //    }
            //    tw.WriteLine(";");
            //}

            cd.Implementation.Body.PreprocessForLoopKindRecognition();
            cd.Implementation.Body.AcceptIfEnabled(new SystemCStatementsGen(tw, this));

            tw.Indent--;
            _sim.PopScope();
        }
 private void AnalyzeProcess(Process process)
 {
     Action func = process.InitialAction;
     MethodInfo method = func.Method;
     List<ISignalOrPortDescriptor> sens = new List<ISignalOrPortDescriptor>();
     if (process.Sensitivity != null)
     {
         foreach (EventSource e in process.Sensitivity)
         {
             DesignObject owner = e.Owner;
             if (!(owner is SignalBase))
             {
                 _context.Report(EIssueClass.Error,
                     "Process " + method.Name + " is sensitive to an event which is not owned by " +
                     "a signal. This is currently not supported by the behavioral model.");
             }
             else
             {
                 var signal = (SignalBase)owner;
                 var spdesc = signal.Descriptor;
                 if (spdesc == null)
                     throw new InvalidOperationException();
                 var sref = spdesc.AsSignalRef(SignalRef.EReferencedProperty.Instance)
                     .RelateToComponent(process.Owner.Descriptor);
                 if (sref == null)
                     ReportError("Did not find a matching port for signal " + signal.Descriptor.Name);
                 else
                     sens.Add(sref.Desc);
             }
         }
     }
     ProcessDescriptor pd = new ProcessDescriptor(method, process)
     {
         Sensitivity = sens.ToArray(),
         Owner = process.Owner.Descriptor
     };
     //DecompileAndEnqueueCallees(pd, process.Owner, new object[] { process.Owner });
     DecompileAndEnqueueCallees(pd, func.Target, new object[] { process.Owner });
     process.Owner.Descriptor.AddChild(pd, method.Name);
 }
Exemple #36
0
        //      ADDED
        private void InitializeProcess(ProcessDescriptor pd, IndentedTextWriter tw)
        {
            bool simuOnly = pd.HasAttribute<SimulationOnly>();
            if (simuOnly)
                SwitchOffSynthesis(tw);

            string pname = MakeIDName(pd.Name, pd);

            if (pd.Kind == Components.Process.EProcessKind.Triggered &&
                    pd.Sensitivity.Length > 0)
            {
                tw.WriteLine("SC_METHOD(" + pname + ");");
                tw.Indent++;
                tw.Write("sensitive");
                var sens = pd.Sensitivity.Select(spd =>
                        DieWithUnknownSensitivityIfNull(spd
                            .AsSignalRef(SignalRef.EReferencedProperty.Instance)
                            .RelateToComponent(_curComponent))
                        .AssimilateIndices()
                        .Desc)
                        .Distinct();
                foreach (var spd in sens)
                {
                    tw.Write(" << ");
                    tw.Write(MakeIDName(spd.Name, spd.GetBoundSignal()));
                }
                tw.WriteLine(";");
                tw.Indent--;

            }
            else if (pd.Kind == Components.Process.EProcessKind.Threaded)
            {
                tw.WriteLine("SC_THREAD(" + pname + ");");
                if (pd.Sensitivity.Length > 0)
                {
                    tw.Indent++;
                    tw.Write("sensitive");
                    var sens = pd.Sensitivity.Select(spd =>
                            DieWithUnknownSensitivityIfNull(spd
                                .AsSignalRef(SignalRef.EReferencedProperty.Instance)
                                .RelateToComponent(_curComponent))
                            .AssimilateIndices()
                            .Desc)
                            .Distinct();
                    foreach (var spd in sens)
                    {
                        tw.Write(" << ");
                        tw.Write(MakeIDName(spd.Name, spd.GetBoundSignal()));
                    }
                    tw.WriteLine(";");
                    tw.Indent--;
                }
            }

            if (simuOnly)
                SwitchOnSynthesis(tw);
        }
Exemple #37
0
        /// <summary>
        /// Executes the HLS design flow.
        /// </summary>
        /// <param name="design">the design</param>
        /// <param name="host">the hosting component</param>
        /// <param name="proc">the process being subject to HLS</param>
        /// <param name="targetProject">the target project</param>
        /// <remarks>Inside the hosting component, the process will be replaced by the synthesized hardware.</remarks>
        public void Execute(DesignContext design, Component host, ProcessDescriptor proc, IProject targetProject)
        {
            Contract.Requires<ArgumentNullException>(design != null);
            Contract.Requires<ArgumentNullException>(host != null);
            Contract.Requires<ArgumentNullException>(proc != null);
            Contract.Requires<ArgumentNullException>(targetProject != null);

            design.CurrentProcess = proc.Instance;

            var clk = proc.Sensitivity[0];
            SignalBase clkI;
            var sdClk = clk as SignalDescriptor;
            if (sdClk == null)
                clkI = ((SignalDescriptor)((PortDescriptor)clk).BoundSignal).Instance;
            else
                clkI = sdClk.Instance;
            
            var state = new HLSState(this, design, host, proc, targetProject);
            proc.AddAttribute(state);

            if (_beginHLS != null)
                _beginHLS(state);

            var dpb = new DefaultDatapathBuilder(host, clkI, proc.Name);
            state.InterconnectBuilder = InterconnectBuilder.Create(host, dpb.ICBinder);
            state.ControlpathBuilder = ControlPathBuilder.Create(host, dpb.FUBinder);
            state.ControlpathBuilder.PersonalizePlan(this);

            do
            {
                XILSFunction fnasm;
                if (!proc.HasAttribute<XILSFunction>())
                {
                    var func = proc.Implementation;
                    IEnumerable<Function> inlinedFunctions;
                    func = func.InlineCalls(out inlinedFunctions);
                    if (ConvertFieldsToLocals)
                    {
                        Variable[] newLocals;
                        func = func.ConvertFieldsToLocals(out newLocals);
                    }
                    state.PreprocessedFunction = func;

                    fnasm = state.PreprocessedFunction.Compile(DefaultInstructionSet.Instance);
                }
                else
                {
                    fnasm = proc.QueryAttribute<XILSFunction>();
                }
                fnasm.SanityCheck();
                state.XILSInput = fnasm;
                IList<XILSInstr> instrs = state.XILSInput.Instructions.ToList();
                foreach (var rw in XILSTransformations)
                {
                    instrs = rw.Rewrite(instrs);
                    fnasm = new XILSFunction(fnasm.Name, fnasm.Arguments, fnasm.Locals, instrs.ToArray());
                    fnasm.SanityCheck();
                }
                state.XILSTransformed = fnasm;

                XIL3Function fnasm3 = fnasm.ToXIL3();
                state.XIL3Input = fnasm3;

                foreach (IXIL3Rewriter rw in XIL3Transformations)
                {
                    fnasm3 = rw.Rewrite(fnasm3);
                    fnasm3.SanityCheck();
                }

                state.XIL3Transformed = fnasm3;
                state.NotifyProgress(EHLSProgress.Compiled);
            } while (state._repeat);
            if (state._cancel)
                return;

            SchedulingConstraints constraints;

            do
            {
                var xmm = new XILMapperManager();
                foreach (var dpu in Enumerable.Reverse(XILMappers))
                    xmm.AddMapper(dpu);

                DesignContext.Push();

                var xilsa = new XILSchedulingAdapter(state.XIL3Transformed, xmm, host, targetProject);
                if (AllocationPolicy != null)
                    xilsa.Allocator.Policy = AllocationPolicy.Create();
                if (_onFUCreated != null)
                    xilsa.Allocator.OnFUAllocation += _onFUCreated;
                state.SchedulingAdapter = xilsa;
                state.NotifyProgress(EHLSProgress.AboutToSchedule);

                constraints = SchedulingConstraints;
                if (constraints == null)
                {
                    if (proc.Implementation != null)
                        constraints = proc.Implementation.QueryAttribute<SchedulingConstraints>();
                    if (constraints == null)
                        constraints = new SchedulingConstraints();
                }
                state.Constraints = constraints;

                if (constraints.MinimizeNumberOfFUs)
                {
                    foreach (var instr in state.XIL3Transformed.Instructions)
                    {
                        xilsa.SetMaxFUAllocation(xilsa.IClass[instr], 1);
                    }
                }

                Scheduler.Schedule(xilsa.CFG, constraints, xilsa);
                DesignContext.Pop();

                state.NotifyProgress(EHLSProgress.Scheduled);
            } while (state._repeat);

            ComputeCStepsForBranchTargets(state.SchedulingAdapter);

            do
            {
                state.ControlpathBuilder.PrepareAllocation(state.SchedulingAdapter.ComputeCStepCount());
                var flowSpec = state.SchedulingAdapter.Allocate(dpb);
                state.RawFlows = flowSpec;
                var realFlow = new FlowMatrix();
                state.InterconnectBuilder.CreateInterconnect(flowSpec, realFlow);
                state.RealFlows = realFlow;
                state.NotifyProgress(EHLSProgress.InterconnectCreated);
            } while (state._repeat);
            if (state._cancel)
                return;

            Debug.Assert(state.RealFlows.FlowSources.All(sr => sr.Desc.Owner != null));
            Debug.Assert(state.RealFlows.FlowTargets.All(sr => sr.Desc.Owner != null));

            do
            {
                state.ControlpathBuilder.CreateControlpath(state.RealFlows, proc.Name);
                foreach (var prof in constraints.Profilers)
                    prof.ExtractFrom(state.XIL3Transformed, state.SchedulingAdapter);
                state.NotifyProgress(EHLSProgress.ControlpathCreated);
            } while (state._repeat);
            if (state._cancel)
                return;
        }
Exemple #38
0
 public Refinement(ProcessDescriptor pd, PropertyInfo planProp)
 {
     _pd = pd;
     _planProp = planProp;
 }
Exemple #39
0
        public void ProcessDescriptorHasMachine()
        {
            ProcessDescriptor process = ProcessDescriptor.Current;

            Expect.IsNotNull(process.LocalMachine, $"{nameof(process.LocalMachine)} was null");
        }
Exemple #40
0
 public static ProcessTr Create(ProcessDescriptor process)
 {
     return new ProcessTr(process.AcDomain)
     {
         CreateOn = process.Process.CreateOn,
         Id = process.Process.Id,
         IsEnabled = process.Process.IsEnabled,
         Name = process.Process.Name,
         NetPort = process.Process.NetPort,
         OntologyId = process.Process.OntologyId,
         CatalogCode = process.Process.CatalogCode,
         Type = process.Process.Type,
         WebApiBaseAddress = process.WebApiBaseAddress
     };
 }
Exemple #41
0
        private void DeclareProcess(ProcessDescriptor pd, IndentedTextWriter tw)
        {
            bool simuOnly = pd.HasAttribute<SimulationOnly>();
            if (simuOnly)
                SwitchOffSynthesis(tw);

            List<ConcurrentStatement> cstmts;
            if (pd.Implementation
                .MakeIntegerIndices()
                .TryAsConcurrentStatements(out cstmts))
            {
                foreach (var cstmt in cstmts)
                {
                    var ls = new LiteralStringifier(this, LiteralReference.EMode.Direct);
                    ls.VisitSignalRef(cstmt.TargetSignal);
                    tw.Write(ls.Result);
                    tw.Write(" <= ");
                    tw.Write(cstmt.SourceExpression.ToString(this));
                    tw.WriteLine(";");
                }
                tw.WriteLine();
            }
            else
            {
                string pname = MakeIDName(pd.Name, pd);
                tw.Write(pname + ": process");
                if (pd.Kind == Components.Process.EProcessKind.Triggered &&
                    pd.Sensitivity.Length > 0)
                {
                    tw.Write("(");
                    bool first = true;
                    var sens = pd.Sensitivity.Select(spd => 
                        DieWithUnknownSensitivityIfNull(spd
                            .AsSignalRef(SignalRef.EReferencedProperty.Instance)
                            .RelateToComponent(_curComponent))
                        .AssimilateIndices()
                        .Desc)
                        .Distinct();
                    foreach (var spd in sens)
                    {
                        if (first)
                            first = false;
                        else
                            tw.Write(", ");
                        tw.Write(MakeIDName(spd.Name, spd.GetBoundSignal()));
                    }
                    tw.Write(")");
                }
                tw.WriteLine();
                GenerateMethodBody(pd, tw);
                tw.WriteLine(" process;");
            }

            if (simuOnly)
                SwitchOnSynthesis(tw);
        }
Exemple #42
0
        /// <summary>
        /// Creates and adds a new symbolic process (i.e. without specification of behavior).
        /// </summary>
        /// <param name="me">component descriptor to host the new process</param>
        /// <param name="kind">kind of process</param>
        /// <param name="name">name of the new process</param>
        /// <param name="sensitivity">sensitivity list of the new process</param>
        /// <returns>the descriptor of the new process</returns>
        public static ProcessDescriptor CreateProcess(this IComponentDescriptor me,
            Process.EProcessKind kind, string name, params ISignalOrPortDescriptor[] sensitivity)
        {
            Contract.Requires<ArgumentNullException>(me != null);
            Contract.Requires<ArgumentNullException>(name != null);
            Contract.Requires<ArgumentNullException>(sensitivity != null);

            ProcessDescriptor pd = new ProcessDescriptor(name)
            {
                Kind = kind,
                Sensitivity = sensitivity
            };
            me.AddChild(pd, pd.Name);
            return pd;
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="process"></param>
 /// <returns></returns>
 public IDispatcher CreateDispatcher(ProcessDescriptor process)
 {
     return new DefaultDispatcher(process);
 }
 /// <summary>
 ///
 /// </summary>
 /// <param name="process"></param>
 /// <returns></returns>
 public IExecutor CreateExecutor(ProcessDescriptor process)
 {
     return(new DefaultExecutor(process));
 }
Exemple #45
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="process"></param>
 /// <returns></returns>
 public IExecutor CreateExecutor(ProcessDescriptor process)
 {
     return new DefaultExecutor(process);
 }