1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
use libc::c_uint;
use llvm::{self, SetUnnamedAddr, True};
use rustc::hir::def_id::DefId;
use rustc::hir::Node;
use debuginfo;
use base;
use monomorphize::MonoItem;
use common::{CodegenCx, val_ty};
use declare;
use monomorphize::Instance;
use syntax_pos::Span;
use syntax_pos::symbol::LocalInternedString;
use type_::Type;
use type_of::LayoutLlvmExt;
use value::Value;
use rustc::ty::{self, Ty};
use rustc::ty::layout::{Align, LayoutOf};
use rustc::hir::{self, CodegenFnAttrs, CodegenFnAttrFlags};
use std::ffi::{CStr, CString};
pub fn ptrcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
unsafe {
llvm::LLVMConstPointerCast(val, ty)
}
}
pub fn bitcast(val: &'ll Value, ty: &'ll Type) -> &'ll Value {
unsafe {
llvm::LLVMConstBitCast(val, ty)
}
}
fn set_global_alignment(cx: &CodegenCx<'ll, '_>,
gv: &'ll Value,
mut align: Align) {
if let Some(min) = cx.sess().target.target.options.min_global_align {
match ty::layout::Align::from_bits(min, min) {
Ok(min) => align = align.max(min),
Err(err) => {
cx.sess().err(&format!("invalid minimum global alignment: {}", err));
}
}
}
unsafe {
llvm::LLVMSetAlignment(gv, align.abi() as u32);
}
}
pub fn addr_of_mut(
cx: &CodegenCx<'ll, '_>,
cv: &'ll Value,
align: Align,
kind: Option<&str>,
) -> &'ll Value {
unsafe {
let gv = match kind {
Some(kind) if !cx.tcx.sess.fewer_names() => {
let name = cx.generate_local_symbol_name(kind);
let gv = declare::define_global(cx, &name[..], val_ty(cv)).unwrap_or_else(||{
bug!("symbol `{}` is already defined", name);
});
llvm::LLVMRustSetLinkage(gv, llvm::Linkage::PrivateLinkage);
gv
},
_ => declare::define_private_global(cx, val_ty(cv)),
};
llvm::LLVMSetInitializer(gv, cv);
set_global_alignment(cx, gv, align);
SetUnnamedAddr(gv, true);
gv
}
}
pub fn addr_of(
cx: &CodegenCx<'ll, '_>,
cv: &'ll Value,
align: Align,
kind: Option<&str>,
) -> &'ll Value {
if let Some(&gv) = cx.const_globals.borrow().get(&cv) {
unsafe {
let llalign = align.abi() as u32;
if llalign > llvm::LLVMGetAlignment(gv) {
llvm::LLVMSetAlignment(gv, llalign);
}
}
return gv;
}
let gv = addr_of_mut(cx, cv, align, kind);
unsafe {
llvm::LLVMSetGlobalConstant(gv, True);
}
cx.const_globals.borrow_mut().insert(cv, gv);
gv
}
pub fn get_static(cx: &CodegenCx<'ll, '_>, def_id: DefId) -> &'ll Value {
let instance = Instance::mono(cx.tcx, def_id);
if let Some(&g) = cx.instances.borrow().get(&instance) {
return g;
}
let defined_in_current_codegen_unit = cx.codegen_unit
.items()
.contains_key(&MonoItem::Static(def_id));
assert!(!defined_in_current_codegen_unit,
"consts::get_static() should always hit the cache for \
statics defined in the same CGU, but did not for `{:?}`",
def_id);
let ty = instance.ty(cx.tcx);
let sym = cx.tcx.symbol_name(instance).as_str();
debug!("get_static: sym={} instance={:?}", sym, instance);
let g = if let Some(id) = cx.tcx.hir.as_local_node_id(def_id) {
let llty = cx.layout_of(ty).llvm_type(cx);
let (g, attrs) = match cx.tcx.hir.get(id) {
Node::Item(&hir::Item {
ref attrs, span, node: hir::ItemKind::Static(..), ..
}) => {
if declare::get_declared_value(cx, &sym[..]).is_some() {
span_bug!(span, "Conflicting symbol names for static?");
}
let g = declare::define_global(cx, &sym[..], llty).unwrap();
if !cx.tcx.is_reachable_non_generic(def_id) {
unsafe {
llvm::LLVMRustSetVisibility(g, llvm::Visibility::Hidden);
}
}
(g, attrs)
}
Node::ForeignItem(&hir::ForeignItem {
ref attrs, span, node: hir::ForeignItemKind::Static(..), ..
}) => {
let fn_attrs = cx.tcx.codegen_fn_attrs(def_id);
(check_and_apply_linkage(cx, &fn_attrs, ty, sym, Some(span)), attrs)
}
item => bug!("get_static: expected static, found {:?}", item)
};
debug!("get_static: sym={} attrs={:?}", sym, attrs);
for attr in attrs {
if attr.check_name("thread_local") {
llvm::set_thread_local_mode(g, cx.tls_model);
}
}
g
} else {
debug!("get_static: sym={} item_attr={:?}", sym, cx.tcx.item_attrs(def_id));
let attrs = cx.tcx.codegen_fn_attrs(def_id);
let g = check_and_apply_linkage(cx, &attrs, ty, sym, None);
if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
llvm::set_thread_local_mode(g, cx.tls_model);
}
let needs_dll_storage_attr =
cx.use_dll_storage_attrs && !cx.tcx.is_foreign_item(def_id) &&
!cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled();
debug_assert!(!(cx.tcx.sess.opts.debugging_opts.cross_lang_lto.enabled() &&
cx.tcx.sess.target.target.options.is_like_msvc &&
cx.tcx.sess.opts.cg.prefer_dynamic));
if needs_dll_storage_attr {
if !cx.tcx.is_codegened_item(def_id) {
unsafe {
llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
}
}
}
g
};
if cx.use_dll_storage_attrs && cx.tcx.is_dllimport_foreign_item(def_id) {
unsafe {
llvm::LLVMSetDLLStorageClass(g, llvm::DLLStorageClass::DllImport);
}
}
cx.instances.borrow_mut().insert(instance, g);
g
}
fn check_and_apply_linkage(
cx: &CodegenCx<'ll, 'tcx>,
attrs: &CodegenFnAttrs,
ty: Ty<'tcx>,
sym: LocalInternedString,
span: Option<Span>
) -> &'ll Value {
let llty = cx.layout_of(ty).llvm_type(cx);
if let Some(linkage) = attrs.linkage {
debug!("get_static: sym={} linkage={:?}", sym, linkage);
let llty2 = match ty.sty {
ty::RawPtr(ref mt) => cx.layout_of(mt.ty).llvm_type(cx),
_ => {
if span.is_some() {
cx.sess().span_fatal(span.unwrap(), "must have type `*const T` or `*mut T`")
} else {
bug!("must have type `*const T` or `*mut T`")
}
}
};
unsafe {
let g1 = declare::declare_global(cx, &sym, llty2);
llvm::LLVMRustSetLinkage(g1, base::linkage_to_llvm(linkage));
let mut real_name = "_rust_extern_with_linkage_".to_string();
real_name.push_str(&sym);
let g2 = declare::define_global(cx, &real_name, llty).unwrap_or_else(||{
if span.is_some() {
cx.sess().span_fatal(
span.unwrap(),
&format!("symbol `{}` is already defined", &sym)
)
} else {
bug!("symbol `{}` is already defined", &sym)
}
});
llvm::LLVMRustSetLinkage(g2, llvm::Linkage::InternalLinkage);
llvm::LLVMSetInitializer(g2, g1);
g2
}
} else {
declare::declare_global(cx, &sym, llty)
}
}
pub fn codegen_static<'a, 'tcx>(
cx: &CodegenCx<'a, 'tcx>,
def_id: DefId,
is_mutable: bool,
) {
unsafe {
let attrs = cx.tcx.codegen_fn_attrs(def_id);
let (v, alloc) = match ::mir::codegen_static_initializer(cx, def_id) {
Ok(v) => v,
Err(_) => return,
};
let g = get_static(cx, def_id);
let mut val_llty = val_ty(v);
let v = if val_llty == Type::i1(cx) {
val_llty = Type::i8(cx);
llvm::LLVMConstZExt(v, val_llty)
} else {
v
};
let instance = Instance::mono(cx.tcx, def_id);
let ty = instance.ty(cx.tcx);
let llty = cx.layout_of(ty).llvm_type(cx);
let g = if val_llty == llty {
g
} else {
let empty_string = const_cstr!("");
let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
llvm::LLVMSetValueName(g, empty_string.as_ptr());
let linkage = llvm::LLVMRustGetLinkage(g);
let visibility = llvm::LLVMRustGetVisibility(g);
let new_g = llvm::LLVMRustGetOrInsertGlobal(
cx.llmod, name_string.as_ptr(), val_llty);
llvm::LLVMRustSetLinkage(new_g, linkage);
llvm::LLVMRustSetVisibility(new_g, visibility);
cx.statics_to_rauw.borrow_mut().push((g, new_g));
new_g
};
set_global_alignment(cx, g, cx.align_of(ty));
llvm::LLVMSetInitializer(g, v);
if !is_mutable {
if cx.type_is_freeze(ty) {
llvm::LLVMSetGlobalConstant(g, llvm::True);
}
}
debuginfo::create_global_var_metadata(cx, def_id, g);
if attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) {
llvm::set_thread_local_mode(g, cx.tls_model);
if cx.tcx.sess.target.target.options.is_like_osx {
let sect_name = if alloc.bytes.iter().all(|b| *b == 0) {
CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_bss\0")
} else {
CStr::from_bytes_with_nul_unchecked(b"__DATA,__thread_data\0")
};
llvm::LLVMSetSection(g, sect_name.as_ptr());
}
}
if cx.tcx.sess.opts.target_triple.triple().starts_with("wasm32") {
if let Some(section) = attrs.link_section {
let section = llvm::LLVMMDStringInContext(
cx.llcx,
section.as_str().as_ptr() as *const _,
section.as_str().len() as c_uint,
);
let alloc = llvm::LLVMMDStringInContext(
cx.llcx,
alloc.bytes.as_ptr() as *const _,
alloc.bytes.len() as c_uint,
);
let data = [section, alloc];
let meta = llvm::LLVMMDNodeInContext(cx.llcx, data.as_ptr(), 2);
llvm::LLVMAddNamedMetadataOperand(
cx.llmod,
"wasm.custom_sections\0".as_ptr() as *const _,
meta,
);
}
} else {
base::set_link_section(g, &attrs);
}
if attrs.flags.contains(CodegenFnAttrFlags::USED) {
let cast = llvm::LLVMConstPointerCast(g, Type::i8p(cx));
cx.used_statics.borrow_mut().push(cast);
}
}
}