Project

General

Profile

Template Description Language » History » Revision 3

Revision 2 (Alexander Kamkin, 04/12/2012 10:56 AM) → Revision 3/139 (Artemiy Utekhin, 03/04/2013 02:59 PM)

h1. Ruby-MT - MicroTESK Template Description Language Язык описания шаблонов тестовых программ 

 Язык *Ruby-MT (Ruby for MicroTESK)* is a Ruby-based domain specific language geared towards writing compact and reusable tests for microprocessors and other programmable devices. The language intends to look similar to the assembler of the target CPU предназначен для компактного и переиспользуемого описания функциональных тестов для микропроцессоров и других программируемых устройств. Язык представляет собой смесь языка ассемблера целевого микропроцессора (*TL, Target Language*) complemented by higher level features consisting of both standard Ruby and features specific to the Ruby-MT implementation и управляющего языка высокого уровня (*ML, Meta Language*). Ruby-MT, in a sense, is similar to a macro processor - it generates code in the target language based on the provided meta language. 

 Since Ruby-MT is built as a При этом ML можно рассматривать как макропроцессор, поскольку в результате выполнения его конструкций генерируется текст на TL. Язык построен на основе Ruby library providing an internal DSL no additional parsers are required. Currently, because of the extensive use of Java, Ruby-MT templates can only be executed by the JRuby interpreter. CRuby will probably be supported at a later stage. в форме библиотечного расширения (не требуется дополнительных парсеров и т.п.). 

 h2. The translation process 

 Код на Ruby-MT code describes a template of a test program which is then translated into TL code using the API of the MicroTESK CPU model parser and simulator (and, by extension, the constraint solver and other MicroTESK components). The process can be described as follows: описывает шаблон тестовой программы (далее для краткости шаблон). Обработка шаблона состоит из следующих шагов: 

 # Receiving model metadata from the simulator; Препроцессирование шаблона. 
 # Template pre-processing; 
 # Constructing commands in the simulator; 
 # Executing commands in the simulator; 
 # Receiving the assembler code from the simulator (based on the CPU Sim-nML description); 
 # Writing the TL output to target files. Выполнение шаблона. 

 Depending on the circumstances some of these steps may be done concurrently.  

 h2. Configuration При выполнении шаблона, он генерирует программу путем обращения к базе данных ограничений, солверам и другим стандартным компонентам генератора через *API генератора*. 

 _Pending..._ 

 h2. Execution Интуитивное описание языка на примерах 

 Right now there is a simple execution script that requires a template file and an optional output file (if it''s not provided the library uses the standard output to print out the results). To run a template, execute the following command: 

 <pre>jruby parse_templates.rb <template file.rb> [<output file.asm>]</pre> 

 h2. Writing templates 

 h3. Basic features Пример 1 (MIPS) 

 The two core abstractions used by MicroTESK parser/simulator and Ruby-MT are an *instruction* and an *addressing mode*. An instruction is rather self-explanatory, it simply represents a target assembler instruction. Every argument of an instruction is a parametrized *addressing mode* that explains the meaning of the provided values to the simulator. The mode could point to the registers, for instance, or to a specific memory location. It can also denote an immediate value - e.g. a simple integer or a string. Thus, a basic template is effectively a sequence of instructions with parametrized addressing modes as their arguments. 

 Each template is a <pre> 
 # В базовом шаблоне содержатся общие инструкции инициализации и завершения работы микропроцессора 
 class that inherits a basic Template class that provides most of the core Ruby-MT functionality. So, to write a template you need to subclass Template first: 

 <pre>require_relative "_path-to-the-rubymt-library_/mtruby" 

 class MyTemplate < Template</pre> 

 While processing a template Ruby-MT calls its %pre%, %run% and %post% methods, loosely meaning the pre-conditions, the main body and the post-conditions. The %pre% method is mostly useful for setup common to many templates, the %post% method will be more important once sequential testing is introduced. Most of the template code is supposed to be in the %run% method. Thus, a template needs to override one or more of these methods, most commonly %run%. 

 To get %pre% and %post% over with, the most common usage of these is to make a special non-executable class and then subclass it with the actual templates: 

 <pre>require_relative "_path-to-the-rubymt-library_/mtruby" 

 class MyPrepost < Template 
   def initialize MIPS::Template 
     super # Главный метод теста 
     @is_executable = no 
   end 

   def pre 
     test() 
         # Your ''startup'' code goes here 
   end 

   def post Повторить в тестовой программе 100 раз следующую ситуацию 
         100.times { 
             # Добавление в тестовую программу комментария 
             text(''# --------------------------------------------------------------------------------''); 
             # Загрузка в регистр reg1 содержимого памяти по адресу, содержащемуся в регистре base1 
             # Функция r выделяет новый регистр общего назначения 
             ld reg1=r, 0x0(base1=r)    ;; goal([l1Hit,50],[!l1Hit,50])          # Попадание в кэш-память L1 осуществляются с вероятностью 50% 
             # Загрузка в регистр reg2 содержимого памяти по адресу, содержащемуся в регистре base2 
             ld reg2=r, 0x0(base2=r)    ;; goal(l1Hit && !equal(base1, base2)) # Адреса первой и второй инструкции загрузки не должны совпадать ([base1] != [base2]) 
             # Запись результата сложения содержимого регистров reg1 и reg2 в регистр res 
             dadd res=r, reg1, reg2     ;; goal(!integerOverflow)                # При сложении не должно возникать переполнения 
         } 
     # Your ''cleanup'' code goes here 
   end 
 end</pre> 

 <pre>require_relative "_path-to-the-rubymt-library_/mtruby" 

 class MyTemplate < MyPrepost 
   def initialize 
     super 
     @is_executable = yes 
   end 
  
   def run 
     # Your template code goes here 
   end 
 end</pre> 

 These methods essentially contain the instructions. The general instruction format is slightly more intimidating than the native assembler and looks like this: 

 <pre> instruction_name addr_mode1(:arg1_1 => value, :arg1_2 => value, ...), addr_mode2(:arg2_1 => value, ...), ...</pre> 

 So, for instance, if the simulator has an ADD(MEM(i), MEM(i)|IMM(i)) instruction, it would look like: 

 <pre> add mem(:i => 42), imm(:i => 128) </pre> 

 Thankfully, there are shortcuts. If there''s only one argument expected in the addressing mode, you can simply write its value and never have to worry about the argument name. And, by convention, the immediate values are always denoted in the simulator as the IMM addressing mode, so the template parser automatically accepts numbers and strings as such. Thus, in this case, the instruction can be simplified to: В результате обработки этого шаблона будет сгенерирована программа следующего вида. 

 <pre> add mem(42), 128 
 ... 
 # -------------------------------------------------------------------------------- 
 ld reg001_1, 0x0(base001_1) 
 ld reg001_2, 0x0(base001_2) 
 dadd res001, reg001_1, reg001_2 
 ... 
 # -------------------------------------------------------------------------------- 
 ld reg100_1, 0x0(base100_1) 
 ld reg100_2, 0x0(base100_2) 
 dadd res100, reg100_1, reg100_2 
 ... 
 </pre> 

 If the name of the instruction conflicts with an already existing Ruby method, the instruction will be available with an %op_% prefix before its name. В этой программе @regXXX_{1,2}@, @baseXXX_{1,2}@ и @resXXX@ - это регистры общего назначения (некоторые из них совпадают друг с другом). В начале программы (возможно, и в некоторых промежуточных точках) располагается *управляющий код*, инициализирующий регистры и память так, чтобы удовлетворить заданным в шаблоне ограничениям. 

 h3. Test situations >> *TODO:* нужно переопределить операции для тестовых ситуаций (!, &&, ||). 
 >> *TODO:* пока можно ограничиться случаем одной тестовой ситуации в @goal()@. 

 _This section is to be taken with a grain of salt because the logic and the interface behind the situations is not yet finalized and mostly missing from the templates and shouldn''t be used yet_ h2. Распределение регистров 

 _Big TODO: define what is a test situation_ 

 To denote a test situation, add a Ruby block that describes situations to an instruction, this will loosely look like this (likely similar to the way the addressing modes are denoted): 

 <pre> sub mem(42), mem(21) do overflow(:op1 => 123, :op2 => 456) end</pre> 

 h3. Instruction blocks 

 Sometimes a certain test situation should influence more than just one instruction. In that case, you can pass the instructions in an atomic block that can optionally accept a Proc of situations as its argument (because Ruby doesn''t want to be nice and allow multiple blocks for a method, and passing a Hash of Proc can hardly be called comfortable). 

 <pre>p Для каждого типа регистров (@GPR@, @FPR@ и т.п.) определена *функция распределения регистров* (например, функция @r = lambda { overflow(:op1 => 123, :op2 => 456) } def(GPR)@ в примере выше). Эта функция имеет один целочисленный параметр - номер регистра. Если при вызове функции распределения регистров параметр не указан, функция выделяет регистр согласно некоторой *стратегии распределения регистров*. Например, она может возвращать один из не занятых регистров (естественно, возвращаемый регистр помечается как занятый). Поскольку регистров конечное число, не исключены случаи, когда все регистры заняты. В таких ситуациях логично выделять регистры, которые давно не использовались и попутно печатать предупреждение о нехватке регистров. При выходе из блока занятые в этом блоке регистры автоматически освобождаются. Кроме того, предусмотрена функция *освобождения занятых регистров* @free@. Для того чтобы "застолбить" регистр @reg@, нужно вызывать @lock(reg)@. 

 atomic p { 
   mov mem(25), mem(26) 
   add mem(27), 28 
   sub mem(29), 30 
 }</pre> Для распределения регистров в программе используются следующие правила: 

 h3. Groups and random selections *1. Если в качестве регистра в шаблоне используется конкретный регистр, то этот регистр используется и в сгенерированной программе.* 

 There are certain ways to group together or randomize addressing modes and instructions. Например, для шаблона 

 To group several addressing modes together (this only works if they have similar arguments) create a mode group like this: 

 <pre> mode_group "my_group" [:mem, :imm] 
 ori reg=r, r0, 0x0 
 </pre> 

 You can also set weights to each of the modes in the group like this: второй регистр инструкции @ori@ (регистр @r0@) фиксирован. Примером программы, соответствующей этому шаблону является 

 <pre> mode_group "my_group" {:mem => 1.5, :imm => 2.5} 
 ori r7, r0, 0x0 # Регистр r0 фиксирован 
 </pre> 

 The name of the group is converted into a method in the Template class. To select a random mode from a group, use %sample% on this generated method: *2. Если имена переменных, обозначающих регистры, в шаблоне совпадают (в пределах одной области видимости), то в соответствующих частях итоговой программы будет использоваться один и тот же регистр.* 

 Например, для шаблона 

 <pre> 
 2.times { 
     add mem(42), my_group.sample(21) reg1=r, r,      r 
     sub r,        reg1, r # Результат сложения используется в качестве вычитаемого 
 } 
 </pre> 

 _TODO: sampling already parametrized modes_ первый регистр инструкции @add@ всегда будет совпадать со вторым регистром инструкции @sub@, хотя эти регистры могут быть разными на разных итерациях: 

 The first method of grouping instructions works in a similar manner with the same restrictions on arguments: 

 <pre> group "i_group" [:add, :sub]</pre> 

 <pre> group "i_group" {:add => 0.3, :sub => 0.7]</pre> 

 <pre>i_group.sample mem(42), 21</pre> 

 You can also run all of the instructions in a group at once by using the %all% method: 

 <pre>i_group.all mem(42), 21</pre> 

 The second one allows you to create a normal block of instructions, setting their arguments separately.  

 <pre> block_group "b_group" do 
   mov mem(25), mem(26) 
   
 # -------------------------------------------------------------------------------- 
 add mem(27), 28 
   r2,    r10, r5 
 sub mem(29), 30 r9,    r2,    r15 # Зависимость по регистру r2 
 end</pre> # -------------------------------------------------------------------------------- 
 add r11, r27, r9 
 sub r9,    r11, r23 # Зависимость по регистру r11 
 </pre> 

 In this case to set weights you should call a %prob% method before every instruction: Более сложный пример 

 <pre> block_group "b_group" do 
   prob 0.1 
   mov mem(25), mem(26) 
   prob 0.7 
   
 ori reg1=r, r0, 0x0 
 2.times { 
     add mem(27), 28 
   prob 0.4 
   reg1, r,      r # Результат сложения заносится в тот же регистр, что и результат вышестоящей инструкции 
     sub mem(29), 30 r,      reg1, r # Результат сложения используется в качестве вычитаемого 
 end</pre> } 
 </pre> 

 The usage is almost identical, but without providing the arguments as they are already set: В этот случае регистры @reg1@ на первой и второй итерациях будут совпадать между собой и будут равны первому регистру инструкции @ori@. 

 <pre>b_group.sample В следующем примере зависимости по регистрам нет, поскольку области видимости переменных-регистров не пересекаются (теоретически, но маловероятно, номера регистров могут совпасть): 

 <pre> 
 b_group.all</pre> 2.times { 
     add reg1=r, r, r 
 } 
 2.times { 
     add reg1=r, r, r # Зависимость по регистрам не предполагается 
 } 
 </pre> 

 _Not sure how does it work inside atomics when the group is defined outside, needs more consideration_ *3. Если имена переменных, обозначающих регистры, в шаблоне различаются, либо переменные находятся в разных областях видимости, то в соответствующих частях итоговой программы возможны совпадающие регистры.* 

 _TODO: Permutations_ 

 Any normal Ruby code is allowed inside the blocks as well as the %run%-type methods, letting you write more complex or inter-dependent templates. Регистров ограниченное число, поэтому пересечения по регистрам неизбежны.