forked from llvm-mirror/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLLParser.cpp
3997 lines (3465 loc) · 137 KB
/
LLParser.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
//===-- LLParser.cpp - Parser Class ---------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the parser class for .ll files.
//
//===----------------------------------------------------------------------===//
#include "LLParser.h"
#include "llvm/AutoUpgrade.h"
#include "llvm/CallingConv.h"
#include "llvm/Constants.h"
#include "llvm/DerivedTypes.h"
#include "llvm/InlineAsm.h"
#include "llvm/Instructions.h"
#include "llvm/Module.h"
#include "llvm/Operator.h"
#include "llvm/ValueSymbolTable.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
static std::string getTypeString(Type *T) {
std::string Result;
raw_string_ostream Tmp(Result);
Tmp << *T;
return Tmp.str();
}
/// Run: module ::= toplevelentity*
bool LLParser::Run() {
// Prime the lexer.
Lex.Lex();
return ParseTopLevelEntities() ||
ValidateEndOfModule();
}
/// ValidateEndOfModule - Do final validity and sanity checks at the end of the
/// module.
bool LLParser::ValidateEndOfModule() {
// Handle any instruction metadata forward references.
if (!ForwardRefInstMetadata.empty()) {
for (DenseMap<Instruction*, std::vector<MDRef> >::iterator
I = ForwardRefInstMetadata.begin(), E = ForwardRefInstMetadata.end();
I != E; ++I) {
Instruction *Inst = I->first;
const std::vector<MDRef> &MDList = I->second;
for (unsigned i = 0, e = MDList.size(); i != e; ++i) {
unsigned SlotNo = MDList[i].MDSlot;
if (SlotNo >= NumberedMetadata.size() || NumberedMetadata[SlotNo] == 0)
return Error(MDList[i].Loc, "use of undefined metadata '!" +
Twine(SlotNo) + "'");
Inst->setMetadata(MDList[i].MDKind, NumberedMetadata[SlotNo]);
}
}
ForwardRefInstMetadata.clear();
}
// If there are entries in ForwardRefBlockAddresses at this point, they are
// references after the function was defined. Resolve those now.
while (!ForwardRefBlockAddresses.empty()) {
// Okay, we are referencing an already-parsed function, resolve them now.
Function *TheFn = 0;
const ValID &Fn = ForwardRefBlockAddresses.begin()->first;
if (Fn.Kind == ValID::t_GlobalName)
TheFn = M->getFunction(Fn.StrVal);
else if (Fn.UIntVal < NumberedVals.size())
TheFn = dyn_cast<Function>(NumberedVals[Fn.UIntVal]);
if (TheFn == 0)
return Error(Fn.Loc, "unknown function referenced by blockaddress");
// Resolve all these references.
if (ResolveForwardRefBlockAddresses(TheFn,
ForwardRefBlockAddresses.begin()->second,
0))
return true;
ForwardRefBlockAddresses.erase(ForwardRefBlockAddresses.begin());
}
for (unsigned i = 0, e = NumberedTypes.size(); i != e; ++i)
if (NumberedTypes[i].second.isValid())
return Error(NumberedTypes[i].second,
"use of undefined type '%" + Twine(i) + "'");
for (StringMap<std::pair<Type*, LocTy> >::iterator I =
NamedTypes.begin(), E = NamedTypes.end(); I != E; ++I)
if (I->second.second.isValid())
return Error(I->second.second,
"use of undefined type named '" + I->getKey() + "'");
if (!ForwardRefVals.empty())
return Error(ForwardRefVals.begin()->second.second,
"use of undefined value '@" + ForwardRefVals.begin()->first +
"'");
if (!ForwardRefValIDs.empty())
return Error(ForwardRefValIDs.begin()->second.second,
"use of undefined value '@" +
Twine(ForwardRefValIDs.begin()->first) + "'");
if (!ForwardRefMDNodes.empty())
return Error(ForwardRefMDNodes.begin()->second.second,
"use of undefined metadata '!" +
Twine(ForwardRefMDNodes.begin()->first) + "'");
// Look for intrinsic functions and CallInst that need to be upgraded
for (Module::iterator FI = M->begin(), FE = M->end(); FI != FE; )
UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
return false;
}
bool LLParser::ResolveForwardRefBlockAddresses(Function *TheFn,
std::vector<std::pair<ValID, GlobalValue*> > &Refs,
PerFunctionState *PFS) {
// Loop over all the references, resolving them.
for (unsigned i = 0, e = Refs.size(); i != e; ++i) {
BasicBlock *Res;
if (PFS) {
if (Refs[i].first.Kind == ValID::t_LocalName)
Res = PFS->GetBB(Refs[i].first.StrVal, Refs[i].first.Loc);
else
Res = PFS->GetBB(Refs[i].first.UIntVal, Refs[i].first.Loc);
} else if (Refs[i].first.Kind == ValID::t_LocalID) {
return Error(Refs[i].first.Loc,
"cannot take address of numeric label after the function is defined");
} else {
Res = dyn_cast_or_null<BasicBlock>(
TheFn->getValueSymbolTable().lookup(Refs[i].first.StrVal));
}
if (Res == 0)
return Error(Refs[i].first.Loc,
"referenced value is not a basic block");
// Get the BlockAddress for this and update references to use it.
BlockAddress *BA = BlockAddress::get(TheFn, Res);
Refs[i].second->replaceAllUsesWith(BA);
Refs[i].second->eraseFromParent();
}
return false;
}
//===----------------------------------------------------------------------===//
// Top-Level Entities
//===----------------------------------------------------------------------===//
bool LLParser::ParseTopLevelEntities() {
while (1) {
switch (Lex.getKind()) {
default: return TokError("expected top-level entity");
case lltok::Eof: return false;
case lltok::kw_declare: if (ParseDeclare()) return true; break;
case lltok::kw_define: if (ParseDefine()) return true; break;
case lltok::kw_module: if (ParseModuleAsm()) return true; break;
case lltok::kw_target: if (ParseTargetDefinition()) return true; break;
case lltok::kw_deplibs: if (ParseDepLibs()) return true; break;
case lltok::LocalVarID: if (ParseUnnamedType()) return true; break;
case lltok::LocalVar: if (ParseNamedType()) return true; break;
case lltok::GlobalID: if (ParseUnnamedGlobal()) return true; break;
case lltok::GlobalVar: if (ParseNamedGlobal()) return true; break;
case lltok::exclaim: if (ParseStandaloneMetadata()) return true; break;
case lltok::MetadataVar: if (ParseNamedMetadata()) return true; break;
// The Global variable production with no name can have many different
// optional leading prefixes, the production is:
// GlobalVar ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
// OptionalAddrSpace OptionalUnNammedAddr
// ('constant'|'global') ...
case lltok::kw_private: // OptionalLinkage
case lltok::kw_linker_private: // OptionalLinkage
case lltok::kw_linker_private_weak: // OptionalLinkage
case lltok::kw_linker_private_weak_def_auto: // OptionalLinkage
case lltok::kw_internal: // OptionalLinkage
case lltok::kw_weak: // OptionalLinkage
case lltok::kw_weak_odr: // OptionalLinkage
case lltok::kw_linkonce: // OptionalLinkage
case lltok::kw_linkonce_odr: // OptionalLinkage
case lltok::kw_appending: // OptionalLinkage
case lltok::kw_dllexport: // OptionalLinkage
case lltok::kw_common: // OptionalLinkage
case lltok::kw_dllimport: // OptionalLinkage
case lltok::kw_extern_weak: // OptionalLinkage
case lltok::kw_external: { // OptionalLinkage
unsigned Linkage, Visibility;
if (ParseOptionalLinkage(Linkage) ||
ParseOptionalVisibility(Visibility) ||
ParseGlobal("", SMLoc(), Linkage, true, Visibility))
return true;
break;
}
case lltok::kw_default: // OptionalVisibility
case lltok::kw_hidden: // OptionalVisibility
case lltok::kw_protected: { // OptionalVisibility
unsigned Visibility;
if (ParseOptionalVisibility(Visibility) ||
ParseGlobal("", SMLoc(), 0, false, Visibility))
return true;
break;
}
case lltok::kw_thread_local: // OptionalThreadLocal
case lltok::kw_addrspace: // OptionalAddrSpace
case lltok::kw_constant: // GlobalType
case lltok::kw_global: // GlobalType
if (ParseGlobal("", SMLoc(), 0, false, 0)) return true;
break;
}
}
}
/// toplevelentity
/// ::= 'module' 'asm' STRINGCONSTANT
bool LLParser::ParseModuleAsm() {
assert(Lex.getKind() == lltok::kw_module);
Lex.Lex();
std::string AsmStr;
if (ParseToken(lltok::kw_asm, "expected 'module asm'") ||
ParseStringConstant(AsmStr)) return true;
M->appendModuleInlineAsm(AsmStr);
return false;
}
/// toplevelentity
/// ::= 'target' 'triple' '=' STRINGCONSTANT
/// ::= 'target' 'datalayout' '=' STRINGCONSTANT
bool LLParser::ParseTargetDefinition() {
assert(Lex.getKind() == lltok::kw_target);
std::string Str;
switch (Lex.Lex()) {
default: return TokError("unknown target property");
case lltok::kw_triple:
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' after target triple") ||
ParseStringConstant(Str))
return true;
M->setTargetTriple(Str);
return false;
case lltok::kw_datalayout:
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' after target datalayout") ||
ParseStringConstant(Str))
return true;
M->setDataLayout(Str);
return false;
}
}
/// toplevelentity
/// ::= 'deplibs' '=' '[' ']'
/// ::= 'deplibs' '=' '[' STRINGCONSTANT (',' STRINGCONSTANT)* ']'
bool LLParser::ParseDepLibs() {
assert(Lex.getKind() == lltok::kw_deplibs);
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' after deplibs") ||
ParseToken(lltok::lsquare, "expected '=' after deplibs"))
return true;
if (EatIfPresent(lltok::rsquare))
return false;
std::string Str;
if (ParseStringConstant(Str)) return true;
M->addLibrary(Str);
while (EatIfPresent(lltok::comma)) {
if (ParseStringConstant(Str)) return true;
M->addLibrary(Str);
}
return ParseToken(lltok::rsquare, "expected ']' at end of list");
}
/// ParseUnnamedType:
/// ::= LocalVarID '=' 'type' type
bool LLParser::ParseUnnamedType() {
LocTy TypeLoc = Lex.getLoc();
unsigned TypeID = Lex.getUIntVal();
Lex.Lex(); // eat LocalVarID;
if (ParseToken(lltok::equal, "expected '=' after name") ||
ParseToken(lltok::kw_type, "expected 'type' after '='"))
return true;
if (TypeID >= NumberedTypes.size())
NumberedTypes.resize(TypeID+1);
Type *Result = 0;
if (ParseStructDefinition(TypeLoc, "",
NumberedTypes[TypeID], Result)) return true;
if (!isa<StructType>(Result)) {
std::pair<Type*, LocTy> &Entry = NumberedTypes[TypeID];
if (Entry.first)
return Error(TypeLoc, "non-struct types may not be recursive");
Entry.first = Result;
Entry.second = SMLoc();
}
return false;
}
/// toplevelentity
/// ::= LocalVar '=' 'type' type
bool LLParser::ParseNamedType() {
std::string Name = Lex.getStrVal();
LocTy NameLoc = Lex.getLoc();
Lex.Lex(); // eat LocalVar.
if (ParseToken(lltok::equal, "expected '=' after name") ||
ParseToken(lltok::kw_type, "expected 'type' after name"))
return true;
Type *Result = 0;
if (ParseStructDefinition(NameLoc, Name,
NamedTypes[Name], Result)) return true;
if (!isa<StructType>(Result)) {
std::pair<Type*, LocTy> &Entry = NamedTypes[Name];
if (Entry.first)
return Error(NameLoc, "non-struct types may not be recursive");
Entry.first = Result;
Entry.second = SMLoc();
}
return false;
}
/// toplevelentity
/// ::= 'declare' FunctionHeader
bool LLParser::ParseDeclare() {
assert(Lex.getKind() == lltok::kw_declare);
Lex.Lex();
Function *F;
return ParseFunctionHeader(F, false);
}
/// toplevelentity
/// ::= 'define' FunctionHeader '{' ...
bool LLParser::ParseDefine() {
assert(Lex.getKind() == lltok::kw_define);
Lex.Lex();
Function *F;
return ParseFunctionHeader(F, true) ||
ParseFunctionBody(*F);
}
/// ParseGlobalType
/// ::= 'constant'
/// ::= 'global'
bool LLParser::ParseGlobalType(bool &IsConstant) {
if (Lex.getKind() == lltok::kw_constant)
IsConstant = true;
else if (Lex.getKind() == lltok::kw_global)
IsConstant = false;
else {
IsConstant = false;
return TokError("expected 'global' or 'constant'");
}
Lex.Lex();
return false;
}
/// ParseUnnamedGlobal:
/// OptionalVisibility ALIAS ...
/// OptionalLinkage OptionalVisibility ... -> global variable
/// GlobalID '=' OptionalVisibility ALIAS ...
/// GlobalID '=' OptionalLinkage OptionalVisibility ... -> global variable
bool LLParser::ParseUnnamedGlobal() {
unsigned VarID = NumberedVals.size();
std::string Name;
LocTy NameLoc = Lex.getLoc();
// Handle the GlobalID form.
if (Lex.getKind() == lltok::GlobalID) {
if (Lex.getUIntVal() != VarID)
return Error(Lex.getLoc(), "variable expected to be numbered '%" +
Twine(VarID) + "'");
Lex.Lex(); // eat GlobalID;
if (ParseToken(lltok::equal, "expected '=' after name"))
return true;
}
bool HasLinkage;
unsigned Linkage, Visibility;
if (ParseOptionalLinkage(Linkage, HasLinkage) ||
ParseOptionalVisibility(Visibility))
return true;
if (HasLinkage || Lex.getKind() != lltok::kw_alias)
return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
return ParseAlias(Name, NameLoc, Visibility);
}
/// ParseNamedGlobal:
/// GlobalVar '=' OptionalVisibility ALIAS ...
/// GlobalVar '=' OptionalLinkage OptionalVisibility ... -> global variable
bool LLParser::ParseNamedGlobal() {
assert(Lex.getKind() == lltok::GlobalVar);
LocTy NameLoc = Lex.getLoc();
std::string Name = Lex.getStrVal();
Lex.Lex();
bool HasLinkage;
unsigned Linkage, Visibility;
if (ParseToken(lltok::equal, "expected '=' in global variable") ||
ParseOptionalLinkage(Linkage, HasLinkage) ||
ParseOptionalVisibility(Visibility))
return true;
if (HasLinkage || Lex.getKind() != lltok::kw_alias)
return ParseGlobal(Name, NameLoc, Linkage, HasLinkage, Visibility);
return ParseAlias(Name, NameLoc, Visibility);
}
// MDString:
// ::= '!' STRINGCONSTANT
bool LLParser::ParseMDString(MDString *&Result) {
std::string Str;
if (ParseStringConstant(Str)) return true;
Result = MDString::get(Context, Str);
return false;
}
// MDNode:
// ::= '!' MDNodeNumber
//
/// This version of ParseMDNodeID returns the slot number and null in the case
/// of a forward reference.
bool LLParser::ParseMDNodeID(MDNode *&Result, unsigned &SlotNo) {
// !{ ..., !42, ... }
if (ParseUInt32(SlotNo)) return true;
// Check existing MDNode.
if (SlotNo < NumberedMetadata.size() && NumberedMetadata[SlotNo] != 0)
Result = NumberedMetadata[SlotNo];
else
Result = 0;
return false;
}
bool LLParser::ParseMDNodeID(MDNode *&Result) {
// !{ ..., !42, ... }
unsigned MID = 0;
if (ParseMDNodeID(Result, MID)) return true;
// If not a forward reference, just return it now.
if (Result) return false;
// Otherwise, create MDNode forward reference.
MDNode *FwdNode = MDNode::getTemporary(Context, ArrayRef<Value*>());
ForwardRefMDNodes[MID] = std::make_pair(FwdNode, Lex.getLoc());
if (NumberedMetadata.size() <= MID)
NumberedMetadata.resize(MID+1);
NumberedMetadata[MID] = FwdNode;
Result = FwdNode;
return false;
}
/// ParseNamedMetadata:
/// !foo = !{ !1, !2 }
bool LLParser::ParseNamedMetadata() {
assert(Lex.getKind() == lltok::MetadataVar);
std::string Name = Lex.getStrVal();
Lex.Lex();
if (ParseToken(lltok::equal, "expected '=' here") ||
ParseToken(lltok::exclaim, "Expected '!' here") ||
ParseToken(lltok::lbrace, "Expected '{' here"))
return true;
NamedMDNode *NMD = M->getOrInsertNamedMetadata(Name);
if (Lex.getKind() != lltok::rbrace)
do {
if (ParseToken(lltok::exclaim, "Expected '!' here"))
return true;
MDNode *N = 0;
if (ParseMDNodeID(N)) return true;
NMD->addOperand(N);
} while (EatIfPresent(lltok::comma));
if (ParseToken(lltok::rbrace, "expected end of metadata node"))
return true;
return false;
}
/// ParseStandaloneMetadata:
/// !42 = !{...}
bool LLParser::ParseStandaloneMetadata() {
assert(Lex.getKind() == lltok::exclaim);
Lex.Lex();
unsigned MetadataID = 0;
LocTy TyLoc;
Type *Ty = 0;
SmallVector<Value *, 16> Elts;
if (ParseUInt32(MetadataID) ||
ParseToken(lltok::equal, "expected '=' here") ||
ParseType(Ty, TyLoc) ||
ParseToken(lltok::exclaim, "Expected '!' here") ||
ParseToken(lltok::lbrace, "Expected '{' here") ||
ParseMDNodeVector(Elts, NULL) ||
ParseToken(lltok::rbrace, "expected end of metadata node"))
return true;
MDNode *Init = MDNode::get(Context, Elts);
// See if this was forward referenced, if so, handle it.
std::map<unsigned, std::pair<TrackingVH<MDNode>, LocTy> >::iterator
FI = ForwardRefMDNodes.find(MetadataID);
if (FI != ForwardRefMDNodes.end()) {
MDNode *Temp = FI->second.first;
Temp->replaceAllUsesWith(Init);
MDNode::deleteTemporary(Temp);
ForwardRefMDNodes.erase(FI);
assert(NumberedMetadata[MetadataID] == Init && "Tracking VH didn't work");
} else {
if (MetadataID >= NumberedMetadata.size())
NumberedMetadata.resize(MetadataID+1);
if (NumberedMetadata[MetadataID] != 0)
return TokError("Metadata id is already used");
NumberedMetadata[MetadataID] = Init;
}
return false;
}
/// ParseAlias:
/// ::= GlobalVar '=' OptionalVisibility 'alias' OptionalLinkage Aliasee
/// Aliasee
/// ::= TypeAndValue
/// ::= 'bitcast' '(' TypeAndValue 'to' Type ')'
/// ::= 'getelementptr' 'inbounds'? '(' ... ')'
///
/// Everything through visibility has already been parsed.
///
bool LLParser::ParseAlias(const std::string &Name, LocTy NameLoc,
unsigned Visibility) {
assert(Lex.getKind() == lltok::kw_alias);
Lex.Lex();
unsigned Linkage;
LocTy LinkageLoc = Lex.getLoc();
if (ParseOptionalLinkage(Linkage))
return true;
if (Linkage != GlobalValue::ExternalLinkage &&
Linkage != GlobalValue::WeakAnyLinkage &&
Linkage != GlobalValue::WeakODRLinkage &&
Linkage != GlobalValue::InternalLinkage &&
Linkage != GlobalValue::PrivateLinkage &&
Linkage != GlobalValue::LinkerPrivateLinkage &&
Linkage != GlobalValue::LinkerPrivateWeakLinkage &&
Linkage != GlobalValue::LinkerPrivateWeakDefAutoLinkage)
return Error(LinkageLoc, "invalid linkage type for alias");
Constant *Aliasee;
LocTy AliaseeLoc = Lex.getLoc();
if (Lex.getKind() != lltok::kw_bitcast &&
Lex.getKind() != lltok::kw_getelementptr) {
if (ParseGlobalTypeAndValue(Aliasee)) return true;
} else {
// The bitcast dest type is not present, it is implied by the dest type.
ValID ID;
if (ParseValID(ID)) return true;
if (ID.Kind != ValID::t_Constant)
return Error(AliaseeLoc, "invalid aliasee");
Aliasee = ID.ConstantVal;
}
if (!Aliasee->getType()->isPointerTy())
return Error(AliaseeLoc, "alias must have pointer type");
// Okay, create the alias but do not insert it into the module yet.
GlobalAlias* GA = new GlobalAlias(Aliasee->getType(),
(GlobalValue::LinkageTypes)Linkage, Name,
Aliasee);
GA->setVisibility((GlobalValue::VisibilityTypes)Visibility);
// See if this value already exists in the symbol table. If so, it is either
// a redefinition or a definition of a forward reference.
if (GlobalValue *Val = M->getNamedValue(Name)) {
// See if this was a redefinition. If so, there is no entry in
// ForwardRefVals.
std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
I = ForwardRefVals.find(Name);
if (I == ForwardRefVals.end())
return Error(NameLoc, "redefinition of global named '@" + Name + "'");
// Otherwise, this was a definition of forward ref. Verify that types
// agree.
if (Val->getType() != GA->getType())
return Error(NameLoc,
"forward reference and definition of alias have different types");
// If they agree, just RAUW the old value with the alias and remove the
// forward ref info.
Val->replaceAllUsesWith(GA);
Val->eraseFromParent();
ForwardRefVals.erase(I);
}
// Insert into the module, we know its name won't collide now.
M->getAliasList().push_back(GA);
assert(GA->getName() == Name && "Should not be a name conflict!");
return false;
}
/// ParseGlobal
/// ::= GlobalVar '=' OptionalLinkage OptionalVisibility OptionalThreadLocal
/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
/// ::= OptionalLinkage OptionalVisibility OptionalThreadLocal
/// OptionalAddrSpace OptionalUnNammedAddr GlobalType Type Const
///
/// Everything through visibility has been parsed already.
///
bool LLParser::ParseGlobal(const std::string &Name, LocTy NameLoc,
unsigned Linkage, bool HasLinkage,
unsigned Visibility) {
unsigned AddrSpace;
bool ThreadLocal, IsConstant, UnnamedAddr;
LocTy UnnamedAddrLoc;
LocTy TyLoc;
Type *Ty = 0;
if (ParseOptionalToken(lltok::kw_thread_local, ThreadLocal) ||
ParseOptionalAddrSpace(AddrSpace) ||
ParseOptionalToken(lltok::kw_unnamed_addr, UnnamedAddr,
&UnnamedAddrLoc) ||
ParseGlobalType(IsConstant) ||
ParseType(Ty, TyLoc))
return true;
// If the linkage is specified and is external, then no initializer is
// present.
Constant *Init = 0;
if (!HasLinkage || (Linkage != GlobalValue::DLLImportLinkage &&
Linkage != GlobalValue::ExternalWeakLinkage &&
Linkage != GlobalValue::ExternalLinkage)) {
if (ParseGlobalValue(Ty, Init))
return true;
}
if (Ty->isFunctionTy() || Ty->isLabelTy())
return Error(TyLoc, "invalid type for global variable");
GlobalVariable *GV = 0;
// See if the global was forward referenced, if so, use the global.
if (!Name.empty()) {
if (GlobalValue *GVal = M->getNamedValue(Name)) {
if (!ForwardRefVals.erase(Name) || !isa<GlobalValue>(GVal))
return Error(NameLoc, "redefinition of global '@" + Name + "'");
GV = cast<GlobalVariable>(GVal);
}
} else {
std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
I = ForwardRefValIDs.find(NumberedVals.size());
if (I != ForwardRefValIDs.end()) {
GV = cast<GlobalVariable>(I->second.first);
ForwardRefValIDs.erase(I);
}
}
if (GV == 0) {
GV = new GlobalVariable(*M, Ty, false, GlobalValue::ExternalLinkage, 0,
Name, 0, false, AddrSpace);
} else {
if (GV->getType()->getElementType() != Ty)
return Error(TyLoc,
"forward reference and definition of global have different types");
// Move the forward-reference to the correct spot in the module.
M->getGlobalList().splice(M->global_end(), M->getGlobalList(), GV);
}
if (Name.empty())
NumberedVals.push_back(GV);
// Set the parsed properties on the global.
if (Init)
GV->setInitializer(Init);
GV->setConstant(IsConstant);
GV->setLinkage((GlobalValue::LinkageTypes)Linkage);
GV->setVisibility((GlobalValue::VisibilityTypes)Visibility);
GV->setThreadLocal(ThreadLocal);
GV->setUnnamedAddr(UnnamedAddr);
// Parse attributes on the global.
while (Lex.getKind() == lltok::comma) {
Lex.Lex();
if (Lex.getKind() == lltok::kw_section) {
Lex.Lex();
GV->setSection(Lex.getStrVal());
if (ParseToken(lltok::StringConstant, "expected global section string"))
return true;
} else if (Lex.getKind() == lltok::kw_align) {
unsigned Alignment;
if (ParseOptionalAlignment(Alignment)) return true;
GV->setAlignment(Alignment);
} else {
TokError("unknown global variable property!");
}
}
return false;
}
//===----------------------------------------------------------------------===//
// GlobalValue Reference/Resolution Routines.
//===----------------------------------------------------------------------===//
/// GetGlobalVal - Get a value with the specified name or ID, creating a
/// forward reference record if needed. This can return null if the value
/// exists but does not have the right type.
GlobalValue *LLParser::GetGlobalVal(const std::string &Name, Type *Ty,
LocTy Loc) {
PointerType *PTy = dyn_cast<PointerType>(Ty);
if (PTy == 0) {
Error(Loc, "global variable reference must have pointer type");
return 0;
}
// Look this name up in the normal function symbol table.
GlobalValue *Val =
cast_or_null<GlobalValue>(M->getValueSymbolTable().lookup(Name));
// If this is a forward reference for the value, see if we already created a
// forward ref record.
if (Val == 0) {
std::map<std::string, std::pair<GlobalValue*, LocTy> >::iterator
I = ForwardRefVals.find(Name);
if (I != ForwardRefVals.end())
Val = I->second.first;
}
// If we have the value in the symbol table or fwd-ref table, return it.
if (Val) {
if (Val->getType() == Ty) return Val;
Error(Loc, "'@" + Name + "' defined with type '" +
getTypeString(Val->getType()) + "'");
return 0;
}
// Otherwise, create a new forward reference for this value and remember it.
GlobalValue *FwdVal;
if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, Name, M);
else
FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
GlobalValue::ExternalWeakLinkage, 0, Name);
ForwardRefVals[Name] = std::make_pair(FwdVal, Loc);
return FwdVal;
}
GlobalValue *LLParser::GetGlobalVal(unsigned ID, Type *Ty, LocTy Loc) {
PointerType *PTy = dyn_cast<PointerType>(Ty);
if (PTy == 0) {
Error(Loc, "global variable reference must have pointer type");
return 0;
}
GlobalValue *Val = ID < NumberedVals.size() ? NumberedVals[ID] : 0;
// If this is a forward reference for the value, see if we already created a
// forward ref record.
if (Val == 0) {
std::map<unsigned, std::pair<GlobalValue*, LocTy> >::iterator
I = ForwardRefValIDs.find(ID);
if (I != ForwardRefValIDs.end())
Val = I->second.first;
}
// If we have the value in the symbol table or fwd-ref table, return it.
if (Val) {
if (Val->getType() == Ty) return Val;
Error(Loc, "'@" + Twine(ID) + "' defined with type '" +
getTypeString(Val->getType()) + "'");
return 0;
}
// Otherwise, create a new forward reference for this value and remember it.
GlobalValue *FwdVal;
if (FunctionType *FT = dyn_cast<FunctionType>(PTy->getElementType()))
FwdVal = Function::Create(FT, GlobalValue::ExternalWeakLinkage, "", M);
else
FwdVal = new GlobalVariable(*M, PTy->getElementType(), false,
GlobalValue::ExternalWeakLinkage, 0, "");
ForwardRefValIDs[ID] = std::make_pair(FwdVal, Loc);
return FwdVal;
}
//===----------------------------------------------------------------------===//
// Helper Routines.
//===----------------------------------------------------------------------===//
/// ParseToken - If the current token has the specified kind, eat it and return
/// success. Otherwise, emit the specified error and return failure.
bool LLParser::ParseToken(lltok::Kind T, const char *ErrMsg) {
if (Lex.getKind() != T)
return TokError(ErrMsg);
Lex.Lex();
return false;
}
/// ParseStringConstant
/// ::= StringConstant
bool LLParser::ParseStringConstant(std::string &Result) {
if (Lex.getKind() != lltok::StringConstant)
return TokError("expected string constant");
Result = Lex.getStrVal();
Lex.Lex();
return false;
}
/// ParseUInt32
/// ::= uint32
bool LLParser::ParseUInt32(unsigned &Val) {
if (Lex.getKind() != lltok::APSInt || Lex.getAPSIntVal().isSigned())
return TokError("expected integer");
uint64_t Val64 = Lex.getAPSIntVal().getLimitedValue(0xFFFFFFFFULL+1);
if (Val64 != unsigned(Val64))
return TokError("expected 32-bit integer (too large)");
Val = Val64;
Lex.Lex();
return false;
}
/// ParseOptionalAddrSpace
/// := /*empty*/
/// := 'addrspace' '(' uint32 ')'
bool LLParser::ParseOptionalAddrSpace(unsigned &AddrSpace) {
AddrSpace = 0;
if (!EatIfPresent(lltok::kw_addrspace))
return false;
return ParseToken(lltok::lparen, "expected '(' in address space") ||
ParseUInt32(AddrSpace) ||
ParseToken(lltok::rparen, "expected ')' in address space");
}
/// ParseOptionalAttrs - Parse a potentially empty attribute list. AttrKind
/// indicates what kind of attribute list this is: 0: function arg, 1: result,
/// 2: function attr.
bool LLParser::ParseOptionalAttrs(Attributes &Attrs, unsigned AttrKind) {
Attrs = Attribute::None;
LocTy AttrLoc = Lex.getLoc();
while (1) {
switch (Lex.getKind()) {
default: // End of attributes.
if (AttrKind != 2 && (Attrs & Attribute::FunctionOnly))
return Error(AttrLoc, "invalid use of function-only attribute");
// As a hack, we allow "align 2" on functions as a synonym for
// "alignstack 2".
if (AttrKind == 2 &&
(Attrs & ~(Attribute::FunctionOnly | Attribute::Alignment)))
return Error(AttrLoc, "invalid use of attribute on a function");
if (AttrKind != 0 && (Attrs & Attribute::ParameterOnly))
return Error(AttrLoc, "invalid use of parameter-only attribute");
return false;
case lltok::kw_zeroext: Attrs |= Attribute::ZExt; break;
case lltok::kw_signext: Attrs |= Attribute::SExt; break;
case lltok::kw_inreg: Attrs |= Attribute::InReg; break;
case lltok::kw_sret: Attrs |= Attribute::StructRet; break;
case lltok::kw_noalias: Attrs |= Attribute::NoAlias; break;
case lltok::kw_nocapture: Attrs |= Attribute::NoCapture; break;
case lltok::kw_byval: Attrs |= Attribute::ByVal; break;
case lltok::kw_nest: Attrs |= Attribute::Nest; break;
case lltok::kw_noreturn: Attrs |= Attribute::NoReturn; break;
case lltok::kw_nounwind: Attrs |= Attribute::NoUnwind; break;
case lltok::kw_uwtable: Attrs |= Attribute::UWTable; break;
case lltok::kw_returns_twice: Attrs |= Attribute::ReturnsTwice; break;
case lltok::kw_noinline: Attrs |= Attribute::NoInline; break;
case lltok::kw_readnone: Attrs |= Attribute::ReadNone; break;
case lltok::kw_readonly: Attrs |= Attribute::ReadOnly; break;
case lltok::kw_inlinehint: Attrs |= Attribute::InlineHint; break;
case lltok::kw_alwaysinline: Attrs |= Attribute::AlwaysInline; break;
case lltok::kw_optsize: Attrs |= Attribute::OptimizeForSize; break;
case lltok::kw_ssp: Attrs |= Attribute::StackProtect; break;
case lltok::kw_sspreq: Attrs |= Attribute::StackProtectReq; break;
case lltok::kw_noredzone: Attrs |= Attribute::NoRedZone; break;
case lltok::kw_noimplicitfloat: Attrs |= Attribute::NoImplicitFloat; break;
case lltok::kw_naked: Attrs |= Attribute::Naked; break;
case lltok::kw_nonlazybind: Attrs |= Attribute::NonLazyBind; break;
case lltok::kw_address_safety: Attrs |= Attribute::AddressSafety; break;
case lltok::kw_alignstack: {
unsigned Alignment;
if (ParseOptionalStackAlignment(Alignment))
return true;
Attrs |= Attribute::constructStackAlignmentFromInt(Alignment);
continue;
}
case lltok::kw_align: {
unsigned Alignment;
if (ParseOptionalAlignment(Alignment))
return true;
Attrs |= Attribute::constructAlignmentFromInt(Alignment);
continue;
}
}
Lex.Lex();
}
}
/// ParseOptionalLinkage
/// ::= /*empty*/
/// ::= 'private'
/// ::= 'linker_private'
/// ::= 'linker_private_weak'
/// ::= 'linker_private_weak_def_auto'
/// ::= 'internal'
/// ::= 'weak'
/// ::= 'weak_odr'
/// ::= 'linkonce'
/// ::= 'linkonce_odr'
/// ::= 'available_externally'
/// ::= 'appending'
/// ::= 'dllexport'
/// ::= 'common'
/// ::= 'dllimport'
/// ::= 'extern_weak'
/// ::= 'external'
bool LLParser::ParseOptionalLinkage(unsigned &Res, bool &HasLinkage) {
HasLinkage = false;
switch (Lex.getKind()) {
default: Res=GlobalValue::ExternalLinkage; return false;
case lltok::kw_private: Res = GlobalValue::PrivateLinkage; break;
case lltok::kw_linker_private: Res = GlobalValue::LinkerPrivateLinkage; break;
case lltok::kw_linker_private_weak:
Res = GlobalValue::LinkerPrivateWeakLinkage;
break;
case lltok::kw_linker_private_weak_def_auto:
Res = GlobalValue::LinkerPrivateWeakDefAutoLinkage;
break;
case lltok::kw_internal: Res = GlobalValue::InternalLinkage; break;
case lltok::kw_weak: Res = GlobalValue::WeakAnyLinkage; break;
case lltok::kw_weak_odr: Res = GlobalValue::WeakODRLinkage; break;
case lltok::kw_linkonce: Res = GlobalValue::LinkOnceAnyLinkage; break;
case lltok::kw_linkonce_odr: Res = GlobalValue::LinkOnceODRLinkage; break;
case lltok::kw_available_externally:
Res = GlobalValue::AvailableExternallyLinkage;
break;
case lltok::kw_appending: Res = GlobalValue::AppendingLinkage; break;
case lltok::kw_dllexport: Res = GlobalValue::DLLExportLinkage; break;
case lltok::kw_common: Res = GlobalValue::CommonLinkage; break;
case lltok::kw_dllimport: Res = GlobalValue::DLLImportLinkage; break;
case lltok::kw_extern_weak: Res = GlobalValue::ExternalWeakLinkage; break;
case lltok::kw_external: Res = GlobalValue::ExternalLinkage; break;
}
Lex.Lex();
HasLinkage = true;
return false;
}
/// ParseOptionalVisibility
/// ::= /*empty*/
/// ::= 'default'
/// ::= 'hidden'
/// ::= 'protected'
///