forked from llvm-mirror/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVerifier.cpp
2473 lines (2141 loc) · 94.2 KB
/
Verifier.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
//===-- Verifier.cpp - Implement the Module Verifier -----------------------==//
//
// 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 function verifier interface, that can be used for some
// sanity checking of input to the system.
//
// Note that this does not provide full `Java style' security and verifications,
// instead it just tries to ensure that code is well-formed.
//
// * Both of a binary operator's parameters are of the same type
// * Verify that the indices of mem access instructions match other operands
// * Verify that arithmetic and other things are only performed on first-class
// types. Verify that shifts & logicals only happen on integrals f.e.
// * All of the constants in a switch statement are of the correct type
// * The code is in valid SSA form
// * It should be illegal to put a label into any other type (like a structure)
// or to return one. [except constant arrays!]
// * Only phi nodes can be self referential: 'add i32 %0, %0 ; <int>:0' is bad
// * PHI nodes must have an entry for each predecessor, with no extras.
// * PHI nodes must be the first thing in a basic block, all grouped together
// * PHI nodes must have at least one entry
// * All basic blocks should only end with terminator insts, not contain them
// * The entry node to a function must not have predecessors
// * All Instructions must be embedded into a basic block
// * Functions cannot take a void-typed parameter
// * Verify that a function's argument list agrees with it's declared type.
// * It is illegal to specify a name for a void value.
// * It is illegal to have a internal global value with no initializer
// * It is illegal to have a ret instruction that returns a value that does not
// agree with the function return value type.
// * Function call argument types match the function prototype
// * A landing pad is defined by a landingpad instruction, and can be jumped to
// only by the unwind edge of an invoke instruction.
// * A landingpad instruction must be the first non-PHI instruction in the
// block.
// * All landingpad instructions must use the same personality function with
// the same function.
// * All other things that are tested by asserts spread about the code...
//
//===----------------------------------------------------------------------===//
#include "llvm/Analysis/Verifier.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/DebugInfo.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/InstVisitor.h"
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/CallSite.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ConstantRange.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstdarg>
using namespace llvm;
static cl::opt<bool> DisableDebugInfoVerifier("disable-debug-info-verifier",
cl::init(true));
namespace { // Anonymous namespace for class
struct PreVerifier : public FunctionPass {
static char ID; // Pass ID, replacement for typeid
PreVerifier() : FunctionPass(ID) {
initializePreVerifierPass(*PassRegistry::getPassRegistry());
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
}
// Check that the prerequisites for successful DominatorTree construction
// are satisfied.
bool runOnFunction(Function &F) {
bool Broken = false;
for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
if (I->empty() || !I->back().isTerminator()) {
dbgs() << "Basic Block in function '" << F.getName()
<< "' does not have terminator!\n";
WriteAsOperand(dbgs(), I, true);
dbgs() << "\n";
Broken = true;
}
}
if (Broken)
report_fatal_error("Broken module, no Basic Block terminator!");
return false;
}
};
}
char PreVerifier::ID = 0;
INITIALIZE_PASS(PreVerifier, "preverify", "Preliminary module verification",
false, false)
static char &PreVerifyID = PreVerifier::ID;
namespace {
struct Verifier : public FunctionPass, public InstVisitor<Verifier> {
static char ID; // Pass ID, replacement for typeid
bool Broken; // Is this module found to be broken?
VerifierFailureAction action;
// What to do if verification fails.
Module *Mod; // Module we are verifying right now
LLVMContext *Context; // Context within which we are verifying
DominatorTree *DT; // Dominator Tree, caution can be null!
const DataLayout *DL;
std::string Messages;
raw_string_ostream MessagesStr;
/// InstInThisBlock - when verifying a basic block, keep track of all of the
/// instructions we have seen so far. This allows us to do efficient
/// dominance checks for the case when an instruction has an operand that is
/// an instruction in the same block.
SmallPtrSet<Instruction*, 16> InstsInThisBlock;
/// MDNodes - keep track of the metadata nodes that have been checked
/// already.
SmallPtrSet<MDNode *, 32> MDNodes;
/// PersonalityFn - The personality function referenced by the
/// LandingPadInsts. All LandingPadInsts within the same function must use
/// the same personality function.
const Value *PersonalityFn;
/// Finder keeps track of all debug info MDNodes in a Module.
DebugInfoFinder Finder;
Verifier()
: FunctionPass(ID), Broken(false),
action(AbortProcessAction), Mod(0), Context(0), DT(0), DL(0),
MessagesStr(Messages), PersonalityFn(0) {
initializeVerifierPass(*PassRegistry::getPassRegistry());
}
explicit Verifier(VerifierFailureAction ctn)
: FunctionPass(ID), Broken(false), action(ctn), Mod(0),
Context(0), DT(0), DL(0), MessagesStr(Messages), PersonalityFn(0) {
initializeVerifierPass(*PassRegistry::getPassRegistry());
}
bool doInitialization(Module &M) {
Mod = &M;
Context = &M.getContext();
DL = getAnalysisIfAvailable<DataLayout>();
// We must abort before returning back to the pass manager, or else the
// pass manager may try to run other passes on the broken module.
return abortIfBroken();
}
bool runOnFunction(Function &F) {
// Get dominator information if we are being run by PassManager
DT = &getAnalysis<DominatorTree>();
Mod = F.getParent();
if (!Context) Context = &F.getContext();
Finder.reset();
visit(F);
InstsInThisBlock.clear();
PersonalityFn = 0;
if (!DisableDebugInfoVerifier)
// Verify Debug Info.
verifyDebugInfo();
// We must abort before returning back to the pass manager, or else the
// pass manager may try to run other passes on the broken module.
return abortIfBroken();
}
bool doFinalization(Module &M) {
// Scan through, checking all of the external function's linkage now...
for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
visitGlobalValue(*I);
// Check to make sure function prototypes are okay.
if (I->isDeclaration()) visitFunction(*I);
}
for (Module::global_iterator I = M.global_begin(), E = M.global_end();
I != E; ++I)
visitGlobalVariable(*I);
for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
I != E; ++I)
visitGlobalAlias(*I);
for (Module::named_metadata_iterator I = M.named_metadata_begin(),
E = M.named_metadata_end(); I != E; ++I)
visitNamedMDNode(*I);
visitModuleFlags(M);
visitModuleIdents(M);
if (!DisableDebugInfoVerifier) {
Finder.reset();
Finder.processModule(M);
// Verify Debug Info.
verifyDebugInfo();
}
// If the module is broken, abort at this time.
return abortIfBroken();
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequiredID(PreVerifyID);
AU.addRequired<DominatorTree>();
}
/// abortIfBroken - If the module is broken and we are supposed to abort on
/// this condition, do so.
///
bool abortIfBroken() {
if (!Broken) return false;
MessagesStr << "Broken module found, ";
switch (action) {
case AbortProcessAction:
MessagesStr << "compilation aborted!\n";
dbgs() << MessagesStr.str();
// Client should choose different reaction if abort is not desired
abort();
case PrintMessageAction:
MessagesStr << "verification continues.\n";
dbgs() << MessagesStr.str();
return false;
case ReturnStatusAction:
MessagesStr << "compilation terminated.\n";
return true;
}
llvm_unreachable("Invalid action");
}
// Verification methods...
void visitGlobalValue(GlobalValue &GV);
void visitGlobalVariable(GlobalVariable &GV);
void visitGlobalAlias(GlobalAlias &GA);
void visitNamedMDNode(NamedMDNode &NMD);
void visitMDNode(MDNode &MD, Function *F);
void visitModuleIdents(Module &M);
void visitModuleFlags(Module &M);
void visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*> &SeenIDs,
SmallVectorImpl<MDNode*> &Requirements);
void visitFunction(Function &F);
void visitBasicBlock(BasicBlock &BB);
using InstVisitor<Verifier>::visit;
void visit(Instruction &I);
void visitTruncInst(TruncInst &I);
void visitZExtInst(ZExtInst &I);
void visitSExtInst(SExtInst &I);
void visitFPTruncInst(FPTruncInst &I);
void visitFPExtInst(FPExtInst &I);
void visitFPToUIInst(FPToUIInst &I);
void visitFPToSIInst(FPToSIInst &I);
void visitUIToFPInst(UIToFPInst &I);
void visitSIToFPInst(SIToFPInst &I);
void visitIntToPtrInst(IntToPtrInst &I);
void visitPtrToIntInst(PtrToIntInst &I);
void visitBitCastInst(BitCastInst &I);
void visitAddrSpaceCastInst(AddrSpaceCastInst &I);
void visitPHINode(PHINode &PN);
void visitBinaryOperator(BinaryOperator &B);
void visitICmpInst(ICmpInst &IC);
void visitFCmpInst(FCmpInst &FC);
void visitExtractElementInst(ExtractElementInst &EI);
void visitInsertElementInst(InsertElementInst &EI);
void visitShuffleVectorInst(ShuffleVectorInst &EI);
void visitVAArgInst(VAArgInst &VAA) { visitInstruction(VAA); }
void visitCallInst(CallInst &CI);
void visitInvokeInst(InvokeInst &II);
void visitGetElementPtrInst(GetElementPtrInst &GEP);
void visitLoadInst(LoadInst &LI);
void visitStoreInst(StoreInst &SI);
void verifyDominatesUse(Instruction &I, unsigned i);
void visitInstruction(Instruction &I);
void visitTerminatorInst(TerminatorInst &I);
void visitBranchInst(BranchInst &BI);
void visitReturnInst(ReturnInst &RI);
void visitSwitchInst(SwitchInst &SI);
void visitIndirectBrInst(IndirectBrInst &BI);
void visitSelectInst(SelectInst &SI);
void visitUserOp1(Instruction &I);
void visitUserOp2(Instruction &I) { visitUserOp1(I); }
void visitIntrinsicFunctionCall(Intrinsic::ID ID, CallInst &CI);
void visitAtomicCmpXchgInst(AtomicCmpXchgInst &CXI);
void visitAtomicRMWInst(AtomicRMWInst &RMWI);
void visitFenceInst(FenceInst &FI);
void visitAllocaInst(AllocaInst &AI);
void visitExtractValueInst(ExtractValueInst &EVI);
void visitInsertValueInst(InsertValueInst &IVI);
void visitLandingPadInst(LandingPadInst &LPI);
void VerifyCallSite(CallSite CS);
bool PerformTypeCheck(Intrinsic::ID ID, Function *F, Type *Ty,
int VT, unsigned ArgNo, std::string &Suffix);
bool VerifyIntrinsicType(Type *Ty,
ArrayRef<Intrinsic::IITDescriptor> &Infos,
SmallVectorImpl<Type*> &ArgTys);
bool VerifyIntrinsicIsVarArg(bool isVarArg,
ArrayRef<Intrinsic::IITDescriptor> &Infos);
bool VerifyAttributeCount(AttributeSet Attrs, unsigned Params);
void VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
bool isFunction, const Value *V);
void VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
bool isReturnValue, const Value *V);
void VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
const Value *V);
void VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy);
void VerifyConstantExprBitcastType(const ConstantExpr *CE);
void verifyDebugInfo();
void WriteValue(const Value *V) {
if (!V) return;
if (isa<Instruction>(V)) {
MessagesStr << *V << '\n';
} else {
WriteAsOperand(MessagesStr, V, true, Mod);
MessagesStr << '\n';
}
}
void WriteType(Type *T) {
if (!T) return;
MessagesStr << ' ' << *T;
}
// CheckFailed - A check failed, so print out the condition and the message
// that failed. This provides a nice place to put a breakpoint if you want
// to see why something is not correct.
void CheckFailed(const Twine &Message,
const Value *V1 = 0, const Value *V2 = 0,
const Value *V3 = 0, const Value *V4 = 0) {
MessagesStr << Message.str() << "\n";
WriteValue(V1);
WriteValue(V2);
WriteValue(V3);
WriteValue(V4);
Broken = true;
}
void CheckFailed(const Twine &Message, const Value *V1,
Type *T2, const Value *V3 = 0) {
MessagesStr << Message.str() << "\n";
WriteValue(V1);
WriteType(T2);
WriteValue(V3);
Broken = true;
}
void CheckFailed(const Twine &Message, Type *T1,
Type *T2 = 0, Type *T3 = 0) {
MessagesStr << Message.str() << "\n";
WriteType(T1);
WriteType(T2);
WriteType(T3);
Broken = true;
}
};
} // End anonymous namespace
char Verifier::ID = 0;
INITIALIZE_PASS_BEGIN(Verifier, "verify", "Module Verifier", false, false)
INITIALIZE_PASS_DEPENDENCY(PreVerifier)
INITIALIZE_PASS_DEPENDENCY(DominatorTree)
INITIALIZE_PASS_END(Verifier, "verify", "Module Verifier", false, false)
// Assert - We know that cond should be true, if not print an error message.
#define Assert(C, M) \
do { if (!(C)) { CheckFailed(M); return; } } while (0)
#define Assert1(C, M, V1) \
do { if (!(C)) { CheckFailed(M, V1); return; } } while (0)
#define Assert2(C, M, V1, V2) \
do { if (!(C)) { CheckFailed(M, V1, V2); return; } } while (0)
#define Assert3(C, M, V1, V2, V3) \
do { if (!(C)) { CheckFailed(M, V1, V2, V3); return; } } while (0)
#define Assert4(C, M, V1, V2, V3, V4) \
do { if (!(C)) { CheckFailed(M, V1, V2, V3, V4); return; } } while (0)
void Verifier::visit(Instruction &I) {
for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
Assert1(I.getOperand(i) != 0, "Operand is null", &I);
InstVisitor<Verifier>::visit(I);
}
void Verifier::visitGlobalValue(GlobalValue &GV) {
Assert1(!GV.isDeclaration() ||
GV.isMaterializable() ||
GV.hasExternalLinkage() ||
GV.hasDLLImportLinkage() ||
GV.hasExternalWeakLinkage() ||
(isa<GlobalAlias>(GV) &&
(GV.hasLocalLinkage() || GV.hasWeakLinkage())),
"Global is external, but doesn't have external or dllimport or weak linkage!",
&GV);
Assert1(!GV.hasDLLImportLinkage() || GV.isDeclaration(),
"Global is marked as dllimport, but not external", &GV);
Assert1(!GV.hasAppendingLinkage() || isa<GlobalVariable>(GV),
"Only global variables can have appending linkage!", &GV);
if (GV.hasAppendingLinkage()) {
GlobalVariable *GVar = dyn_cast<GlobalVariable>(&GV);
Assert1(GVar && GVar->getType()->getElementType()->isArrayTy(),
"Only global arrays can have appending linkage!", GVar);
}
}
void Verifier::visitGlobalVariable(GlobalVariable &GV) {
if (GV.hasInitializer()) {
Assert1(GV.getInitializer()->getType() == GV.getType()->getElementType(),
"Global variable initializer type does not match global "
"variable type!", &GV);
// If the global has common linkage, it must have a zero initializer and
// cannot be constant.
if (GV.hasCommonLinkage()) {
Assert1(GV.getInitializer()->isNullValue(),
"'common' global must have a zero initializer!", &GV);
Assert1(!GV.isConstant(), "'common' global may not be marked constant!",
&GV);
}
} else {
Assert1(GV.hasExternalLinkage() || GV.hasDLLImportLinkage() ||
GV.hasExternalWeakLinkage(),
"invalid linkage type for global declaration", &GV);
}
if (GV.hasName() && (GV.getName() == "llvm.global_ctors" ||
GV.getName() == "llvm.global_dtors")) {
Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
"invalid linkage for intrinsic global variable", &GV);
// Don't worry about emitting an error for it not being an array,
// visitGlobalValue will complain on appending non-array.
if (ArrayType *ATy = dyn_cast<ArrayType>(GV.getType())) {
StructType *STy = dyn_cast<StructType>(ATy->getElementType());
PointerType *FuncPtrTy =
FunctionType::get(Type::getVoidTy(*Context), false)->getPointerTo();
Assert1(STy && STy->getNumElements() == 2 &&
STy->getTypeAtIndex(0u)->isIntegerTy(32) &&
STy->getTypeAtIndex(1) == FuncPtrTy,
"wrong type for intrinsic global variable", &GV);
}
}
if (GV.hasName() && (GV.getName() == "llvm.used" ||
GV.getName() == "llvm.compiler.used")) {
Assert1(!GV.hasInitializer() || GV.hasAppendingLinkage(),
"invalid linkage for intrinsic global variable", &GV);
Type *GVType = GV.getType()->getElementType();
if (ArrayType *ATy = dyn_cast<ArrayType>(GVType)) {
PointerType *PTy = dyn_cast<PointerType>(ATy->getElementType());
Assert1(PTy, "wrong type for intrinsic global variable", &GV);
if (GV.hasInitializer()) {
Constant *Init = GV.getInitializer();
ConstantArray *InitArray = dyn_cast<ConstantArray>(Init);
Assert1(InitArray, "wrong initalizer for intrinsic global variable",
Init);
for (unsigned i = 0, e = InitArray->getNumOperands(); i != e; ++i) {
Value *V = Init->getOperand(i)->stripPointerCastsNoFollowAliases();
Assert1(
isa<GlobalVariable>(V) || isa<Function>(V) || isa<GlobalAlias>(V),
"invalid llvm.used member", V);
Assert1(V->hasName(), "members of llvm.used must be named", V);
}
}
}
}
if (!GV.hasInitializer()) {
visitGlobalValue(GV);
return;
}
// Walk any aggregate initializers looking for bitcasts between address spaces
SmallPtrSet<const Value *, 4> Visited;
SmallVector<const Value *, 4> WorkStack;
WorkStack.push_back(cast<Value>(GV.getInitializer()));
while (!WorkStack.empty()) {
const Value *V = WorkStack.pop_back_val();
if (!Visited.insert(V))
continue;
if (const User *U = dyn_cast<User>(V)) {
for (unsigned I = 0, N = U->getNumOperands(); I != N; ++I)
WorkStack.push_back(U->getOperand(I));
}
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
VerifyConstantExprBitcastType(CE);
if (Broken)
return;
}
}
visitGlobalValue(GV);
}
void Verifier::visitGlobalAlias(GlobalAlias &GA) {
Assert1(!GA.getName().empty(),
"Alias name cannot be empty!", &GA);
Assert1(GlobalAlias::isValidLinkage(GA.getLinkage()),
"Alias should have external or external weak linkage!", &GA);
Assert1(GA.getAliasee(),
"Aliasee cannot be NULL!", &GA);
Assert1(GA.getType() == GA.getAliasee()->getType(),
"Alias and aliasee types should match!", &GA);
Assert1(!GA.hasUnnamedAddr(), "Alias cannot have unnamed_addr!", &GA);
Constant *Aliasee = GA.getAliasee();
if (!isa<GlobalValue>(Aliasee)) {
ConstantExpr *CE = dyn_cast<ConstantExpr>(Aliasee);
Assert1(CE &&
(CE->getOpcode() == Instruction::BitCast ||
CE->getOpcode() == Instruction::AddrSpaceCast ||
CE->getOpcode() == Instruction::GetElementPtr) &&
isa<GlobalValue>(CE->getOperand(0)),
"Aliasee should be either GlobalValue, bitcast or "
"addrspacecast of GlobalValue",
&GA);
if (CE->getOpcode() == Instruction::BitCast) {
unsigned SrcAS = CE->getOperand(0)->getType()->getPointerAddressSpace();
unsigned DstAS = CE->getType()->getPointerAddressSpace();
Assert1(SrcAS == DstAS,
"Alias bitcasts cannot be between different address spaces",
&GA);
}
}
const GlobalValue* Resolved = GA.resolveAliasedGlobal(/*stopOnWeak*/ false);
Assert1(Resolved,
"Aliasing chain should end with function or global variable", &GA);
visitGlobalValue(GA);
}
void Verifier::visitNamedMDNode(NamedMDNode &NMD) {
for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) {
MDNode *MD = NMD.getOperand(i);
if (!MD)
continue;
Assert1(!MD->isFunctionLocal(),
"Named metadata operand cannot be function local!", MD);
visitMDNode(*MD, 0);
}
}
void Verifier::visitMDNode(MDNode &MD, Function *F) {
// Only visit each node once. Metadata can be mutually recursive, so this
// avoids infinite recursion here, as well as being an optimization.
if (!MDNodes.insert(&MD))
return;
for (unsigned i = 0, e = MD.getNumOperands(); i != e; ++i) {
Value *Op = MD.getOperand(i);
if (!Op)
continue;
if (isa<Constant>(Op) || isa<MDString>(Op))
continue;
if (MDNode *N = dyn_cast<MDNode>(Op)) {
Assert2(MD.isFunctionLocal() || !N->isFunctionLocal(),
"Global metadata operand cannot be function local!", &MD, N);
visitMDNode(*N, F);
continue;
}
Assert2(MD.isFunctionLocal(), "Invalid operand for global metadata!", &MD, Op);
// If this was an instruction, bb, or argument, verify that it is in the
// function that we expect.
Function *ActualF = 0;
if (Instruction *I = dyn_cast<Instruction>(Op))
ActualF = I->getParent()->getParent();
else if (BasicBlock *BB = dyn_cast<BasicBlock>(Op))
ActualF = BB->getParent();
else if (Argument *A = dyn_cast<Argument>(Op))
ActualF = A->getParent();
assert(ActualF && "Unimplemented function local metadata case!");
Assert2(ActualF == F, "function-local metadata used in wrong function",
&MD, Op);
}
}
void Verifier::visitModuleIdents(Module &M) {
const NamedMDNode *Idents = M.getNamedMetadata("llvm.ident");
if (!Idents)
return;
// llvm.ident takes a list of metadata entry. Each entry has only one string.
// Scan each llvm.ident entry and make sure that this requirement is met.
for (unsigned i = 0, e = Idents->getNumOperands(); i != e; ++i) {
const MDNode *N = Idents->getOperand(i);
Assert1(N->getNumOperands() == 1,
"incorrect number of operands in llvm.ident metadata", N);
Assert1(isa<MDString>(N->getOperand(0)),
("invalid value for llvm.ident metadata entry operand"
"(the operand should be a string)"),
N->getOperand(0));
}
}
void Verifier::visitModuleFlags(Module &M) {
const NamedMDNode *Flags = M.getModuleFlagsMetadata();
if (!Flags) return;
// Scan each flag, and track the flags and requirements.
DenseMap<MDString*, MDNode*> SeenIDs;
SmallVector<MDNode*, 16> Requirements;
for (unsigned I = 0, E = Flags->getNumOperands(); I != E; ++I) {
visitModuleFlag(Flags->getOperand(I), SeenIDs, Requirements);
}
// Validate that the requirements in the module are valid.
for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
MDNode *Requirement = Requirements[I];
MDString *Flag = cast<MDString>(Requirement->getOperand(0));
Value *ReqValue = Requirement->getOperand(1);
MDNode *Op = SeenIDs.lookup(Flag);
if (!Op) {
CheckFailed("invalid requirement on flag, flag is not present in module",
Flag);
continue;
}
if (Op->getOperand(2) != ReqValue) {
CheckFailed(("invalid requirement on flag, "
"flag does not have the required value"),
Flag);
continue;
}
}
}
void Verifier::visitModuleFlag(MDNode *Op, DenseMap<MDString*, MDNode*>&SeenIDs,
SmallVectorImpl<MDNode*> &Requirements) {
// Each module flag should have three arguments, the merge behavior (a
// constant int), the flag ID (an MDString), and the value.
Assert1(Op->getNumOperands() == 3,
"incorrect number of operands in module flag", Op);
ConstantInt *Behavior = dyn_cast<ConstantInt>(Op->getOperand(0));
MDString *ID = dyn_cast<MDString>(Op->getOperand(1));
Assert1(Behavior,
"invalid behavior operand in module flag (expected constant integer)",
Op->getOperand(0));
unsigned BehaviorValue = Behavior->getZExtValue();
Assert1(ID,
"invalid ID operand in module flag (expected metadata string)",
Op->getOperand(1));
// Sanity check the values for behaviors with additional requirements.
switch (BehaviorValue) {
default:
Assert1(false,
"invalid behavior operand in module flag (unexpected constant)",
Op->getOperand(0));
break;
case Module::Error:
case Module::Warning:
case Module::Override:
// These behavior types accept any value.
break;
case Module::Require: {
// The value should itself be an MDNode with two operands, a flag ID (an
// MDString), and a value.
MDNode *Value = dyn_cast<MDNode>(Op->getOperand(2));
Assert1(Value && Value->getNumOperands() == 2,
"invalid value for 'require' module flag (expected metadata pair)",
Op->getOperand(2));
Assert1(isa<MDString>(Value->getOperand(0)),
("invalid value for 'require' module flag "
"(first value operand should be a string)"),
Value->getOperand(0));
// Append it to the list of requirements, to check once all module flags are
// scanned.
Requirements.push_back(Value);
break;
}
case Module::Append:
case Module::AppendUnique: {
// These behavior types require the operand be an MDNode.
Assert1(isa<MDNode>(Op->getOperand(2)),
"invalid value for 'append'-type module flag "
"(expected a metadata node)", Op->getOperand(2));
break;
}
}
// Unless this is a "requires" flag, check the ID is unique.
if (BehaviorValue != Module::Require) {
bool Inserted = SeenIDs.insert(std::make_pair(ID, Op)).second;
Assert1(Inserted,
"module flag identifiers must be unique (or of 'require' type)",
ID);
}
}
void Verifier::VerifyAttributeTypes(AttributeSet Attrs, unsigned Idx,
bool isFunction, const Value *V) {
unsigned Slot = ~0U;
for (unsigned I = 0, E = Attrs.getNumSlots(); I != E; ++I)
if (Attrs.getSlotIndex(I) == Idx) {
Slot = I;
break;
}
assert(Slot != ~0U && "Attribute set inconsistency!");
for (AttributeSet::iterator I = Attrs.begin(Slot), E = Attrs.end(Slot);
I != E; ++I) {
if (I->isStringAttribute())
continue;
if (I->getKindAsEnum() == Attribute::NoReturn ||
I->getKindAsEnum() == Attribute::NoUnwind ||
I->getKindAsEnum() == Attribute::NoInline ||
I->getKindAsEnum() == Attribute::AlwaysInline ||
I->getKindAsEnum() == Attribute::OptimizeForSize ||
I->getKindAsEnum() == Attribute::StackProtect ||
I->getKindAsEnum() == Attribute::StackProtectReq ||
I->getKindAsEnum() == Attribute::StackProtectStrong ||
I->getKindAsEnum() == Attribute::NoRedZone ||
I->getKindAsEnum() == Attribute::NoImplicitFloat ||
I->getKindAsEnum() == Attribute::Naked ||
I->getKindAsEnum() == Attribute::InlineHint ||
I->getKindAsEnum() == Attribute::StackAlignment ||
I->getKindAsEnum() == Attribute::UWTable ||
I->getKindAsEnum() == Attribute::NonLazyBind ||
I->getKindAsEnum() == Attribute::ReturnsTwice ||
I->getKindAsEnum() == Attribute::SanitizeAddress ||
I->getKindAsEnum() == Attribute::SanitizeThread ||
I->getKindAsEnum() == Attribute::SanitizeMemory ||
I->getKindAsEnum() == Attribute::MinSize ||
I->getKindAsEnum() == Attribute::NoDuplicate ||
I->getKindAsEnum() == Attribute::Builtin ||
I->getKindAsEnum() == Attribute::NoBuiltin ||
I->getKindAsEnum() == Attribute::Cold ||
I->getKindAsEnum() == Attribute::OptimizeNone) {
if (!isFunction) {
CheckFailed("Attribute '" + I->getAsString() +
"' only applies to functions!", V);
return;
}
} else if (I->getKindAsEnum() == Attribute::ReadOnly ||
I->getKindAsEnum() == Attribute::ReadNone) {
if (Idx == 0) {
CheckFailed("Attribute '" + I->getAsString() +
"' does not apply to function returns");
return;
}
} else if (isFunction) {
CheckFailed("Attribute '" + I->getAsString() +
"' does not apply to functions!", V);
return;
}
}
}
// VerifyParameterAttrs - Check the given attributes for an argument or return
// value of the specified type. The value V is printed in error messages.
void Verifier::VerifyParameterAttrs(AttributeSet Attrs, unsigned Idx, Type *Ty,
bool isReturnValue, const Value *V) {
if (!Attrs.hasAttributes(Idx))
return;
VerifyAttributeTypes(Attrs, Idx, false, V);
if (isReturnValue)
Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
!Attrs.hasAttribute(Idx, Attribute::Nest) &&
!Attrs.hasAttribute(Idx, Attribute::StructRet) &&
!Attrs.hasAttribute(Idx, Attribute::NoCapture) &&
!Attrs.hasAttribute(Idx, Attribute::Returned) &&
!Attrs.hasAttribute(Idx, Attribute::InAlloca),
"Attributes 'byval', 'inalloca', 'nest', 'sret', 'nocapture', and "
"'returned' do not apply to return values!", V);
// Check for mutually incompatible attributes. Only inreg is compatible with
// sret.
unsigned AttrCount = 0;
AttrCount += Attrs.hasAttribute(Idx, Attribute::ByVal);
AttrCount += Attrs.hasAttribute(Idx, Attribute::InAlloca);
AttrCount += Attrs.hasAttribute(Idx, Attribute::StructRet) ||
Attrs.hasAttribute(Idx, Attribute::InReg);
AttrCount += Attrs.hasAttribute(Idx, Attribute::Nest);
Assert1(AttrCount <= 1, "Attributes 'byval', 'inalloca', 'inreg', 'nest', "
"and 'sret' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::InAlloca) &&
Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
"'inalloca and readonly' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::StructRet) &&
Attrs.hasAttribute(Idx, Attribute::Returned)), "Attributes "
"'sret and returned' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::ZExt) &&
Attrs.hasAttribute(Idx, Attribute::SExt)), "Attributes "
"'zeroext and signext' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::ReadNone) &&
Attrs.hasAttribute(Idx, Attribute::ReadOnly)), "Attributes "
"'readnone and readonly' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(Idx, Attribute::NoInline) &&
Attrs.hasAttribute(Idx, Attribute::AlwaysInline)), "Attributes "
"'noinline and alwaysinline' are incompatible!", V);
Assert1(!AttrBuilder(Attrs, Idx).
hasAttributes(AttributeFuncs::typeIncompatible(Ty, Idx), Idx),
"Wrong types for attribute: " +
AttributeFuncs::typeIncompatible(Ty, Idx).getAsString(Idx), V);
if (PointerType *PTy = dyn_cast<PointerType>(Ty)) {
if (!PTy->getElementType()->isSized()) {
Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal) &&
!Attrs.hasAttribute(Idx, Attribute::InAlloca),
"Attributes 'byval' and 'inalloca' do not support unsized types!",
V);
}
} else {
Assert1(!Attrs.hasAttribute(Idx, Attribute::ByVal),
"Attribute 'byval' only applies to parameters with pointer type!",
V);
}
}
// VerifyFunctionAttrs - Check parameter attributes against a function type.
// The value V is printed in error messages.
void Verifier::VerifyFunctionAttrs(FunctionType *FT, AttributeSet Attrs,
const Value *V) {
if (Attrs.isEmpty())
return;
bool SawNest = false;
bool SawReturned = false;
for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
unsigned Idx = Attrs.getSlotIndex(i);
Type *Ty;
if (Idx == 0)
Ty = FT->getReturnType();
else if (Idx-1 < FT->getNumParams())
Ty = FT->getParamType(Idx-1);
else
break; // VarArgs attributes, verified elsewhere.
VerifyParameterAttrs(Attrs, Idx, Ty, Idx == 0, V);
if (Idx == 0)
continue;
if (Attrs.hasAttribute(Idx, Attribute::Nest)) {
Assert1(!SawNest, "More than one parameter has attribute nest!", V);
SawNest = true;
}
if (Attrs.hasAttribute(Idx, Attribute::Returned)) {
Assert1(!SawReturned, "More than one parameter has attribute returned!",
V);
Assert1(Ty->canLosslesslyBitCastTo(FT->getReturnType()), "Incompatible "
"argument and return types for 'returned' attribute", V);
SawReturned = true;
}
if (Attrs.hasAttribute(Idx, Attribute::StructRet))
Assert1(Idx == 1, "Attribute sret is not on first parameter!", V);
}
if (!Attrs.hasAttributes(AttributeSet::FunctionIndex))
return;
VerifyAttributeTypes(Attrs, AttributeSet::FunctionIndex, true, V);
Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::ReadNone) &&
Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::ReadOnly)),
"Attributes 'readnone and readonly' are incompatible!", V);
Assert1(!(Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::NoInline) &&
Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::AlwaysInline)),
"Attributes 'noinline and alwaysinline' are incompatible!", V);
if (Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::OptimizeNone)) {
Assert1(Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::NoInline),
"Attribute 'optnone' requires 'noinline'!", V);
Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::OptimizeForSize),
"Attributes 'optsize and optnone' are incompatible!", V);
Assert1(!Attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::MinSize),
"Attributes 'minsize and optnone' are incompatible!", V);
}
}
void Verifier::VerifyBitcastType(const Value *V, Type *DestTy, Type *SrcTy) {
// Get the size of the types in bits, we'll need this later
unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
// BitCast implies a no-op cast of type only. No bits change.
// However, you can't cast pointers to anything but pointers.
Assert1(SrcTy->isPointerTy() == DestTy->isPointerTy(),
"Bitcast requires both operands to be pointer or neither", V);
Assert1(SrcBitSize == DestBitSize,
"Bitcast requires types of same width", V);
// Disallow aggregates.
Assert1(!SrcTy->isAggregateType(),
"Bitcast operand must not be aggregate", V);
Assert1(!DestTy->isAggregateType(),
"Bitcast type must not be aggregate", V);
// Without datalayout, assume all address spaces are the same size.
// Don't check if both types are not pointers.
// Skip casts between scalars and vectors.
if (!DL ||
!SrcTy->isPtrOrPtrVectorTy() ||
!DestTy->isPtrOrPtrVectorTy() ||
SrcTy->isVectorTy() != DestTy->isVectorTy()) {
return;
}
unsigned SrcAS = SrcTy->getPointerAddressSpace();
unsigned DstAS = DestTy->getPointerAddressSpace();
Assert1(SrcAS == DstAS,
"Bitcasts between pointers of different address spaces is not legal."
"Use AddrSpaceCast instead.", V);
}
void Verifier::VerifyConstantExprBitcastType(const ConstantExpr *CE) {
if (CE->getOpcode() == Instruction::BitCast) {
Type *SrcTy = CE->getOperand(0)->getType();
Type *DstTy = CE->getType();
VerifyBitcastType(CE, DstTy, SrcTy);
}
}
bool Verifier::VerifyAttributeCount(AttributeSet Attrs, unsigned Params) {
if (Attrs.getNumSlots() == 0)
return true;
unsigned LastSlot = Attrs.getNumSlots() - 1;
unsigned LastIndex = Attrs.getSlotIndex(LastSlot);
if (LastIndex <= Params
|| (LastIndex == AttributeSet::FunctionIndex