]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_gcc/src/declare.rs
339a613c096614a2b38296c31458533e694ee415
[rust.git] / compiler / rustc_codegen_gcc / src / declare.rs
1 use gccjit::{Function, FunctionType, GlobalKind, LValue, RValue, Type};
2 use rustc_codegen_ssa::traits::BaseTypeMethods;
3 use rustc_middle::ty::Ty;
4 use rustc_span::Symbol;
5 use rustc_target::abi::call::FnAbi;
6
7 use crate::abi::FnAbiGccExt;
8 use crate::context::{CodegenCx, unit_name};
9 use crate::intrinsic::llvm;
10 use crate::mangled_std_symbols::{ARGV_INIT_ARRAY, ARGV_INIT_WRAPPER};
11
12 impl<'gcc, 'tcx> CodegenCx<'gcc, 'tcx> {
13     pub fn get_or_insert_global(&self, name: &str, ty: Type<'gcc>, is_tls: bool, link_section: Option<Symbol>) -> RValue<'gcc> {
14         if self.globals.borrow().contains_key(name) {
15             let typ = self.globals.borrow().get(name).expect("global").get_type();
16             let global = self.context.new_global(None, GlobalKind::Imported, typ, name);
17             if is_tls {
18                 global.set_tls_model(self.tls_model);
19             }
20             if let Some(link_section) = link_section {
21                 global.set_link_section(&link_section.as_str());
22             }
23             global.get_address(None)
24         }
25         else {
26             self.declare_global(name, ty, is_tls, link_section)
27         }
28     }
29
30     pub fn declare_unnamed_global(&self, ty: Type<'gcc>) -> LValue<'gcc> {
31         let index = self.global_gen_sym_counter.get();
32         self.global_gen_sym_counter.set(index + 1);
33         let name = format!("global_{}_{}", index, unit_name(&self.codegen_unit));
34         self.context.new_global(None, GlobalKind::Exported, ty, &name)
35     }
36
37     pub fn declare_global_with_linkage(&self, name: &str, ty: Type<'gcc>, linkage: GlobalKind) -> RValue<'gcc> {
38         //debug!("declare_global_with_linkage(name={:?})", name);
39         let global = self.context.new_global(None, linkage, ty, name)
40             .get_address(None);
41         self.globals.borrow_mut().insert(name.to_string(), global);
42         // NOTE: global seems to only be global in a module. So save the name instead of the value
43         // to import it later.
44         self.global_names.borrow_mut().insert(global, name.to_string());
45         global
46     }
47
48     pub fn declare_func(&self, name: &str, return_type: Type<'gcc>, params: &[Type<'gcc>], variadic: bool) -> RValue<'gcc> {
49         self.linkage.set(FunctionType::Exported);
50         let func = declare_raw_fn(self, name, () /*llvm::CCallConv*/, return_type, params, variadic);
51         // FIXME: this is a wrong cast. That requires changing the compiler API.
52         unsafe { std::mem::transmute(func) }
53     }
54
55     pub fn declare_global(&self, name: &str, ty: Type<'gcc>, is_tls: bool, link_section: Option<Symbol>) -> RValue<'gcc> {
56         //debug!("declare_global(name={:?})", name);
57         // FIXME: correctly support global variable initialization.
58         if name.starts_with(ARGV_INIT_ARRAY) {
59             // NOTE: hack to avoid having to update the names in mangled_std_symbols: we save the
60             // name of the variable now to actually declare it later.
61             *self.init_argv_var.borrow_mut() = name.to_string();
62
63             let global = self.context.new_global(None, GlobalKind::Imported, ty, name);
64             if let Some(link_section) = link_section {
65                 global.set_link_section(&link_section.as_str());
66             }
67             return global.get_address(None);
68         }
69         let global = self.context.new_global(None, GlobalKind::Exported, ty, name);
70         if is_tls {
71             global.set_tls_model(self.tls_model);
72         }
73         if let Some(link_section) = link_section {
74             global.set_link_section(&link_section.as_str());
75         }
76         let global = global.get_address(None);
77         self.globals.borrow_mut().insert(name.to_string(), global);
78         // NOTE: global seems to only be global in a module. So save the name instead of the value
79         // to import it later.
80         self.global_names.borrow_mut().insert(global, name.to_string());
81         global
82     }
83
84     pub fn declare_cfn(&self, name: &str, _fn_type: Type<'gcc>) -> RValue<'gcc> {
85         // TODO: use the fn_type parameter.
86         let const_string = self.context.new_type::<u8>().make_pointer().make_pointer();
87         let return_type = self.type_i32();
88         let variadic = false;
89         self.linkage.set(FunctionType::Exported);
90         let func = declare_raw_fn(self, name, () /*llvm::CCallConv*/, return_type, &[self.type_i32(), const_string], variadic);
91         // NOTE: it is needed to set the current_func here as well, because get_fn() is not called
92         // for the main function.
93         *self.current_func.borrow_mut() = Some(func);
94         // FIXME: this is a wrong cast. That requires changing the compiler API.
95         unsafe { std::mem::transmute(func) }
96     }
97
98     pub fn declare_fn(&self, name: &str, fn_abi: &FnAbi<'tcx, Ty<'tcx>>) -> RValue<'gcc> {
99         // NOTE: hack to avoid having to update the names in mangled_std_symbols: we found the name
100         // of the variable earlier, so we declare it now.
101         // Since we don't correctly support initializers yet, we initialize this variable manually
102         // for now.
103         if name.starts_with(ARGV_INIT_WRAPPER) && !self.argv_initialized.get() {
104             let global_name = &*self.init_argv_var.borrow();
105             let return_type = self.type_void();
106             let params = [
107                 self.context.new_parameter(None, self.int_type, "argc"),
108                 self.context.new_parameter(None, self.u8_type.make_pointer().make_pointer(), "argv"),
109                 self.context.new_parameter(None, self.u8_type.make_pointer().make_pointer(), "envp"),
110             ];
111             let function = self.context.new_function(None, FunctionType::Extern, return_type, &params, name, false);
112             let initializer = function.get_address(None);
113
114             let param_types = [
115                 self.int_type,
116                 self.u8_type.make_pointer().make_pointer(),
117                 self.u8_type.make_pointer().make_pointer(),
118             ];
119             let ty = self.context.new_function_pointer_type(None, return_type, &param_types, false);
120
121             let global = self.context.new_global(None, GlobalKind::Exported, ty, global_name);
122             global.set_link_section(".init_array.00099");
123             global.global_set_initializer_value(initializer);
124             let global = global.get_address(None);
125             self.globals.borrow_mut().insert(global_name.to_string(), global);
126             // NOTE: global seems to only be global in a module. So save the name instead of the value
127             // to import it later.
128             self.global_names.borrow_mut().insert(global, global_name.to_string());
129             self.argv_initialized.set(true);
130         }
131         //debug!("declare_rust_fn(name={:?}, fn_abi={:?})", name, fn_abi);
132         let (return_type, params, variadic) = fn_abi.gcc_type(self);
133         let func = declare_raw_fn(self, name, () /*fn_abi.llvm_cconv()*/, return_type, &params, variadic);
134         //fn_abi.apply_attrs_llfn(self, func);
135         // FIXME: this is a wrong cast. That requires changing the compiler API.
136         unsafe { std::mem::transmute(func) }
137     }
138
139     pub fn define_global(&self, name: &str, ty: Type<'gcc>, is_tls: bool, link_section: Option<Symbol>) -> Option<RValue<'gcc>> {
140         Some(self.get_or_insert_global(name, ty, is_tls, link_section))
141     }
142
143     pub fn define_private_global(&self, ty: Type<'gcc>) -> RValue<'gcc> {
144         let global = self.declare_unnamed_global(ty);
145         global.get_address(None)
146     }
147
148     pub fn get_declared_value(&self, name: &str) -> Option<RValue<'gcc>> {
149         //debug!("get_declared_value(name={:?})", name);
150         // TODO: use a different field than globals, because this seems to return a function?
151         self.globals.borrow().get(name).cloned()
152     }
153
154     /*fn get_defined_value(&self, name: &str) -> Option<RValue<'gcc>> {
155         // TODO: gcc does not allow global initialization.
156         None
157         /*self.get_declared_value(name).and_then(|val| {
158             let declaration = unsafe { llvm::LLVMIsDeclaration(val) != 0 };
159             if !declaration { Some(val) } else { None }
160         })*/
161     }*/
162 }
163
164 /// Declare a function.
165 ///
166 /// If there’s a value with the same name already declared, the function will
167 /// update the declaration and return existing Value instead.
168 fn declare_raw_fn<'gcc>(cx: &CodegenCx<'gcc, '_>, name: &str, _callconv: () /*llvm::CallConv*/, return_type: Type<'gcc>, param_types: &[Type<'gcc>], variadic: bool) -> Function<'gcc> {
169     //debug!("declare_raw_fn(name={:?}, ty={:?})", name, ty);
170     /*let llfn = unsafe {
171         llvm::LLVMRustGetOrInsertFunction(cx.llmod, name.as_ptr().cast(), name.len(), ty)
172     };*/
173
174     if name.starts_with("llvm.") {
175         return llvm::intrinsic(name, cx);
176     }
177     let func =
178         if cx.functions.borrow().contains_key(name) {
179             *cx.functions.borrow().get(name).expect("function")
180         }
181         else {
182             let params: Vec<_> = param_types.into_iter().enumerate()
183                 .map(|(index, param)| cx.context.new_parameter(None, *param, &format!("param{}", index))) // TODO: set name.
184                 .collect();
185             let func = cx.context.new_function(None, cx.linkage.get(), return_type, &params, mangle_name(name), variadic);
186             cx.functions.borrow_mut().insert(name.to_string(), func);
187             func
188         };
189
190     //llvm::SetFunctionCallConv(llfn, callconv); // TODO
191     // Function addresses in Rust are never significant, allowing functions to
192     // be merged.
193     //llvm::SetUnnamedAddress(llfn, llvm::UnnamedAddr::Global); // TODO
194
195     /*if cx.tcx.sess.opts.cg.no_redzone.unwrap_or(cx.tcx.sess.target.target.options.disable_redzone) {
196         llvm::Attribute::NoRedZone.apply_llfn(Function, llfn);
197     }*/
198
199     //attributes::default_optimisation_attrs(cx.tcx.sess, llfn);
200     //attributes::non_lazy_bind(cx.sess(), llfn);
201
202     // FIXME: invalid cast.
203     // TODO: is this line useful?
204     //cx.globals.borrow_mut().insert(name.to_string(), unsafe { std::mem::transmute(func) });
205     func
206 }
207
208 // FIXME: this is a hack because libgccjit currently only supports alpha, num and _.
209 // Unsupported characters: `$` and `.`.
210 pub fn mangle_name(name: &str) -> String {
211     name.replace(|char: char| {
212         if !char.is_alphanumeric() && char != '_' {
213             debug_assert!("$.".contains(char), "Unsupported char in function name: {}", char);
214             true
215         }
216         else {
217             false
218         }
219     }, "_")
220 }