import ctypes import logging import os import pyGHDL.libghdl.name_table as name_table import pyGHDL.libghdl.files_map as files_map import pyGHDL.libghdl.files_map_editor as files_map_editor import pyGHDL.libghdl.libraries as libraries import pyGHDL.libghdl.vhdl.nodes as nodes import pyGHDL.libghdl.vhdl.sem_lib as sem_lib import pyGHDL.libghdl.vhdl.sem as sem import pyGHDL.libghdl.vhdl.formatters as formatters from . import symbols, references log = logging.getLogger(__name__) class Document(object): # The encoding used for the files. # Unfortunately this is not fully reliable. The client can read the # file using its own view of the encoding. It then pass the document # to the server using unicode(utf-8). Then the document is converted # back to bytes using this encoding. And we hope the result would be # the same as the file. Because VHDL uses the iso 8859-1 character # set, we use the same encoding. The client should also use 8859-1. encoding = "iso-8859-1" initial_gap_size = 4096 def __init__(self, uri, sfe=None, version=None): self.uri = uri self.version = version self._fe = sfe self.gap_size = Document.initial_gap_size self._tree = nodes.Null_Iir @staticmethod def load(src_bytes, dirname, filename): # Write text to file buffer. src_len = len(src_bytes) buf_len = src_len + Document.initial_gap_size fileid = name_table.Get_Identifier(filename) if os.path.isabs(filename): dirid = name_table.Null_Identifier else: dirid = name_table.Get_Identifier(dirname) sfe = files_map.Reserve_Source_File(dirid, fileid, buf_len) files_map_editor.Fill_Text(sfe, ctypes.c_char_p(src_bytes), src_len) return sfe def __extend_source_buffer(self, new_size): self.gap_size *= 2 fileid = files_map.Get_File_Name(self._fe) dirid = files_map.Get_Directory_Name(self._fe) buf_len = files_map.Get_File_Length(self._fe) + new_size + self.gap_size files_map.Discard_Source_File(self._fe) new_sfe = files_map.Reserve_Source_File(dirid, fileid, buf_len) files_map_editor.Copy_Source_File(new_sfe, self._fe) files_map.Free_Source_File(self._fe) self._fe = new_sfe def reload(self, source): """Reload the source of a document.""" src_bytes = source.encode(Document.encoding, "replace") l = len(src_bytes) if l >= files_map.Get_Buffer_Length(self._fe): self.__extend_source_buffer(l) files_map_editor.Fill_Text(self._fe, ctypes.c_char_p(src_bytes), l) def __str__(self): return str(self.uri) def apply_change(self, change): """Apply a change to the document.""" text = change["text"] change_range = change.get("range") text_bytes = text.encode(Document.encoding, "replace") if not change_range: # The whole file has changed raise AssertionError # if len(text_bytes) < libghdl.Files_Map.Get_Buffer_Length(self._fe): # xxxx_replace # else: # xxxx_free # xxxx_allocate # return start_line = change_range["start"]["line"] start_col = change_range["start"]["character"] end_line = change_range["end"]["line"] end_col = change_range["end"]["character"] status = files_map_editor._Replace_Text( self._fe, start_line + 1, start_col, end_line + 1, end_col, ctypes.c_char_p(text_bytes), len(text_bytes), ) if status: return # Failed to replace text. # Increase size self.__extend_source_buffer(len(text_bytes)) status = files_map_editor._Replace_Text( self._fe, start_line + 1, start_col, end_line + 1, end_col, ctypes.c_char_p(text_bytes), len(text_bytes), ) assert status def check_document(self, text): log.debug("Checking document: %s", self.uri) text_bytes = text.encode(Document.encoding, "replace") files_map_editor.Check_Buffer_Content(self._fe, ctypes.c_char_p(text_bytes), len(text_bytes)) @staticmethod def add_to_library(tree): # Detach the chain of units. unit = nodes.Get_First_Design_Unit(tree) nodes.Set_First_Design_Unit(tree, nodes.Null_Iir) # FIXME: free the design file ? tree = nodes.Null_Iir # Analyze unit after unit. while unit != nodes.Null_Iir: # Pop the first unit. next_unit = nodes.Get_Chain(unit) nodes.Set_Chain(unit, nodes.Null_Iir) lib_unit = nodes.Get_Library_Unit(unit) if lib_unit != nodes.Null_Iir and nodes.Get_Identifier(unit) != name_table.Null_Identifier: # Put the unit (only if it has a library unit) in the library. libraries.Add_Design_Unit_Into_Library(unit, False) tree = nodes.Get_Design_File(unit) unit = next_unit return tree def parse_document(self): """Parse a document and put the units in the library.""" assert self._tree == nodes.Null_Iir tree = sem_lib.Load_File(self._fe) if tree == nodes.Null_Iir: return self._tree = Document.add_to_library(tree) log.debug("add_to_library(%u) -> %u", tree, self._tree) if self._tree == nodes.Null_Iir: return nodes.Set_Design_File_Source(self._tree, self._fe) def compute_diags(self): log.debug("parse doc %d %s", self._fe, self.uri) self.parse_document() if self._tree == nodes.Null_Iir: # No units, nothing to add. return # Semantic analysis. unit = nodes.Get_First_Design_Unit(self._tree) while unit != nodes.Null_Iir: sem.Semantic(unit) nodes.Set_Date_State(unit, nodes.DateStateType.Analyze) unit = nodes.Get_Chain(unit) def flatten_symbols(self, syms, parent): res = [] for s in syms: s["location"] = {"uri": self.uri, "range": s["range"]} del s["range"] s.pop("detail", None) if parent is not None: s["containerName"] = parent res.append(s) children = s.pop("children", None) if children is not None: res.extend(self.flatten_symbols(children, s)) return res def document_symbols(self): log.debug("document_symbols") if self._tree == nodes.Null_Iir: return [] syms = symbols.get_symbols_chain(self._fe, nodes.Get_First_Design_Unit(self._tree)) return self.flatten_symbols(syms, None) def position_to_location(self, position): pos = files_map.File_Line_To_Position(self._fe, position["line"] + 1) return files_map.File_Pos_To_Location(self._fe, pos) + position["character"] def goto_definition(self, position): loc = self.position_to_location(position) return references.goto_definition(self._tree, loc) def format_range(self, rng): first_line = rng["start"]["line"] + 1 last_line = rng["end"]["line"] + (1 if rng["end"]["character"] != 0 else 0) if last_line < first_line: return None if self._tree == nodes.Null_Iir: return None hand = formatters.Allocate_Handle() formatters.Indent_String(self._tree, hand, first_line, last_line) buffer = formatters.Get_C_String(hand) buf_len = formatters.Get_Length(hand) newtext = buffer[:buf_len].decode(Document.encoding) res = [ { "range": { "start": {"line": first_line - 1, "character": 0}, "end": {"line": last_line, "character": 0}, }, "newText": newtext, } ] formatters.Free_Handle(hand) return res > 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
--  Synthesis context.
--  Copyright (C) 2017 Tristan Gingold
--
--  This file is part of GHDL.
--
--  This program is free software; you can redistribute it and/or modify
--  it under the terms of the GNU General Public License as published by
--  the Free Software Foundation; either version 2 of the License, or
--  (at your option) any later version.
--
--  This program is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--  GNU General Public License for more details.
--
--  You should have received a copy of the GNU General Public License
--  along with this program; if not, write to the Free Software
--  Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
--  MA 02110-1301, USA.

