public IOEmitter( PointerType sourceType, HardwareRegister addressRegister) { SourceType = sourceType; AddressRegister = addressRegister; }
public IOEmitter( PointerType targetType, HardwareRegister addressRegister) { TargetType = targetType; AddressRegister = addressRegister; }
/// <summary> /// Append the value given register argument. /// </summary> /// <param name="argument">The register argument.</param> public void AppendArgumentValue(HardwareRegister argument) { AppendArgument(); stringBuilder.Append('['); stringBuilder.Append('%'); stringBuilder.Append(GetStringRepresentation(argument)); stringBuilder.Append(']'); }
private static HardwareRegisterSet TransformRegisterSet(XmlElement el) { var name = el.GetAttribute("name"); if (name == null) { return(null); } return(new HardwareRegisterSet { UserFriendlyName = name, Registers = el.SelectNodes("register").OfType <XmlElement>().SelectMany(r => new[] { r }.Concat(r.SelectNodes("register").OfType <XmlElement>())).Select(r => { var regSize = r.GetAttribute("size"); var regAccess = r.GetAttribute("access"); var reg = new HardwareRegister { Name = r.GetAttribute("name"), Address = r.GetAttribute("address") }; if (reg.Name == null || reg.Address == null) { return null; } switch (regSize ?? "") { case "B": reg.SizeInBits = 8; break; case "W": reg.SizeInBits = 16; break; default: return null; } switch (regAccess) { case "R": reg.ReadOnly = true; break; case "RW": reg.ReadOnly = false; break; default: return null; } reg.SubRegisters = r.SelectNodes("bitfield").OfType <XmlElement>().Select(TransformSubregister).Where(sr => sr != null).ToArray(); return reg; }).Where(r => r != null).ToArray() }); }
/// <summary> /// Constructs a new predicate register. /// </summary> /// <param name="predicateRegister">The underlying predicate register.</param> public PredicateScope(HardwareRegister predicateRegister) { Debug.Assert(predicateRegister != null, "Invalid register allocator"); Debug.Assert( predicateRegister.Kind == PTXRegisterKind.Predicate, "Invalid predicate register"); RegisterAllocator = null; PredicateRegister = predicateRegister; }
private void OnRegisterWithoutSubregisters() { _register = new HardwareRegister(); _register.Name = _lastMatch.Groups[3].Value; _register.ReadOnly = IsReadOnly(_lastMatch.Groups[1].Value); _register.SizeInBits = int.Parse(_lastMatch.Groups[2].Value); _registers.Add(_register); SetExpectedMatches(REGISTER_WITHOUT_SUBREGISTERS, REGISTER_BEGIN, REGISTER_SET_END, RESERVED_BITS); }
/// <summary> /// Constructs a new predicate configuration. /// </summary> /// <param name="predicateRegister">The predicate register to test.</param> /// <param name="isTrue">Branch if the predicate register is true.</param> public PredicateConfiguration( HardwareRegister predicateRegister, bool isTrue) { Debug.Assert( predicateRegister.Kind == PTXRegisterKind.Predicate, "Invalid predicate register"); PredicateRegister = predicateRegister; IsTrue = isTrue; }
//--------------------------------- private static List <HardwareRegisterSet> ProcessLoadHardwareRegisterSet() { List <HardwareRegisterSet> oReg = new List <HardwareRegisterSet>(); List <HardwareSubRegister> alstSubReg = new List <HardwareSubRegister>(); var aLstPerep = GetBaseAdress(mNameCurrentAdr); foreach (var perep in aLstPerep) { List <HardwareRegister> alstReg = new List <HardwareRegister>(); ulong aBaseAdress = perep.adress; perep.used = true; foreach (var reg in adicAdrrOffsetDriv) { HardwareRegister Reg = new HardwareRegister(); alstSubReg.Clear(); Reg.Name = reg.Key; Reg.Address = FormatToHex(reg.Value + aBaseAdress); Reg.SizeInBits = 32; foreach (var subReg in adicBitsOffsetDriv) { if (subReg.Key.StartsWith(Reg.Name)) { HardwareSubRegister hsr = new HardwareSubRegister { Name = subReg.Key.Remove(0, Reg.Name.Length + 1), ParentRegister = Reg, OriginalMacroBase = Reg.Name, SizeInBits = GetSizeBit(subReg.Value), FirstBit = GetFirstBit(subReg.Value), }; if (hsr.SizeInBits == 0) { Console.WriteLine("size subreg 0 " + hsr.Name); } alstSubReg.Add(hsr); } } Reg.SubRegisters = alstSubReg.ToArray(); alstReg.Add(Reg); } if (alstReg.Count > 0) { oReg.Add(new HardwareRegisterSet { ExpressionPrefix = mNameCurrentAdr, UserFriendlyName = perep.Name,// astrUserFrendlyName, Registers = alstReg.ToArray() }); } } return(oReg); }
/// <summary> /// Creates an address-space cast conversion. /// </summary> /// <param name="sourceRegister">The source register.</param> /// <param name="targetRegister">The target register.</param> /// <param name="sourceAddressSpace">The source address space.</param> /// <param name="targetAddressSpace">The target address space.</param> private void CreateAddressSpaceCast( PrimitiveRegister sourceRegister, HardwareRegister targetRegister, MemoryAddressSpace sourceAddressSpace, MemoryAddressSpace targetAddressSpace) { var toGeneric = targetAddressSpace == MemoryAddressSpace.Generic; var addressSpaceOperation = PTXInstructions.GetAddressSpaceCast(toGeneric); var addressSpaceOperationSuffix = PTXInstructions.GetAddressSpaceCastSuffix(Backend); using var command = BeginCommand(addressSpaceOperation); command.AppendAddressSpace( toGeneric ? sourceAddressSpace : targetAddressSpace); command.AppendSuffix(addressSpaceOperationSuffix); command.AppendArgument(targetRegister); command.AppendArgument(sourceRegister); }
private void OnReservedBits() { var arraySize = int.Parse(_lastMatch.Groups[4].Value); var arrayName = _lastMatch.Groups[3].Value; var isReadOnly = IsReadOnly(_lastMatch.Groups[1].Value); for (int i = 0; i < arraySize; i++) { var register = new HardwareRegister { Name = arrayName + "_" + i.ToString(), ReadOnly = isReadOnly, SizeInBits = int.Parse(_lastMatch.Groups[2].Value) }; _registers.Add(register); } SetExpectedMatches(REGISTER_WITHOUT_SUBREGISTERS, REGISTER_BEGIN, REGISTER_SET_END, RESERVED_BITS); }
private void OnStart() { _processedBits = 0; _registerNameToAddress = new Dictionary <string, string>(); _registerSetToAddress = new Dictionary <string, string>(); _subRegistersKnownValues = new Dictionary <string, IList <KeyValuePair <string, ulong> > >(); _registers = new List <HardwareRegister>(); _registerSets = new List <HardwareRegisterSet>(); _subRegisters = new List <HardwareSubRegister>(); _registersWithWrongBitsSum = new List <string>(); _duplicateRegisterDefinition = false; _lastMatch = Match.Empty; _matchedRegex = null; _registerSet = null; _register = null; _subRegister = null; _registerBits = new Dictionary <string, HardwareSubRegister>(); _expectedMatches = new List <Regex> { REGISTER_SET_ADDRESS }; }
private static HardwareRegister DeepCopy(HardwareRegister reg) { HardwareRegister reg_new = new HardwareRegister { Name = reg.Name, Address = reg.Address, GDBExpression = reg.GDBExpression, ReadOnly = reg.ReadOnly, SizeInBits = reg.SizeInBits }; if (reg.SubRegisters != null) { reg_new.SubRegisters = new HardwareSubRegister[reg.SubRegisters.Length]; for (int i = 0; i < reg.SubRegisters.Length; i++) { reg_new.SubRegisters[i] = DeepCopy(reg.SubRegisters[i]); } } return(reg_new); }
public static List <HardwareRegisterSet> ProcessRegisterSetNamesList(string pFileName, ref List <HardwareRegister> lstRegCustomType) { List <HardwareRegisterSet> oReg = new List <HardwareRegisterSet>(); bool aStartCheckReg = false; Regex argSearchReg = new Regex(@"[ \t]*([\w]+)[ \t]+([\w]+)[[]*([\w]+)*[]]*[;]?.*"); Regex argSearchFrendName = new Regex(@"^[ \t]*}[ ]*([\w]*).*"); List <HardwareRegister> lstReg = new List <HardwareRegister>(); int sizeArray; bool aflUnion = false; Match m1; int aSizeUnion = 0; foreach (var ln in File.ReadAllLines(pFileName)) { if (ln.Contains("typedef struct")) { lstReg = new List <HardwareRegister>(); aStartCheckReg = true; continue; } if (ln.Contains("typedef union {")) { aflUnion = true; continue; } if (aflUnion) { m1 = Regex.Match(ln, @"[ ]*(uint[\d]+_t).*"); if (m1.Success) { aSizeUnion = GetSizeInBitsPoor(m1.Groups[1].Value); continue; } m1 = Regex.Match(ln, @"^}[ ]*([\w_]+).*"); if (m1.Success) { if (aSizeUnion == 0) { throw new Exception(m1.Groups[1].Value + " is 0 in " + ln); } if (!aDicSizeTypeDefStuct.ContainsKey(m1.Groups[1].Value)) { aDicSizeTypeDefStuct.Add(m1.Groups[1].Value, aSizeUnion); } aflUnion = false; } continue; } if (!aStartCheckReg) { continue; } Match m = argSearchReg.Match(ln); if (m.Success) { sizeArray = 0; if (m.Groups[1].Value == "__I" || m.Groups[1].Value == "__O" || m.Groups[1].Value == "__IO") {//SAM4 m = Regex.Match(ln, @"[ \t]*[_IO]+[ \t]+(uint32_t|uint16_t|uint8_t|[\w_]+)[ \t]+([a-zA-Z0-9_]+)[[]*([0-9]+)*[]]*[;]?.*"); if (!m.Success) { throw new Exception("unkonow format registr :" + ln); } } if (m.Groups[3].Value.StartsWith("0x")) { string aDigStr = m.Groups[3].Value.Replace("0x", ""); sizeArray = Convert.ToInt32(aDigStr, 16); } else if (IsDigit(m.Groups[3].Value)) { sizeArray = m.Groups[3].Value == "" ? 1 : Convert.ToInt16(m.Groups[3].Value); } else { string astrDefArray = m.Groups[3].Value; foreach (var lndef in File.ReadAllLines(pFileName)) { var md = Regex.Match(lndef, @"[ \t]*#define[ \t]+" + astrDefArray + @"[ \t]+([0-9]+).*"); if (md.Success) { if (IsDigit(md.Groups[1].Value)) { sizeArray = Convert.ToInt16(md.Groups[1].Value); } else { throw new Exception("No define " + astrDefArray); } } } } string aType = m.Groups[1].Value; for (int a_cnt = 0; a_cnt < sizeArray; a_cnt++) { HardwareRegister setReg = new HardwareRegister(); if (aType == "PortGroup") { setReg.Name = m.Groups[2].Value + "[" + a_cnt + "]"; } else { setReg.Name = (sizeArray > 1) ? m.Groups[2].Value + "[" + a_cnt + "]" : m.Groups[2].Value; } setReg.ReadOnly = (aType == "RoReg" || m.Groups[0].Value.Contains("__I ")) ? true : false; if (!STANDARD_TYPE_SIZES.ContainsKey(aType)) { setReg.SizeInBits = 0; setReg.Name = setReg.Name + ":1-" + aType;//name register - custom type lstRegCustomType.Add(setReg); } else { setReg.SizeInBits = GetSizeInBitsPoor(aType); } lstReg.Add(setReg); } } else { //end m = argSearchFrendName.Match(ln); if (m.Success) { HardwareRegisterSet setReg = new HardwareRegisterSet(); setReg.UserFriendlyName = m.Groups[1].Value; aStartCheckReg = false; oReg.Add(setReg); foreach (var HardReg in lstReg) { var lstSubRegs = ProcessRegisterSetSubRegisters(pFileName); List <HardwareSubRegister> lstSubRegToHard = new List <HardwareSubRegister>(); string aPrefNameSubReg = (HardReg.Name + "_").ToUpper(); int idx = aPrefNameSubReg.LastIndexOf("["); if (idx > 0) { aPrefNameSubReg = aPrefNameSubReg.Substring(0, idx) + "_"; } foreach (var SubReg in lstSubRegs) { if (SubReg.Name.StartsWith(aPrefNameSubReg)) { SubReg.Name = SubReg.Name.Remove(0, aPrefNameSubReg.Length); SubReg.ParentRegister = HardReg; lstSubRegToHard.Add(SubReg); } } HardReg.SubRegisters = lstSubRegToHard.ToArray(); } setReg.Registers = lstReg.ToArray(); } } } return(oReg); }
private void OnRegisterBegin() { _duplicateRegisterDefinition = false; _register = new HardwareRegister(); SetExpectedMatches(REGISTER_DEFINITION); }
/// <summary> /// Converts the underlying predicate register to a /// default target register. /// </summary> /// <param name="codeGenerator">The target code generator.</param> /// <param name="targetRegister">The target register to write to.</param> public void ConvertToValue( PTXCodeGenerator codeGenerator, HardwareRegister targetRegister) => codeGenerator.ConvertPredicateToValue( PredicateRegister, targetRegister);
private static Dictionary<string, HardwareRegisterSet> ProcessRegisterSetTypes(string file, out Dictionary<string, string> nested_types) { Dictionary<string, HardwareRegisterSet> types = new Dictionary<string, HardwareRegisterSet>(); nested_types = new Dictionary<string, string>(); Dictionary<string, int> dict_type_sizes = new Dictionary<string, int>(); dict_type_sizes["uint32_t"] = 32; dict_type_sizes["uint16_t"] = 16; dict_type_sizes["uint8_t"] = 8; Regex struct_regex = new Regex(@"typedef struct[ \t]*\r\n\{[ \t]*\r\n([^}]*)\r\n\}[ \t\r\n]*([A-Za-z0-9_]*)_(Global)?TypeDef;"); var structs = struct_regex.Matches(file); foreach (Match strct in structs) { HardwareRegisterSet set = new HardwareRegisterSet() { UserFriendlyName = strct.Groups[2].Value, ExpressionPrefix = strct.Groups[2].Value + "->" }; int set_size = 0; RegexOptions option = RegexOptions.IgnoreCase; Regex register_regex = new Regex(@"[ ]*(__IO|__I)*[ ]*(?:const )*[ ]*([^ #\r\n]*)[ ]*(?:const )*([^\[;#\r\n]*)[\[]?([0-9xXa-fA-F]+)*[\]]?;[ ]*(/\*)*(!<)*[ ]?([^,*\r\n]*)[,]?[ ]*(Ad[d]?ress)*( offset:)*[ ]*([0-9xXa-fA-F]*)[ ]?[-]?[ ]?([^ *\r\n]*)[ ]*(\*/)*[ ]*(\r\n)*", option); var regs = register_regex.Matches(strct.Groups[1].Value); List<HardwareRegister> hw_regs = new List<HardwareRegister>(); if (regs.Count == 0) throw new Exception("Register row parsing failed!"); foreach (Match m in regs) { string type = m.Groups[2].Value; if (!dict_type_sizes.ContainsKey(type)) throw new Exception("Unknown register type: " + type); int size = dict_type_sizes[type]; int array_size = 1; try { array_size = string.IsNullOrEmpty(m.Groups[4].Value) ? 1 : Int32.Parse(m.Groups[4].Value); } catch (FormatException ex) { string hex = m.Groups[4].Value; if (hex.StartsWith("0x")) hex = hex.Substring("0x".Length); array_size = Int32.Parse(hex, System.Globalization.NumberStyles.HexNumber); } string hex_offset = FormatToHex((ulong)(set_size / 8));// Do not use address from header file, sometimes they have errors //m.Groups[10].Value; if (size == 32)// all 32 bit addresses should start from an address divisible by 4 { hex_offset = FormatToHex((((ulong)(set_size / 8) + 3) / 4) * 4); set_size = Math.Max(set_size, (int)(ParseHex(hex_offset) * 8)) + array_size * size; } else set_size += array_size * size; string name = m.Groups[3].Value; if (name.StartsWith("RESERVED", StringComparison.InvariantCultureIgnoreCase)) continue; string readonly_type = m.Groups[1].Value; string desc = m.Groups[7].Value.TrimEnd(); bool flNameArrayFromOne = true; if (desc.StartsWith("DSI ")) flNameArrayFromOne = false; for (int i = 1; i <= array_size; i++) { if (array_size != 1) if ((set.UserFriendlyName == "GPIO") && (m.Groups[3].Value == "AFR")) { if (i == 1) name = m.Groups[3].Value + "L"; else if (i == 2) name = m.Groups[3].Value + "H"; else throw new Exception("Cannot use low-high naming with array sizes greater than 2!"); } else if(flNameArrayFromOne) name = m.Groups[3].Value + i.ToString(); else name = m.Groups[3].Value + (i-1).ToString(); if ((type != "uint32_t") && (type != "uint16_t") && (type != "uint8_t")) { int index = type.LastIndexOf("_TypeDef"); nested_types[set.UserFriendlyName + "_" + name] = type.Substring(0, index);// Chop the TypeDef off the type as it is easier to process later on } HardwareRegister hw_reg = new HardwareRegister { Name = name, SizeInBits = size, ReadOnly = (readonly_type == "__I") ? true : false, Address = hex_offset }; if (hw_regs.Find(x => ((x.Name == hw_reg.Name) && (x.Address == hw_reg.Address))) != null) throw new Exception("Register with the same name and address already exists in the set!"); hw_regs.Add(hw_reg); hex_offset = FormatToHex(ParseHex(hex_offset) + Math.Max((ulong)(size/8.0), (ulong)4)); } } dict_type_sizes[set.UserFriendlyName + "_TypeDef"] = set_size; set.Registers = hw_regs.ToArray(); if (types.ContainsKey(set.UserFriendlyName)) throw new Exception("Two registerset definitions with the same of " + set.UserFriendlyName + " found!"); types[set.UserFriendlyName] = set; } return types; }
public IOEmitter(string paramName, HardwareRegister tempRegister) { ParamName = paramName; TempRegister = tempRegister; }
public StoreEmitter( PointerType targetType, HardwareRegister addressRegister) { Emitter = new IOEmitter(targetType, addressRegister); }
private void OnStart() { _processedBits = 0; _registerNameToAddress = new Dictionary<string, string>(); _registerSetToAddress = new Dictionary<string, string>(); _subRegistersKnownValues = new Dictionary<string, IList<KeyValuePair<string, ulong>>>(); _registers = new List<HardwareRegister>(); _registerSets = new List<HardwareRegisterSet>(); _subRegisters = new List<HardwareSubRegister>(); _registersWithWrongBitsSum = new List<string>(); _duplicateRegisterDefinition = false; _lastMatch = Match.Empty; _matchedRegex = null; _registerSet = null; _register = null; _subRegister = null; _registerBits = new Dictionary<string, HardwareSubRegister>(); _expectedMatches = new List<Regex> { REGISTER_SET_ADDRESS }; }
public LoadEmitter( PointerType sourceType, HardwareRegister addressRegister) { Emitter = new IOEmitter(sourceType, addressRegister); }
static void GenerateBSP(string toolchainDir, string ccsDir) { string[] keys = null; string bspDir = toolchainDir + @"\msp430-bsp"; Dictionary <string, Dictionary <string, string> > tiMCUs = new Dictionary <string, Dictionary <string, string> >(StringComparer.CurrentCultureIgnoreCase); foreach (var line in File.ReadAllLines(@"..\..\msp430.csv")) { string[] cells = line.Split(';'); if (keys == null) { keys = cells; continue; } Dictionary <string, string> entry = new Dictionary <string, string>(); for (int i = 0; i < cells.Length; i++) { entry[keys[i]] = cells[i]; } tiMCUs[cells[0]] = entry; int idx = cells[0].IndexOf('-'); if (idx != -1) { tiMCUs[cells[0].Substring(0, idx)] = entry; } } Regex rgLen = new Regex(".*LENGTH = 0x([0-9a-fA-F]{4}).*"); Regex rgOrigin = new Regex(".*ORIGIN = 0x([0-9a-fA-F]{4}).*"); Regex rgPeriph = new Regex("__([^ ]+) = (0x[a-fA-F0-9]+);"); List <string> families = new List <string>(); List <MCU> MCUs = new List <MCU>(); List <MCUFamily> famList = new List <MCUFamily>(); Directory.CreateDirectory(bspDir); Directory.CreateDirectory(bspDir + "\\devices"); XmlSerializer regSer = new XmlSerializer(typeof(MCUDefinition)); string[] files = Directory.GetFiles(Path.Combine(toolchainDir, "include"), "*.h"); for (int i = 0; i < files.Length; i++) { string file = files[i]; var proc = new Process(); string mcuName = Path.GetFileNameWithoutExtension(file).ToLower(); proc.StartInfo.FileName = toolchainDir + @"\bin\msp430-elf-gcc.exe"; proc.StartInfo.Arguments = $"-I. -E {mcuName}.h -o - -mmcu={mcuName}"; proc.StartInfo.WorkingDirectory = Path.Combine(toolchainDir, "include"); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); List <string> lines = new List <string>(); for (; ;) { var line = proc.StandardOutput.ReadLine(); if (line == null) { break; } lines.Add(line); } proc.WaitForExit(); if (proc.ExitCode != 0) { continue; } List <HardwareRegister> regs = new List <HardwareRegister>(); MCU mcu = new MCU(); mcu.ID = mcuName; mcu.CompilationFlags.COMMONFLAGS = "-mmcu=" + mcuName; string ld = Path.ChangeExtension(file, ".ld"); if (!File.Exists(ld)) { continue; } foreach (var line in File.ReadAllLines(ld)) { if (line.StartsWith(" RAM")) { var m = rgLen.Match(line); mcu.RAMSize = int.Parse(m.Groups[1].ToString(), System.Globalization.NumberStyles.HexNumber); m = rgOrigin.Match(line); mcu.RAMBase = uint.Parse(m.Groups[1].ToString(), System.Globalization.NumberStyles.HexNumber); } if (line.StartsWith(" ROM")) { var m = rgLen.Match(line); mcu.FLASHSize = int.Parse(m.Groups[1].ToString(), System.Globalization.NumberStyles.HexNumber); m = rgOrigin.Match(line); mcu.FLASHBase = uint.Parse(m.Groups[1].ToString(), System.Globalization.NumberStyles.HexNumber); } } if (mcu.RAMSize == 0) { throw new Exception("RAM size cannot be 0"); } foreach (var line in lines) { Regex rgRegister = new Regex("extern volatile (.*) ([^ ]+) __asm__\\(\"([^\"]+)\"\\)"); var m = rgRegister.Match(line); if (!m.Success) { if (line.Contains("extern") && line.Contains("__asm__")) { throw new Exception("Suspicious line"); } continue; } string type = m.Groups[1].Value; string name = m.Groups[2].Value; if (name.EndsWith("_H") || name.EndsWith("_L")) { continue; } if (!m.Groups[3].Value.StartsWith("0x")) { throw new Exception("Invalid addr for " + name); } ulong addr = ulong.Parse(m.Groups[3].Value.Substring(2), System.Globalization.NumberStyles.HexNumber); HardwareRegister reg = new HardwareRegister(); // TODO: the registers are not all 8 bits // According to some datasheets (not all were checked): // 01FFh to 0100h -> 16 bits // 0FFh to 010h -> 8bits // 0Fh to 00h -> 8-bit SFR (special function register) if (type == "unsigned char") { reg.SizeInBits = 8; } else if (type == "unsigned int") { reg.SizeInBits = 16; } else if (type == "unsigned long int") { reg.SizeInBits = 32; } else { throw new Exception("Unknown type"); } reg.Name = name; reg.Address = m.Groups[3].Value; regs.Add(reg); } string family = "Other"; Dictionary <string, string> info; if (tiMCUs.TryGetValue(mcu.ID, out info)) { family = info["Description"]; } int idx = families.IndexOf(family); if (idx == -1) { idx = families.Count; families.Add(family); famList.Add(new MCUFamily { ID = "fam_" + idx, UserFriendlyName = family, CompilationFlags = null }); } mcu.FamilyID = "fam_" + idx.ToString(); mcu.MCUDefinitionFile = "devices\\" + mcu.ID + ".xml"; mcu.HierarchicalPath = family; MCUs.Add(mcu); MCUDefinition desc = new MCUDefinition { MCUName = mcu.ID, RegisterSets = new HardwareRegisterSet[] { new HardwareRegisterSet { Registers = regs.ToArray() } } }; //, Specs = specs }; AdjustHardwareRegisters(ccsDir, mcu.ID, ref desc.RegisterSets); using (var fs = File.Create(bspDir + "\\" + mcu.MCUDefinitionFile + ".gz")) using (var gs = new GZipStream(fs, CompressionMode.Compress)) regSer.Serialize(gs, desc); Console.WriteLine($"Processed {mcuName} ({i}/{files.Length}) [{i * 100 / files.Length}%]"); } //Build the XML file BoardSupportPackage bsp = new BoardSupportPackage { GNUTargetID = "msp430", PackageID = "com.sysprogs.msp430.core", PackageDescription = "MSP430 MCUs" }; bsp.SupportedMCUs = MCUs.ToArray(); bsp.MCUFamilies = famList.ToArray(); bsp.DebugMethodPackages = new string[] { "debuggers\\core", "debuggers\\mspdebug" }; bsp.Examples = new string[] { "Samples\\LEDBlink" }; #if BSP_ADDITIONAL_GCC_FLAGS bsp.AdditionalGCCFlags = new PropertyList { PropertyGroups = new PropertyGroup[] { new PropertyGroup { Name = "MSP430 Options", Properties = new PropertyEntry[] { new PropertyEntry.Boolean { Name = "Disable watchdog on startup", Description = "Link the crt0 modules that disable the watchdog on startup", UniqueID = "com.sysprogs.msp430.mdisable-watchdog", ValueForTrue = "-mdisable-watchdog", ValueForFalse = "", }, new PropertyEntry.Boolean { Name = "Enable libcalls for shifts", Description = "Use library routines for non-constant shifts", UniqueID = "com.sysprogs.msp430.menable-libcall-shift", ValueForTrue = "-menable-libcall-shift", ValueForFalse = "", }, new PropertyEntry.Boolean { Name = "Inline hardware multiplication", Description = "Issue inline multiplication code for 32-bit integers", UniqueID = "com.sysprogs.msp430.minline-hwmul", ValueForTrue = "-minline-hwmul", ValueForFalse = "", }, new PropertyEntry.Enumerated { Name = "Interrupt vector count", Description = "Specify number of interrupt vectors on chip:", UniqueID = "com.sysprogs.msp430.mivcnt", GNUPrefix = "-mivcnt=", SuggestionList = new PropertyEntry.Enumerated.Suggestion[] { new PropertyEntry.Enumerated.Suggestion { InternalValue = "", UserFriendlyName = "(default)" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "16" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "32" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "64" }, }, AllowFreeEntry = true, }, new PropertyEntry.Enumerated { Name = "Hardware multiplier", Description = "Define available hardware multiplier", UniqueID = "com.sysprogs.msp430.mmpy", GNUPrefix = "-mmpy=", SuggestionList = new PropertyEntry.Enumerated.Suggestion[] { new PropertyEntry.Enumerated.Suggestion { InternalValue = "", UserFriendlyName = "(default)" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "16" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "16se" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "32" }, new PropertyEntry.Enumerated.Suggestion { InternalValue = "32dw" }, } }, new PropertyEntry.Boolean { Name = "No hardware multiplication in ISRs", Description = "Assume interrupt routine does not do hardware multiplication", UniqueID = "com.sysprogs.msp430.noint-hwmul", ValueForTrue = "-noint-hwmul", ValueForFalse = "", }, new PropertyEntry.Boolean { Name = "Prologue space optimization", Description = "Use subroutine call for function prologue/epilogue when possible", UniqueID = "com.sysprogs.msp430.msave-prologue", ValueForTrue = "-msave-prologue", ValueForFalse = "", }, } } } }; #endif XmlSerializer ser = new XmlSerializer(typeof(BoardSupportPackage), PropertyEntry.EntryTypes); using (var fs = File.Create(bspDir + "\\BSP.xml")) ser.Serialize(fs, bsp); //mcuSelector1.Reset(); var lBsp = LoadedBSP.Load(new BSPSummary(bspDir), null); //mcuSelector1.AddBSP(lBsp); //embeddedDebugSettingsControl1.Reset(); //embeddedDebugSettingsControl1.AddDebugMethods(lBsp.KnownDebugMethods); }
/// <summary> /// Frees the given register. /// </summary> /// <param name="hardwareRegister">The register to free.</param> public abstract void FreeRegister(HardwareRegister hardwareRegister);
//--------------------------------- private static List<HardwareRegisterSet> ProcessLoadHardwareRegisterSet() { List<HardwareRegisterSet> oReg = new List<HardwareRegisterSet>(); List<HardwareSubRegister> alstSubReg = new List<HardwareSubRegister>(); var aLstPerep = GetBaseAdress(mNameCurrentAdr); foreach (var perep in aLstPerep) { List<HardwareRegister> alstReg = new List<HardwareRegister>(); ulong aBaseAdress = perep.adress; perep.used = true; foreach (var reg in adicAdrrOffsetDriv) { HardwareRegister Reg = new HardwareRegister(); alstSubReg.Clear(); Reg.Name = reg.Key; Reg.Address = FormatToHex(reg.Value + aBaseAdress); Reg.SizeInBits = 32; foreach (var subReg in adicBitsOffsetDriv) { if (subReg.Key.StartsWith(Reg.Name)) { HardwareSubRegister hsr = new HardwareSubRegister { Name = subReg.Key.Remove(0, Reg.Name.Length + 1), ParentRegister = Reg, OriginalMacroBase = Reg.Name, SizeInBits = GetSizeBit(subReg.Value), FirstBit = GetFirstBit(subReg.Value), }; if (hsr.SizeInBits == 0) Console.WriteLine("size subreg 0 " + hsr.Name); alstSubReg.Add(hsr); } } Reg.SubRegisters = alstSubReg.ToArray(); alstReg.Add(Reg); } if (alstReg.Count > 0) oReg.Add(new HardwareRegisterSet { ExpressionPrefix = mNameCurrentAdr, UserFriendlyName = perep.Name,// astrUserFrendlyName, Registers = alstReg.ToArray() }); } return oReg; }
public static Dictionary <string, HardwareRegisterSet[]> GenerateFamilyPeripheralRegistersAtmel(string familyDirectory, string fam) { // Create the hardware register sets for each subfamily Dictionary <string, HardwareRegisterSet[]> peripherals = new Dictionary <string, HardwareRegisterSet[]>(); // Create a hardware register set for each base address with the correctly calculated addresses List <HardwareRegisterSet> sets = new List <HardwareRegisterSet>(); HardwareRegisterSet set = new HardwareRegisterSet(); List <HardwareRegister> lstRegCustomType = new List <HardwareRegister>(); List <HardwareRegisterSet> setsCustom = new List <HardwareRegisterSet>(); aDicSizeTypeDefStuct.Clear(); int aSizeStruct = 0; Console.WriteLine("{0}Process PeripheralRegisters{1} ", ++aCountProgress, fam); // var aHRegs = UpdateSetsReg(familyDirectory, ref lstRegCustomType); // if (aHRegs != null) sets.AddRange(UpdateSetsReg(familyDirectory, ref lstRegCustomType)); /* if (fam.Contains("SAMl21")) * { * var aAddDir = familyDirectory.Replace("\\Include", "\\Include_b"); * sets.AddRange(UpdateSetsReg(familyDirectory, ref lstRegCustomType)); * }*/ List <HardwareRegisterSet> setsCustomMcu = sets; //Calculate size Struct foreach (var PerStruct in setsCustomMcu) { aSizeStruct = 0; foreach (var reg in PerStruct.Registers) { if (reg.SizeInBits == 0) { aSizeStruct = 0; break; } else { aSizeStruct += reg.SizeInBits; } } aDicSizeTypeDefStuct[PerStruct.UserFriendlyName] = aSizeStruct; } //Calculate size array custom type foreach (var CustTypReg in lstRegCustomType) { int strIdx1 = CustTypReg.Name.IndexOf("-"); int strIdx2 = CustTypReg.Name.IndexOf(":"); if (strIdx1 < 0 || strIdx2 < 0) { continue; } string str1 = CustTypReg.Name.Substring(strIdx1 + 1, CustTypReg.Name.Length - strIdx1 - 1); string asArray = CustTypReg.Name.Substring(strIdx2 + 1, strIdx1 - strIdx2 - 1); int asize; if (str1.StartsWith("RwReg") || str1.StartsWith("RoReg") || str1.StartsWith("WoReg")) { asize = int.Parse(str1.Substring(5)); } else { asize = aDicSizeTypeDefStuct[str1] * Convert.ToInt32(asArray); } CustTypReg.SizeInBits = asize; if (asize <= 32 && asize != 0) { CustTypReg.Name = CustTypReg.Name.Substring(0, strIdx2); } } //Rename big strucures foreach (var v in setsCustomMcu) { List <HardwareRegister> lr = new List <HardwareRegister>(); foreach (var r in v.Registers) { int strIdx1 = r.Name.IndexOf("-"); int strIdx2 = r.Name.IndexOf(":"); if (((r.SizeInBits <= 32 || r.Name.Contains("RESERVED")) && r.SizeInBits != 0)) { lr.Add(DeepCopy(r)); continue; } string typ = r.Name.Substring(strIdx1 + 1, r.Name.Length - strIdx1 - 1); foreach (var st in setsCustomMcu) { if (st.UserFriendlyName != typ) { continue; } foreach (var stsub in st.Registers) { HardwareRegister hr = DeepCopy(r); hr.Name = hr.Name.Substring(0, strIdx2) + "." + stsub.Name; hr.SizeInBits = stsub.SizeInBits; lr.Add(hr); } } } v.Registers = lr.ToArray(); } foreach (var fn in Directory.GetFiles(familyDirectory, "*.h")) { string aFileNameout = fn; if (fn.EndsWith("_1.h")) { continue; } if (fn.EndsWith("_0.h")) { aFileNameout = fn.Replace("_0.h", ".h"); } ///Set Base adress var aHrdRegFile = ProcessRegisterSetBaseAdress(fn, sets);//etsCustomMcu); if (aHrdRegFile.Count > 0) { peripherals.Add(Path.GetFileNameWithoutExtension(aFileNameout).ToUpper(), aHrdRegFile.ToArray()); } } /*if (fam.Contains("SAMl21")) * { * var aAddDir = familyDirectory.Replace("\\Include", "\\Include_b"); * * foreach (var fn in Directory.GetFiles(aAddDir, "*.h")) * { * string aFileNameout = fn; * if (fn.EndsWith("_1.h")) * continue; * if (fn.EndsWith("_0.h")) * aFileNameout = fn.Replace("_0.h", ".h"); * * ///Set Base adress * var aHrdRegFile = ProcessRegisterSetBaseAdress(fn, sets);//etsCustomMcu); * if (aHrdRegFile.Count > 0) * peripherals.Add(Path.GetFileNameWithoutExtension(aFileNameout).ToUpper(), aHrdRegFile.ToArray()); * } * }*/ return(peripherals); }
private static HardwareRegister DeepCopy(HardwareRegister reg) { HardwareRegister reg_new = new HardwareRegister { Name = reg.Name, Address = reg.Address, GDBExpression = reg.GDBExpression, ReadOnly = reg.ReadOnly, SizeInBits = reg.SizeInBits }; if (reg.SubRegisters != null) { reg_new.SubRegisters = new HardwareSubRegister[reg.SubRegisters.Length]; for (int i = 0; i < reg.SubRegisters.Length; i++) { reg_new.SubRegisters[i] = DeepCopy(reg.SubRegisters[i]); } } return reg_new; }
public static Dictionary <string, HardwareRegisterSet[]> GenerateFamilyPeripheralRegistersEFM32(string familyDirectory, string fam) { // Create the hardware register sets for each subfamily Dictionary <string, HardwareRegisterSet[]> peripherals = new Dictionary <string, HardwareRegisterSet[]>(); // Create a hardware register set for each base address with the correctly calculated addresses List <HardwareRegisterSet> sets = new List <HardwareRegisterSet>(); HardwareRegisterSet set = new HardwareRegisterSet(); List <HardwareRegister> lstRegCustomType = new List <HardwareRegister>(); List <HardwareRegisterSet> setsCustom = new List <HardwareRegisterSet>(); Dictionary <string, int> aDicSizeTypeDefStuct = new Dictionary <string, int>(); int aSizeStruct = 0; foreach (var fn in Directory.GetFiles(familyDirectory, fam + "_*.h")) { var aHRegs = ProcessRegisterSetNamesList(fn, ref lstRegCustomType); if (aHRegs != null) { sets.AddRange(aHRegs); } } foreach (var fn in Directory.GetFiles(familyDirectory, fam + "*.h")) { string sr = "^" + fam + "[0-9]+.*"; if (!Regex.IsMatch(Path.GetFileName(fn), sr, RegexOptions.IgnoreCase)) { continue; } setsCustom = ProcessRegisterSetNamesList(fn, ref lstRegCustomType); List <HardwareRegisterSet> setsCustomMcu = new List <HardwareRegisterSet>(); foreach (var aHRegMcu in sets) { bool aflRegRedefined = false; foreach (var aHrCustom in setsCustom) { if (aHrCustom.UserFriendlyName == aHRegMcu.UserFriendlyName) { aflRegRedefined = true; setsCustomMcu.Add(aHrCustom); break; } } if (!aflRegRedefined) { setsCustomMcu.Add(aHRegMcu); } } //Calculate size Struct foreach (var PerStruct in setsCustomMcu) { aSizeStruct = 0; foreach (var reg in PerStruct.Registers) { if (reg.SizeInBits == 0) { aSizeStruct = 0; break; } else { aSizeStruct += reg.SizeInBits; } } aDicSizeTypeDefStuct[PerStruct.UserFriendlyName] = aSizeStruct; } //Calculate size array custom type foreach (var CustTypReg in lstRegCustomType) { int strIdx1 = CustTypReg.Name.IndexOf("-"); int strIdx2 = CustTypReg.Name.IndexOf(":"); if (strIdx1 < 0 || strIdx2 < 0) { continue; } string str1 = CustTypReg.Name.Substring(strIdx1 + 1, CustTypReg.Name.Length - strIdx1 - 1); string asArray = CustTypReg.Name.Substring(strIdx2 + 1, strIdx1 - strIdx2 - 1); int asize = aDicSizeTypeDefStuct[str1] * Convert.ToInt32(asArray); CustTypReg.SizeInBits = asize; if (asize <= 32) { CustTypReg.Name = CustTypReg.Name.Substring(0, strIdx2); } } //Rename big strucures foreach (var v in setsCustomMcu) { List <HardwareRegister> lr = new List <HardwareRegister>(); foreach (var r in v.Registers) { int strIdx1 = r.Name.IndexOf("-"); int strIdx2 = r.Name.IndexOf(":"); if (r.SizeInBits <= 32 || r.Name.Contains("RESERVED")) { lr.Add(DeepCopy(r)); continue; } string typ = r.Name.Substring(strIdx1 + 1, r.Name.Length - strIdx1 - 1); foreach (var st in setsCustomMcu) { if (st.UserFriendlyName != typ) { continue; } foreach (var stsub in st.Registers) { HardwareRegister hr = DeepCopy(r); hr.Name = hr.Name.Substring(0, strIdx2) + "." + stsub.Name; hr.SizeInBits = stsub.SizeInBits; lr.Add(hr); } } } v.Registers = lr.ToArray(); } ///Set Base adress var aHrdRegFile = ProcessRegisterSetBaseAdress(fn, setsCustomMcu); peripherals.Add(Path.GetFileNameWithoutExtension(fn).ToUpper(), aHrdRegFile.ToArray()); } return(peripherals); }
private static HardwareRegister[] ProcessStructContents(string structContents, bool insideUnion, out ulong structSize) { List <HardwareRegister> regs = new List <HardwareRegister>(); ulong hex_offset = 0; structSize = 0; Dictionary <string, int> dict_type_sizes = new Dictionary <string, int>(); dict_type_sizes["uint32_t"] = 32; dict_type_sizes["uint16_t"] = 16; dict_type_sizes["uint8_t"] = 8; Regex reg_regex = new Regex(@"([ \t_IO]*)([^ }]+) ([^ \[\]]*)[\[]?([0-9]*)[\]]?[\[]?([0-9]*)[\]]?;", RegexOptions.Multiline); Regex union_regex = new Regex(@"union {(.+?)};", RegexOptions.Singleline); Regex inner_struct_regex = new Regex(@"struct {(.+?)} ([^ \[\]]+)[\[]?([0-9]*)[\]]?[\[]?([0-9]*)[\]]?", RegexOptions.Singleline); Match union_m = null, inner_struct_m = null, reg_m = null; int struct_regs_index = 0; while (true) { union_m = union_regex.Match(structContents, struct_regs_index); inner_struct_m = inner_struct_regex.Match(structContents, struct_regs_index); reg_m = reg_regex.Match(structContents, struct_regs_index); if (!(union_m.Success || inner_struct_m.Success || reg_m.Success)) { break; } if (reg_m.Success && !(union_m.Success && (union_m.Index < reg_m.Index)) && !(inner_struct_m.Success && (inner_struct_m.Index < reg_m.Index)))// next match is a register { string reg_type = reg_m.Groups[2].ToString(); string reg_name = reg_m.Groups[3].ToString(); int reg_array_size = string.IsNullOrEmpty(reg_m.Groups[4].Value) ? 1 : Int32.Parse(reg_m.Groups[4].Value); int reg_array_size2 = string.IsNullOrEmpty(reg_m.Groups[5].Value) ? 1 : Int32.Parse(reg_m.Groups[5].Value); struct_regs_index = reg_m.Index + reg_m.Length; if (reg_name.StartsWith("RESERVED")) { hex_offset += (ulong)reg_array_size * (ulong)reg_array_size2 * (ulong)(dict_type_sizes[reg_type] / 8.0); if (insideUnion) { throw new Exception("There should be no RESERVED registers inside unions!"); } continue; // RESERVED registers are not true registers, do not save them } for (int i = 1; i <= reg_array_size; i++) { for (int j = 1; j <= reg_array_size2; j++) { string name = reg_name; if (reg_array_size != 1) { name += "_" + (i - 1).ToString(); } if (reg_array_size2 != 1) { name += "_" + (j - 1).ToString(); } regs.Add(new HardwareRegister() { Name = name, SizeInBits = dict_type_sizes[reg_type], Address = FormatToHex(hex_offset), }); hex_offset += (ulong)(dict_type_sizes[reg_type] / 8.0); if (insideUnion && (structSize == 0)) { structSize = (ulong)reg_array_size * (ulong)reg_array_size2 * (ulong)(dict_type_sizes[reg_type] / 8.0); } } } if (insideUnion) { hex_offset = 0; } } else if (union_m.Success && !(reg_m.Success && (reg_m.Index < union_m.Index)) && !(inner_struct_m.Success && (inner_struct_m.Index < union_m.Index))) // next match is an union { string union_contents = union_m.Groups[1].ToString(); ulong size; HardwareRegister[] union_regs = ProcessStructContents(union_contents, true, out size); //Filter out useless registers of unions HardwareRegister main_reg = null; foreach (var reg in union_regs) { if ((main_reg == null) || (main_reg.Name.Length > reg.Name.Length)) { main_reg = reg; } reg.Address = FormatToHex(ParseHex(reg.Address) + hex_offset); } bool split_reg = true; foreach (var reg in union_regs) { if (!((reg.Name == main_reg.Name) || (reg.Name == main_reg.Name + "L") || (reg.Name == main_reg.Name + "H") || (reg.Name == main_reg.Name + "LL") || (reg.Name == main_reg.Name + "LU") || (reg.Name == main_reg.Name + "HL") || (reg.Name == main_reg.Name + "HU"))) { split_reg = false; break; } } if (split_reg) { regs.Add(main_reg); } else { regs.AddRange(union_regs); } hex_offset += size; struct_regs_index = union_m.Index + union_m.Length; } else if (inner_struct_m.Success && !(union_m.Success && (union_m.Index < inner_struct_m.Index)) && !(reg_m.Success && (reg_m.Index < inner_struct_m.Index))) // next match is a struct { string inner_struct_name = inner_struct_m.Groups[2].ToString(); string inner_struct_contents = inner_struct_m.Groups[1].ToString(); int inner_struct_array_size = string.IsNullOrEmpty(inner_struct_m.Groups[3].Value) ? 1 : Int32.Parse(inner_struct_m.Groups[3].Value); int inner_struct_array_size2 = string.IsNullOrEmpty(inner_struct_m.Groups[4].Value) ? 1 : Int32.Parse(inner_struct_m.Groups[4].Value); ulong inner_struct_size; HardwareRegister[] struct_regs = ProcessStructContents(inner_struct_contents, false, out inner_struct_size); for (int i = 1; i <= inner_struct_array_size; i++) { for (int j = 1; j <= inner_struct_array_size2; j++) { string suffix = ""; if (inner_struct_array_size != 1) { suffix += "_" + i.ToString(); } if (inner_struct_array_size2 != 1) { suffix += "_" + j.ToString(); } foreach (var struct_reg in struct_regs) { HardwareRegister cpy = DeepCopy(struct_reg); cpy.Name += suffix; cpy.Address = FormatToHex(ParseHex(cpy.Address) + hex_offset); regs.Add(cpy); } if (!insideUnion) { hex_offset += inner_struct_size; } else { structSize = inner_struct_size; if ((inner_struct_array_size != 1) || (inner_struct_array_size2 != 1)) { throw new Exception("Structures inside unions are not expected to be arrays!"); } } } } struct_regs_index = inner_struct_m.Index + inner_struct_m.Length; } else { throw new Exception("Cannot parse struct contents!"); } } if (!insideUnion) { structSize = hex_offset; } return(regs.ToArray()); }
public static List <HardwareRegisterSet> ProcessRegisterSetNamesList(string pFileName, ref List <HardwareRegister> lstRegCustomType) { List <HardwareRegisterSet> oReg = new List <HardwareRegisterSet>(); bool aStartCheckReg = false; List <HardwareRegister> lstReg = new List <HardwareRegister>(); int sizeArray; foreach (var ln in File.ReadAllLines(pFileName)) { if (ln == "typedef struct") { lstReg = new List <HardwareRegister>(); aStartCheckReg = true; } if (!aStartCheckReg) { continue; } Match m = Regexes.argSearchReg.Match(ln); if (m.Success) { sizeArray = m.Groups[4].Value == "" ? 1 : Convert.ToInt16(m.Groups[4].Value); for (int a_cnt = 0; a_cnt < sizeArray; a_cnt++) { lstReg.Add(new HardwareRegister() { Name = (sizeArray > 1) ? m.Groups[3].Value + "[" + a_cnt + "]" : m.Groups[3].Value, ReadOnly = (m.Groups[1].Value == "__I") ? true : false, SizeInBits = GetSizeInBitsPoor(m.Groups[2].Value) }); } } else { m = Regexes.argSearchRegReserv.Match(ln); //reserverd array if (m.Success) { sizeArray = m.Groups[3].Value == "" ? 1 : Convert.ToInt32(m.Groups[3].Value); lstReg.Add(new HardwareRegister() { Name = m.Groups[2].Value, SizeInBits = GetSizeInBitsPoor(m.Groups[1].Value, Convert.ToInt32(sizeArray)), }); } // Typedef Array m = Regexes.argSearchRegTypeDef.Match(ln); if (m.Success) { sizeArray = m.Groups[3].Value == "" ? 1 : Convert.ToInt16(m.Groups[3].Value); for (int a_cnt = 0; a_cnt < sizeArray; a_cnt++) { HardwareRegister setReg = new HardwareRegister(); if (sizeArray > 1) { setReg.Name = m.Groups[2].Value + "[" + a_cnt + "]:1-" + m.Groups[1].Value;//name register - custom type } else { setReg.Name = m.Groups[2].Value + ":" + sizeArray + "-" + m.Groups[1].Value;//name register - custom type } setReg.SizeInBits = 0; lstReg.Add(setReg); lstRegCustomType.Add(setReg); } } //end m = Regexes.argSearchFrendName.Match(ln); if (m.Success) { HardwareRegisterSet setReg = new HardwareRegisterSet(); setReg.UserFriendlyName = m.Groups[1].Value; aStartCheckReg = false; oReg.Add(setReg); var originalSubRegs = ProcessRegisterSetSubRegisters(pFileName); foreach (var HardReg in lstReg) { var lstSubRegs = originalSubRegs.Select(s => CloneSubregister(s)).ToList(); List <HardwareSubRegister> lstSubRegToHard = new List <HardwareSubRegister>(); string aPrefNameSubReg = setReg.UserFriendlyName + "_" + HardReg.Name + "_"; foreach (var SubReg in lstSubRegs) { if (SubReg.Name.StartsWith(aPrefNameSubReg)) { SubReg.Name = SubReg.Name.Remove(0, aPrefNameSubReg.Length); SubReg.ParentRegister = HardReg; lstSubRegToHard.Add(SubReg); } } HardReg.SubRegisters = lstSubRegToHard.ToArray(); } setReg.Registers = lstReg.ToArray(); } } } return(oReg); }
static void AdjustHardwareRegisters(string ccsDir, string mcuName, ref HardwareRegisterSet[] hardwareRegisterSets) { string dir = ccsDir + @"\ccs_base\common\targetdb\devices"; if (!Directory.Exists(dir)) { throw new Exception("Missing " + dir); } string tiDefinitionFile = dir + "\\" + mcuName + ".xml"; if (!File.Exists(tiDefinitionFile)) { return; } XmlDocument doc = new XmlDocument(); doc.Load(tiDefinitionFile); Dictionary <string, ulong> oldRegisters = new Dictionary <string, ulong>(); foreach (var set in hardwareRegisterSets) { foreach (var reg in set.Registers) { string name = reg.Name; if (name.EndsWith("_H")) { continue; } else if (name.EndsWith("_L")) { name = name.Substring(0, name.Length - 2); } oldRegisters[name] = ParseAddr(reg.Address); } } List <HardwareRegisterSet> newRegisterSets = new List <HardwareRegisterSet>(); foreach (XmlNode node in doc.SelectNodes("device/cpu/instance")) { XmlElement el = node as XmlElement; if (el == null) { continue; } string peripheralDefinition = Path.Combine(Path.GetDirectoryName(tiDefinitionFile), el.Attributes["href"].Value); if (!File.Exists(peripheralDefinition)) { throw new NotSupportedException(); } string addr = el.Attributes["baseaddr"].Value; if (addr != "0x0000") { throw new NotSupportedException(); } if (peripheralDefinition.EndsWith("_NotVisible.xml")) { continue; } XmlDocument xmlModule = new XmlDocument(); xmlModule.Load(peripheralDefinition); var newSet = new HardwareRegisterSet { UserFriendlyName = xmlModule.SelectSingleNode("module").Attributes["description"].Value }; newRegisterSets.Add(newSet); List <HardwareRegister> newRegs = new List <HardwareRegister>(); foreach (XmlElement reg in xmlModule.SelectNodes("module/register")) { string registerID = reg.Attributes["id"].Value; ulong lAddr = ParseAddr(reg.Attributes["offset"].Value.Trim()); ulong oldAddr; int sizeInBits = int.Parse(reg.Attributes["width"].Value); if (oldRegisters.TryGetValue(registerID, out oldAddr)) { if (oldAddr != lAddr) { Debugger.Log(0, "Warning", "Address mismatch for " + registerID + "\n"); } oldRegisters[registerID] = ulong.MaxValue; } HardwareRegister newReg = new HardwareRegister { Name = registerID, Address = string.Format("0x{0:x}", lAddr), SizeInBits = sizeInBits }; List <HardwareSubRegister> subRegs = new List <HardwareSubRegister>(); foreach (XmlElement field in reg.SelectNodes("bitfield")) { string fieldID = field.Attributes["id"].Value; int start = int.Parse(field.Attributes["begin"].Value); int end = int.Parse(field.Attributes["end"].Value); int width = int.Parse(field.Attributes["width"].Value); if (start == (end + width - 1)) { int tmp = start; start = end; end = tmp; } if (end != (start + width - 1)) { throw new NotSupportedException(); } var subReg = new HardwareSubRegister { Name = fieldID, FirstBit = start, SizeInBits = width }; KnownSubRegisterValue[] subValues = null; bool bad = false; int bitenumValuesChecked = 0; foreach (XmlElement val in field.SelectNodes("bitenum")) { if (subValues == null) { subValues = new KnownSubRegisterValue[1 << width]; } string valName = val.Attributes["id"].Value; int value = int.Parse(val.Attributes["value"].Value); if (value >= subValues.Length) { bad = true; } else { subValues[value] = new KnownSubRegisterValue { Name = valName } }; bitenumValuesChecked++; } if (bad) { subValues = null; if (bitenumValuesChecked == (1 << width)) { //There's a typo in the XML files. Sometimes the 'value' for a divider is taken from the divider value and not the bitfield value. Let's try fixing it! subValues = new KnownSubRegisterValue[1 << width]; int idx = 0; int lastDividerValue = 0; foreach (XmlElement val in field.SelectNodes("bitenum")) { string valName = val.Attributes["id"].Value; int tmp = valName.LastIndexOf('_'); int dividerValue = int.Parse(valName.Substring(tmp + 1)); if (dividerValue < lastDividerValue) { throw new NotSupportedException(); //If the values are listed in the ascending order, we can assume that they are listed in the bitfield value order. } lastDividerValue = dividerValue; subValues[idx++] = new KnownSubRegisterValue { Name = valName }; } } } if (subValues != null) { foreach (var v in subValues) { if (v == null) { subValues = null; break; } } } subReg.KnownValues = subValues; subRegs.Add(subReg); } if (subRegs.Count > 0) { newReg.SubRegisters = subRegs.ToArray(); } newRegs.Add(newReg); } newSet.Registers = newRegs.ToArray(); } foreach (var kv in oldRegisters) { if (kv.Value != ulong.MaxValue) { Debugger.Log(0, "", "TI XML does not list " + kv.Key + "\n"); } } hardwareRegisterSets = newRegisterSets.ToArray(); }