-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.cpp
2771 lines (2398 loc) · 105 KB
/
module.cpp
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2010-2014, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file module.cpp
@brief Impementation of the Module class, which collects the result of compiling
a source file and then generates output (object files, etc.)
*/
#include "module.h"
#include "util.h"
#include "ctx.h"
#include "func.h"
#include "builtins.h"
#include "type.h"
#include "expr.h"
#include "sym.h"
#include "stmt.h"
#include "opt.h"
#include "llvmutil.h"
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <algorithm>
#include <set>
#include <sstream>
#include <iostream>
#ifdef ISPC_IS_WINDOWS
#include <windows.h>
#include <io.h>
#define strcasecmp stricmp
#endif
#if defined(LLVM_3_1) || defined(LLVM_3_2)
#include <llvm/LLVMContext.h>
#include <llvm/Module.h>
#include <llvm/Type.h>
#include <llvm/Instructions.h>
#include <llvm/Intrinsics.h>
#include <llvm/DerivedTypes.h>
#else
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/DerivedTypes.h>
#endif
#include <llvm/PassManager.h>
#include <llvm/PassRegistry.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/FileUtilities.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Target/TargetOptions.h>
#if defined(LLVM_3_2)
#include <llvm/DataLayout.h>
#include <llvm/TargetTransformInfo.h>
#else // LLVM 3.3+
#include <llvm/IR/DataLayout.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#endif
#if defined(LLVM_3_5)
#include <llvm/IR/Verifier.h>
#include <llvm/IR/IRPrintingPasses.h>
#include <llvm/IR/CFG.h>
#else
#include <llvm/Analysis/Verifier.h>
#include <llvm/Assembly/PrintModulePass.h>
#include <llvm/Support/CFG.h>
#endif
#include <clang/Frontend/CompilerInstance.h>
#include <clang/Frontend/TextDiagnosticPrinter.h>
#include <clang/Frontend/Utils.h>
#include <clang/Basic/TargetInfo.h>
#include <llvm/Support/ToolOutputFile.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Bitcode/ReaderWriter.h>
/*! list of files encountered by the parser. this allows emitting of
the module file's dependencies via the -MMM option */
std::set<std::string> registeredDependencies;
/*! this is where the parser tells us that it has seen the given file
name in the CPP hash */
void RegisterDependency(const std::string &fileName)
{
if (fileName[0] != '<' && fileName != "stdlib.ispc")
registeredDependencies.insert(fileName);
}
static void
lDeclareSizeAndPtrIntTypes(SymbolTable *symbolTable) {
const Type *ptrIntType = (g->target->is32Bit()) ? AtomicType::VaryingInt32 :
AtomicType::VaryingInt64;
ptrIntType = ptrIntType->GetAsUnboundVariabilityType();
symbolTable->AddType("intptr_t", ptrIntType, SourcePos());
symbolTable->AddType("uintptr_t", ptrIntType->GetAsUnsignedType(),
SourcePos());
symbolTable->AddType("ptrdiff_t", ptrIntType, SourcePos());
const Type *sizeType = (g->target->is32Bit() || g->opt.force32BitAddressing) ?
AtomicType::VaryingUInt32 : AtomicType::VaryingUInt64;
sizeType = sizeType->GetAsUnboundVariabilityType();
symbolTable->AddType("size_t", sizeType, SourcePos());
}
/** After compilation completes, there's often a lot of extra debugging
metadata left around that isn't needed any more--for example, for
static functions that weren't actually used, function information for
functions that were inlined, etc. This function takes a llvm::Module
and tries to strip out all of this extra stuff.
*/
static void
lStripUnusedDebugInfo(llvm::Module *module) {
if (g->generateDebuggingSymbols == false)
return;
// loop over the compile units that contributed to the final module
if (llvm::NamedMDNode *cuNodes = module->getNamedMetadata("llvm.dbg.cu")) {
for (unsigned i = 0, ie = cuNodes->getNumOperands(); i != ie; ++i) {
llvm::MDNode *cuNode = cuNodes->getOperand(i);
llvm::DICompileUnit cu(cuNode);
llvm::DIArray subprograms = cu.getSubprograms();
std::vector<llvm::Value *> usedSubprograms;
if (subprograms.getNumElements() == 0)
continue;
// And now loop over the subprograms inside each compile unit.
for (unsigned j = 0, je = subprograms.getNumElements(); j != je; ++j) {
llvm::MDNode *spNode =
llvm::dyn_cast<llvm::MDNode>(subprograms->getOperand(j));
Assert(spNode != NULL);
llvm::DISubprogram sp(spNode);
// Get the name of the subprogram. Start with the mangled
// name; if that's empty then we have an export'ed
// function, so grab the unmangled name in that case.
std::string name = sp.getLinkageName();
if (name == "")
name = sp.getName();
// Does the llvm::Function for this function survive in the
// module?
if (module->getFunction(name) != NULL)
usedSubprograms.push_back(sp);
}
Debug(SourcePos(), "%d / %d functions left in module with debug "
"info.", (int)usedSubprograms.size(),
(int)subprograms.getNumElements());
// We'd now like to replace the array of subprograms in the
// compile unit with only the ones that actually have function
// definitions present. Unfortunately, llvm::DICompileUnit
// doesn't provide a method to set the subprograms. Therefore,
// we end up needing to directly stuff a new array into the
// appropriate slot (number 12) in the MDNode for the compile
// unit.
//
// Because this is all so hard-coded and would break if the
// debugging metadata organization on the LLVM side changed,
// here is a bunch of asserting to make sure that element 12 of
// the compile unit's MDNode has the subprograms array....
//
// Update: This is not an approved way of working with debug info
// metadata. It's not supposed to be deleted. But in out use-case
// it's quite useful thing, as we link in bunch of unnecessary
// stuff and remove it later on. Removing it is useful, as it
// reduces size of the binary significantly (manyfold for small
// programs).
#if defined(LLVM_3_1) || defined(LLVM_3_2)
llvm::MDNode *nodeSPMD =
llvm::dyn_cast<llvm::MDNode>(cuNode->getOperand(12));
Assert(nodeSPMD != NULL);
llvm::MDNode *nodeSPMDArray =
llvm::dyn_cast<llvm::MDNode>(nodeSPMD->getOperand(0));
llvm::DIArray nodeSPs(nodeSPMDArray);
Assert(nodeSPs.getNumElements() == subprograms.getNumElements());
for (int i = 0; i < (int)nodeSPs.getNumElements(); ++i)
Assert(nodeSPs.getElement(i) == subprograms.getElement(i));
// And now we can go and stuff it into the node with some
// confidence...
llvm::Value *usedSubprogramsArray =
m->diBuilder->getOrCreateArray(llvm::ArrayRef<llvm::Value *>(usedSubprograms));
llvm::MDNode *replNode =
llvm::MDNode::get(*g->ctx, llvm::ArrayRef<llvm::Value *>(usedSubprogramsArray));
cuNode->replaceOperandWith(12, replNode);
#else // LLVM 3.3+
llvm::MDNode *nodeSPMDArray =
llvm::dyn_cast<llvm::MDNode>(cuNode->getOperand(9));
Assert(nodeSPMDArray != NULL);
llvm::DIArray nodeSPs(nodeSPMDArray);
Assert(nodeSPs.getNumElements() == subprograms.getNumElements());
for (int i = 0; i < (int)nodeSPs.getNumElements(); ++i)
Assert(nodeSPs.getElement(i) == subprograms.getElement(i));
// And now we can go and stuff it into the node with some
// confidence...
llvm::MDNode *replNode =
m->diBuilder->getOrCreateArray(llvm::ArrayRef<llvm::Value *>(usedSubprograms));
cuNode->replaceOperandWith(9, replNode);
#endif
}
}
// Also, erase a bunch of named metadata detrius; for each function
// there is sometimes named metadata llvm.dbg.lv.{funcname} that
// doesn't seem to be otherwise needed.
std::vector<llvm::NamedMDNode *> toErase;
llvm::Module::named_metadata_iterator iter = module->named_metadata_begin();
for (; iter != module->named_metadata_end(); ++iter) {
if (!strncmp(iter->getName().str().c_str(), "llvm.dbg.lv", 11))
toErase.push_back(iter);
}
for (int i = 0; i < (int)toErase.size(); ++i)
module->eraseNamedMetadata(toErase[i]);
// Wrap up by running the LLVM pass to remove anything left that's
// unused.
llvm::PassManager pm;
pm.add(llvm::createStripDeadDebugInfoPass());
pm.run(*module);
}
///////////////////////////////////////////////////////////////////////////
// Module
Module::Module(const char *fn) {
// It's a hack to do this here, but it must be done after the target
// information has been set (so e.g. the vector width is known...) In
// particular, if we're compiling to multiple targets with different
// vector widths, this needs to be redone each time through.
InitLLVMUtil(g->ctx, *g->target);
filename = fn;
errorCount = 0;
symbolTable = new SymbolTable;
ast = new AST;
lDeclareSizeAndPtrIntTypes(symbolTable);
module = new llvm::Module(filename ? filename : "<stdin>", *g->ctx);
module->setTargetTriple(g->target->GetTripleString());
// DataLayout information supposed to be managed in single place in Target class.
module->setDataLayout(g->target->getDataLayout()->getStringRepresentation());
if (g->generateDebuggingSymbols) {
diBuilder = new llvm::DIBuilder(*module);
// Let the DIBuilder know that we're starting a new compilation
// unit.
if (filename == NULL) {
// Unfortunately we can't yet call Error() since the global 'm'
// variable hasn't been initialized yet.
fprintf(stderr, "Can't emit debugging information with no "
"source file on disk.\n");
++errorCount;
delete diBuilder;
diBuilder = NULL;
}
else {
std::string directory, name;
GetDirectoryAndFileName(g->currentDirectory, filename, &directory,
&name);
char producerString[512];
#if defined(BUILD_VERSION) && defined (BUILD_DATE)
sprintf(producerString, "ispc version %s (build %s on %s)",
ISPC_VERSION, BUILD_VERSION, BUILD_DATE);
#else
sprintf(producerString, "ispc version %s (built on %s)",
ISPC_VERSION, __DATE__);
#endif
#if !defined(LLVM_3_1) && !defined(LLVM_3_2) && !defined(LLVM_3_3)
diCompileUnit =
#endif // LLVM_3_4+
diBuilder->createCompileUnit(llvm::dwarf::DW_LANG_C99, /* lang */
name, /* filename */
directory, /* directory */
producerString, /* producer */
g->opt.level > 0 /* is optimized */,
"-g", /* command line args */
0 /* run time version */);
}
}
else
diBuilder = NULL;
}
extern FILE *yyin;
extern int yyparse();
typedef struct yy_buffer_state *YY_BUFFER_STATE;
extern void yy_switch_to_buffer(YY_BUFFER_STATE);
extern YY_BUFFER_STATE yy_scan_string(const char *);
extern YY_BUFFER_STATE yy_create_buffer(FILE *, int);
extern void yy_delete_buffer(YY_BUFFER_STATE);
int
Module::CompileFile() {
extern void ParserInit();
ParserInit();
// FIXME: it'd be nice to do this in the Module constructor, but this
// function ends up calling into routines that expect the global
// variable 'm' to be initialized and available (which it isn't until
// the Module constructor returns...)
DefineStdlib(symbolTable, g->ctx, module, g->includeStdlib);
bool runPreprocessor = g->runCPP;
if (runPreprocessor) {
if (filename != NULL) {
// Try to open the file first, since otherwise we crash in the
// preprocessor if the file doesn't exist.
FILE *f = fopen(filename, "r");
if (!f) {
perror(filename);
return 1;
}
fclose(f);
}
std::string buffer;
llvm::raw_string_ostream os(buffer);
execPreprocessor((filename != NULL) ? filename : "-", &os);
YY_BUFFER_STATE strbuf = yy_scan_string(os.str().c_str());
yyparse();
yy_delete_buffer(strbuf);
}
else {
// No preprocessor, just open up the file if it's not stdin..
FILE* f = NULL;
if (filename == NULL)
f = stdin;
else {
f = fopen(filename, "r");
if (f == NULL) {
perror(filename);
return 1;
}
}
yyin = f;
yy_switch_to_buffer(yy_create_buffer(yyin, 4096));
yyparse();
fclose(f);
}
ast->GenerateIR();
if (errorCount == 0)
Optimize(module, g->opt.level);
return errorCount;
}
void
Module::AddTypeDef(const std::string &name, const Type *type,
SourcePos pos) {
// Typedefs are easy; just add the mapping between the given name and
// the given type.
symbolTable->AddType(name.c_str(), type, pos);
}
void
Module::AddGlobalVariable(const std::string &name, const Type *type, Expr *initExpr,
bool isConst, StorageClass storageClass, SourcePos pos) {
// These may be NULL due to errors in parsing; just gracefully return
// here if so.
if (name == "" || type == NULL) {
Assert(errorCount > 0);
return;
}
if (symbolTable->LookupFunction(name.c_str())) {
Error(pos, "Global variable \"%s\" shadows previously-declared "
"function.", name.c_str());
return;
}
if (storageClass == SC_EXTERN_C) {
Error(pos, "extern \"C\" qualifier can only be used for "
"functions.");
return;
}
if (type->IsVoidType()) {
Error(pos, "\"void\" type global variable is illegal.");
return;
}
type = ArrayType::SizeUnsizedArrays(type, initExpr);
if (type == NULL)
return;
const ArrayType *at = CastType<ArrayType>(type);
if (at != NULL && at->TotalElementCount() == 0) {
Error(pos, "Illegal to declare a global variable with unsized "
"array dimensions that aren't set with an initializer "
"expression.");
return;
}
llvm::Type *llvmType = type->LLVMType(g->ctx);
if (llvmType == NULL)
return;
// See if we have an initializer expression for the global. If so,
// make sure it's a compile-time constant!
llvm::Constant *llvmInitializer = NULL;
ConstExpr *constValue = NULL;
if (storageClass == SC_EXTERN || storageClass == SC_EXTERN_C) {
if (initExpr != NULL)
Error(pos, "Initializer can't be provided with \"extern\" "
"global variable \"%s\".", name.c_str());
}
else {
if (initExpr != NULL) {
initExpr = TypeCheck(initExpr);
if (initExpr != NULL) {
// We need to make sure the initializer expression is
// the same type as the global. (But not if it's an
// ExprList; they don't have types per se / can't type
// convert themselves anyway.)
if (dynamic_cast<ExprList *>(initExpr) == NULL)
initExpr = TypeConvertExpr(initExpr, type, "initializer");
if (initExpr != NULL) {
initExpr = Optimize(initExpr);
// Fingers crossed, now let's see if we've got a
// constant value..
llvmInitializer = initExpr->GetConstant(type);
if (llvmInitializer != NULL) {
if (type->IsConstType())
// Try to get a ConstExpr associated with
// the symbol. This dynamic_cast can
// validly fail, for example for types like
// StructTypes where a ConstExpr can't
// represent their values.
constValue = dynamic_cast<ConstExpr *>(initExpr);
}
else
Error(initExpr->pos, "Initializer for global variable \"%s\" "
"must be a constant.", name.c_str());
}
}
}
// If no initializer was provided or if we couldn't get a value
// above, initialize it with zeros..
if (llvmInitializer == NULL)
llvmInitializer = llvm::Constant::getNullValue(llvmType);
}
Symbol *sym = symbolTable->LookupVariable(name.c_str());
llvm::GlobalVariable *oldGV = NULL;
if (sym != NULL) {
// We've already seen either a declaration or a definition of this
// global.
// If the type doesn't match with the previous one, issue an error.
if (!Type::Equal(sym->type, type) ||
(sym->storageClass != SC_EXTERN &&
sym->storageClass != SC_EXTERN_C &&
sym->storageClass != storageClass)) {
Error(pos, "Definition of variable \"%s\" conflicts with "
"definition at %s:%d.", name.c_str(),
sym->pos.name, sym->pos.first_line);
return;
}
llvm::GlobalVariable *gv =
llvm::dyn_cast<llvm::GlobalVariable>(sym->storagePtr);
Assert(gv != NULL);
// And issue an error if this is a redefinition of a variable
if (gv->hasInitializer() &&
sym->storageClass != SC_EXTERN && sym->storageClass != SC_EXTERN_C) {
Error(pos, "Redefinition of variable \"%s\" is illegal. "
"(Previous definition at %s:%d.)", sym->name.c_str(),
sym->pos.name, sym->pos.first_line);
return;
}
// Now, we either have a redeclaration of a global, or a definition
// of a previously-declared global. First, save the pointer to the
// previous llvm::GlobalVariable
oldGV = gv;
}
else {
sym = new Symbol(name, pos, type, storageClass);
symbolTable->AddVariable(sym);
}
sym->constValue = constValue;
llvm::GlobalValue::LinkageTypes linkage =
(sym->storageClass == SC_STATIC) ? llvm::GlobalValue::InternalLinkage :
llvm::GlobalValue::ExternalLinkage;
// Note that the NULL llvmInitializer is what leads to "extern"
// declarations coming up extern and not defining storage (a bit
// subtle)...
sym->storagePtr = new llvm::GlobalVariable(*module, llvmType, isConst,
linkage, llvmInitializer,
sym->name.c_str());
// Patch up any references to the previous GlobalVariable (e.g. from a
// declaration of a global that was later defined.)
if (oldGV != NULL) {
oldGV->replaceAllUsesWith(sym->storagePtr);
oldGV->removeFromParent();
sym->storagePtr->setName(sym->name.c_str());
}
if (diBuilder) {
llvm::DIFile file = pos.GetDIFile();
llvm::DIGlobalVariable var =
diBuilder->createGlobalVariable(name,
file,
pos.first_line,
sym->type->GetDIType(file),
(sym->storageClass == SC_STATIC),
sym->storagePtr);
Assert(var.Verify());
}
}
/** Given an arbitrary type, see if it or any of the leaf types contained
in it has a type that's illegal to have exported to C/C++
code.
(Note that it's fine for the original struct or a contained struct to
be varying, so long as all of its members have bound 'uniform'
variability.)
This functions returns true and issues an error if are any illegal
types are found and returns false otherwise.
*/
static bool
lRecursiveCheckValidParamType(const Type *t, bool vectorOk) {
const StructType *st = CastType<StructType>(t);
if (st != NULL) {
for (int i = 0; i < st->GetElementCount(); ++i)
if (!lRecursiveCheckValidParamType(st->GetElementType(i),
vectorOk))
return false;
return true;
}
// Vector types are also not supported, pending ispc properly
// supporting the platform ABI. (Pointers to vector types are ok,
// though.) (https://github.com/ispc/ispc/issues/363)...
if (vectorOk == false && CastType<VectorType>(t) != NULL)
return false;
const SequentialType *seqt = CastType<SequentialType>(t);
if (seqt != NULL)
return lRecursiveCheckValidParamType(seqt->GetElementType(), vectorOk);
const PointerType *pt = CastType<PointerType>(t);
if (pt != NULL) {
// Only allow exported uniform pointers
// Uniform pointers to varying data, however, are ok.
if (pt->IsVaryingType())
return false;
else
return lRecursiveCheckValidParamType(pt->GetBaseType(), true);
}
if (t->IsVaryingType() && !vectorOk)
return false;
else
return true;
}
/** Given a Symbol representing a function parameter, see if it or any
contained types are varying. If so, issue an error. (This function
should only be called for parameters to 'export'ed functions, where
varying parameters is illegal.
*/
static void
lCheckExportedParameterTypes(const Type *type, const std::string &name,
SourcePos pos) {
if (lRecursiveCheckValidParamType(type, false) == false) {
if (CastType<PointerType>(type))
Error(pos, "Varying pointer type parameter \"%s\" is illegal "
"in an exported function.", name.c_str());
if (CastType<StructType>(type->GetBaseType()))
Error(pos, "Struct parameter \"%s\" with vector typed "
"member(s) is illegal in an exported function.", name.c_str());
else if (CastType<VectorType>(type))
Error(pos, "Vector-typed parameter \"%s\" is illegal in an exported "
"function.", name.c_str());
else
Error(pos, "Varying parameter \"%s\" is illegal in an exported function.",
name.c_str());
}
}
/** Given a function type, loop through the function parameters and see if
any are StructTypes. If so, issue an error; this is currently broken
(https://github.com/ispc/ispc/issues/3).
*/
static void
lCheckForStructParameters(const FunctionType *ftype, SourcePos pos) {
for (int i = 0; i < ftype->GetNumParameters(); ++i) {
const Type *type = ftype->GetParameterType(i);
if (CastType<StructType>(type) != NULL) {
Error(pos, "Passing structs to/from application functions is "
"currently broken. Use a pointer or const pointer to the "
"struct instead for now.");
return;
}
}
}
/** We've got a declaration for a function to process. This function does
all the work of creating the corresponding llvm::Function instance,
adding the symbol for the function to the symbol table and doing
various sanity checks. This function returns true upon success and
false if any errors were encountered.
*/
void
Module::AddFunctionDeclaration(const std::string &name,
const FunctionType *functionType,
StorageClass storageClass, bool isInline,
SourcePos pos) {
Assert(functionType != NULL);
// If a global variable with the same name has already been declared
// issue an error.
if (symbolTable->LookupVariable(name.c_str()) != NULL) {
Error(pos, "Function \"%s\" shadows previously-declared global variable. "
"Ignoring this definition.",
name.c_str());
return;
}
std::vector<Symbol *> overloadFuncs;
symbolTable->LookupFunction(name.c_str(), &overloadFuncs);
if (overloadFuncs.size() > 0) {
for (unsigned int i = 0; i < overloadFuncs.size(); ++i) {
Symbol *overloadFunc = overloadFuncs[i];
const FunctionType *overloadType =
CastType<FunctionType>(overloadFunc->type);
if (overloadType == NULL) {
Assert(m->errorCount == 0);
continue;
}
// Check for a redeclaration of a function with the same name
// and type. This also hits when we have previously declared
// the function and are about to define it.
if (Type::Equal(overloadFunc->type, functionType))
return;
if (functionType->isExported || overloadType->isExported)
Error(pos, "Illegal to provide \"export\" qualifier for "
"functions with the same name but different types. "
"(Previous function declaration (%s:%d).)",
overloadFunc->pos.name, overloadFunc->pos.first_line);
// If all of the parameter types match but the return type is
// different, return an error--overloading by return type isn't
// allowed.
const FunctionType *ofType =
CastType<FunctionType>(overloadFunc->type);
Assert(ofType != NULL);
if (ofType->GetNumParameters() == functionType->GetNumParameters()) {
int i;
for (i = 0; i < functionType->GetNumParameters(); ++i) {
if (Type::Equal(ofType->GetParameterType(i),
functionType->GetParameterType(i)) == false)
break;
}
if (i == functionType->GetNumParameters()) {
std::string thisRetType = functionType->GetReturnTypeString();
std::string otherRetType = ofType->GetReturnTypeString();
Error(pos, "Illegal to overload function by return "
"type only. This function returns \"%s\" while "
"previous declaration at %s:%d returns \"%s\".",
thisRetType.c_str(), overloadFunc->pos.name,
overloadFunc->pos.first_line, otherRetType.c_str());
return;
}
}
}
}
if (storageClass == SC_EXTERN_C) {
// Make sure the user hasn't supplied both an 'extern "C"' and a
// 'task' qualifier with the function
if (functionType->isTask) {
Error(pos, "\"task\" qualifier is illegal with C-linkage extern "
"function \"%s\". Ignoring this function.", name.c_str());
return;
}
std::vector<Symbol *> funcs;
symbolTable->LookupFunction(name.c_str(), &funcs);
if (funcs.size() > 0) {
if (funcs.size() > 1) {
// Multiple functions with this name have already been declared;
// can't overload here
Error(pos, "Can't overload extern \"C\" function \"%s\"; "
"%d functions with the same name have already been declared.",
name.c_str(), (int)funcs.size());
return;
}
// One function with the same name has been declared; see if it
// has the same type as this one, in which case it's ok.
if (Type::Equal(funcs[0]->type, functionType))
return;
else {
Error(pos, "Can't overload extern \"C\" function \"%s\".",
name.c_str());
return;
}
}
}
// Get the LLVM FunctionType
bool disableMask = (storageClass == SC_EXTERN_C);
llvm::FunctionType *llvmFunctionType =
functionType->LLVMFunctionType(g->ctx, disableMask);
if (llvmFunctionType == NULL)
return;
// And create the llvm::Function
llvm::GlobalValue::LinkageTypes linkage = (storageClass == SC_STATIC ||
isInline) ?
llvm::GlobalValue::InternalLinkage : llvm::GlobalValue::ExternalLinkage;
std::string functionName = name;
if (storageClass != SC_EXTERN_C) {
functionName += functionType->Mangle();
if (g->mangleFunctionsWithTarget)
functionName += g->target->GetISAString();
}
llvm::Function *function =
llvm::Function::Create(llvmFunctionType, linkage, functionName.c_str(),
module);
// Set function attributes: we never throw exceptions
function->setDoesNotThrow();
if (storageClass != SC_EXTERN_C &&
isInline)
#ifdef LLVM_3_2
function->addFnAttr(llvm::Attributes::AlwaysInline);
#else // LLVM 3.1 and 3.3+
function->addFnAttr(llvm::Attribute::AlwaysInline);
#endif
if (functionType->isTask)
// This also applies transitively to members I think?
#if defined(LLVM_3_1)
function->setDoesNotAlias(1, true);
#else // LLVM 3.2+
function->setDoesNotAlias(1);
#endif
g->target->markFuncWithTargetAttr(function);
// Make sure that the return type isn't 'varying' or vector typed if
// the function is 'export'ed.
if (functionType->isExported &&
lRecursiveCheckValidParamType(functionType->GetReturnType(), false) == false)
Error(pos, "Illegal to return a \"varying\" or vector type from "
"exported function \"%s\"", name.c_str());
if (functionType->isTask &&
functionType->GetReturnType()->IsVoidType() == false)
Error(pos, "Task-qualified functions must have void return type.");
if (functionType->isExported || functionType->isExternC)
lCheckForStructParameters(functionType, pos);
// Loop over all of the arguments; process default values if present
// and do other checks and parameter attribute setting.
bool seenDefaultArg = false;
int nArgs = functionType->GetNumParameters();
for (int i = 0; i < nArgs; ++i) {
const Type *argType = functionType->GetParameterType(i);
const std::string &argName = functionType->GetParameterName(i);
Expr *defaultValue = functionType->GetParameterDefault(i);
const SourcePos &argPos = functionType->GetParameterSourcePos(i);
// If the function is exported, make sure that the parameter
// doesn't have any funky stuff going on in it.
// JCB nomosoa - Varying is now a-ok.
if (functionType->isExported) {
lCheckExportedParameterTypes(argType, argName, argPos);
}
// ISPC assumes that no pointers alias. (It should be possible to
// specify when this is not the case, but this should be the
// default.) Set parameter attributes accordingly. (Only for
// uniform pointers, since varying pointers are int vectors...)
if (!functionType->isTask &&
((CastType<PointerType>(argType) != NULL &&
argType->IsUniformType() &&
// Exclude SOA argument because it is a pair {struct *, int}
// instead of pointer
!CastType<PointerType>(argType)->IsSlice())
||
CastType<ReferenceType>(argType) != NULL)) {
// NOTE: LLVM indexes function parameters starting from 1.
// This is unintuitive.
#if defined(LLVM_3_1)
function->setDoesNotAlias(i+1, true);
#else
function->setDoesNotAlias(i+1);
#endif
#if 0
int align = 4 * RoundUpPow2(g->target->nativeVectorWidth);
function->addAttribute(i+1, llvm::Attribute::constructAlignmentFromInt(align));
#endif
}
if (symbolTable->LookupFunction(argName.c_str()))
Warning(argPos, "Function parameter \"%s\" shadows a function "
"declared in global scope.", argName.c_str());
if (defaultValue != NULL)
seenDefaultArg = true;
else if (seenDefaultArg) {
// Once one parameter has provided a default value, then all of
// the following ones must have them as well.
Error(argPos, "Parameter \"%s\" is missing default: all "
"parameters after the first parameter with a default value "
"must have default values as well.", argName.c_str());
}
}
// If llvm gave us back a Function * with a different name than the one
// we asked for, then there's already a function with that same
// (mangled) name in the llvm::Module. In that case, erase the one we
// tried to add and just work with the one it already had.
if (function->getName() != functionName) {
function->eraseFromParent();
function = module->getFunction(functionName);
}
// Finally, we know all is good and we can add the function to the
// symbol table
Symbol *funSym = new Symbol(name, pos, functionType, storageClass);
funSym->function = function;
bool ok = symbolTable->AddFunction(funSym);
Assert(ok);
}
void
Module::AddFunctionDefinition(const std::string &name, const FunctionType *type,
Stmt *code) {
Symbol *sym = symbolTable->LookupFunction(name.c_str(), type);
if (sym == NULL || code == NULL) {
Assert(m->errorCount > 0);
return;
}
sym->pos = code->pos;
// FIXME: because we encode the parameter names in the function type,
// we need to override the function type here in case the function had
// earlier been declared with anonymous parameter names but is now
// defined with actual names. This is yet another reason we shouldn't
// include the names in FunctionType...
sym->type = type;
ast->AddFunction(sym, code);
}
void
Module::AddExportedTypes(const std::vector<std::pair<const Type *,
SourcePos> > &types) {
for (int i = 0; i < (int)types.size(); ++i) {
if (CastType<StructType>(types[i].first) == NULL &&
CastType<VectorType>(types[i].first) == NULL &&
CastType<EnumType>(types[i].first) == NULL)
Error(types[i].second, "Only struct, vector, and enum types, "
"not \"%s\", are allowed in type export lists.",
types[i].first->GetString().c_str());
else
exportedTypes.push_back(types[i]);
}
}
bool
Module::writeOutput(OutputType outputType, const char *outFileName,
const char *includeFileName, DispatchHeaderInfo *DHI) {
if (diBuilder != NULL && (outputType != Header && outputType != Deps)) {
diBuilder->finalize();
lStripUnusedDebugInfo(module);
}
#if defined (LLVM_3_4) || defined (LLVM_3_5)
// In LLVM_3_4 after r195494 and r195504 revisions we should pass
// "Debug Info Version" constant to the module. LLVM will ignore
// our Debug Info metadata without it.
if (g->generateDebuggingSymbols == true) {
module->addModuleFlag(llvm::Module::Error, "Debug Info Version", llvm::DEBUG_METADATA_VERSION);
}
#endif
// First, issue a warning if the output file suffix and the type of
// file being created seem to mismatch. This can help catch missing
// command-line arguments specifying the output file type.
const char *suffix = strrchr(outFileName, '.');
if (suffix != NULL) {
++suffix;
const char *fileType = NULL;
switch (outputType) {
case Asm:
if (strcasecmp(suffix, "s"))
fileType = "assembly";
break;
case Bitcode:
if (strcasecmp(suffix, "bc"))
fileType = "LLVM bitcode";
break;
case Object:
if (strcasecmp(suffix, "o") && strcasecmp(suffix, "obj"))
fileType = "object";
break;
case CXX:
if (strcasecmp(suffix, "c") && strcasecmp(suffix, "cc") &&
strcasecmp(suffix, "c++") && strcasecmp(suffix, "cxx") &&
strcasecmp(suffix, "cpp"))
fileType = "c++";
break;
case Header:
if (strcasecmp(suffix, "h") && strcasecmp(suffix, "hh") &&
strcasecmp(suffix, "hpp"))
fileType = "header";
break;
case Deps:
break;
case DevStub:
if (strcasecmp(suffix, "c") && strcasecmp(suffix, "cc") &&
strcasecmp(suffix, "c++") && strcasecmp(suffix, "cxx") &&
strcasecmp(suffix, "cpp"))
fileType = "dev-side offload stub";
break;
case HostStub:
if (strcasecmp(suffix, "c") && strcasecmp(suffix, "cc") &&