diff --git a/docs/LangRef.html b/docs/LangRef.html index 0b639c00990..05de0bd4cfb 100644 --- a/docs/LangRef.html +++ b/docs/LangRef.html @@ -1,582 +1,508 @@ - +
Written by Chris Lattner and Vikram Adve
-
This document is a reference manual for the LLVM assembly language. LLVM is -an SSA based representation that provides type safety, low-level operations, -flexibility, and the capability of representing 'all' high-level languages -cleanly. It is the common code representation used throughout all phases of the -LLVM compilation strategy.
- -This document is a reference manual for the LLVM assembly language. +LLVM is an SSA based representation that provides type safety, +low-level operations, flexibility, and the capability of representing +'all' high-level languages cleanly. It is the common code +representation used throughout all phases of the LLVM compilation +strategy.
The LLVM code representation is designed to be used in three different forms: -as an in-memory compiler IR, as an on-disk bytecode representation (suitable for -fast loading by a Just-In-Time compiler), and as a human readable assembly -language representation. This allows LLVM to provide a powerful intermediate -representation for efficient compiler transformations and analysis, while -providing a natural means to debug and visualize the transformations. The three -different forms of LLVM are all equivalent. This document describes the human -readable representation and notation.
- -The LLVM representation aims to be a light-weight and low-level while being -expressive, typed, and extensible at the same time. It aims to be a "universal -IR" of sorts, by being at a low enough level that high-level ideas may be -cleanly mapped to it (similar to how microprocessors are "universal IR's", -allowing many source languages to be mapped to them). By providing type -information, LLVM can be used as the target of optimizations: for example, -through pointer analysis, it can be proven that a C automatic variable is never -accessed outside of the current function... allowing it to be promoted to a -simple SSA value instead of a memory location.
- +The LLVM code representation is designed to be used in three +different forms: as an in-memory compiler IR, as an on-disk bytecode +representation (suitable for fast loading by a Just-In-Time compiler), +and as a human readable assembly language representation. This allows +LLVM to provide a powerful intermediate representation for efficient +compiler transformations and analysis, while providing a natural means +to debug and visualize the transformations. The three different forms +of LLVM are all equivalent. This document describes the human readable +representation and notation.
+The LLVM representation aims to be a light-weight and low-level +while being expressive, typed, and extensible at the same time. It +aims to be a "universal IR" of sorts, by being at a low enough level +that high-level ideas may be cleanly mapped to it (similar to how +microprocessors are "universal IR's", allowing many source languages to +be mapped to them). By providing type information, LLVM can be used as +the target of optimizations: for example, through pointer analysis, it +can be proven that a C automatic variable is never accessed outside of +the current function... allowing it to be promoted to a simple SSA +value instead of a memory location.
It is important to note that this document describes 'well formed' LLVM -assembly language. There is a difference between what the parser accepts and -what is considered 'well formed'. For example, the following instruction is -syntactically okay, but not well formed:
- -- %x = add int 1, %x -- -
...because the definition of %x does not dominate all of its uses. -The LLVM infrastructure provides a verification pass that may be used to verify -that an LLVM module is well formed. This pass is automatically run by the -parser after parsing input assembly, and by the optimizer before it outputs -bytecode. The violations pointed out by the verifier pass indicate bugs in -transformation passes or input to the parser.
- - - -It is important to note that this document describes 'well formed' +LLVM assembly language. There is a difference between what the parser +accepts and what is considered 'well formed'. For example, the +following instruction is syntactically okay, but not well formed:
+%x = add int 1, %x+
...because the definition of %x does not dominate all of +its uses. The LLVM infrastructure provides a verification pass that may +be used to verify that an LLVM module is well formed. This pass is +automatically run by the parser after parsing input assembly, and by +the optimizer before it outputs bytecode. The violations pointed out +by the verifier pass indicate bugs in transformation passes or input to +the parser.
+ -LLVM uses three different forms of identifiers, for different purposes:
- +LLVM uses three different forms of identifiers, for different +purposes:
LLVM requires the values start with a '%' sign for two reasons: Compilers -don't need to worry about name clashes with reserved words, and the set of -reserved words may be expanded in the future without penalty. Additionally, -unnamed identifiers allow a compiler to quickly come up with a temporary -variable without having to avoid symbol table conflicts.
- -Reserved words in LLVM are very similar to reserved words in other languages. -There are keywords for different opcodes ('add', -'cast', 'ret', -etc...), for primitive type names ('void', -'uint', etc...), and others. These reserved -words cannot conflict with variable names, because none of them start with a '%' -character.
- -Here is an example of LLVM code to multiply the integer variable -'%X' by 8:
- +LLVM requires the values start with a '%' sign for two reasons: +Compilers don't need to worry about name clashes with reserved words, +and the set of reserved words may be expanded in the future without +penalty. Additionally, unnamed identifiers allow a compiler to quickly +come up with a temporary variable without having to avoid symbol table +conflicts.
+Reserved words in LLVM are very similar to reserved words in other +languages. There are keywords for different opcodes ('add', 'cast', 'ret', etc...), for primitive type names ('void', 'uint', +etc...), and others. These reserved words cannot conflict with +variable names, because none of them start with a '%' character.
+Here is an example of LLVM code to multiply the integer variable '%X' +by 8:
The easy way:
- -- %result = mul uint %X, 8 -- +
%result = mul uint %X, 8
After strength reduction:
- -- %result = shl uint %X, ubyte 3 -- +
%result = shl uint %X, ubyte 3
And the hard way:
- -- add uint %X, %X ; yields {uint}:%0 - add uint %0, %0 ; yields {uint}:%1 - %result = add uint %1, %1 -- -
This last way of multiplying %X by 8 illustrates several important -lexical features of LLVM:
- +add uint %X, %X ; yields {uint}:%0 + add uint %0, %0 ; yields {uint}:%1 + %result = add uint %1, %1+
This last way of multiplying %X by 8 illustrates several +important lexical features of LLVM:
...and it also show a convention that we follow in this document. When -demonstrating instructions, we will follow an instruction with a comment that -defines the type and name of value produced. Comments are shown in italic -text.
- -The one non-intuitive notation for constants is the optional hexidecimal form -of floating point constants. For example, the form 'double +
...and it also show a convention that we follow in this document. +When demonstrating instructions, we will follow an instruction with a +comment that defines the type and name of value produced. Comments are +shown in italic text.
+The one non-intuitive notation for constants is the optional +hexidecimal form of floating point constants. For example, the form 'double 0x432ff973cafa8000' is equivalent to (but harder to read than) 'double -4.5e+15' which is also supported by the parser. The only time hexadecimal -floating point constants are useful (and the only time that they are generated -by the disassembler) is when an FP constant has to be emitted that is not -representable as a decimal floating point number exactly. For example, NaN's, -infinities, and other special cases are represented in their IEEE hexadecimal -format so that assembly and disassembly do not cause any bits to change in the -constants.
- -The LLVM type system is one of the most important features of the -intermediate representation. Being typed enables a number of optimizations to -be performed on the IR directly, without having to do extra analyses on the side -before the transformation. A strong type system makes it easier to read the -generated code and enables novel analyses and transformations that are not -feasible to perform on normal three address code representations.
- +intermediate representation. Being typed enables a number of +optimizations to be performed on the IR directly, without having to do +extra analyses on the side before the transformation. A strong type +system makes it easier to read the generated code and enables novel +analyses and transformations that are not feasible to perform on normal +three address code representations. - ---> -
The primitive types are the fundemental building blocks of the LLVM system. -The current set of primitive types are as follows:
- +The primitive types are the fundemental building blocks of the LLVM +system. The current set of primitive types are as follows:
-
-
|
-
-
|
-||||||||||||||||||||||||||
+
|
+
+
|
+
These different primitive types fall into a few useful classifications:
- +These different primitive types fall into a few useful +classifications:
signed | -sbyte, short, int, long, float, double | -
unsigned | -ubyte, ushort, uint, ulong | -
integer | -ubyte, sbyte, ushort, short, uint, int, ulong, long | -
integral | -bool, ubyte, sbyte, ushort, short, uint, int, ulong, long | -
floating point | -float, double | -
first class | -bool, ubyte, sbyte, ushort, short, - uint, int, ulong, long, float, double, - pointer |
-
signed | +sbyte, short, int, long, float, double | +
unsigned | +ubyte, ushort, uint, ulong | +
integer | +ubyte, sbyte, ushort, short, uint, int, ulong, long | +
integral | +bool, ubyte, sbyte, ushort, short, uint, int, ulong, long | +
floating point | +float, double | +
first class | +bool, ubyte, sbyte, ushort, short, +uint, int, ulong, long, float, double, pointer |
+
The first class types are perhaps the most -important. Values of these types are the only ones which can be produced by -instructions, passed as arguments, or used as operands to instructions. This -means that all structures and arrays must be manipulated either by pointer or by -component.
- +The first class types are perhaps the +most important. Values of these types are the only ones which can be +produced by instructions, passed as arguments, or used as operands to +instructions. This means that all structures and arrays must be +manipulated either by pointer or by component.
The real power in LLVM comes from the derived types in the system. This is -what allows a programmer to represent arrays, functions, pointers, and other -useful types. Note that these derived types may be recursive: For example, it -is possible to have a two dimensional array.
- +The real power in LLVM comes from the derived types in the system. +This is what allows a programmer to represent arrays, functions, +pointers, and other useful types. Note that these derived types may be +recursive: For example, it is possible to have a two dimensional array.
The array type is a very simple derived type that arranges elements -sequentially in memory. The array type requires a size (number of elements) and -an underlying data type.
- +sequentially in memory. The array type requires a size (number of +elements) and an underlying data type.- [<# elements> x <elementtype>] -- -
The number of elements is a constant integer value, elementtype may be any -type with a size.
- +[<# elements> x <elementtype>]+
The number of elements is a constant integer value, elementtype may +be any type with a size.
- [40 x int ]: Array of 40 integer values.
- [41 x int ]: Array of 41 integer values.
- [40 x uint]: Array of 40 unsigned integer values.
-
- + [40 x int ]: Array of 40 integer values.
+[41 x int ]: Array of 41 integer values.
+[40 x uint]: Array of 40 unsigned integer values.
Here are some examples of multidimensional arrays:
-
[3 x [4 x int]] | -: 3x4 array integer values. | -
[12 x [10 x float]] | -: 12x10 array of single precision floating point values. | -
[2 x [3 x [4 x uint]]] | -: 2x3x4 array of unsigned integer values. | -
[3 x [4 x int]] | +: 3x4 array integer values. | +
[12 x [10 x float]] | +: 12x10 array of single precision floating point values. | +
[2 x [3 x [4 x uint]]] | +: 2x3x4 array of unsigned integer values. | +
The function type can be thought of as a function signature. It consists of -a return type and a list of formal parameter types. Function types are usually -used when to build virtual function tables (which are structures of pointers to -functions), for indirect function calls, and when defining a function.
- +The function type can be thought of as a function signature. It +consists of a return type and a list of formal parameter types. +Function types are usually used when to build virtual function tables +(which are structures of pointers to functions), for indirect function +calls, and when defining a function.
- <returntype> (<parameter list>) -- -
Where '<parameter list>' is a comma-separated list of type -specifiers. Optionally, the parameter list may include a type ..., +
<returntype> (<parameter list>)+
Where '<parameter list>' is a comma-separated list of +type specifiers. Optionally, the parameter list may include a type ..., which indicates that the function takes a variable number of arguments. Variable argument functions can access their arguments with the variable argument handling intrinsic functions.
- + href="#int_varargs">variable argument handling intrinsic functions.
int (int) | -: function taking an int, returning an int | -
float (int, int *) * | -: Pointer to a function that takes an - int and a pointer to int, - returning float. | -
int (sbyte *, ...) | -: A vararg function that takes at least one pointer to sbyte (signed char in C), which - returns an integer. This is the signature for printf in - LLVM. | -
int (int) | +: function taking an int, returning an int | +
float (int, int *) * | +: Pointer to a function that takes +an int and a pointer to int, +returning float. | +
int (sbyte *, ...) | +: A vararg function that takes at least one pointer to sbyte (signed char in C), +which returns an integer. This is the signature for printf +in LLVM. | +
The structure type is used to represent a collection of data members together -in memory. The packing of the field types is defined to match the ABI of the -underlying processor. The elements of a structure may be any type that has a -size.
- -Structures are accessed using 'load and -'store' by getting a pointer to a field with the -'getelementptr' instruction.
- +The structure type is used to represent a collection of data members +together in memory. The packing of the field types is defined to match +the ABI of the underlying processor. The elements of a structure may +be any type that has a size.
+Structures are accessed using 'load +and 'store' by getting a pointer to a +field with the 'getelementptr' +instruction.
- { <type list> } -- +
{ <type list> }
{ int, int, int } | -: a triple of three int values | -
{ float, int (int) * } | -: A pair, where the first element is a float and the second - element is a pointer to a function that takes an int, returning an - int. | -
{ int, int, int } | +: a triple of three int values | +
{ float, int (int) * } | +: A pair, where the first element is a float and the +second element is a pointer to a function that takes an int, returning +an int. | +
As in many languages, the pointer type represents a pointer or reference to -another object, which must live in memory.
- +As in many languages, the pointer type represents a pointer or +reference to another object, which must live in memory.
- <type> * -- +
<type> *
[4x int]* | -: pointer to array of four - int values | -
int (int *) * | -: A pointer to a function that takes an int, returning an - int. | -
[4x int]* | +: pointer to array +of four int values | +
int (int *) * | +: A pointer to a function that takes an int, returning +an int. | +
LLVM programs are composed of "Module"s, each of which is a translation unit -of the input programs. Each module consists of functions, global variables, and -symbol table entries. Modules may be combined together with the LLVM linker, -which merges function (and global variable) definitions, resolves forward -declarations, and merges symbol table entries. Here is an example of the "hello -world" module:
- --; Declare the string constant as a global constant... -%.LC0 = internal constant [13 x sbyte] c"hello world\0A\00" ; [13 x sbyte]* ++LLVM programs are composed of "Module"s, each of which is a +translation unit of the input programs. Each module consists of +functions, global variables, and symbol table entries. Modules may be +combined together with the LLVM linker, which merges function (and +global variable) definitions, resolves forward declarations, and merges +symbol table entries. Here is an example of the "hello world" module:
+; Declare the string constant as a global constant... +%.LC0 = internal constant [13 x sbyte] c"hello world\0A\00" ; [13 x sbyte]* ; External declaration of the puts function declare int %puts(sbyte*) ; int(sbyte*)* @@ -623,307 +536,223 @@ world" module: ; Definition of main function int %main() { ; int()* ; Convert [13x sbyte]* to sbyte *... - %cast210 = getelementptr [13 x sbyte]* %.LC0, long 0, long 0 ; sbyte* + %cast210 = getelementptr [13 x sbyte]* %.LC0, long 0, long 0 ; sbyte* ; Call puts function to write out the string to stdout... - call int %puts(sbyte* %cast210) ; int - ret int 0 -} -- -This example is made up of a global variable named -".LC0", an external declaration of the "puts" function, and a -function definition for "main".
- - -In general, a module is made up of a list of global values, where both functions -and global variables are global values. Global values are represented by a -pointer to a memory location (in this case, a pointer to an array of char, and a -pointer to a function), and have one of the following linkage types:
This example is made up of a global variable +named ".LC0", an external declaration of the "puts" +function, and a function definition +for "main".
+ In general, a module is made up of a list of global +values, where both functions and global variables are global values. +Global values are represented by a pointer to a memory location (in +this case, a pointer to an array of char, and a pointer to a function), +and have one of the following linkage types: +
-
-
-
-
-
-
- -
For example, since the ".LC0" variable is defined to be internal, if -another module defined a ".LC0" variable and was linked with this one, -one of the two would be renamed, preventing a collision. Since "main" -and "puts" are external (i.e., lacking any linkage declarations), they -are accessible outside of the current module. It is illegal for a function -declaration to have any linkage type other than "externally visible".
- ++
+
+
+
+
+
Global variables define regions of memory allocated at compilation time -instead of run-time. Global variables may optionally be initialized. A -variable may be defined as a global "constant", which indicates that the -contents of the variable will never be modified (opening options for -optimization). Constants must always have an initial value.
- -As SSA values, global variables define pointer values that are in scope -(i.e. they dominate) for all basic blocks in the program. Global variables -always define a pointer to their "content" type because they describe a region -of memory, and all memory objects in LLVM are accessed through pointers.
- +Global variables define regions of memory allocated at compilation +time instead of run-time. Global variables may optionally be +initialized. A variable may be defined as a global "constant", which +indicates that the contents of the variable will never be modified +(opening options for optimization). Constants must always have an +initial value.
+As SSA values, global variables define pointer values that are in +scope (i.e. they dominate) for all basic blocks in the program. Global +variables always define a pointer to their "content" type because they +describe a region of memory, and all memory objects in LLVM are +accessed through pointers.
LLVM function definitions are composed of a (possibly empty) argument list, -an opening curly brace, a list of basic blocks, and a closing curly brace. LLVM -function declarations are defined with the "declare" keyword, a -function name, and a function signature.
- -A function definition contains a list of basic blocks, forming the CFG for -the function. Each basic block may optionally start with a label (giving the -basic block a symbol table entry), contains a list of instructions, and ends -with a terminator instruction (such as a branch or -function return).
- -The first basic block in program is special in two ways: it is immediately -executed on entrance to the function, and it is not allowed to have predecessor -basic blocks (i.e. there can not be any branches to the entry block of a -function). Because the block can have no predecessors, it also cannot have any -PHI nodes.
- -LLVM function definitions are composed of a (possibly empty) +argument list, an opening curly brace, a list of basic blocks, and a +closing curly brace. LLVM function declarations are defined with the "declare" +keyword, a function name, and a function signature.
+A function definition contains a list of basic blocks, forming the +CFG for the function. Each basic block may optionally start with a +label (giving the basic block a symbol table entry), contains a list of +instructions, and ends with a terminator +instruction (such as a branch or function return).
+The first basic block in program is special in two ways: it is +immediately executed on entrance to the function, and it is not allowed +to have predecessor basic blocks (i.e. there can not be any branches to +the entry block of a function). Because the block can have no +predecessors, it also cannot have any PHI nodes.
The LLVM instruction set consists of several different classifications of -instructions: terminator instructions, binary instructions, memory -instructions, and other instructions.
- +The LLVM instruction set consists of several different +classifications of instructions: terminator +instructions, binary instructions, memory instructions, and other +instructions.
As mentioned previously, every basic block -in a program ends with a "Terminator" instruction, which indicates which block -should be executed after the current block is finished. These terminator -instructions typically yield a 'void' value: they produce control flow, -not values (the one exception being the 'invoke' instruction).
- +As mentioned previously, every +basic block in a program ends with a "Terminator" instruction, which +indicates which block should be executed after the current block is +finished. These terminator instructions typically yield a 'void' +value: they produce control flow, not values (the one exception being +the 'invoke' instruction).
There are five different terminator instructions: the 'ret' instruction, the 'br' instruction, the 'switch' instruction, the 'invoke' instruction, and the 'unwind' instruction.
- + href="#i_ret">ret' instruction, the 'br' +instruction, the 'switch' instruction, +the 'invoke' instruction, and the 'unwind' instruction.- ret <type> <value> ; Return a value from a non-void function +ret <type> <value> ; Return a value from a non-void function ret void ; Return from void function-Overview:
- -The 'ret' instruction is used to return control flow (and a value) -from a function, back to the caller.
- -There are two forms of the 'ret' instructruction: one that returns a -value and then causes control flow, and one that just causes control flow to -occur.
- +The 'ret' instruction is used to return control flow (and a +value) from a function, back to the caller.
+There are two forms of the 'ret' instructruction: one that +returns a value and then causes control flow, and one that just causes +control flow to occur.
Arguments:
- -The 'ret' instruction may return any 'first -class' type. Notice that a function is not well -formed if there exists a 'ret' instruction inside of the function -that returns a value that does not match the return type of the function.
- +The 'ret' instruction may return any 'first class' type. Notice that a function is +not well formed if there exists a 'ret' +instruction inside of the function that returns a value that does not +match the return type of the function.
Semantics:
- -When the 'ret' instruction is executed, control flow returns back to -the calling function's context. If the caller is a "call instruction, execution continues at the -instruction after the call. If the caller was an "invoke" instruction, execution continues at the -beginning "normal" of the destination block. If the instruction returns a -value, that value shall set the call or invoke instruction's return value.
- +When the 'ret' instruction is executed, control flow +returns back to the calling function's context. If the caller is a "call instruction, execution continues at +the instruction after the call. If the caller was an "invoke" instruction, execution continues +at the beginning "normal" of the destination block. If the instruction +returns a value, that value shall set the call or invoke instruction's +return value.
Example:
-- ret int 5 ; Return an integer value of 5 +ret int 5 ; Return an integer value of 5 ret void ; Return from a void function-
- br bool <cond>, label <iftrue>, label <iffalse> - br label <dest> ; Unconditional branch +br bool <cond>, label <iftrue>, label <iffalse>-
br label <dest> ; Unconditional branchOverview:
- -The 'br' instruction is used to cause control flow to transfer to a -different basic block in the current function. There are two forms of this -instruction, corresponding to a conditional branch and an unconditional -branch.
- +The 'br' instruction is used to cause control flow to +transfer to a different basic block in the current function. There are +two forms of this instruction, corresponding to a conditional branch +and an unconditional branch.
Arguments:
- -The conditional branch form of the 'br' instruction takes a single -'bool' value and two 'label' values. The unconditional form -of the 'br' instruction takes a single 'label' value as a -target.
- +The conditional branch form of the 'br' instruction takes a +single 'bool' value and two 'label' values. The +unconditional form of the 'br' instruction takes a single 'label' +value as a target.
Semantics:
- -Upon execution of a conditional 'br' instruction, the -'bool' argument is evaluated. If the value is true, control -flows to the 'iftrue' label argument. If "cond" is -false, control flows to the 'iffalse' label -argument.
- +Upon execution of a conditional 'br' instruction, the 'bool' +argument is evaluated. If the value is true, control flows +to the 'iftrue' label argument. If "cond" is false, +control flows to the 'iffalse' label argument.
Example:
- --Test: - %cond = seteq int %a, %b - br bool %cond, label %IfEqual, label %IfUnequal -IfEqual: - ret int 1 -IfUnequal: - ret int 0 -- +Test:
%cond = seteq int %a, %b
br bool %cond, label %IfEqual, label %IfUnequal
IfEqual:
ret int 1
IfUnequal:
ret int 0
- switch uint <value>, label <defaultdest> [ int <val>, label &dest>, ... ] -- +
switch uint <value>, label <defaultdest> [ int <val>, label &dest>, ... ]
The 'switch' instruction is used to transfer control flow to one of -several different places. It is a generalization of the 'br' +
The 'switch' instruction is used to transfer control flow +to one of several different places. It is a generalization of the 'br' instruction, allowing a branch to occur to one of many possible destinations.
-The 'switch' instruction uses three parameters: a 'uint' -comparison value 'value', a default 'label' destination, and -an array of pairs of comparison value constants and 'label's.
- +comparison value 'value', a default 'label' +destination, and an array of pairs of comparison value constants and 'label's.The switch instruction specifies a table of values and destinations. -When the 'switch' instruction is executed, this table is searched for -the given value. If the value is found, the corresponding destination is -branched to, otherwise the default value it transfered to.
- +The switch instruction specifies a table of values and +destinations. When the 'switch' instruction is executed, this +table is searched for the given value. If the value is found, the +corresponding destination is branched to, otherwise the default value +it transfered to.
Depending on properties of the target machine and the particular -switch instruction, this instruction may be code generated as a series -of chained conditional branches, or with a lookup table.
- +Depending on properties of the target machine and the particular switch +instruction, this instruction may be code generated as a series of +chained conditional branches, or with a lookup table.
- ; Emulate a conditional br instruction - %Val = cast bool %value to uint - switch uint %Val, label %truedest [int 0, label %falsedest ] - - ; Emulate an unconditional br instruction +; Emulate a conditional br instruction + %Val = cast bool %value to uint-
switch uint %Val, label %truedest [int 0, label %falsedest ]
; Emulate an unconditional br instruction switch uint 0, label %dest [ ] ; Implement a jump table: @@ -931,934 +760,647 @@ of chained conditional branches, or with a lookup table. int 1, label %onone, int 2, label %ontwo ]
- <result> = invoke <ptr to function ty> %<function ptr val>(<function args>) - to label <normal label> except label <exception label> -- +
<result> = invoke <ptr to function ty> %<function ptr val>(<function args>)
to label <normal label> except label <exception label>
The 'invoke' instruction causes control to transfer to a specified -function, with the possibility of control flow transfer to either the -'normal' label label or the 'exception' -label. If the callee function returns with the "ret" instruction, control flow will return to the -"normal" label. If the callee (or any indirect callees) returns with the "unwind" instruction, control is interrupted, and -continued at the dynamically nearest "except" label.
- +The 'invoke' instruction causes control to transfer to a +specified function, with the possibility of control flow transfer to +either the 'normal' label label or the 'exception'label. +If the callee function returns with the "ret" +instruction, control flow will return to the "normal" label. If the +callee (or any indirect callees) returns with the "unwind" +instruction, control is interrupted, and continued at the dynamically +nearest "except" label.
This instruction requires several arguments:
-This instruction is designed to operate as a standard 'call' instruction in most regards. The primary -difference is that it establishes an association with a label, which is used by the runtime library to unwind the stack.
- -This instruction is used in languages with destructors to ensure that proper -cleanup is performed in the case of either a longjmp or a thrown -exception. Additionally, this is important for implementation of -'catch' clauses in high-level languages that support them.
- + href="#i_call">call' instruction in most regards. The +primary difference is that it establishes an association with a label, +which is used by the runtime library to unwind the stack. +This instruction is used in languages with destructors to ensure +that proper cleanup is performed in the case of either a longjmp +or a thrown exception. Additionally, this is important for +implementation of 'catch' clauses in high-level languages that +support them.
- %retval = invoke int %Test(int 15) - to label %Continue - except label %TestCleanup ; {int}:retval set +%retval = invoke int %Test(int 15)-
to label %Continue
except label %TestCleanup ; {int}:retval set
- unwind -- +
unwind
The 'unwind' instruction unwinds the stack, continuing control flow -at the first callee in the dynamic call stack which used an invoke instruction to perform the call. This is -primarily used to implement exception handling.
- +The 'unwind' instruction unwinds the stack, continuing +control flow at the first callee in the dynamic call stack which used +an invoke instruction to perform the +call. This is primarily used to implement exception handling.
The 'unwind' intrinsic causes execution of the current function to -immediately halt. The dynamic call stack is then searched for the first invoke instruction on the call stack. Once found, -execution continues at the "exceptional" destination block specified by the -invoke instruction. If there is no invoke instruction in the -dynamic call chain, undefined behavior results.
- +The 'unwind' intrinsic causes execution of the current +function to immediately halt. The dynamic call stack is then searched +for the first invoke instruction on +the call stack. Once found, execution continues at the "exceptional" +destination block specified by the invoke instruction. If +there is no invoke instruction in the dynamic call chain, +undefined behavior results.
Binary operators are used to do most of the computation in a program. They -require two operands, execute an operation on them, and produce a single value. -The result value of a binary operator is not necessarily the same type as its -operands.
- +Binary operators are used to do most of the computation in a +program. They require two operands, execute an operation on them, and +produce a single value. The result value of a binary operator is not +necessarily the same type as its operands.
There are several different binary operators:
-- <result> = add <ty> <var1>, <var2> ; yields {ty}:result +<result> = add <ty> <var1>, <var2> ; yields {ty}:result-Overview:
-The 'add' instruction returns the sum of its two operands.
-Arguments:
-The two arguments to the 'add' instruction must be either integer or floating point -values. Both arguments must have identical types.
- + href="#t_integer">integer or floating point +values. Both arguments must have identical types.Semantics:
-The value produced is the integer or floating point sum of the two operands.
-Example:
- -- <result> = add int 4, %var ; yields {int}:result = 4 + %var +<result> = add int 4, %var ; yields {int}:result = 4 + %var-
- <result> = sub <ty> <var1>, <var2> ; yields {ty}:result +<result> = sub <ty> <var1>, <var2> ; yields {ty}:result-Overview:
-The 'sub' instruction returns the difference of its two operands.
- -Note that the 'sub' instruction is used to represent the -'neg' instruction present in most other intermediate -representations.
- +Note that the 'sub' instruction is used to represent the 'neg' +instruction present in most other intermediate representations.
Arguments:
-The two arguments to the 'sub' instruction must be either integer or floating point -values. Both arguments must have identical types.
- + href="#t_integer">integer or floating point +values. Both arguments must have identical types.Semantics:
- -The value produced is the integer or floating point difference of the two -operands.
- +The value produced is the integer or floating point difference of +the two operands.
Example:
- -- <result> = sub int 4, %var ; yields {int}:result = 4 - %var +<result> = sub int 4, %var ; yields {int}:result = 4 - %var <result> = sub int 0, %val ; yields {int}:result = -%var-
- <result> = mul <ty> <var1>, <var2> ; yields {ty}:result +<result> = mul <ty> <var1>, <var2> ; yields {ty}:result-Overview:
- -The 'mul' instruction returns the product of its two operands.
- +The 'mul' instruction returns the product of its two +operands.
Arguments:
-The two arguments to the 'mul' instruction must be either integer or floating point -values. Both arguments must have identical types.
- + href="#t_integer">integer or floating point +values. Both arguments must have identical types.Semantics:
- -The value produced is the integer or floating point product of the two -operands.
- -There is no signed vs unsigned multiplication. The appropriate action is -taken based on the type of the operand.
- -Example:
- -- <result> = mul int 4, %var ; yields {int}:result = 4 * %var -- -
- <result> = div <ty> <var1>, <var2> ; yields {ty}:result -- -
The 'div' instruction returns the quotient of its two operands.
- -The two arguments to the 'div' instruction must be either integer or floating point -values. Both arguments must have identical types.
- -The value produced is the integer or floating point quotient of the two -operands.
- -- <result> = div int 4, %var ; yields {int}:result = 4 / %var -- -
- <result> = rem <ty> <var1>, <var2> ; yields {ty}:result -- -
The 'rem' instruction returns the remainder from the division of its +
The value produced is the integer or floating point product of the two operands.
- -The two arguments to the 'rem' instruction must be either integer or floating point -values. Both arguments must have identical types.
- -This returns the remainder of a division (where the result has the -same sign as the divisor), not the modulus (where the result has the same -sign as the dividend) of a value. For more information about the difference, -see: The Math -Forum.
- +There is no signed vs unsigned multiplication. The appropriate +action is taken based on the type of the operand.
- <result> = rem int 4, %var ; yields {int}:result = 4 % %var +<result> = mul int 4, %var ; yields {int}:result = 4 * %var-
- <result> = seteq <ty> <var1>, <var2> ; yields {bool}:result +<result> = div <ty> <var1>, <var2> ; yields {ty}:result ++Overview:
+The 'div' instruction returns the quotient of its two +operands.
+Arguments:
+The two arguments to the 'div' instruction must be either integer or floating point +values. Both arguments must have identical types.
+Semantics:
+The value produced is the integer or floating point quotient of the +two operands.
+Example:
+<result> = div int 4, %var ; yields {int}:result = 4 / %var ++
<result> = rem <ty> <var1>, <var2> ; yields {ty}:result ++
The 'rem' instruction returns the remainder from the +division of its two operands.
+The two arguments to the 'rem' instruction must be either integer or floating point +values. Both arguments must have identical types.
+This returns the remainder of a division (where the result +has the same sign as the divisor), not the modulus (where the +result has the same sign as the dividend) of a value. For more +information about the difference, see: The +Math Forum.
+<result> = rem int 4, %var ; yields {int}:result = 4 % %var ++
<result> = seteq <ty> <var1>, <var2> ; yields {bool}:result <result> = setne <ty> <var1>, <var2> ; yields {bool}:result <result> = setlt <ty> <var1>, <var2> ; yields {bool}:result <result> = setgt <ty> <var1>, <var2> ; yields {bool}:result <result> = setle <ty> <var1>, <var2> ; yields {bool}:result <result> = setge <ty> <var1>, <var2> ; yields {bool}:result- -
The 'setcc' family of instructions returns a boolean value -based on a comparison of their two operands.
- -The two arguments to the 'setcc' instructions must be of first class type (it is not possible to compare -'label's, 'array's, 'structure' or 'void' -values, etc...). Both arguments must have identical types.
- +The 'setcc' family of instructions returns a boolean +value based on a comparison of their two operands.
+The two arguments to the 'setcc' instructions must +be of first class type (it is not possible +to compare 'label's, 'array's, 'structure' +or 'void' values, etc...). Both arguments must have identical +types.
The 'seteq' instruction yields a true 'bool' value
-if both operands are equal.
-
-The 'setne' instruction yields a true 'bool' value if
-both operands are unequal.
-
-The 'setlt' instruction yields a true 'bool' value if
-the first operand is less than the second operand.
-
-The 'setgt' instruction yields a true 'bool' value if
-the first operand is greater than the second operand.
-
-The 'setle' instruction yields a true 'bool' value if
-the first operand is less than or equal to the second operand.
-
-The 'setge' instruction yields a true 'bool' value if
-the first operand is greater than or equal to the second operand.
The 'seteq' instruction yields a true 'bool'
+value if both operands are equal.
+The 'setne' instruction yields a true 'bool'
+value if both operands are unequal.
+The 'setlt' instruction yields a true 'bool'
+value if the first operand is less than the second operand.
+The 'setgt' instruction yields a true 'bool'
+value if the first operand is greater than the second operand.
+The 'setle' instruction yields a true 'bool'
+value if the first operand is less than or equal to the second operand.
+The 'setge' instruction yields a true 'bool'
+value if the first operand is greater than or equal to the second
+operand.
- <result> = seteq int 4, 5 ; yields {bool}:result = false +<result> = seteq int 4, 5 ; yields {bool}:result = false <result> = setne float 4, 5 ; yields {bool}:result = true <result> = setlt uint 4, 5 ; yields {bool}:result = true <result> = setgt sbyte 4, 5 ; yields {bool}:result = false <result> = setle sbyte 4, 5 ; yields {bool}:result = true <result> = setge sbyte 4, 5 ; yields {bool}:result = false-
Bitwise binary operators are used to do various forms of bit-twiddling in a -program. They are generally very efficient instructions, and can commonly be -strength reduced from other instructions. They require two operands, execute an -operation on them, and produce a single value. The resulting value of the -bitwise binary operators is always the same type as its first operand.
- +Bitwise binary operators are used to do various forms of +bit-twiddling in a program. They are generally very efficient +instructions, and can commonly be strength reduced from other +instructions. They require two operands, execute an operation on them, +and produce a single value. The resulting value of the bitwise binary +operators is always the same type as its first operand.
- <result> = and <ty> <var1>, <var2> ; yields {ty}:result +<result> = and <ty> <var1>, <var2> ; yields {ty}:result-Overview:
- -The 'and' instruction returns the bitwise logical and of its two -operands.
- +The 'and' instruction returns the bitwise logical and of +its two operands.
Arguments:
-The two arguments to the 'and' instruction must be integral values. Both arguments must have identical -types.
- + href="#t_integral">integral values. Both arguments must have +identical types.Semantics:
-The truth table used for the 'and' instruction is:
- -+
- - + + -
- In0 In1 Out - 0 0 0 - 0 1 0 - 1 0 0 - 1 1 1 + +In0 +In1 +Out ++ +0 +0 +0 ++ +0 +1 +0 ++ +1 +0 +0 ++ + + +1 +1 +1 +Example:
- -- <result> = and int 4, %var ; yields {int}:result = 4 & %var +<result> = and int 4, %var ; yields {int}:result = 4 & %var <result> = and int 15, 40 ; yields {int}:result = 8 <result> = and int 4, 8 ; yields {int}:result = 0-
- <result> = or <ty> <var1>, <var2> ; yields {ty}:result +<result> = or <ty> <var1>, <var2> ; yields {ty}:result- -Overview:
- -The 'or' instruction returns the bitwise logical inclusive or of its -two operands.
- +Overview:
+The 'or' instruction returns the bitwise logical inclusive +or of its two operands.
Arguments:
-The two arguments to the 'or' instruction must be integral values. Both arguments must have identical -types.
- + href="#t_integral">integral values. Both arguments must have +identical types.Semantics:
-The truth table used for the 'or' instruction is:
- --
- - + -
- In0 In1 Out - 0 0 0 - 0 1 1 - 1 0 1 - 1 1 1 +
+ + +
++ +In0 +In1 +Out ++ +0 +0 +0 ++ +0 +1 +1 ++ +1 +0 +1 ++ + +1 +1 +1 +Example:
- -- <result> = or int 4, %var ; yields {int}:result = 4 | %var +<result> = or int 4, %var ; yields {int}:result = 4 | %var <result> = or int 15, 40 ; yields {int}:result = 47 <result> = or int 4, 8 ; yields {int}:result = 12-
- <result> = xor <ty> <var1>, <var2> ; yields {ty}:result +<result> = xor <ty> <var1>, <var2> ; yields {ty}:result-Overview:
- -The 'xor' instruction returns the bitwise logical exclusive or of -its two operands. The xor is used to implement the "one's complement" -operation, which is the "~" operator in C.
- +The 'xor' instruction returns the bitwise logical exclusive +or of its two operands. The xor is used to implement the +"one's complement" operation, which is the "~" operator in C.
Arguments:
-The two arguments to the 'xor' instruction must be integral values. Both arguments must have identical -types.
- + href="#t_integral">integral values. Both arguments must have +identical types.Semantics:
-The truth table used for the 'xor' instruction is:
- --
- -
- In0 In1 Out - 0 0 0 - 0 1 1 - 1 0 1 - 1 1 0 - +
+
+ ++ +
++ +In0 +In1 +Out ++ +0 +0 +0 ++ +0 +1 +1 ++ +1 +0 +1 ++ + +1 +1 +0 +
Example:
- -- <result> = xor int 4, %var ; yields {int}:result = 4 ^ %var +<result> = xor int 4, %var ; yields {int}:result = 4 ^ %var <result> = xor int 15, 40 ; yields {int}:result = 39 <result> = xor int 4, 8 ; yields {int}:result = 12 <result> = xor int %V, -1 ; yields {int}:result = ~%V-
- <result> = shl <ty> <var1>, ubyte <var2> ; yields {ty}:result +<result> = shl <ty> <var1>, ubyte <var2> ; yields {ty}:result-Overview:
- -The 'shl' instruction returns the first operand shifted to the left -a specified number of bits.
- +The 'shl' instruction returns the first operand shifted to +the left a specified number of bits.
Arguments:
-The first argument to the 'shl' instruction must be an integer type. The second argument must be an -'ubyte' type.
- + href="#t_integer">integer type. The second argument must be an 'ubyte' +type.Semantics:
-The value produced is var1 * 2var2.
-Example:
- -- <result> = shl int 4, ubyte %var ; yields {int}:result = 4 << %var +<result> = shl int 4, ubyte %var ; yields {int}:result = 4 << %var <result> = shl int 4, ubyte 2 ; yields {int}:result = 16 <result> = shl int 1, ubyte 10 ; yields {int}:result = 1024-
- <result> = shr <ty> <var1>, ubyte <var2> ; yields {ty}:result +<result> = shr <ty> <var1>, ubyte <var2> ; yields {ty}:result-Overview:
- -The 'shr' instruction returns the first operand shifted to the right -a specified number of bits.
- +The 'shr' instruction returns the first operand shifted to +the right a specified number of bits.
Arguments:
-The first argument to the 'shr' instruction must be an integer type. The second argument must be an -'ubyte' type.
- + href="#t_integer">integer type. The second argument must be an 'ubyte' +type.Semantics:
- -If the first argument is a signed type, the most -significant bit is duplicated in the newly free'd bit positions. If the first -argument is unsigned, zero bits shall fill the empty positions.
- +If the first argument is a signed type, the +most significant bit is duplicated in the newly free'd bit positions. +If the first argument is unsigned, zero bits shall fill the empty +positions.
Example:
- -- <result> = shr int 4, ubyte %var ; yields {int}:result = 4 >> %var +<result> = shr int 4, ubyte %var ; yields {int}:result = 4 >> %var <result> = shr uint 4, ubyte 1 ; yields {uint}:result = 2 <result> = shr int 4, ubyte 2 ; yields {int}:result = 1 <result> = shr sbyte 4, ubyte 3 ; yields {sbyte}:result = 0 <result> = shr sbyte -2, ubyte 1 ; yields {sbyte}:result = -1-
A key design point of an SSA-based representation is how it represents -memory. In LLVM, no memory locations are in SSA form, which makes things very -simple. This section describes how to read, write, allocate and free memory in -LLVM.
- +A key design point of an SSA-based representation is how it +represents memory. In LLVM, no memory locations are in SSA form, which +makes things very simple. This section describes how to read, write, +allocate and free memory in LLVM.
- <result> = malloc <type>, uint <NumElements> ; yields {type*}:result +<result> = malloc <type>, uint <NumElements> ; yields {type*}:result <result> = malloc <type> ; yields {type*}:result-Overview:
- -The 'malloc' instruction allocates memory from the system heap and -returns a pointer to it.
- +The 'malloc' instruction allocates memory from the system +heap and returns a pointer to it.
Arguments:
- -The the 'malloc' instruction allocates -sizeof(<type>)*NumElements bytes of memory from the operating -system, and returns a pointer of the appropriate type to the program. The -second form of the instruction is a shorter version of the first instruction -that defaults to allocating one element.
- +The the 'malloc' instruction allocates sizeof(<type>)*NumElements +bytes of memory from the operating system, and returns a pointer of the +appropriate type to the program. The second form of the instruction is +a shorter version of the first instruction that defaults to allocating +one element.
'type' must be a sized type.
-Semantics:
- -Memory is allocated using the system "malloc" function, and a -pointer is returned.
- +Memory is allocated using the system "malloc" function, and +a pointer is returned.
Example:
+%array = malloc [4 x ubyte ] ; yields {[%4 x ubyte]*}:array -- %array = malloc [4 x ubyte ] ; yields {[%4 x ubyte]*}:array - - %size = add uint 2, 2 ; yields {uint}:size = uint 4 + %size = add uint 2, 2 ; yields {uint}:size = uint 4 %array1 = malloc ubyte, uint 4 ; yields {ubyte*}:array1 %array2 = malloc [12 x ubyte], uint %size ; yields {[12 x ubyte]*}:array2-
- free <type> <value> ; yields {void} +free <type> <value> ; yields {void}-Overview:
- -The 'free' instruction returns memory back to the unused memory -heap, to be reallocated in the future.
- +
The 'free' instruction returns memory back to the unused +memory heap, to be reallocated in the future.
+
Arguments:
- -'value' shall be a pointer value that points to a value that was -allocated with the 'malloc' instruction.
- +'value' shall be a pointer value that points to a value +that was allocated with the 'malloc' +instruction.
Semantics:
- -Access to the memory pointed to by the pointer is not longer defined after -this instruction executes.
- +Access to the memory pointed to by the pointer is not longer defined +after this instruction executes.
Example:
-- %array = malloc [4 x ubyte] ; yields {[4 x ubyte]*}:array +%array = malloc [4 x ubyte] ; yields {[4 x ubyte]*}:array free [4 x ubyte]* %array-
- <result> = alloca <type>, uint <NumElements> ; yields {type*}:result +<result> = alloca <type>, uint <NumElements> ; yields {type*}:result <result> = alloca <type> ; yields {type*}:result-Overview:
- -The 'alloca' instruction allocates memory on the current stack frame -of the procedure that is live until the current function returns to its -caller.
- +The 'alloca' instruction allocates memory on the current +stack frame of the procedure that is live until the current function +returns to its caller.
Arguments:
- -The the 'alloca' instruction allocates -sizeof(<type>)*NumElements bytes of memory on the runtime stack, -returning a pointer of the appropriate type to the program. The second form of -the instruction is a shorter version of the first that defaults to allocating -one element.
- +The the 'alloca' instruction allocates sizeof(<type>)*NumElements +bytes of memory on the runtime stack, returning a pointer of the +appropriate type to the program. The second form of the instruction is +a shorter version of the first that defaults to allocating one element.
'type' may be any sized type.
-Semantics:
- -Memory is allocated, a pointer is returned. 'alloca'd memory is -automatically released when the function returns. The 'alloca' -instruction is commonly used to represent automatic variables that must have an -address available. When the function returns (either with the ret or invoke +
Memory is allocated, a pointer is returned. 'alloca'd +memory is automatically released when the function returns. The 'alloca' +instruction is commonly used to represent automatic variables that must +have an address available. When the function returns (either with the ret or invoke instructions), the memory is reclaimed.
-Example:
- -- %ptr = alloca int ; yields {int*}:ptr +%ptr = alloca int ; yields {int*}:ptr %ptr = alloca int, uint 4 ; yields {int*}:ptr-
- <result> = load <ty>* <pointer> - <result> = volatile load <ty>* <pointer> -- +
<result> = load <ty>* <pointer>
<result> = volatile load <ty>* <pointer>
The 'load' instruction is used to read from memory.
-The argument to the 'load' instruction specifies the memory address -to load from. The pointer must point to a first -class type. If the load is marked as volatile then the -optimizer is not allowed to modify the number or order of execution of this -load with other volatile load and store instructions.
- +The argument to the 'load' instruction specifies the memory +address to load from. The pointer must point to a first class type. If the load is +marked as volatile then the optimizer is not allowed to modify +the number or order of execution of this load with other +volatile load and store +instructions.
The location of memory pointed to is loaded.
-- %ptr = alloca int ; yields {int*}:ptr - store int 3, int* %ptr ; yields {void} +%ptr = alloca int ; yields {int*}:ptr + store int 3, int* %ptr ; yields {void} %val = load int* %ptr ; yields {int}:val = int 3-
- store <ty> <value>, <ty>* <pointer> ; yields {void} +store <ty> <value>, <ty>* <pointer> ; yields {void} volatile store <ty> <value>, <ty>* <pointer> ; yields {void}-Overview:
-The 'store' instruction is used to write to memory.
-Arguments:
- -There are two arguments to the 'store' instruction: a value to store -and an address to store it into. The type of the '<pointer>' -operand must be a pointer to the type of the '<value>' operand. -If the store is marked as volatile then the optimizer is not -allowed to modify the number or order of execution of this store with -other volatile load and store -instructions.
- -Semantics:
- -The contents of memory are updated to contain '<value>' at the -location specified by the '<pointer>' operand.
- +There are two arguments to the 'store' instruction: a value +to store and an address to store it into. The type of the '<pointer>' +operand must be a pointer to the type of the '<value>' +operand. If the store is marked as volatile then the +optimizer is not allowed to modify the number or order of execution of +this store with other volatile load and store instructions.
+Semantics:
+The contents of memory are updated to contain '<value>' +at the location specified by the '<pointer>' operand.
Example:
- -- %ptr = alloca int ; yields {int*}:ptr - store int 3, int* %ptr ; yields {void} +%ptr = alloca int ; yields {int*}:ptr + store int 3, int* %ptr ; yields {void} %val = load int* %ptr ; yields {int}:val = int 3- - - - - +-- +Syntax:
- -- <result> = getelementptr <ty>* <ptrval>{, long <aidx>|, ubyte <sidx>}* -- +<result> = getelementptr <ty>* <ptrval>{, long <aidx>|, ubyte <sidx>}*Overview:
- -The 'getelementptr' instruction is used to get the address of a -subelement of an aggregate data structure.
- +The 'getelementptr' instruction is used to get the address +of a subelement of an aggregate data structure.
Arguments:
-This instruction takes a list of long values and ubyte -constants that indicate what form of addressing to perform. The actual types of -the arguments provided depend on the type of the first pointer argument. The -'getelementptr' instruction is used to index down through the type -levels of a structure.
- -For example, let's consider a C code fragment and how it gets compiled to -LLVM:
- --struct RT { - char A; - int B[10][20]; - char C; -}; -struct ST { - int X; - double Y; - struct RT Z; -}; - -int *foo(struct ST *s) { - return &s[1].Z.B[5][13]; -} -- +constants that indicate what form of addressing to perform. The actual +types of the arguments provided depend on the type of the first pointer +argument. The 'getelementptr' instruction is used to index +down through the type levels of a structure. +For example, let's consider a C code fragment and how it gets +compiled to LLVM:
+struct RT {
char A;
int B[10][20];
char C;
};
struct ST {
int X;
double Y;
struct RT Z;
};
int *foo(struct ST *s) {
return &s[1].Z.B[5][13];
}The LLVM code generated by the GCC frontend is:
- --%RT = type { sbyte, [10 x [20 x int]], sbyte } -%ST = type { int, double, %RT } - -int* "foo"(%ST* %s) { - %reg = getelementptr %ST* %s, long 1, ubyte 2, ubyte 1, long 5, long 13 - ret int* %reg -} -- +%RT = type { sbyte, [10 x [20 x int]], sbyte }
%ST = type { int, double, %RT }
int* "foo"(%ST* %s) {
%reg = getelementptr %ST* %s, long 1, ubyte 2, ubyte 1, long 5, long 13
ret int* %reg
}Semantics:
- -The index types specified for the 'getelementptr' instruction depend -on the pointer type that is being index into. Pointer -and array types require 'long' values, and structure types require 'ubyte' -constants.
- +The index types specified for the 'getelementptr' +instruction depend on the pointer type that is being index into. Pointer and array types +require 'long' values, and structure +types require 'ubyte' constants.
In the example above, the first index is indexing into the '%ST*' -type, which is a pointer, yielding a '%ST' = '{ int, double, %RT -}' type, a structure. The second index indexes into the third element of -the structure, yielding a '%RT' = '{ sbyte, [10 x [20 x int]], -sbyte }' type, another structure. The third index indexes into the second -element of the structure, yielding a '[10 x [20 x int]]' type, an -array. The two dimensions of the array are subscripted into, yielding an -'int' type. The 'getelementptr' instruction return a pointer -to this element, thus yielding a 'int*' type.
- -Note that it is perfectly legal to index partially through a structure, -returning a pointer to an inner element. Because of this, the LLVM code for the -given testcase is equivalent to:
- --int* "foo"(%ST* %s) { - %t1 = getelementptr %ST* %s , long 1 ; yields %ST*:%t1 +type, which is a pointer, yielding a '%ST' = '{ int, +double, %RT }' type, a structure. The second index indexes into +the third element of the structure, yielding a '%RT' = '{ +sbyte, [10 x [20 x int]], sbyte }' type, another structure. The +third index indexes into the second element of the structure, yielding +a '[10 x [20 x int]]' type, an array. The two dimensions of +the array are subscripted into, yielding an 'int' type. The 'getelementptr' +instruction return a pointer to this element, thus yielding a 'int*' +type. +Note that it is perfectly legal to index partially through a +structure, returning a pointer to an inner element. Because of this, +the LLVM code for the given testcase is equivalent to:
+int* "foo"(%ST* %s) {-
%t1 = getelementptr %ST* %s , long 1 ; yields %ST*:%t1 %t2 = getelementptr %ST* %t1, long 0, ubyte 2 ; yields %RT*:%t2 %t3 = getelementptr %RT* %t2, long 0, ubyte 1 ; yields [10 x [20 x int]]*:%t3 %t4 = getelementptr [10 x [20 x int]]* %t3, long 0, long 5 ; yields [20 x int]*:%t4 @@ -1866,450 +1408,281 @@ int* "foo"(%ST* %s) { ret int* %t5 }Example:
- -- ; yields [12 x ubyte]*:aptr - %aptr = getelementptr {int, [12 x ubyte]}* %sptr, long 0, ubyte 1 -- -; yields [12 x ubyte]*:aptr + %aptr = getelementptr {int, [12 x ubyte]}* %sptr, long 0, ubyte 1+Note To The Novice:
+When using indexing into global arrays with the 'getelementptr' +instruction, you must remember that the -- Other Operations -- +- -- - - +The instructions in this catagory are the "miscellaneous" instructions, which -defy better classification.
- +The instructions in this catagory are the "miscellaneous" +instructions, which defy better classification.
-- - - +Syntax:
- -- <result> = phi <ty> [ <val0>, <label0>], ... -- +<result> = phi <ty> [ <val0>, <label0>], ...Overview:
- -The 'phi' instruction is used to implement the φ node in the SSA -graph representing the function.
- +The 'phi' instruction is used to implement the φ node in +the SSA graph representing the function.
Arguments:
- -The type of the incoming values are specified with the first type field. -After this, the 'phi' instruction takes a list of pairs as arguments, -with one pair for each predecessor basic block of the current block. Only -values of first class type may be used as the value -arguments to the PHI node. Only labels may be used as the label arguments.
- -There must be no non-phi instructions between the start of a basic block and -the PHI instructions: i.e. PHI instructions must be first in a basic block.
- +The type of the incoming values are specified with the first type +field. After this, the 'phi' instruction takes a list of pairs +as arguments, with one pair for each predecessor basic block of the +current block. Only values of first class +type may be used as the value arguments to the PHI node. Only labels +may be used as the label arguments.
+There must be no non-phi instructions between the start of a basic +block and the PHI instructions: i.e. PHI instructions must be first in +a basic block.
Semantics:
- -At runtime, the 'phi' instruction logically takes on the value -specified by the parameter, depending on which basic block we came from in the -last terminator instruction.
- +At runtime, the 'phi' instruction logically takes on the +value specified by the parameter, depending on which basic block we +came from in the last terminator instruction.
Example:
- --Loop: ; Infinite loop that counts from 0 on up... - %indvar = phi uint [ 0, %LoopHeader ], [ %nextindvar, %Loop ] - %nextindvar = add uint %indvar, 1 - br label %Loop -- +Loop: ; Infinite loop that counts from 0 on up...
%indvar = phi uint [ 0, %LoopHeader ], [ %nextindvar, %Loop ]
%nextindvar = add uint %indvar, 1
br label %Loop-- - - +Syntax:
- -- <result> = cast <ty> <value> to <ty2> ; yields ty2 +<result> = cast <ty> <value> to <ty2> ; yields ty2-Overview:
- -The 'cast' instruction is used as the primitive means to convert -integers to floating point, change data type sizes, and break type safety (by -casting pointers).
- +The 'cast' instruction is used as the primitive means to +convert integers to floating point, change data type sizes, and break +type safety (by casting pointers).
Arguments:
- -The 'cast' instruction takes a value to cast, which must be a first -class value, and a type to cast it to, which must also be a first class type.
- +The 'cast' instruction takes a value to cast, which must be +a first class value, and a type to cast it to, which must also be a first class type.
Semantics:
- -This instruction follows the C rules for explicit casts when determining how -the data being cast must change to fit in its new container.
- -When casting to bool, any value that would be considered true in the context -of a C 'if' condition is converted to the boolean 'true' +
This instruction follows the C rules for explicit casts when +determining how the data being cast must change to fit in its new +container.
+When casting to bool, any value that would be considered true in the +context of a C 'if' condition is converted to the boolean 'true' values, all else are 'false'.
- -When extending an integral value from a type of one signness to another (for -example 'sbyte' to 'ulong'), the value is sign-extended if the -source value is signed, and zero-extended if the source value is -unsigned. bool values are always zero extended into either zero or -one.
- +When extending an integral value from a type of one signness to +another (for example 'sbyte' to 'ulong'), the value +is sign-extended if the source value is signed, and +zero-extended if the source value is unsigned. bool values +are always zero extended into either zero or one.
Example:
- -- %X = cast int 257 to ubyte ; yields ubyte:1 +%X = cast int 257 to ubyte ; yields ubyte:1 %Y = cast int 123 to bool ; yields bool:true--- - - +Syntax:
- -- <result> = call <ty>* <fnptrval>(<param list>) -- +<result> = call <ty>* <fnptrval>(<param list>)Overview:
-The 'call' instruction represents a simple function call.
-Arguments:
-This instruction requires several arguments:
-- -
-- - -
'ty': shall be the signature of the pointer to function value - being invoked. The argument types must match the types implied by this - signature.
- - -
'fnptrval': An LLVM value containing a pointer to a function - to be invoked. In most cases, this is a direct function invocation, but - indirect calls are just as possible, calling an arbitrary pointer to - function values.
- - +
'function args': argument list whose types match the function - signature argument types. If the function signature indicates the function - accepts a variable number of arguments, the extra arguments can be - specified.
- +
+'ty': shall be the signature of the pointer to function +value being invoked. The argument types must match the types implied +by this signature.
+- +
+'fnptrval': An LLVM value containing a pointer to a +function to be invoked. In most cases, this is a direct function +invocation, but indirect calls are just as possible, +calling an arbitrary pointer to function values.
+- +
'function args': argument list whose types match the +function signature argument types. If the function signature +indicates the function accepts a variable number of arguments, the +extra arguments can be specified.
+Semantics:
- -The 'call' instruction is used to cause control flow to transfer to -a specified function, with its incoming arguments bound to the specified values. -Upon a 'ret' instruction in the called function, -control flow continues with the instruction after the function call, and the -return value of the function is bound to the result argument. This is a simpler -case of the invoke instruction.
- +The 'call' instruction is used to cause control flow to +transfer to a specified function, with its incoming arguments bound to +the specified values. Upon a 'ret' +instruction in the called function, control flow continues with the +instruction after the function call, and the return value of the +function is bound to the result argument. This is a simpler case of +the invoke instruction.
Example:
- -- %retval = call int %test(int %argc) - call int(sbyte*, ...) *%printf(sbyte* %msg, int 12, sbyte 42); -- +%retval = call int %test(int %argc)
call int(sbyte*, ...) *%printf(sbyte* %msg, int 12, sbyte 42);-- - - +Syntax:
- -- <resultarglist> = vanext <va_list> <arglist>, <argty> -- +<resultarglist> = vanext <va_list> <arglist>, <argty>Overview:
- -The 'vanext' instruction is used to access arguments passed through -the "variable argument" area of a function call. It is used to implement the -va_arg macro in C.
- +The 'vanext' instruction is used to access arguments passed +through the "variable argument" area of a function call. It is used to +implement the va_arg macro in C.
Arguments:
- -This instruction takes a valist value and the type of the argument. -It returns another valist.
- +This instruction takes a valist value and the type of the +argument. It returns another valist.
Semantics:
- -The 'vanext' instruction advances the specified valist past -an argument of the specified type. In conjunction with the vaarg instruction, it is used to implement the -va_arg macro available in C. For more information, see the variable -argument handling Intrinsic Functions.
- -It is legal for this instruction to be called in a function which does not -take a variable number of arguments, for example, the vfprintf +
The 'vanext' instruction advances the specified valist +past an argument of the specified type. In conjunction with the vaarg instruction, it is used to implement +the va_arg macro available in C. For more information, see +the variable argument handling Intrinsic +Functions.
+It is legal for this instruction to be called in a function which +does not take a variable number of arguments, for example, the vfprintf function.
-vanext is an LLVM instruction instead of an intrinsic function because it takes an type as an -argument.
- + href="#intrinsics">intrinsic function because it takes an type as +an argument.Example:
- -See the variable argument processing section.
- +See the variable argument processing +section.
-- - -Syntax:
- -- <resultval> = vaarg <va_list> <arglist>, <argty> -- +<resultval> = vaarg <va_list> <arglist>, <argty>Overview:
- -The 'vaarg' instruction is used to access arguments passed through -the "variable argument" area of a function call. It is used to implement the -va_arg macro in C.
- +The 'vaarg' instruction is used to access arguments passed +through the "variable argument" area of a function call. It is used to +implement the va_arg macro in C.
Arguments:
- -This instruction takes a valist value and the type of the argument. -It returns a value of the specified argument type.
- +This instruction takes a valist value and the type of the +argument. It returns a value of the specified argument type.
Semantics:
- -The 'vaarg' instruction loads an argument of the specified type from -the specified va_list. In conjunction with the vanext instruction, it is used to implement the -va_arg macro available in C. For more information, see the variable -argument handling Intrinsic Functions.
- -It is legal for this instruction to be called in a function which does not -take a variable number of arguments, for example, the vfprintf +
The 'vaarg' instruction loads an argument of the specified +type from the specified va_list. In conjunction with the vanext instruction, it is used to +implement the va_arg macro available in C. For more +information, see the variable argument handling Intrinsic +Functions.
+It is legal for this instruction to be called in a function which +does not take a variable number of arguments, for example, the vfprintf function.
-vaarg is an LLVM instruction instead of an intrinsic function because it takes an type as an -argument.
- + href="#intrinsics">intrinsic function because it takes an type as +an argument.Example:
- -See the variable argument processing section.
- -- Intrinsic Functions +- + +See the variable argument processing +section.
- -- - - +LLVM supports the notion of an "intrinsic function". These functions have -well known names and semantics, and are required to follow certain restrictions. -Overall, these instructions represent an extension mechanism for the LLVM -language that does not require changing all of the transformations in LLVM to -add to the language (or the bytecode reader/writer, the parser, etc...).
- -Intrinsic function names must all start with an "llvm." prefix, this -prefix is reserved in LLVM for intrinsic names, thus functions may not be named -this. Intrinsic functions must always be external functions: you cannot define -the body of intrinsic functions. Intrinsic functions may only be used in call -or invoke instructions: it is illegal to take the address of an intrinsic -function. Additionally, because intrinsic functions are part of the LLVM -language, it is required that they all be documented here if any are added.
- -Unless an intrinsic function is target-specific, there must be a lowering -pass to eliminate the intrinsic or all backends must support the intrinsic -function.
- +LLVM supports the notion of an "intrinsic function". These +functions have well known names and semantics, and are required to +follow certain restrictions. Overall, these instructions represent an +extension mechanism for the LLVM language that does not require +changing all of the transformations in LLVM to add to the language (or +the bytecode reader/writer, the parser, etc...).
+Intrinsic function names must all start with an "llvm." +prefix, this prefix is reserved in LLVM for intrinsic names, thus +functions may not be named this. Intrinsic functions must always be +external functions: you cannot define the body of intrinsic functions. +Intrinsic functions may only be used in call or invoke instructions: it +is illegal to take the address of an intrinsic function. Additionally, +because intrinsic functions are part of the LLVM language, it is +required that they all be documented here if any are added.
+Unless an intrinsic function is target-specific, there must be a +lowering pass to eliminate the intrinsic or all backends must support +the intrinsic function.
-- - - +Variable argument support is defined in LLVM with the vanext instruction and these three intrinsic -functions. These functions are related to the similarly named macros defined in -the <stdarg.h> header file.
- -All of these functions operate on arguments that use a target-specific value -type "va_list". The LLVM assembly language reference manual does not -define what this type is, so all transformations should be prepared to handle -intrinsics with any type used.
- + href="#i_vanext">vanext instruction and these three +intrinsic functions. These functions are related to the similarly +named macros defined in the <stdarg.h> header file. +All of these functions operate on arguments that use a +target-specific value type "va_list". The LLVM assembly +language reference manual does not define what this type is, so all +transformations should be prepared to handle intrinsics with any type +used.
This example shows how the vanext -instruction and the variable argument handling intrinsic functions are used.
- --int %test(int %X, ...) { - ; Initialize variable argument processing - %ap = call sbyte*()* %llvm.va_start() - - ; Read a single integer argument - %tmp = vaarg sbyte* %ap, int - - ; Advance to the next argument - %ap2 = vanext sbyte* %ap, int - - ; Demonstrate usage of llvm.va_copy and llvm.va_end - %aq = call sbyte* (sbyte*)* %llvm.va_copy(sbyte* %ap2) - call void %llvm.va_end(sbyte* %aq) - - ; Stop processing of arguments. - call void %llvm.va_end(sbyte* %ap2) - ret int %tmp -} -- +instruction and the variable argument handling intrinsic functions are +used. +int %test(int %X, ...) {
; Initialize variable argument processing
%ap = call sbyte*()* %llvm.va_start()
; Read a single integer argument
%tmp = vaarg sbyte* %ap, int
; Advance to the next argument
%ap2 = vanext sbyte* %ap, int
; Demonstrate usage of llvm.va_copy and llvm.va_end
%aq = call sbyte* (sbyte*)* %llvm.va_copy(sbyte* %ap2)
call void %llvm.va_end(sbyte* %aq)
; Stop processing of arguments.
call void %llvm.va_end(sbyte* %ap2)
ret int %tmp
}-- - - +Syntax:
- -- call va_list ()* %llvm.va_start() -- +call va_list ()* %llvm.va_start()Overview:
-The 'llvm.va_start' intrinsic returns a new <arglist> for subsequent use by the variable argument intrinsics.
-Semantics:
-The 'llvm.va_start' intrinsic works just like the va_start -macro available in C. In a target-dependent way, it initializes and returns a -va_list element, so that the next vaarg will produce the first -variable argument passed to the function. Unlike the C va_start macro, -this intrinsic does not need to know the last argument of the function, the -compiler can figure that out.
- -Note that this intrinsic function is only legal to be called from within the -body of a variable argument function.
- +macro available in C. In a target-dependent way, it initializes and +returns a va_list element, so that the next vaarg +will produce the first variable argument passed to the function. Unlike +the C va_start macro, this intrinsic does not need to know the +last argument of the function, the compiler can figure that out. +Note that this intrinsic function is only legal to be called from +within the body of a variable argument function.
-- - - +Syntax:
- -- call void (va_list)* %llvm.va_end(va_list <arglist>) -- +call void (va_list)* %llvm.va_end(va_list <arglist>)Overview:
- -The 'llvm.va_end' intrinsic destroys <arglist> which -has been initialized previously with llvm.va_start or llvm.va_copy.
- +The 'llvm.va_end' intrinsic destroys <arglist> +which has been initialized previously with llvm.va_start +or llvm.va_copy.
Arguments:
-The argument is a va_list to destroy.
-Semantics:
-The 'llvm.va_end' intrinsic works just like the va_end -macro available in C. In a target-dependent way, it destroys the -va_list. Calls to llvm.va_start and -llvm.va_copy must be matched exactly with -calls to llvm.va_end.
- +macro available in C. In a target-dependent way, it destroys the va_list. +Calls to llvm.va_start and llvm.va_copy must be matched exactly +with calls to llvm.va_end.-- -Syntax:
- -- call va_list (va_list)* %llvm.va_copy(va_list <destarglist>) -- +call va_list (va_list)* %llvm.va_copy(va_list <destarglist>)Overview:
- -The 'llvm.va_copy' intrinsic copies the current argument position -from the source argument list to the destination argument list.
- +The 'llvm.va_copy' intrinsic copies the current argument +position from the source argument list to the destination argument list.
Arguments:
-The argument is the va_list to copy.
-Semantics:
-The 'llvm.va_copy' intrinsic works just like the va_copy -macro available in C. In a target-dependent way, it copies the source -va_list element into the returned list. This intrinsic is necessary -because the llvm.va_start intrinsic may be -arbitrarily complex and require memory allocation, for example.
- +macro available in C. In a target-dependent way, it copies the source va_list +element into the returned list. This intrinsic is necessary because the llvm.va_start intrinsic may be arbitrarily +complex and require memory allocation, for example.
- +Chris Lattner +The LLVM Compiler Infrastructure
+Last modified: $Date$ diff --git a/docs/ProgrammersManual.html b/docs/ProgrammersManual.html index bacb0d6b81b..1ac08b42f4e 100644 --- a/docs/ProgrammersManual.html +++ b/docs/ProgrammersManual.html @@ -1,68 +1,75 @@ -LLVM Programmer's Manual - - - -
LLVM Programmer's Manual | -
LLVM Programmer's Manual | +
Written by Chris Lattner, - Dinakar Dhurjati, and - Joel Stanley
+
Written by Chris Lattner,Dinakar Dhurjati, and Joel Stanley
++
-Introduction - |
Introduction | +
- -This document should get you oriented so that you can find your way in the -continuously growing source code that makes up the LLVM infrastructure. Note -that this manual is not intended to serve as a replacement for reading the -source code, so if you think there should be a method in one of these classes to -do something, but it's not listed, check the source. Links to the doxygen sources are provided to make this as easy as -possible.
- -The first section of this document describes general information that is useful -to know when working in the LLVM infrastructure, and the second describes the -Core LLVM classes. In the future this manual will be extended with information -describing how to use extension libraries, such as dominator information, CFG -traversal routines, and useful utilities like the InstVisitor template.
- - +This document is meant to highlight some of the important classes and +interfaces available in the LLVM source-base. This manual is not +intended to explain what LLVM is, how it works, and what LLVM code looks +like. It assumes that you know the basics of LLVM and are interested +in writing transformations or otherwise analyzing or manipulating the +code. +
This document should get you oriented so that you can find your +way in the continuously growing source code that makes up the LLVM +infrastructure. Note that this manual is not intended to serve as a +replacement for reading the source code, so if you think there should be +a method in one of these classes to do something, but it's not listed, +check the source. Links to the doxygen sources +are provided to make this as easy as possible.
+The first section of this document describes general information +that is useful to know when working in the LLVM infrastructure, and the +second describes the Core LLVM classes. In the future this manual will +be extended with information describing how to use extension libraries, +such as dominator information, CFG traversal routines, and useful +utilities like the InstVisitor +template.
++
General Information | +
-General Information - |
+
+ | The C++ Standard Template +Library | +
Here are some useful links:
++
You are also encouraged to take a look at the LLVM Coding Standards guide which +focuses on how to write maintainable code more than where to put your +curly braces.
++
+ | Other useful references | +
+ +
+
Important and useful LLVM +APIs | +
- - - -
- -The C++ Standard Template Library - |
- -Here are some useful links:
- -
- -You are also encouraged to take a look at the LLVM Coding Standards guide which focuses on how -to write maintainable code more than where to put your curly braces.
- - -
- -Other useful references - |
- -
- - -
-Important and useful LLVM APIs - |
- - -
- -The isa<>, cast<> and dyn_cast<> templates - |
- -
- - -
- -
-static bool isLoopInvariant(const Value *V, const Loop *L) { - if (isa<Constant>(V) || isa<Argument>(V) || isa<GlobalValue>(V)) - return true; - - // Otherwise, it must be an instruction... - return !L->contains(cast<Instruction>(V)->getParent()); -
- -Note that you should not use an isa<> test followed by a -cast<>, for that use the dyn_cast<> operator.
- - -
- -
- if (AllocationInst *AI = dyn_cast<AllocationInst>(Val)) { - ... - } -
- -This form of the if statement effectively combines together a call to -isa<> and a call to cast<> into one statement, -which is very convenient.
- -Another common example is:
- -
- // Loop over all of the phi nodes in a basic block - BasicBlock::iterator BBI = BB->begin(); - for (; PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI) - cerr << *PN; -
- -Note that the dyn_cast<> operator, like C++'s -dynamic_cast or Java's instanceof operator, can be abused. In -particular you should not use big chained if/then/else blocks to check -for lots of different variants of classes. If you find yourself wanting to do -this, it is much cleaner and more efficient to use the InstVisitor class to -dispatch over the instruction type directly.
- - -
- - -
- -
- - - -
- -The DEBUG() macro & -debug option - |
- -Naturally, because of this, you don't want to delete the debug printouts, but -you don't want them to always be noisy. A standard compromise is to comment -them out, allowing you to enable them if you need them in the future.
- -The "Support/Debug.h" file -provides a macro named DEBUG() that is a much nicer solution to this -problem. Basically, you can put arbitrary code into the argument of the -DEBUG macro, and it is only executed if 'opt' (or any other -tool) is run with the '-debug' command line argument: - -
- ... - DEBUG(std::cerr << "I am here!\n"); - ... -
- -Then you can run your pass like this:
- -
- $ opt < a.bc > /dev/null -mypass - <no output> - $ opt < a.bc > /dev/null -mypass -debug - I am here! - $ -
- -Using the DEBUG() macro instead of a home-brewed solution allows you to -now have to create "yet another" command line option for the debug output for -your pass. Note that DEBUG() macros are disabled for optimized builds, -so they do not cause a performance impact at all (for the same reason, they -should also not contain side-effects!).
- -One additional nice thing about the DEBUG() macro is that you can -enable or disable it directly in gdb. Just use "set DebugFlag=0" or -"set DebugFlag=1" from the gdb if the program is running. If the -program hasn't been started yet, you can always just run it with --debug.
- - -
+
+ | The isa<>, +cast<> and dyn_cast<> templates | +
+
+
+
static bool isLoopInvariant(const Value *V, const Loop *L) {+
if (isa<Constant>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
return true;
// Otherwise, it must be an instruction...
return !L->contains(cast<Instruction>(V)->getParent());
Note that you should not use an isa<> +test followed by a cast<>, for that use the dyn_cast<> +operator.
++
+
if (AllocationInst *AI = dyn_cast<AllocationInst>(Val)) {+
...
}
This form of the if statement effectively combines +together a call to isa<> and a call to cast<> +into one statement, which is very convenient.
+Another common example is:
++
// Loop over all of the phi nodes in a basic block+
BasicBlock::iterator BBI = BB->begin();
for (; PHINode *PN = dyn_cast<PHINode>(BBI); ++BBI)
cerr << *PN;
Note that the dyn_cast<> operator, like C++'s dynamic_cast +or Java's instanceof operator, can be abused. In particular +you should not use big chained if/then/else blocks to check for +lots of different variants of classes. If you find yourself wanting to +do this, it is much cleaner and more efficient to use the InstVisitor +class to dispatch over the instruction type directly.
++
+
+
+
+ | The DEBUG() macro +& -debug option | +
Naturally, because of this, you don't want to delete the debug +printouts, but you don't want them to always be noisy. A standard +compromise is to comment them out, allowing you to enable them if you +need them in the future.
+The "Support/Debug.h" +file provides a macro named DEBUG() that is a much nicer +solution to this problem. Basically, you can put arbitrary code into +the argument of the DEBUG macro, and it is only executed if 'opt' +(or any other tool) is run with the '-debug' command line +argument:
+...+
DEBUG(std::cerr << "I am here!\n");
...
Then you can run your pass like this:
++
$ opt < a.bc > /dev/null -mypass+
<no output>
$ opt < a.bc > /dev/null -mypass -debug
I am here!
$
Using the DEBUG() macro instead of a home-brewed solution +allows you to now have to create "yet another" command line option for +the debug output for your pass. Note that DEBUG() macros are +disabled for optimized builds, so they do not cause a performance impact +at all (for the same reason, they should also not contain +side-effects!).
+One additional nice thing about the DEBUG() macro is that +you can enable or disable it directly in gdb. Just use "set +DebugFlag=0" or "set DebugFlag=1" from the gdb if the +program is running. If the program hasn't been started yet, you can +always just run it with -debug.
++ +
- -
- ... - DEBUG(std::cerr << "No debug type\n"); - #undef DEBUG_TYPE - #define DEBUG_TYPE "foo" - DEBUG(std::cerr << "'foo' debug type\n"); - #undef DEBUG_TYPE - #define DEBUG_TYPE "bar" - DEBUG(std::cerr << "'bar' debug type\n"); - #undef DEBUG_TYPE - #define DEBUG_TYPE "" - DEBUG(std::cerr << "No debug type (2)\n"); - ... -
- -Then you can run your pass like this:
- -
- $ opt < a.bc > /dev/null -mypass - <no output> - $ opt < a.bc > /dev/null -mypass -debug - No debug type - 'foo' debug type - 'bar' debug type - No debug type (2) - $ opt < a.bc > /dev/null -mypass -debug-only=foo - 'foo' debug type - $ opt < a.bc > /dev/null -mypass -debug-only=bar - 'bar' debug type - $ -
- -Of course, in practice, you should only set DEBUG_TYPE at the top of a -file, to specify the debug type for the entire module (if you do this before you -#include "Support/Debug.h", you don't have to insert the ugly -#undef's). Also, you should use names more meaningful that "foo" and -"bar", because there is no system in place to ensure that names do not conflict: -if two different modules use the same string, they will all be turned on when -the name is specified. This allows all, say, instruction scheduling, debug -information to be enabled with -debug-type=InstrSched, even if the -source lives in multiple files.
- - - -
- -The Statistic template & -stats -option - |
- -Often you may run your pass on some big program, and you're interested to see -how many times it makes a certain transformation. Although you can do this with -hand inspection, or some ad-hoc method, this is a real pain and not very useful -for big programs. Using the Statistic template makes it very easy to -keep track of this information, and the calculated information is presented in a -uniform manner with the rest of the passes being executed.
- -There are many examples of Statistic users, but this basics of using it -are as follows:
- -
- -
-static Statistic<> NumXForms("mypassname", "The # of times I did stuff"); -
- -The Statistic template can emulate just about any data-type, but if you -do not specify a template argument, it defaults to acting like an unsigned int -counter (this is usually what you want).
- -
- -
- ++NumXForms; // I did stuff -
- -
- -That's all you have to do. To get 'opt' to print out the statistics -gathered, use the '-stats' option:
- -
- $ opt -stats -mypassname < program.bc > /dev/null - ... statistic output ... -
- -When running gccas on a C file from the SPEC benchmark suite, it gives -a report that looks like this:
- -
- 7646 bytecodewriter - Number of normal instructions - 725 bytecodewriter - Number of oversized instructions - 129996 bytecodewriter - Number of bytecode bytes written - 2817 raise - Number of insts DCEd or constprop'd - 3213 raise - Number of cast-of-self removed - 5046 raise - Number of expression trees converted - 75 raise - Number of other getelementptr's formed - 138 raise - Number of load/store peepholes - 42 deadtypeelim - Number of unused typenames removed from symtab - 392 funcresolve - Number of varargs functions resolved - 27 globaldce - Number of global variables removed - 2 adce - Number of basic blocks removed - 134 cee - Number of branches revectored - 49 cee - Number of setcc instruction eliminated - 532 gcse - Number of loads removed - 2919 gcse - Number of instructions removed - 86 indvars - Number of canonical indvars added - 87 indvars - Number of aux indvars removed - 25 instcombine - Number of dead inst eliminate - 434 instcombine - Number of insts combined - 248 licm - Number of load insts hoisted - 1298 licm - Number of insts hoisted to a loop pre-header - 3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header) - 75 mem2reg - Number of alloca's promoted - 1444 cfgsimplify - Number of blocks simplified -
- -Obviously, with so many optimizations, having a unified framework for this stuff -is very nice. Making your pass fit well into the framework makes it more -maintainable and useful.
- - - -
-Helpful Hints for Common Operations - |
+ | The Statistic +template & -stats option | +
Often you may run your pass on some big program, and you're +interested to see how many times it makes a certain transformation. +Although you can do this with hand inspection, or some ad-hoc method, +this is a real pain and not very useful for big programs. Using the Statistic +template makes it very easy to keep track of this information, and the +calculated information is presented in a uniform manner with the rest of +the passes being executed.
+There are many examples of Statistic uses, but the basics +of using it are as follows:
++
+
static Statistic<> NumXForms("mypassname", "The # of times I did stuff");+
The Statistic template can emulate just about any +data-type, but if you do not specify a template argument, it defaults to +acting like an unsigned int counter (this is usually what you want).
++
+
++NumXForms; // I did stuff+
+
That's all you have to do. To get 'opt' to print out the +statistics gathered, use the '-stats' option:
++
$ opt -stats -mypassname < program.bc > /dev/null+
... statistic output ...
When running gccas on a C file from the SPEC benchmark +suite, it gives a report that looks like this:
++
7646 bytecodewriter - Number of normal instructions+
725 bytecodewriter - Number of oversized instructions
129996 bytecodewriter - Number of bytecode bytes written
2817 raise - Number of insts DCEd or constprop'd
3213 raise - Number of cast-of-self removed
5046 raise - Number of expression trees converted
75 raise - Number of other getelementptr's formed
138 raise - Number of load/store peepholes
42 deadtypeelim - Number of unused typenames removed from symtab
392 funcresolve - Number of varargs functions resolved
27 globaldce - Number of global variables removed
2 adce - Number of basic blocks removed
134 cee - Number of branches revectored
49 cee - Number of setcc instruction eliminated
532 gcse - Number of loads removed
2919 gcse - Number of instructions removed
86 indvars - Number of canonical indvars added
87 indvars - Number of aux indvars removed
25 instcombine - Number of dead inst eliminate
434 instcombine - Number of insts combined
248 licm - Number of load insts hoisted
1298 licm - Number of insts hoisted to a loop pre-header
3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
75 mem2reg - Number of alloca's promoted
1444 cfgsimplify - Number of blocks simplified
Obviously, with so many optimizations, having a unified framework +for this stuff is very nice. Making your pass fit well into the +framework makes it more maintainable and useful.
++ +
Helpful Hints for Common +Operations | +
- -Because this is a "how-to" section, you should also read about the main classes -that you will be working with. The Core LLVM Class -Hierarchy Reference contains details and descriptions of the main classes -that you should know about.
- - - - - -
- -Basic Inspection and Traversal Routines - |
- -Because the pattern for iteration is common across many different aspects of the -program representation, the standard template library algorithms may be used on -them, and it is easier to remember how to iterate. First we show a few common -examples of the data structures that need to be traversed. Other data -structures are traversed in very similar ways.
- - - -
Because this is a "how-to" section, you should also read about the +main classes that you will be working with. The Core +LLVM Class Hierarchy Reference contains details and descriptions of +the main classes that you should know about.
++
+ | Basic Inspection and +Traversal Routines | +
Because the pattern for iteration is common across many different +aspects of the program representation, the standard template library +algorithms may be used on them, and it is easier to remember how to +iterate. First we show a few common examples of the data structures that +need to be traversed. Other data structures are traversed in very +similar ways.
++
- // func is a pointer to a Function instance - for (Function::iterator i = func->begin(), e = func->end(); i != e; ++i) { - - // print out the name of the basic block if it has one, and then the - // number of instructions that it contains - - cerr << "Basic block (name=" << i->getName() << ") has " - << i->size() << " instructions.\n"; - } -- +to transform in some way; in particular, you'd like to manipulate its BasicBlocks. +To facilitate this, you'll need to iterate over all of the BasicBlocks +that constitute the Function. The following is an example +that prints the name of a BasicBlock and the number of Instructions +it contains: +
// func is a pointer to a Function instanceNote that i can be used as if it were a pointer for the purposes of invoking member functions of the Instruction class. This is because the indirection operator is overloaded for the iterator classes. In the above code, the expression i->size() is -exactly equivalent to (*i).size() just like you'd expect. - - -
for (Function::iterator i = func->begin(), e = func->end(); i != e; ++i) {
// print out the name of the basic block if it has one, and then the
// number of instructions that it contains
cerr << "Basic block (name=" << i->getName() << ") has "
<< i->size() << " instructions.\n";
}
- // blk is a pointer to a BasicBlock instance - for (BasicBlock::iterator i = blk->begin(), e = blk->end(); i != e; ++i) - // the next statement works since operator<<(ostream&,...) - // is overloaded for Instruction& - cerr << *i << "\n"; -- -However, this isn't really the best way to print out the contents of a -BasicBlock! Since the ostream operators are overloaded for -virtually anything you'll care about, you could have just invoked the -print routine on the basic block itself: cerr << *blk << -"\n";.
- -Note that currently operator<< is implemented for Value*, so it -will print out the contents of the pointer, instead of -the pointer value you might expect. This is a deprecated interface that will -be removed in the future, so it's best not to depend on it. To print out the -pointer value for now, you must cast to void*.
- - - -
-#include "llvm/Support/InstIterator.h" -... -// Suppose F is a ptr to a function -for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i) - cerr << **i << "\n"; -- +exactly equivalent to (*i).size() just like you'd expect. + +
// blk is a pointer to a BasicBlock instance+However, this isn't really the best way to print out the contents of a BasicBlock! +Since the ostream operators are overloaded for virtually anything +you'll care about, you could have just invoked the print routine on the +basic block itself: cerr << *blk << "\n";. +
for (BasicBlock::iterator i = blk->begin(), e = blk->end(); i != e; ++i)
// the next statement works since operator<<(ostream&,...)
// is overloaded for Instruction&
cerr << *i << "\n";
Note that currently operator<< is implemented for Value*, +so it will print out the contents of the pointer, instead of the +pointer value you might expect. This is a deprecated interface that +will be removed in the future, so it's best not to depend on it. To +print out the pointer value for now, you must cast to void*.
++ +
#include "llvm/Support/InstIterator.h"Easy, isn't it? You can also use InstIterators to fill a worklist with its initial contents. For example, if you wanted to -initialize a worklist to contain all instructions in a -Function F, all you would need to do is something like: - -
...
// Suppose F is a ptr to a function
for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
cerr << **i << "\n";
-std::set<Instruction*> worklist; -worklist.insert(inst_begin(F), inst_end(F)); -- -The STL set worklist would now contain all instructions in -the Function pointed to by F. - - -
std::set<Instruction*> worklist;+The STL set worklist would now contain all instructions in the Function +pointed to by F. + +
worklist.insert(inst_begin(F), inst_end(F));
- Instruction& inst = *i; // grab reference to instruction reference - Instruction* pinst = &*i; // grab pointer to instruction reference - const Instruction& inst = *j; --However, the iterators you'll be working with in the LLVM framework -are special: they will automatically convert to a ptr-to-instance type +Assuming that i is a BasicBlock::iterator and j +is a BasicBlock::const_iterator: +
Instruction& inst = *i; // grab reference to instruction reference+However, the iterators you'll be working with in the LLVM framework are +special: they will automatically convert to a ptr-to-instance type whenever they need to. Instead of dereferencing the iterator and then -taking the address of the result, you can simply assign the iterator -to the proper pointer type and you get the dereference and address-of +taking the address of the result, you can simply assign the iterator to +the proper pointer type and you get the dereference and address-of operation as a result of the assignment (behind the scenes, this is a result of overloading casting mechanisms). Thus the last line of the last example, - -
Instruction* pinst = &*i; // grab pointer to instruction reference
const Instruction& inst = *j;
Instruction* pinst = &*i;- +
Instruction* pinst = &*i;is semantically equivalent to - -
Instruction* pinst = i;- +
Instruction* pinst = i;It's also possible to turn a class pointer into the corresponding iterator. Usually, this conversion is quite inexpensive. The following code snippet illustrates use of the conversion constructors provided by LLVM iterators. By using these, you can explicitly grab the iterator of something without actually obtaining it via iteration over some structure: - -
-void printNextInstruction(Instruction* inst) { - BasicBlock::iterator it(inst); - ++it; // after this line, it refers to the instruction after *inst. - if (it != inst->getParent()->end()) cerr << *it << "\n"; -} -+
void printNextInstruction(Instruction* inst) {Of course, this example is strictly pedagogical, because it'd be much -better to explicitly grab the next instruction directly from inst. - - - -
BasicBlock::iterator it(inst);
++it; // after this line, it refers to the instruction after *inst.
if (it != inst->getParent()->end()) cerr << *it << "\n";
}
-initialize callCounter to zero -for each Function f in the Module - for each BasicBlock b in f - for each Instruction i in b - if (i is a CallInst and calls the given function) - increment callCounter -- -And the actual code is (remember, since we're writing a -FunctionPass, our FunctionPass-derived class simply -has to override the runOnFunction method...): - -
-Function* targetFunc = ...; - -class OurFunctionPass : public FunctionPass { - public: - OurFunctionPass(): callCounter(0) { } - - virtual runOnFunction(Function& F) { - for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) { - for (BasicBlock::iterator i = b->begin(); ie = b->end(); i != ie; ++i) { - if (CallInst* callInst = dyn_cast<CallInst>(&*i)) { - // we know we've encountered a call instruction, so we - // need to determine if it's a call to the - // function pointed to by m_func or not. - - if (callInst->getCalledFunction() == targetFunc) - ++callCounter; - } - } - } - - private: - unsigned callCounter; -}; -- - +locations in the entire module (that is, across every Function) +where a certain function (i.e., some Function*) is already in +scope. As you'll learn later, you may want to use an InstVisitor +to accomplish this in a much more straightforward manner, but this +example will allow us to explore how you'd do it if you didn't have InstVisitor +around. In pseudocode, this is what we want to do: +
initialize callCounter to zero+And the actual code is (remember, since we're writing a FunctionPass, +our FunctionPass-derived class simply has to override the runOnFunction +method...): +
for each Function f in the Module
for each BasicBlock b in f
for each Instruction i in b
if (i is a CallInst and calls the given function)
increment callCounter
Function* targetFunc = ...;-
class OurFunctionPass : public FunctionPass {
public:
OurFunctionPass(): callCounter(0) { }
virtual runOnFunction(Function& F) {
for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {
for (BasicBlock::iterator i = b->begin(); ie = b->end(); i != ie; ++i) {
if (CallInst* callInst = dyn_cast<CallInst>(&*i)) {
// we know we've encountered a call instruction, so we
// need to determine if it's a call to the
// function pointed to by m_func or not.
if (callInst->getCalledFunction() == targetFunc)
++callCounter;
}
}
}
private:
unsigned callCounter;
};
You may have noticed that the previous example was a bit +
You may have noticed that the previous example was a bit oversimplified in that it did not deal with call sites generated by 'invoke' instructions. In this, and in other situations, you may find -that you want to treat CallInsts and InvokeInsts the -same way, even though their most-specific common base class is -Instruction, which includes lots of less closely-related -things. For these cases, LLVM provides a handy wrapper class called CallSite -. It is essentially a wrapper around an Instruction -pointer, with some methods that provide functionality common to -CallInsts and InvokeInsts.
- -This class is supposed to have "value semantics". So it should be +that you want to treat CallInsts and InvokeInsts +the same way, even though their most-specific common base class is Instruction, +which includes lots of less closely-related things. For these cases, +LLVM provides a handy wrapper class called CallSite . +It is essentially a wrapper around an Instruction pointer, +with some methods that provide functionality common to CallInsts +and InvokeInsts.
+This class is supposed to have "value semantics". So it should be passed by value, not by reference; it should not be dynamically allocated or deallocated using operator new or operator delete. It is efficiently copyable, assignable and constructable, with costs equivalents to that of a bare pointer. (You will notice, if you look at its definition, that it has only a single data member.)
- - --Function* F = ...; - -for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) { - if (Instruction *Inst = dyn_cast<Instruction>(*i)) { - cerr << "F is used in instruction:\n"; - cerr << *Inst << "\n"; - } -} -- +all Users of a particular Value is called a def-use +chain. For example, let's say we have a Function* named F +to a particular function foo. Finding all of the instructions +that use foo is as simple as iterating over the def-use +chain of F: +
Function* F = ...;Alternately, it's common to have an instance of the User Class and need to know what -Values are used by it. The list of all Values used -by a User is known as a use-def chain. Instances of -class Instruction are common Users, so we might want -to iterate over all of the values that a particular instruction uses -(that is, the operands of the particular Instruction): - -
for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) {
if (Instruction *Inst = dyn_cast<Instruction>(*i)) {
cerr << "F is used in instruction:\n";
cerr << *Inst << "\n";
}
}
-Instruction* pi = ...; - -for (User::op_iterator i = pi->op_begin(), e = pi->op_end(); i != e; ++i) { - Value* v = *i; - ... -} -- - + href="/doxygen/classUser.html">User Class and need to know what Values +are used by it. The list of all Values used by a User +is known as a use-def chain. Instances of class Instruction +are common Users, so we might want to iterate over all of the +values that a particular instruction uses (that is, the operands of the +particular Instruction): +
Instruction* pi = ...;- - -
for (User::op_iterator i = pi->op_begin(), e = pi->op_end(); i != e; ++i) {
Value* v = *i;
...
}
- -Making simple changes - |
+ | Making simple +changes | +
Creation of Instructions is straightforward: simply call the -constructor for the kind of instruction to instantiate and provide the -necessary parameters. For example, an AllocaInst only -requires a (const-ptr-to) Type. Thus: - -
AllocaInst* ai = new AllocaInst(Type::IntTy);- +transformations, it's fairly common to manipulate the contents of basic +blocks. This section describes some of the common methods for doing so +and gives example code. + +
Creation of Instructions is straightforward: simply call +the constructor for the kind of instruction to instantiate and provide +the necessary parameters. For example, an AllocaInst only requires +a (const-ptr-to) Type. Thus:
+AllocaInst* ai = new AllocaInst(Type::IntTy);will create an AllocaInst instance that represents the -allocation of one integer in the current stack frame, at runtime. -Each Instruction subclass is likely to have varying default -parameters which change the semantics of the instruction, so refer to -the doxygen documentation for -the subclass of Instruction that you're interested in -instantiating. - -
Naming values
- --It is very useful to name the values of instructions when you're able -to, as this facilitates the debugging of your transformations. If you -end up looking at generated LLVM machine code, you definitely want to -have logical names associated with the results of instructions! By -supplying a value for the Name (default) parameter of the -Instruction constructor, you associate a logical name with -the result of the instruction's execution at runtime. For example, -say that I'm writing a transformation that dynamically allocates space -for an integer on the stack, and that integer is going to be used as -some kind of index by some other code. To accomplish this, I place an -AllocaInst at the first point in the first -BasicBlock of some Function, and I'm intending to -use it within the same Function. I might do: - -
AllocaInst* pa = new AllocaInst(Type::IntTy, 0, "indexLoc");- +allocation of one integer in the current stack frame, at runtime. Each Instruction +subclass is likely to have varying default parameters which change the +semantics of the instruction, so refer to the doxygen documentation for the +subclass of Instruction that you're interested in instantiating. +
Naming values
+It is very useful to name the values of instructions when you're +able to, as this facilitates the debugging of your transformations. If +you end up looking at generated LLVM machine code, you definitely want +to have logical names associated with the results of instructions! By +supplying a value for the Name (default) parameter of the Instruction +constructor, you associate a logical name with the result of the +instruction's execution at runtime. For example, say that I'm writing a +transformation that dynamically allocates space for an integer on the +stack, and that integer is going to be used as some kind of index by +some other code. To accomplish this, I place an AllocaInst at +the first point in the first BasicBlock of some Function, +and I'm intending to use it within the same Function. I +might do:
+AllocaInst* pa = new AllocaInst(Type::IntTy, 0, "indexLoc");where indexLoc is now the logical name of the instruction's -execution value, which is a pointer to an integer on the runtime -stack. - - -
Inserting instructions
- --There are essentially two ways to insert an Instruction into -an existing sequence of instructions that form a BasicBlock: -
Given a BasicBlock* pb, an Instruction* pi within -that BasicBlock, and a newly-created instruction -we wish to insert before *pi, we do the following: - -
- BasicBlock *pb = ...; - Instruction *pi = ...; - Instruction *newInst = new Instruction(...); - pb->getInstList().insert(pi, newInst); // inserts newInst before pi in pb -- - -
Instruction instances that are already in -BasicBlocks are implicitly associated with an existing -instruction list: the instruction list of the enclosing basic block. -Thus, we could have accomplished the same thing as the above code -without being given a BasicBlock by doing: -
- Instruction *pi = ...; - Instruction *newInst = new Instruction(...); - pi->getParent()->getInstList().insert(pi, newInst); --In fact, this sequence of steps occurs so frequently that the -Instruction class and Instruction-derived classes -provide constructors which take (as a default parameter) a pointer to -an Instruction which the newly-created Instruction -should precede. That is, Instruction constructors are -capable of inserting the newly-created instance into the -BasicBlock of a provided instruction, immediately before that -instruction. Using an Instruction constructor with a -insertBefore (default) parameter, the above code becomes: -
-Instruction* pi = ...; -Instruction* newInst = new Instruction(..., pi); -+execution value, which is a pointer to an integer on the runtime stack. +
Inserting instructions
+There are essentially two ways to insert an Instruction +into an existing sequence of instructions that form a BasicBlock:
+Given a BasicBlock* pb, an Instruction* pi +within that BasicBlock, and a newly-created instruction we +wish to insert before *pi, we do the following:
+BasicBlock *pb = ...;+
Instruction *pi = ...;
Instruction *newInst = new Instruction(...);
pb->getInstList().insert(pi, newInst); // inserts newInst before pi in pb
Instruction instances that are already in BasicBlocks +are implicitly associated with an existing instruction list: the +instruction list of the enclosing basic block. Thus, we could have +accomplished the same thing as the above code without being given a BasicBlock +by doing:
+Instruction *pi = ...;+In fact, this sequence of steps occurs so frequently that the Instruction +class and Instruction-derived classes provide constructors +which take (as a default parameter) a pointer to an Instruction +which the newly-created Instruction should precede. That is, Instruction +constructors are capable of inserting the newly-created instance into +the BasicBlock of a provided instruction, immediately before +that instruction. Using an Instruction constructor with a insertBefore +(default) parameter, the above code becomes: +
Instruction *newInst = new Instruction(...);
pi->getParent()->getInstList().insert(pi, newInst);
Instruction* pi = ...;which is much cleaner, especially if you're creating a lot of -instructions and adding them to BasicBlocks. - - +instructions and adding them to BasicBlocks.
Instruction* newInst = new Instruction(..., pi);
- -For example:
- -
- Instruction *I = .. ; - BasicBlock *BB = I->getParent(); - BB->getInstList().erase(I); -
- - -
Replacing individual instructions
--Including "llvm/Transforms/Utils/BasicBlockUtils.h" permits use of two very useful replace functions: -ReplaceInstWithValue and ReplaceInstWithInst. - +
This function replaces all uses (within a basic block) of a given -instruction with a value, and then removes the original instruction. -The following example illustrates the replacement of the result of a -particular AllocaInst that allocates memory for a single -integer with an null pointer to an integer.
- --AllocaInst* instToReplace = ...; -BasicBlock::iterator ii(instToReplace); -ReplaceInstWithValue(instToReplace->getParent()->getInstList(), ii, - Constant::getNullValue(PointerType::get(Type::IntTy))); -- -
This function replaces a particular instruction with another -instruction. The following example illustrates the replacement of one -AllocaInst with another.
- -
-AllocaInst* instToReplace = ...; -BasicBlock::iterator ii(instToReplace); -ReplaceInstWithInst(instToReplace->getParent()->getInstList(), ii, - new AllocaInst(Type::IntTy, 0, "ptrToReplacedInt")); -- +Deleting an instruction from an existing sequence of instructions that +form a BasicBlock is very +straightforward. First, you must have a pointer to the instruction that +you wish to delete. Second, you need to obtain the pointer to that +instruction's basic block. You use the pointer to the basic block to +get its list of instructions and then use the erase function to remove +your instruction. +
For example:
++
Instruction *I = .. ;+
BasicBlock *BB = I->getParent();
BB->getInstList().erase(I);
Replacing multiple uses of Users and - Values
- -You can use Value::replaceAllUsesWith and -User::replaceUsesOfWith to change more than one use at a -time. See the doxygen documentation for the Value Class and User Class, respectively, for more -information. - - - +--> +The Core LLVM Class +Hierarchy Reference | +
-The Core LLVM Class Hierarchy Reference - |
- - - -
- -The Value class - |
- - -The Value class is the most important class in LLVM Source base. It -represents a typed value that may be used (among other things) as an operand to -an instruction. There are many different types of Values, such as Constants, Arguments, and even Instructions and Functions are Values.
- -A particular Value may be used many times in the LLVM representation -for a program. For example, an incoming argument to a function (represented -with an instance of the Argument class) is "used" by -every instruction in the function that references the argument. To keep track -of this relationship, the Value class keeps a list of all of the Users that is using it (the User class is a base class for all nodes in the LLVM -graph that can refer to Values). This use list is how LLVM represents -def-use information in the program, and is accessible through the use_* -methods, shown below.
-
-Because LLVM is a typed representation, every LLVM Value is typed, and
-this Type is available through the getType()
-method. In addition, all LLVM values can be named. The
-"name" of the Value is symbolic string printed in the LLVM code:
-
-
-
-One important aspect of LLVM is that there is no distinction between an SSA
-variable and the operation that produces it. Because of this, any reference to
-the value produced by an instruction (or the value available as an incoming
-argument, for example) is represented as a direct pointer to the class that
-represents this value. Although this may take some getting used to, it
-simplifies the representation and makes it easier to manipulate.
-
-
-
-
- %foo = add int 1, 2
-
-
-The name of this instruction is "foo". NOTE that the name of any value
-may be missing (an empty string), so names should ONLY be used for
-debugging (making the source code easier to read, debugging printouts), they
-should not be used to keep track of values or map between them. For this
-purpose, use a std::map of pointers to the Value itself
-instead.
+
+ | The Value class | +
The Value class is the most important class in the LLVM +Source base. It represents a typed value that may be used (among other +things) as an operand to an instruction. There are many different types +of Values, such as Constants,Arguments. Even Instructions +and Functions are Values.
+A particular Value may be used many times in the LLVM +representation for a program. For example, an incoming argument to a +function (represented with an instance of the Argument +class) is "used" by every instruction in the function that references +the argument. To keep track of this relationship, the Value +class keeps a list of all of the Users +that is using it (the User class is a base +class for all nodes in the LLVM graph that can refer to Values). +This use list is how LLVM represents def-use information in the +program, and is accessible through the use_* methods, shown +below.
+Because LLVM is a typed representation, every LLVM Value +is typed, and this Type is available through the getType() +method. In addition, all LLVM values can be named. The "name" of the Value +is a symbolic string printed in the LLVM code:
++
%foo = add int 1, 2+ The name of this instruction is "foo". NOTE +that the name of any value may be missing (an empty string), so names +should ONLY be used for debugging (making the source code easier +to read, debugging printouts), they should not be used to keep track of +values or map between them. For this purpose, use a std::map +of pointers to the Value itself instead. +
One important aspect of LLVM is that there is no distinction +between an SSA variable and the operation that produces it. Because of +this, any reference to the value produced by an instruction (or the +value available as an incoming argument, for example) is represented as +a direct pointer to the class that represents this value. Although +this may take some getting used to, it simplifies the representation +and makes it easier to manipulate.
++ +
- -These methods are the interface to access the def-use information in LLVM. As with all other iterators in LLVM, the naming conventions follow the conventions defined by the STL.
- -
-This method returns the Type of the Value. - -
These methods are the interface to access the def-use +information in LLVM. As with all other iterators in LLVM, the naming +conventions follow the conventions defined by the STL.
++
This method returns the Type of the Value.
+- -This family of methods is used to access and assign a name to a Value, -be aware of the precaution above.
- - -
- -This method traverses the use list of a Value changing all Users of the current value to refer to "V" -instead. For example, if you detect that an instruction always produces a -constant value (for example through constant folding), you can replace all uses -of the instruction with the constant like this:
- -
- Inst->replaceAllUsesWith(ConstVal); -
- - - - -
- -The User class - |
This family of methods is used to access and assign a name to a Value, +be aware of the precaution above.
++ +
This method traverses the use list of a Value changing +all Users of the current value to refer to "V" +instead. For example, if you detect that an instruction always +produces a constant value (for example through constant folding), you +can replace all uses of the instruction with the constant like this:
++
Inst->replaceAllUsesWith(ConstVal);+
+
+ | The User class | +
- - -The User class is the common base class of all LLVM nodes that may -refer to Values. It exposes a list of "Operands" -that are all of the Values that the User is -referring to. The User class itself is a subclass of -Value.
- -The operands of a User point directly to the LLVM Value that it refers to. Because LLVM uses Static -Single Assignment (SSA) form, there can only be one definition referred to, -allowing this direct connection. This connection provides the use-def -information in LLVM.
- - -
- -
- -These two methods expose the operands of the User in a convenient form -for direct access.
- -
- -Together, these methods make up the iterator based interface to the operands of -a User.
- - - - -
- -The Instruction class - |
- -The Instruction class is the common base class for all LLVM -instructions. It provides only a few methods, but is a very commonly used -class. The primary data tracked by the Instruction class itself is the -opcode (instruction type) and the parent BasicBlock the Instruction is embedded -into. To represent a specific type of instruction, one of many subclasses of -Instruction are used.
- -Because the Instruction class subclasses the User class, its operands can be accessed in the same -way as for other Users (with the -getOperand()/getNumOperands() and -op_begin()/op_end() methods).
- -An important file for the Instruction class is the -llvm/Instruction.def file. This file contains some meta-data about the -various different types of instructions in LLVM. It describes the enum values -that are used as opcodes (for example Instruction::Add and -Instruction::SetLE), as well as the concrete sub-classes of -Instruction that implement the instruction (for example BinaryOperator and SetCondInst). Unfortunately, the use of macros in -this file confused doxygen, so these enum values don't show up correctly in the -doxygen output.
- - - -
- -Returns the BasicBlock that this -Instruction is embedded into.
- -
- -Returns true if the instruction writes to memory, i.e. it is a call, -free, invoke, or store.
- -
- -Returns the opcode for the Instruction.
- -
- -Returns another instance of the specified instruction, identical in all ways to -the original except that the instruction has no parent (ie it's not embedded -into a BasicBlock), and it has no name.
- - - - - - - -
- -The BasicBlock class - |
The User class is the common base class of all LLVM nodes +that may refer to Values. It exposes a +list of "Operands" that are all of the Values +that the User is referring to. The User class itself is a +subclass of Value.
+The operands of a User point directly to the LLVM Value that it refers to. Because LLVM uses +Static Single Assignment (SSA) form, there can only be one definition +referred to, allowing this direct connection. This connection provides +the use-def information in LLVM.
++
+
These two methods expose the operands of the User in a +convenient form for direct access.
++
Together, these methods make up the iterator based interface to +the operands of a User.
++
+ | The Instruction +class | +
The Instruction class is the common base class for all +LLVM instructions. It provides only a few methods, but is a very +commonly used class. The primary data tracked by the Instruction +class itself is the opcode (instruction type) and the parent BasicBlock the Instruction is +embedded into. To represent a specific type of instruction, one of many +subclasses of Instruction are used.
+Because the Instruction class subclasses the User class, its operands can be accessed in +the same way as for other Users (with the getOperand()/getNumOperands() +and op_begin()/op_end() methods).
+An important file for the Instruction class is the llvm/Instruction.def +file. This file contains some meta-data about the various different +types of instructions in LLVM. It describes the enum values that are +used as opcodes (for example Instruction::Add and Instruction::SetLE), +as well as the concrete sub-classes of Instruction that +implement the instruction (for example BinaryOperator +and SetCondInst). Unfortunately, +the use of macros in this file confuses doxygen, so these enum values +don't show up correctly in the doxygen +output.
++
Returns the BasicBlock that +this Instruction is embedded into.
++
Returns true if the instruction writes to memory, i.e. it is a call,free,invoke, +or store.
++
Returns the opcode for the Instruction.
++
Returns another instance of the specified instruction, identical +in all ways to the original except that the instruction has no parent +(ie it's not embedded into a BasicBlock), +and it has no name
++ | The BasicBlock +class | +
- - -This class represents a single entry multiple exit section of the code, commonly -known as a basic block by the compiler community. The BasicBlock class -maintains a list of Instructions, which form -the body of the block. Matching the language definition, the last element of -this list of instructions is always a terminator instruction (a subclass of the -TerminatorInst class).
- -In addition to tracking the list of instructions that make up the block, the -BasicBlock class also keeps track of the Function that it is embedded into.
- -Note that BasicBlocks themselves are Values, because they are referenced by instructions -like branches and can go in the switch tables. BasicBlocks have type -label.
- - - -
- -The BasicBlock constructor is used to create new basic blocks for -insertion into a function. The constructor simply takes a name for the new -block, and optionally a Function to insert it -into. If the Parent parameter is specified, the new -BasicBlock is automatically inserted at the end of the specified Function, if not specified, the BasicBlock must be -manually inserted into the Function.
- -
This class represents a single entry multiple exit section of the +code, commonly known as a basic block by the compiler community. The BasicBlock +class maintains a list of Instructions, +which form the body of the block. Matching the language definition, +the last element of this list of instructions is always a terminator +instruction (a subclass of the TerminatorInst +class).
+In addition to tracking the list of instructions that make up the +block, the BasicBlock class also keeps track of the Function that it is embedded into.
+Note that BasicBlocks themselves are Values, +because they are referenced by instructions like branches and can go in +the switch tables. BasicBlocks have type label.
++
The BasicBlock constructor is used to create new basic +blocks for insertion into a function. The constructor optionally takes +a name for the new block, and a Function +to insert it into. If the Parent parameter is specified, the +new BasicBlock is automatically inserted at the end of the +specified Function, if not specified, +the BasicBlock must be manually inserted into the Function.
++
- -These methods and typedefs are forwarding functions that have the same semantics -as the standard library methods of the same names. These methods expose the -underlying instruction list of a basic block in a way that is easy to -manipulate. To get the full complement of container operations (including -operations to update the list), you must use the getInstList() -method.
- -
- -This method is used to get access to the underlying container that actually -holds the Instructions. This method must be used when there isn't a forwarding -function in the BasicBlock class for the operation that you would like -to perform. Because there are no forwarding functions for "updating" -operations, you need to use this if you want to update the contents of a -BasicBlock.
- -
- -Returns a pointer to Function the block is -embedded into, or a null pointer if it is homeless.
- -
- -Returns a pointer to the terminator instruction that appears at the end of the -BasicBlock. If there is no terminator instruction, or if the last -instruction in the block is not a terminator, then a null pointer is -returned.
- - - -
- -The GlobalValue class - |
- -Global values (GlobalVariables or Functions) are the only LLVM values that are -visible in the bodies of all Functions. -Because they are visible at global scope, they are also subject to linking with -other globals defined in different translation units. To control the linking -process, GlobalValues know their linkage rules. Specifically, -GlobalValues know whether they have internal or external linkage.
- -If a GlobalValue has internal linkage (equivalent to being -static in C), it is not visible to code outside the current translation -unit, and does not participate in linking. If it has external linkage, it is -visible to external code, and does participate in linking. In addition to -linkage information, GlobalValues keep track of which Module they are currently part of.
- -Because GlobalValues are memory objects, they are always referred to by -their address. As such, the Type of a global is -always a pointer to its contents. This is explained in the LLVM Language -Reference Manual.
- - - -
These methods and typedefs are forwarding functions that have +the same semantics as the standard library methods of the same names. +These methods expose the underlying instruction list of a basic block in +a way that is easy to manipulate. To get the full complement of +container operations (including operations to update the list), you must +use the getInstList() method.
++
This method is used to get access to the underlying container +that actually holds the Instructions. This method must be used when +there isn't a forwarding function in the BasicBlock class for +the operation that you would like to perform. Because there are no +forwarding functions for "updating" operations, you need to use this if +you want to update the contents of a BasicBlock.
++
Returns a pointer to Function +the block is embedded into, or a null pointer if it is homeless.
++
Returns a pointer to the terminator instruction that appears at +the end of the BasicBlock. If there is no terminator +instruction, or if the last instruction in the block is not a +terminator, then a null pointer is returned.
++
+ | The GlobalValue +class | +
Global values (GlobalVariables +or Functions) are the only LLVM +values that are visible in the bodies of all Functions. +Because they are visible at global scope, they are also subject to +linking with other globals defined in different translation units. To +control the linking process, GlobalValues know their linkage +rules. Specifically, GlobalValues know whether they have +internal or external linkage, as defined by the LinkageTypes enumerator.
+If a GlobalValue has internal linkage (equivalent to +being static in C), it is not visible to code outside the +current translation unit, and does not participate in linking. If it +has external linkage, it is visible to external code, and does +participate in linking. In addition to linkage information, GlobalValues +keep track of which Module they are +currently part of.
+Because GlobalValues are memory objects, they are always +referred to by their address. As such, the Type +of a global is always a pointer to its contents. It is important to +remember this when using the GetElementPtrInst +instruction because this pointer must be dereferenced first. For +example, if you have a GlobalVariable +(a subclass of GlobalValue) +that is an array of 24 ints, type [24 +x int], then the GlobalVariable +is a pointer to that array. Although the address of the first element of +this array and the value of the GlobalVariable +are the same, they have different types. The GlobalVariable's type is [24 x int]. The first element's +type is int. Because of +this, accessing a global value requires you to dereference the pointer +with GetElementPtrInst +first, then its elements can be accessed. This is explained in +the LLVM Language Reference Manual.
++
- -These methods manipulate the linkage characteristics of the -GlobalValue.
- -
- -This returns the Module that the GlobalValue is -currently embedded into.
- - - - -
- -The Function class - |
These methods manipulate the linkage characteristics of the GlobalValue.
++ +
This returns the Module that the +GlobalValue is currently embedded into.
++
+ | The Function +class | +
- -The Function class represents a single procedure in LLVM. It is -actually one of the more complex classes in the LLVM heirarchy because it must -keep track of a large amount of data. The Function class keeps track -of a list of BasicBlocks, a list of formal Arguments, and a SymbolTable.
- -The list of BasicBlocks is the most commonly -used part of Function objects. The list imposes an implicit ordering -of the blocks in the function, which indicate how the code will be layed out by -the backend. Additionally, the first BasicBlock is the implicit entry node for the -Function. It is not legal in LLVM explicitly branch to this initial -block. There are no implicit exit nodes, and in fact there may be multiple exit -nodes from a single Function. If the BasicBlock list is empty, this indicates that -the Function is actually a function declaration: the actual body of the -function hasn't been linked in yet.
- -In addition to a list of BasicBlocks, the -Function class also keeps track of the list of formal Arguments that the function receives. This -container manages the lifetime of the Argument -nodes, just like the BasicBlock list does for -the BasicBlocks.
- -The SymbolTable is a very rarely used LLVM -feature that is only used when you have to look up a value by name. Aside from -that, the SymbolTable is used internally to -make sure that there are not conflicts between the names of Instructions, BasicBlocks, or Arguments in the function body.
- - - -
- -Constructor used when you need to create new Functions to add the the -program. The constructor must specify the type of the function to create and -whether or not it should start out with internal or external linkage.
- -
- -Return whether or not the Function has a body defined. If the function -is "external", it does not have a body, and thus must be resolved by linking -with a function defined in a different translation unit.
- - -
The Function class represents a single procedure in LLVM. +It is actually one of the more complex classes in the LLVM heirarchy +because it must keep track of a large amount of data. The Function +class keeps track of a list of BasicBlocks, +a list of formal Arguments, and a SymbolTable.
+The list of BasicBlocks is the +most commonly used part of Function objects. The list imposes +an implicit ordering of the blocks in the function, which indicate how +the code will be layed out by the backend. Additionally, the first BasicBlock is the implicit entry node +for the Function. It is not legal in LLVM to explicitly +branch to this initial block. There are no implicit exit nodes, and in +fact there may be multiple exit nodes from a single Function. +If the BasicBlock list is empty, +this indicates that the Function is actually a function +declaration: the actual body of the function hasn't been linked in yet.
+In addition to a list of BasicBlocks, +the Function class also keeps track of the list of formal Arguments that the function receives. +This container manages the lifetime of the Argument +nodes, just like the BasicBlock list +does for the BasicBlocks.
+The SymbolTable is a very +rarely used LLVM feature that is only used when you have to look up a +value by name. Aside from that, the SymbolTable +is used internally to make sure that there are not conflicts between the +names of Instructions, BasicBlocks, or Arguments +in the function body.
++
Constructor used when you need to create new Functions +to add the the program. The constructor must specify the type of the +function to create and whether or not it should start out with internal +or external linkage. The FunctionType argument specifies the +formal arguments and return value for the function. The same FunctionType +value can be used to create multiple functions. The Parent argument specifies the +Module in which the function is defined. If this argument is provided, +the function will automatically be inserted into that module's list of +functions.
++
Return whether or not the Function has a body defined. +If the function is "external", it does not have a body, and thus must be +resolved by linking with a function defined in a different translation +unit.
++
- -These are forwarding methods that make it easy to access the contents of a -Function object's BasicBlock -list.
- -
- -Returns the list of BasicBlocks. This is -necessary to use when you need to update the list or perform a complex action -that doesn't have a forwarding method.
- - -
These are forwarding methods that make it easy to access the +contents of a Function object's BasicBlock +list.
++
Returns the list of BasicBlocks. +This is necessary to use when you need to update the list or perform a +complex action that doesn't have a forwarding method.
++
- -These are forwarding methods that make it easy to access the contents of a -Function object's Argument list.
- -
- -Returns the list of Arguments. This is -necessary to use when you need to update the list or perform a complex action -that doesn't have a forwarding method.
- - - -
- -Returns the entry BasicBlock for the -function. Because the entry block for the function is always the first block, -this returns the first block of the Function.
- -
- -This traverses the Type of the Function + abegin(), aend(), afront(), aback(),asize(),aempty(),arbegin(),arend() +
These are forwarding methods that make it easy to access the +contents of a Function object's Argument +list.
++
Returns the list of Arguments. +This is necessary to use when you need to update the list or perform a +complex action that doesn't have a forwarding method.
++
Returns the entry BasicBlock +for the function. Because the entry block for the function is always +the first block, this returns the first block of the Function.
++
This traverses the Type of the Function and returns the return type of the function, or the FunctionType of the actual function.
- -
- -Return a pointer to the SymbolTable for this -Function.
- - - - -
- -The GlobalVariable class - |
+ +
Return a pointer to the SymbolTable +for this Function.
++
+ | The GlobalVariable +class | +
- -Global variables are represented with the (suprise suprise) -GlobalVariable class. Like functions, GlobalVariables are -also subclasses of GlobalValue, and as such -are always referenced by their address (global values must live in memory, so -their "name" refers to their address). Global variables may have an initial -value (which must be a Constant), and if they -have an initializer, they may be marked as "constant" themselves (indicating -that their contents never change at runtime).
- - - -
- -Create a new global variable of the specified type. If isConstant is -true then the global variable will be marked as unchanging for the program, and -if isInternal is true the resultant global variable will have internal -linkage. Optionally an initializer and name may be specified for the global variable as well.
- - -
- -Returns true if this is a global variable is known not to be modified at -runtime.
- - -
- -Returns true if this GlobalVariable has an intializer.
- - -
- -Returns the intial value for a GlobalVariable. It is not legal to call -this method if there is no initializer.
- - - -
- -The Module class - |
- -The Module class represents the top level structure present in LLVM -programs. An LLVM module is effectively either a translation unit of the -original program or a combination of several translation units merged by the -linker. The Module class keeps track of a list of Functions, a list of GlobalVariables, and a SymbolTable. Additionally, it contains a few -helpful member functions that try to make common operations easy.
- - - -
Global variables are represented with the (suprise suprise) GlobalVariable +class. Like functions, GlobalVariables are also subclasses of GlobalValue, and as such are always +referenced by their address (global values must live in memory, so their +"name" refers to their address). See GlobalValue for more on +this. Global variables may have an initial value (which must be a Constant), and if they have an +initializer, they may be marked as "constant" themselves (indicating +that their contents never change at runtime).
++
Create a new global variable of the specified type. If isConstant +is true then the global variable will be marked as unchanging for the +program. The Linkage parameter specifies the type of linkage (internal, +external, weak, linkonce, appending) for the variable. If the linkage +is InternalLinkage, WeakLinkage, or LinkOnceLinkage, then the +resultant global variable will have internal linkage. AppendingLinkage +concatenates together all instances (in different translation units) of +the variable into a single variable but is only applicable to arrays. + See the LLVM Language +Reference for further details on linkage types. Optionally an +initializer, a name, and the module to put the variable into may be +specified for the global variable as well.
++
Returns true if this is a global variable that is known not to +be modified at runtime.
++
Returns true if this GlobalVariable has an intializer.
++
Returns the intial value for a GlobalVariable. It is +not legal to call this method if there is no initializer.
++
+ | The Module class | +
The Module class represents the top level structure +present in LLVM programs. An LLVM module is effectively either a +translation unit of the original program or a combination of several +translation units merged by the linker. The Module class keeps +track of a list of Functions, a list +of GlobalVariables, and a SymbolTable. Additionally, it +contains a few helpful member functions that try to make common +operations easy.
++
Constructing a Module +is easy. You can optionally provide a name for it (probably based on the +name of the translation unit).
+- -These are forwarding methods that make it easy to access the contents of a -Module object's Function -list.
- -
- -Returns the list of Functions. This is -necessary to use when you need to update the list or perform a complex action -that doesn't have a forwarding method.
- - -
These are forwarding methods that make it easy to access the +contents of a Module object's Function +list.
++
Returns the list of Functions. +This is necessary to use when you need to update the list or perform a +complex action that doesn't have a forwarding method.
++
- -These are forwarding methods that make it easy to access the contents of a -Module object's GlobalVariable -list.
- -
- -Returns the list of GlobalVariables. -This is necessary to use when you need to update the list or perform a complex -action that doesn't have a forwarding method.
- - - -
- -Return a reference to the SymbolTable for -this Module.
- - - -
- -Look up the specified function in the Module SymbolTable. If it does not exist, return -null.
- - -
- -Look up the specified function in the Module SymbolTable. If it does not exist, add an -external declaration for the function and return it.
- - -
- -If there is at least one entry in the SymbolTable for the specified Type, return it. Otherwise return the empty -string.
- - -
- -Insert an entry in the SymbolTable mapping -Name to Ty. If there is already an entry for this name, true -is returned and the SymbolTable is not -modified.
- - - -
- -The Constant class and subclasses - |
- - - -
- -
These are forwarding methods that make it easy to access the +contents of a Module object's GlobalVariable +list.
++
Returns the list of GlobalVariables. +This is necessary to use when you need to update the list or perform a +complex action that doesn't have a forwarding method.
++
Return a reference to the SymbolTable +for this Module.
++
Look up the specified function in the Module SymbolTable. If it does not exist, +return null.
++
Look up the specified function in the Module SymbolTable. If it does not exist, +add an external declaration for the function and return it.
++
If there is at least one entry in the SymbolTable +for the specified Type, return it. +Otherwise return the empty string.
++
Insert an entry in the SymbolTable +mapping Name to Ty. If there is already an entry for +this name, true is returned and the SymbolTable +is not modified.
++
+ | The Constant +class and subclasses | +
+
+ | The Type class and +Derived Types | +
+
+
+ | The Argument +class | +
- -The Type class and Derived Types - |
- -
- -
- -The Argument class - |