with Ada.Unchecked_Deallocation;

with Types; use Types;
with Name_Table; use Name_Table;

with Vhdl.Errors; use Vhdl.Errors;
with Vhdl.Utils;

with Netlists.Builders; use Netlists.Builders;
with Netlists.Folds; use Netlists.Folds;

with Synth.Expr; use Synth.Expr;
with Netlists.Locations;

package body Synth.Context is
   function Make_Base_Instance return Synth_Instance_Acc
   is
      Base : Base_Instance_Acc;
      Top_Module : Module;
      Res : Synth_Instance_Acc;
   begin
      Top_Module :=
        New_Design (New_Sname_Artificial (Get_Identifier ("top"), No_Sname));
      pragma Assert (Build_Context = null);
      Build_Context := Build_Builders (Top_Module);

      Base := new Base_Instance_Type'(Builder => Build_Context,
                                      Top_Module => Top_Module,
                                      Cur_Module => No_Module,
                                      Bit0 => No_Net,
                                      Bit1 => No_Net);

      Res := new Synth_Instance_Type'(Max_Objs => Global_Info.Nbr_Objects,
                                      Is_Const => False,
                                      Is_Error => False,
                                      Base => Base,
                                      Name => No_Sname,
                                      Block_Scope => Global_Info,
                                      Up_Block => null,
                                      Uninst_Scope => null,
                                      Source_Scope => Null_Node,
                                      Elab_Objects => 0,
                                      Objects => (others =>
                                                    (Kind => Obj_None)));
      return Res;
   end Make_Base_Instance;

   procedure Free_Base_Instance is
   begin
      --  TODO: really free.
      Build_Context := null;
   end Free_Base_Instance;

   function Make_Instance (Parent : Synth_Instance_Acc;
                           Blk : Node;
                           Name : Sname := No_Sname)
                          return Synth_Instance_Acc
   is
      Info : constant Sim_Info_Acc := Get_Info (Blk);
      Scope : Sim_Info_Acc;
      Res : Synth_Instance_Acc;
   begin
      if Get_Kind (Blk) = Iir_Kind_Architecture_Body then
         --  Architectures are extensions of entities.
         Scope := Get_Info (Vhdl.Utils.Get_Entity (Blk));
      else
         Scope := Info;
      end if;

      Res := new Synth_Instance_Type'(Max_Objs => Info.Nbr_Objects,
                                      Is_Const => False,
                                      Is_Error => False,
                                      Base => Parent.Base,
                                      Name => Name,
                                      Block_Scope => Scope,
                                      Up_Block => Parent,
                                      Uninst_Scope => null,
                                      Source_Scope => Blk,
                                      Elab_Objects => 0,
                                      Objects => (others =>
                                                    (Kind => Obj_None)));
      return Res;
   end Make_Instance;

   procedure Set_Instance_Base (Inst : Synth_Instance_Acc;
                                Base : Synth_Instance_Acc) is
   begin
      Inst.Base := Base.Base;
   end Set_Instance_Base;

   procedure Free_Instance (Synth_Inst : in out Synth_Instance_Acc)
   is
      procedure Deallocate is new Ada.Unchecked_Deallocation
        (Synth_Instance_Type, Synth_Instance_Acc);
   begin
      Deallocate (Synth_Inst);
   end Free_Instance;

   procedure Set_Instance_Module (Inst : Synth_Instance_Acc; M : Module)
   is
      Prev_Base : constant Base_Instance_Acc := Inst.Base;
      Base : Base_Instance_Acc;
      Self_Inst : Instance;
   begin
      Base := new Base_Instance_Type'(Builder => Prev_Base.Builder,
                                      Top_Module => Prev_Base.Top_Module,
                                      Cur_Module => M,
                                      Bit0 => No_Net,
                                      Bit1 => No_Net);
      Builders.Set_Parent (Base.Builder, M);

      Self_Inst := Create_Self_Instance (M);
      pragma Unreferenced (Self_Inst);

      Base.Bit0 := Build_Const_UB32 (Base.Builder, 0, 1);
      Base.Bit1 := Build_Const_UB32 (Base.Builder, 1, 1);
      Inst.Base := Base;
   end Set_Instance_Module;

   function Is_Error (Inst : Synth_Instance_Acc) return Boolean is
   begin
      return Inst.Is_Error;
   end Is_Error;

   procedure Set_Error (Inst : Synth_Instance_Acc) is
   begin
      Inst.Is_Error := True;
   end Set_Error;

   function Get_Instance_Module (Inst : Synth_Instance_Acc) return Module is
   begin
      return Inst.Base.Cur_Module;
   end Get_Instance_Module;

   function Get_Source_Scope (Inst : Synth_Instance_Acc) return Node is
   begin
      return Inst.Source_Scope;
   end Get_Source_Scope;

   function Get_Top_Module (Inst : Synth_Instance_Acc) return Module is
   begin
      return Inst.Base.Top_Module;
   end Get_Top_Module;

   function Get_Sname (Inst : Synth_Instance_Acc) return Sname is
   begin
      return Inst.Name;
   end Get_Sname;

   function Get_Build (Inst : Synth_Instance_Acc)
                      return Netlists.Builders.Context_Acc is
   begin
      return Inst.Base.Builder;
   end Get_Build;

   function Get_Inst_Bit0 (Inst : Synth_Instance_Acc) return Net is
   begin
      return Inst.Base.Bit0;
   end Get_Inst_Bit0;

   function Get_Inst_Bit1 (Inst : Synth_Instance_Acc) return Net is
   begin
      return Inst.Base.Bit1;
   end Get_Inst_Bit1;

   function Get_Instance_Const (Inst : Synth_Instance_Acc) return Boolean is
   begin
      return Inst.Is_Const;
   end Get_Instance_Const;

   function Check_Set_Instance_Const (Inst : Synth_Instance_Acc)
                                     return Boolean is
   begin
      for I in 1 .. Inst.Elab_Objects loop
         if Inst.Objects (I).Kind /= Obj_Subtype then
            return False;
         end if;
      end loop;
      return True;
   end Check_Set_Instance_Const;

   procedure Set_Instance_Const (Inst : Synth_Instance_Acc; Val : Boolean) is
   begin
      pragma Assert (not Val or else Check_Set_Instance_Const (Inst));
      Inst.Is_Const := Val;
   end Set_Instance_Const;

   procedure Create_Object (Syn_Inst : Synth_Instance_Acc;
                            Slot : Object_Slot_Type;
                            Num : Object_Slot_Type := 1) is
   begin
      --  Check elaboration order.
      --  Note: this is not done for package since objects from package are
      --  commons (same scope), and package annotation order can be different
      --  from package elaboration order (eg: body).
      if Slot /= Syn_Inst.Elab_Objects + 1
        or else Syn_Inst.Objects (Slot).Kind /= Obj_None
      then
         Error_Msg_Elab ("synth: bad elaboration order of objects");
         raise Internal_Error;
      end if;
      Syn_Inst.Elab_Objects := Slot + Num - 1;
   end Create_Object;

   procedure Create_Object_Force
     (Syn_Inst : Synth_Instance_Acc; Decl : Node; Vt : Valtyp)
   is
      Info : constant Sim_Info_Acc := Get_Info (Decl);
   begin
      pragma Assert
        (Syn_Inst.Objects (Info.Slot).Kind = Obj_None
           or else Vt = (null, null)
           or else Syn_Inst.Objects (Info.Slot) = (Kind => Obj_Object,
                                                   Obj => No_Valtyp));
      Syn_Inst.Objects (Info.Slot) := (Kind => Obj_Object, Obj => Vt);
   end Create_Object_Force;

   procedure Create_Object
     (Syn_Inst : Synth_Instance_Acc; Decl : Node; Vt : Valtyp)
   is
      Info : constant Sim_Info_Acc := Get_Info (Decl);
   begin
      Create_Object (Syn_Inst, Info.Slot, 1);
      Create_Object_Force (Syn_Inst, Decl, Vt);
   end Create_Object;

   procedure Create_Subtype_Object
     (Syn_Inst : Synth_Instance_Acc; Decl : Node; Typ : Type_Acc)
   is
      pragma Assert (Typ /= null);
      Info : constant Sim_Info_Acc := Get_Info (Decl);
   begin
      Create_Object (Syn_Inst, Info.Slot, 1);
      pragma Assert (Syn_Inst.Objects (Info.Slot).Kind = Obj_None);
      Syn_Inst.Objects (Info.Slot) := (Kind => Obj_Subtype, T_Typ => Typ);
   end Create_Subtype_Object;

   procedure Create_Package_Object (Syn_Inst : Synth_Instance_Acc;
                                    Decl : Node;
                                    Inst : Synth_Instance_Acc;
                                    Is_Global : Boolean)
   is
      Info : constant Sim_Info_Acc := Get_Info (Decl);
   begin
      if Is_Global then
         pragma Assert (Syn_Inst.Objects (Info.Pkg_Slot).Kind = Obj_None);
         pragma Assert (Syn_Inst.Up_Block = null);
         null;
      else
         pragma Assert (Syn_Inst.Up_Block /= null);
         Create_Object (Syn_Inst, Info.Slot, 1);
      end if;
      Syn_Inst.Objects (Info.Pkg_Slot) := (Kind => Obj_Instance,
                                           I_Inst => Inst);
   end Create_Package_Object;

   function Get_Package_Object
     (Syn_Inst : Synth_Instance_Acc; Info : Sim_Info_Acc)
     return Synth_Instance_Acc
   is
      Parent : Synth_Instance_Acc;
   begin
      Parent := Get_Instance_By_Scope (Syn_Inst, Info.Pkg_Parent);
      return Parent.Objects (Info.Pkg_Slot).I_Inst;
   end Get_Package_Object;

   function Get_Package_Object
     (Syn_Inst : Synth_Instance_Acc; Pkg : Node) return Synth_Instance_Acc is
   begin
      return Get_Package_Object (Syn_Inst, Get_Info (Pkg));
   end Get_Package_Object;

   procedure Set_Uninstantiated_Scope
     (Syn_Inst : Synth_Instance_Acc; Bod : Node) is
   begin
      Syn_Inst.Uninst_Scope := Get_Info (Bod);
   end Set_Uninstantiated_Scope;

   procedure Destroy_Object
     (Syn_Inst : Synth_Instance_Acc; Decl : Node)
   is
      Info : constant Sim_Info_Acc := Get_Info (Decl);
      Slot : constant Object_Slot_Type := Info.Slot;
   begin
      if Slot /= Syn_Inst.Elab_Objects
        or else Info.Obj_Scope /= Syn_Inst.Block_Scope
      then
         Error_Msg_Elab ("synth: bad destroy order");
      end if;
      Syn_Inst.Objects (Slot) := (Kind => Obj_None);
      Syn_Inst.Elab_Objects := Slot - 1;
   end Destroy_Object;

   procedure Create_Wire_Object (Syn_Inst : Synth_Instance_Acc;
                                 Kind : Wire_Kind;
                                 Obj : Node)
   is
      Obj_Type : constant Node := Get_Type (Obj);
      Otyp : constant Type_Acc := Get_Subtype_Object (Syn_Inst, Obj_Type);
      Val : Valtyp;
      Wid : Wire_Id;
   begin
      if Kind = Wire_None then
         Wid := No_Wire_Id;
      else
         Wid := Alloc_Wire (Kind, Obj);
      end if;
      Val := Create_Value_Wire (Wid, Otyp);

      Create_Object (Syn_Inst, Obj, Val);
   end Create_Wire_Object;

   function Get_Instance_By_Scope
     (Syn_Inst: Synth_Instance_Acc; Scope: Sim_Info_Acc)
     return Synth_Instance_Acc is
   begin
      case Scope.Kind is
         when Kind_Block
           | Kind_Frame
           | Kind_Process =>
            declare
               Current : Synth_Instance_Acc;
            begin
               Current := Syn_Inst;
               while Current /= null loop
                  if Current.Block_Scope = Scope then
                     return Current;
                  end if;
                  Current := Current.Up_Block;
               end loop;
               raise Internal_Error;
            end;
         when Kind_Package =>
            if Scope.Pkg_Parent = null then
               --  This is a scope for an uninstantiated package.
               declare
                  Current : Synth_Instance_Acc;
               begin
                  Current := Syn_Inst;
                  while Current /= null loop
                     if Current.Uninst_Scope = Scope then
                        return Current;
                     end if;
                  Current := Current.Up_Block;
                  end loop;
                  raise Internal_Error;
               end;
            else
               --  Instantiated package.
               return Get_Package_Object (Syn_Inst, Scope);
            end if;
         when others =>
            raise Internal_Error;
      end case;
   end Get_Instance_By_Scope;

   function Get_Parent_Scope (Blk : Node) return Sim_Info_Acc
   is
      Parent : Node;
   begin
      Parent := Get_Parent (Blk);
      if Get_Kind (Parent) = Iir_Kind_Architecture_Body then
         Parent := Vhdl.Utils.Get_Entity (Parent);
      end if;
      return Get_Info (Parent);
   end Get_Parent_Scope;

   function Get_Value (Syn_Inst: Synth_Instance_Acc; Obj : Node)
                      return Valtyp
   is
      Info : constant Sim_Info_Acc := Get_Info (Obj);
      Obj_Inst : Synth_Instance_Acc;
   begin
      Obj_Inst := Get_Instance_By_Scope (Syn_Inst, Info.Obj_Scope);
      return Obj_Inst.Objects (Info.Slot).Obj;
   end Get_Value;

   function Get_Subtype_Object
     (Syn_Inst : Synth_Instance_Acc; Decl : Node) return Type_Acc
   is
      Info : constant Sim_Info_Acc := Get_Info (Decl);
      Obj_Inst : Synth_Instance_Acc;
   begin
      Obj_Inst := Get_Instance_By_Scope (Syn_Inst, Info.Obj_Scope);
      return Obj_Inst.Objects (Info.Slot).T_Typ;
   end Get_Subtype_Object;

   --  Set Is_0 to True iff VEC is 000...
   --  Set Is_X to True iff VEC is XXX...
   procedure Is_Full (Vec : Logvec_Array;
                      Is_0 : out Boolean;
                      Is_X : out Boolean)
   is
      Val : Uns32;
      Zx : Uns32;
   begin
      Val := Vec (0).Val;
      Zx := Vec (0).Zx;
      Is_0 := False;
      Is_X := False;
      if Val = 0 and Zx = 0 then
         Is_0 := True;
         Is_X := False;
      elsif Val = not 0 and Zx = not 0 then
         Is_0 := False;
         Is_X := True;
      end if;

      for I in 1 .. Vec'Last loop
         if Vec (I).Val /= Val or else Vec (I).Zx /= Zx then
            Is_0 := False;
            Is_X := False;
            return;
         end if;
      end loop;
   end Is_Full;

   procedure Value2net
     (Val : Valtyp; W : Width; Vec : in out Logvec_Array; Res : out Net)
   is
      Off : Uns32;
      Has_Zx : Boolean;
      Inst : Instance;
      Is_0, Is_X : Boolean;
   begin
      Has_Zx := False;
      Off := 0;
      Value2logvec (Val, Vec, Off, Has_Zx);
      if W = 0 then
         --  For null range (like the null string literal "")
         Res := Build_Const_UB32 (Build_Context, 0, 0);
      elsif W <= 32 then
         --  32 bit result.
         if not Has_Zx then
            Res := Build_Const_UB32 (Build_Context, Vec (0).Val, W);
         else
            Res := Build_Const_UL32
              (Build_Context, Vec (0).Val, Vec (0).Zx, W);
         end if;
         return;
      else
         Is_Full (Vec, Is_0, Is_X);
         if Is_0 then
            Res := Build_Const_UB32 (Build_Context, 0, W);
         elsif Is_X then
            Res := Build_Const_X (Build_Context, W);
         elsif not Has_Zx then
            Inst := Build_Const_Bit (Build_Context, W);
            for I in Vec'Range loop
               Set_Param_Uns32 (Inst, Param_Idx (I), Vec (I).Val);
            end loop;
            Res := Get_Output (Inst, 0);
         else
            Inst := Build_Const_Log (Build_Context, W);
            for I in Vec'Range loop
               Set_Param_Uns32 (Inst, Param_Idx (2 * I), Vec (I).Val);
               Set_Param_Uns32 (Inst, Param_Idx (2 * I + 1), Vec (I).Zx);
            end loop;
            Res := Get_Output (Inst, 0);
         end if;
      end if;
   end Value2net;

   function Get_Net (Val : Valtyp) return Net is
   begin
      case Val.Val.Kind is
         when Value_Wire =>
            return Get_Current_Value (Build_Context, Val.Val.W);
         when Value_Net =>
            return Val.Val.N;
         when Value_Alias =>
            declare
               Res : Net;
            begin
               if Val.Val.A_Obj.Kind = Value_Wire then
                  Res := Get_Current_Value (Build_Context, Val.Val.A_Obj.W);
                  return Build2_Extract
                    (Build_Context, Res, Val.Val.A_Off.Net_Off, Val.Typ.W);
               else
                  pragma Assert (Val.Val.A_Off.Net_Off = 0);
                  return Get_Net ((Val.Typ, Val.Val.A_Obj));
               end if;
            end;
         when Value_Const =>
            if Val.Val.C_Net = No_Net then
               Val.Val.C_Net := Get_Net ((Val.Typ, Val.Val.C_Val));
               Locations.Set_Location (Get_Net_Parent (Val.Val.C_Net),
                                       Get_Location (Val.Val.C_Loc));
            end if;
            return Val.Val.C_Net;
         when Value_Memory =>
            declare
               W : constant Width := Val.Typ.W;
               Nd : constant Digit_Index := Digit_Index ((W + 31) / 32);
               Res : Net;
            begin
               if Nd > 64 then
                  declare
                     Vecp : Logvec_Array_Acc;
                  begin
                     Vecp := new Logvec_Array'(0 .. Nd - 1 => (0, 0));
                     Value2net (Val, W, Vecp.all, Res);
                     Free_Logvec_Array (Vecp);
                     return Res;
                  end;
               else
                  declare
                     Vec : Logvec_Array (0 .. Nd - 1) := (others => (0, 0));
                  begin
                     Value2net (Val, W, Vec, Res);
                     return Res;
                  end;
               end if;
            end;
         when others =>
            raise Internal_Error;
      end case;
   end Get_Net;
end Synth.Context;