1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
33 // The following is a gross hack. In order to rid the libAsmParser library of
34 // exceptions, we have to have a way of getting the yyparse function to go into
35 // an error situation. So, whenever we want an error to occur, the GenerateError
36 // function (see bottom of file) sets TriggerError. Then, at the end of each
37 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
38 // (a goto) to put YACC in error state. Furthermore, several calls to
39 // GenerateError are made from inside productions and they must simulate the
40 // previous exception behavior by exiting the production immediately. We have
41 // replaced these with the GEN_ERROR macro which calls GeneratError and then
42 // immediately invokes YYERROR. This would be so much cleaner if it was a
43 // recursive descent parser.
44 static bool TriggerError = false;
45 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
48 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49 int yylex(); // declaration" of xxx warnings.
53 static Module *ParserResult;
55 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56 // relating to upreferences in the input stream.
58 //#define DEBUG_UPREFS 1
60 #define UR_OUT(X) cerr << X
65 #define YYERROR_VERBOSE 1
67 static GlobalVariable *CurGV;
70 // This contains info used when building the body of a function. It is
71 // destroyed when the function is completed.
73 typedef std::vector<Value *> ValueList; // Numbered defs
76 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
78 static struct PerModuleInfo {
79 Module *CurrentModule;
80 ValueList Values; // Module level numbered definitions
81 ValueList LateResolveValues;
82 std::vector<PATypeHolder> Types;
83 std::map<ValID, PATypeHolder> LateResolveTypes;
85 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86 /// how they were referenced and on which line of the input they came from so
87 /// that we can resolve them later and print error messages as appropriate.
88 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
90 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91 // references to global values. Global values may be referenced before they
92 // are defined, and if so, the temporary object that they represent is held
93 // here. This is used for forward references of GlobalValues.
95 typedef std::map<std::pair<const PointerType *,
96 ValID>, GlobalValue*> GlobalRefsType;
97 GlobalRefsType GlobalRefs;
100 // If we could not resolve some functions at function compilation time
101 // (calls to functions before they are defined), resolve them now... Types
102 // are resolved when the constant pool has been completely parsed.
104 ResolveDefinitions(LateResolveValues);
108 // Check to make sure that all global value forward references have been
111 if (!GlobalRefs.empty()) {
112 std::string UndefinedReferences = "Unresolved global references exist:\n";
114 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
116 UndefinedReferences += " " + I->first.first->getDescription() + " " +
117 I->first.second.getName() + "\n";
119 GenerateError(UndefinedReferences);
123 // Look for intrinsic functions and CallInst that need to be upgraded
124 for (Module::iterator FI = CurrentModule->begin(),
125 FE = CurrentModule->end(); FI != FE; )
126 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
128 Values.clear(); // Clear out function local definitions
133 // GetForwardRefForGlobal - Check to see if there is a forward reference
134 // for this global. If so, remove it from the GlobalRefs map and return it.
135 // If not, just return null.
136 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
137 // Check to see if there is a forward reference to this global variable...
138 // if there is, eliminate it and patch the reference to use the new def'n.
139 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
140 GlobalValue *Ret = 0;
141 if (I != GlobalRefs.end()) {
148 bool TypeIsUnresolved(PATypeHolder* PATy) {
149 // If it isn't abstract, its resolved
150 const Type* Ty = PATy->get();
151 if (!Ty->isAbstract())
153 // Traverse the type looking for abstract types. If it isn't abstract then
154 // we don't need to traverse that leg of the type.
155 std::vector<const Type*> WorkList, SeenList;
156 WorkList.push_back(Ty);
157 while (!WorkList.empty()) {
158 const Type* Ty = WorkList.back();
159 SeenList.push_back(Ty);
161 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
162 // Check to see if this is an unresolved type
163 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
164 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
165 for ( ; I != E; ++I) {
166 if (I->second.get() == OpTy)
169 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
170 const Type* TheTy = SeqTy->getElementType();
171 if (TheTy->isAbstract() && TheTy != Ty) {
172 std::vector<const Type*>::iterator I = SeenList.begin(),
178 WorkList.push_back(TheTy);
180 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
181 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
182 const Type* TheTy = StrTy->getElementType(i);
183 if (TheTy->isAbstract() && TheTy != Ty) {
184 std::vector<const Type*>::iterator I = SeenList.begin(),
190 WorkList.push_back(TheTy);
199 static struct PerFunctionInfo {
200 Function *CurrentFunction; // Pointer to current function being created
202 ValueList Values; // Keep track of #'d definitions
204 ValueList LateResolveValues;
205 bool isDeclare; // Is this function a forward declararation?
206 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
207 GlobalValue::VisibilityTypes Visibility;
209 /// BBForwardRefs - When we see forward references to basic blocks, keep
210 /// track of them here.
211 std::map<ValID, BasicBlock*> BBForwardRefs;
213 inline PerFunctionInfo() {
216 Linkage = GlobalValue::ExternalLinkage;
217 Visibility = GlobalValue::DefaultVisibility;
220 inline void FunctionStart(Function *M) {
225 void FunctionDone() {
226 // Any forward referenced blocks left?
227 if (!BBForwardRefs.empty()) {
228 GenerateError("Undefined reference to label " +
229 BBForwardRefs.begin()->second->getName());
233 // Resolve all forward references now.
234 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
236 Values.clear(); // Clear out function local definitions
237 BBForwardRefs.clear();
240 Linkage = GlobalValue::ExternalLinkage;
241 Visibility = GlobalValue::DefaultVisibility;
243 } CurFun; // Info for the current function...
245 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
248 //===----------------------------------------------------------------------===//
249 // Code to handle definitions of all the types
250 //===----------------------------------------------------------------------===//
252 static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
253 // Things that have names or are void typed don't get slot numbers
254 if (V->hasName() || (V->getType() == Type::VoidTy))
257 // In the case of function values, we have to allow for the forward reference
258 // of basic blocks, which are included in the numbering. Consequently, we keep
259 // track of the next insertion location with NextValNum. When a BB gets
260 // inserted, it could change the size of the CurFun.Values vector.
261 if (&ValueTab == &CurFun.Values) {
262 if (ValueTab.size() <= CurFun.NextValNum)
263 ValueTab.resize(CurFun.NextValNum+1);
264 ValueTab[CurFun.NextValNum++] = V;
267 // For all other lists, its okay to just tack it on the back of the vector.
268 ValueTab.push_back(V);
271 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
273 case ValID::LocalID: // Is it a numbered definition?
274 // Module constants occupy the lowest numbered slots...
275 if (D.Num < CurModule.Types.size())
276 return CurModule.Types[D.Num];
278 case ValID::LocalName: // Is it a named definition?
279 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
280 D.destroy(); // Free old strdup'd memory...
285 GenerateError("Internal parser error: Invalid symbol type reference");
289 // If we reached here, we referenced either a symbol that we don't know about
290 // or an id number that hasn't been read yet. We may be referencing something
291 // forward, so just create an entry to be resolved later and get to it...
293 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
296 if (inFunctionScope()) {
297 if (D.Type == ValID::LocalName) {
298 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
301 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
306 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
307 if (I != CurModule.LateResolveTypes.end())
310 Type *Typ = OpaqueType::get();
311 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
315 // getExistingVal - Look up the value specified by the provided type and
316 // the provided ValID. If the value exists and has already been defined, return
317 // it. Otherwise return null.
319 static Value *getExistingVal(const Type *Ty, const ValID &D) {
320 if (isa<FunctionType>(Ty)) {
321 GenerateError("Functions are not values and "
322 "must be referenced as pointers");
327 case ValID::LocalID: { // Is it a numbered definition?
328 // Check that the number is within bounds.
329 if (D.Num >= CurFun.Values.size())
331 Value *Result = CurFun.Values[D.Num];
332 if (Ty != Result->getType()) {
333 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
334 Result->getType()->getDescription() + "' does not match "
335 "expected type, '" + Ty->getDescription() + "'");
340 case ValID::GlobalID: { // Is it a numbered definition?
341 if (D.Num >= CurModule.Values.size())
343 Value *Result = CurModule.Values[D.Num];
344 if (Ty != Result->getType()) {
345 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
346 Result->getType()->getDescription() + "' does not match "
347 "expected type, '" + Ty->getDescription() + "'");
353 case ValID::LocalName: { // Is it a named definition?
354 if (!inFunctionScope())
356 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
357 Value *N = SymTab.lookup(D.getName());
360 if (N->getType() != Ty)
363 D.destroy(); // Free old strdup'd memory...
366 case ValID::GlobalName: { // Is it a named definition?
367 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
368 Value *N = SymTab.lookup(D.getName());
371 if (N->getType() != Ty)
374 D.destroy(); // Free old strdup'd memory...
378 // Check to make sure that "Ty" is an integral type, and that our
379 // value will fit into the specified type...
380 case ValID::ConstSIntVal: // Is it a constant pool reference??
381 if (!isa<IntegerType>(Ty) ||
382 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
383 GenerateError("Signed integral constant '" +
384 itostr(D.ConstPool64) + "' is invalid for type '" +
385 Ty->getDescription() + "'");
388 return ConstantInt::get(Ty, D.ConstPool64, true);
390 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
391 if (isa<IntegerType>(Ty) &&
392 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
393 return ConstantInt::get(Ty, D.UConstPool64);
395 if (!isa<IntegerType>(Ty) ||
396 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
397 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
398 "' is invalid or out of range for type '" +
399 Ty->getDescription() + "'");
402 // This is really a signed reference. Transmogrify.
403 return ConstantInt::get(Ty, D.ConstPool64, true);
405 case ValID::ConstFPVal: // Is it a floating point const pool reference?
406 if (!Ty->isFloatingPoint() ||
407 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
408 GenerateError("FP constant invalid for type");
411 // Lexer has no type info, so builds all float and double FP constants
412 // as double. Fix this here. Long double does not need this.
413 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
415 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
416 return ConstantFP::get(Ty, *D.ConstPoolFP);
418 case ValID::ConstNullVal: // Is it a null value?
419 if (!isa<PointerType>(Ty)) {
420 GenerateError("Cannot create a a non pointer null");
423 return ConstantPointerNull::get(cast<PointerType>(Ty));
425 case ValID::ConstUndefVal: // Is it an undef value?
426 return UndefValue::get(Ty);
428 case ValID::ConstZeroVal: // Is it a zero value?
429 return Constant::getNullValue(Ty);
431 case ValID::ConstantVal: // Fully resolved constant?
432 if (D.ConstantValue->getType() != Ty) {
433 GenerateError("Constant expression type different from required type");
436 return D.ConstantValue;
438 case ValID::InlineAsmVal: { // Inline asm expression
439 const PointerType *PTy = dyn_cast<PointerType>(Ty);
440 const FunctionType *FTy =
441 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
442 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
443 GenerateError("Invalid type for asm constraint string");
446 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
447 D.IAD->HasSideEffects);
448 D.destroy(); // Free InlineAsmDescriptor.
452 assert(0 && "Unhandled case!");
456 assert(0 && "Unhandled case!");
460 // getVal - This function is identical to getExistingVal, except that if a
461 // value is not already defined, it "improvises" by creating a placeholder var
462 // that looks and acts just like the requested variable. When the value is
463 // defined later, all uses of the placeholder variable are replaced with the
466 static Value *getVal(const Type *Ty, const ValID &ID) {
467 if (Ty == Type::LabelTy) {
468 GenerateError("Cannot use a basic block here");
472 // See if the value has already been defined.
473 Value *V = getExistingVal(Ty, ID);
475 if (TriggerError) return 0;
477 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
478 GenerateError("Invalid use of a composite type");
482 // If we reached here, we referenced either a symbol that we don't know about
483 // or an id number that hasn't been read yet. We may be referencing something
484 // forward, so just create an entry to be resolved later and get to it...
487 case ValID::GlobalName:
488 case ValID::GlobalID: {
489 const PointerType *PTy = dyn_cast<PointerType>(Ty);
491 GenerateError("Invalid type for reference to global" );
494 const Type* ElTy = PTy->getElementType();
495 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
496 V = new Function(FTy, GlobalValue::ExternalLinkage);
498 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
499 (Module*)0, false, PTy->getAddressSpace());
503 V = new Argument(Ty);
506 // Remember where this forward reference came from. FIXME, shouldn't we try
507 // to recycle these things??
508 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
511 if (inFunctionScope())
512 InsertValue(V, CurFun.LateResolveValues);
514 InsertValue(V, CurModule.LateResolveValues);
518 /// defineBBVal - This is a definition of a new basic block with the specified
519 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
520 static BasicBlock *defineBBVal(const ValID &ID) {
521 assert(inFunctionScope() && "Can't get basic block at global scope!");
525 // First, see if this was forward referenced
527 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
528 if (BBI != CurFun.BBForwardRefs.end()) {
530 // The forward declaration could have been inserted anywhere in the
531 // function: insert it into the correct place now.
532 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
533 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
535 // We're about to erase the entry, save the key so we can clean it up.
536 ValID Tmp = BBI->first;
538 // Erase the forward ref from the map as its no longer "forward"
539 CurFun.BBForwardRefs.erase(ID);
541 // The key has been removed from the map but so we don't want to leave
542 // strdup'd memory around so destroy it too.
545 // If its a numbered definition, bump the number and set the BB value.
546 if (ID.Type == ValID::LocalID) {
547 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
555 // We haven't seen this BB before and its first mention is a definition.
556 // Just create it and return it.
557 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
558 BB = new BasicBlock(Name, CurFun.CurrentFunction);
559 if (ID.Type == ValID::LocalID) {
560 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
564 ID.destroy(); // Free strdup'd memory
568 /// getBBVal - get an existing BB value or create a forward reference for it.
570 static BasicBlock *getBBVal(const ValID &ID) {
571 assert(inFunctionScope() && "Can't get basic block at global scope!");
575 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
576 if (BBI != CurFun.BBForwardRefs.end()) {
578 } if (ID.Type == ValID::LocalName) {
579 std::string Name = ID.getName();
580 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
582 if (N->getType()->getTypeID() == Type::LabelTyID)
583 BB = cast<BasicBlock>(N);
585 GenerateError("Reference to label '" + Name + "' is actually of type '"+
586 N->getType()->getDescription() + "'");
587 } else if (ID.Type == ValID::LocalID) {
588 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
589 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
590 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
592 GenerateError("Reference to label '%" + utostr(ID.Num) +
593 "' is actually of type '"+
594 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
597 GenerateError("Illegal label reference " + ID.getName());
601 // If its already been defined, return it now.
603 ID.destroy(); // Free strdup'd memory.
607 // Otherwise, this block has not been seen before, create it.
609 if (ID.Type == ValID::LocalName)
611 BB = new BasicBlock(Name, CurFun.CurrentFunction);
613 // Insert it in the forward refs map.
614 CurFun.BBForwardRefs[ID] = BB;
620 //===----------------------------------------------------------------------===//
621 // Code to handle forward references in instructions
622 //===----------------------------------------------------------------------===//
624 // This code handles the late binding needed with statements that reference
625 // values not defined yet... for example, a forward branch, or the PHI node for
628 // This keeps a table (CurFun.LateResolveValues) of all such forward references
629 // and back patchs after we are done.
632 // ResolveDefinitions - If we could not resolve some defs at parsing
633 // time (forward branches, phi functions for loops, etc...) resolve the
637 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
638 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
639 while (!LateResolvers.empty()) {
640 Value *V = LateResolvers.back();
641 LateResolvers.pop_back();
643 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
644 CurModule.PlaceHolderInfo.find(V);
645 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
647 ValID &DID = PHI->second.first;
649 Value *TheRealValue = getExistingVal(V->getType(), DID);
653 V->replaceAllUsesWith(TheRealValue);
655 CurModule.PlaceHolderInfo.erase(PHI);
656 } else if (FutureLateResolvers) {
657 // Functions have their unresolved items forwarded to the module late
659 InsertValue(V, *FutureLateResolvers);
661 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
662 GenerateError("Reference to an invalid definition: '" +DID.getName()+
663 "' of type '" + V->getType()->getDescription() + "'",
667 GenerateError("Reference to an invalid definition: #" +
668 itostr(DID.Num) + " of type '" +
669 V->getType()->getDescription() + "'",
675 LateResolvers.clear();
678 // ResolveTypeTo - A brand new type was just declared. This means that (if
679 // name is not null) things referencing Name can be resolved. Otherwise, things
680 // refering to the number can be resolved. Do this now.
682 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
685 D = ValID::createLocalName(*Name);
687 D = ValID::createLocalID(CurModule.Types.size());
689 std::map<ValID, PATypeHolder>::iterator I =
690 CurModule.LateResolveTypes.find(D);
691 if (I != CurModule.LateResolveTypes.end()) {
692 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
693 CurModule.LateResolveTypes.erase(I);
697 // setValueName - Set the specified value to the name given. The name may be
698 // null potentially, in which case this is a noop. The string passed in is
699 // assumed to be a malloc'd string buffer, and is free'd by this function.
701 static void setValueName(Value *V, std::string *NameStr) {
702 if (!NameStr) return;
703 std::string Name(*NameStr); // Copy string
704 delete NameStr; // Free old string
706 if (V->getType() == Type::VoidTy) {
707 GenerateError("Can't assign name '" + Name+"' to value with void type");
711 assert(inFunctionScope() && "Must be in function scope!");
712 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
713 if (ST.lookup(Name)) {
714 GenerateError("Redefinition of value '" + Name + "' of type '" +
715 V->getType()->getDescription() + "'");
723 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
724 /// this is a declaration, otherwise it is a definition.
725 static GlobalVariable *
726 ParseGlobalVariable(std::string *NameStr,
727 GlobalValue::LinkageTypes Linkage,
728 GlobalValue::VisibilityTypes Visibility,
729 bool isConstantGlobal, const Type *Ty,
730 Constant *Initializer, bool IsThreadLocal,
731 unsigned AddressSpace = 0) {
732 if (isa<FunctionType>(Ty)) {
733 GenerateError("Cannot declare global vars of function type");
737 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
741 Name = *NameStr; // Copy string
742 delete NameStr; // Free old string
745 // See if this global value was forward referenced. If so, recycle the
749 ID = ValID::createGlobalName(Name);
751 ID = ValID::createGlobalID(CurModule.Values.size());
754 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
755 // Move the global to the end of the list, from whereever it was
756 // previously inserted.
757 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
758 CurModule.CurrentModule->getGlobalList().remove(GV);
759 CurModule.CurrentModule->getGlobalList().push_back(GV);
760 GV->setInitializer(Initializer);
761 GV->setLinkage(Linkage);
762 GV->setVisibility(Visibility);
763 GV->setConstant(isConstantGlobal);
764 GV->setThreadLocal(IsThreadLocal);
765 InsertValue(GV, CurModule.Values);
769 // If this global has a name
771 // if the global we're parsing has an initializer (is a definition) and
772 // has external linkage.
773 if (Initializer && Linkage != GlobalValue::InternalLinkage)
774 // If there is already a global with external linkage with this name
775 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
776 // If we allow this GVar to get created, it will be renamed in the
777 // symbol table because it conflicts with an existing GVar. We can't
778 // allow redefinition of GVars whose linking indicates that their name
779 // must stay the same. Issue the error.
780 GenerateError("Redefinition of global variable named '" + Name +
781 "' of type '" + Ty->getDescription() + "'");
786 // Otherwise there is no existing GV to use, create one now.
788 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
789 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
790 GV->setVisibility(Visibility);
791 InsertValue(GV, CurModule.Values);
795 // setTypeName - Set the specified type to the name given. The name may be
796 // null potentially, in which case this is a noop. The string passed in is
797 // assumed to be a malloc'd string buffer, and is freed by this function.
799 // This function returns true if the type has already been defined, but is
800 // allowed to be redefined in the specified context. If the name is a new name
801 // for the type plane, it is inserted and false is returned.
802 static bool setTypeName(const Type *T, std::string *NameStr) {
803 assert(!inFunctionScope() && "Can't give types function-local names!");
804 if (NameStr == 0) return false;
806 std::string Name(*NameStr); // Copy string
807 delete NameStr; // Free old string
809 // We don't allow assigning names to void type
810 if (T == Type::VoidTy) {
811 GenerateError("Can't assign name '" + Name + "' to the void type");
815 // Set the type name, checking for conflicts as we do so.
816 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
818 if (AlreadyExists) { // Inserting a name that is already defined???
819 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
820 assert(Existing && "Conflict but no matching type?!");
822 // There is only one case where this is allowed: when we are refining an
823 // opaque type. In this case, Existing will be an opaque type.
824 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
825 // We ARE replacing an opaque type!
826 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
830 // Otherwise, this is an attempt to redefine a type. That's okay if
831 // the redefinition is identical to the original. This will be so if
832 // Existing and T point to the same Type object. In this one case we
833 // allow the equivalent redefinition.
834 if (Existing == T) return true; // Yes, it's equal.
836 // Any other kind of (non-equivalent) redefinition is an error.
837 GenerateError("Redefinition of type named '" + Name + "' of type '" +
838 T->getDescription() + "'");
844 //===----------------------------------------------------------------------===//
845 // Code for handling upreferences in type names...
848 // TypeContains - Returns true if Ty directly contains E in it.
850 static bool TypeContains(const Type *Ty, const Type *E) {
851 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
852 E) != Ty->subtype_end();
857 // NestingLevel - The number of nesting levels that need to be popped before
858 // this type is resolved.
859 unsigned NestingLevel;
861 // LastContainedTy - This is the type at the current binding level for the
862 // type. Every time we reduce the nesting level, this gets updated.
863 const Type *LastContainedTy;
865 // UpRefTy - This is the actual opaque type that the upreference is
869 UpRefRecord(unsigned NL, OpaqueType *URTy)
870 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
874 // UpRefs - A list of the outstanding upreferences that need to be resolved.
875 static std::vector<UpRefRecord> UpRefs;
877 /// HandleUpRefs - Every time we finish a new layer of types, this function is
878 /// called. It loops through the UpRefs vector, which is a list of the
879 /// currently active types. For each type, if the up reference is contained in
880 /// the newly completed type, we decrement the level count. When the level
881 /// count reaches zero, the upreferenced type is the type that is passed in:
882 /// thus we can complete the cycle.
884 static PATypeHolder HandleUpRefs(const Type *ty) {
885 // If Ty isn't abstract, or if there are no up-references in it, then there is
886 // nothing to resolve here.
887 if (!ty->isAbstract() || UpRefs.empty()) return ty;
890 UR_OUT("Type '" << Ty->getDescription() <<
891 "' newly formed. Resolving upreferences.\n" <<
892 UpRefs.size() << " upreferences active!\n");
894 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
895 // to zero), we resolve them all together before we resolve them to Ty. At
896 // the end of the loop, if there is anything to resolve to Ty, it will be in
898 OpaqueType *TypeToResolve = 0;
900 for (unsigned i = 0; i != UpRefs.size(); ++i) {
901 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
902 << UpRefs[i].second->getDescription() << ") = "
903 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
904 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
905 // Decrement level of upreference
906 unsigned Level = --UpRefs[i].NestingLevel;
907 UpRefs[i].LastContainedTy = Ty;
908 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
909 if (Level == 0) { // Upreference should be resolved!
910 if (!TypeToResolve) {
911 TypeToResolve = UpRefs[i].UpRefTy;
913 UR_OUT(" * Resolving upreference for "
914 << UpRefs[i].second->getDescription() << "\n";
915 std::string OldName = UpRefs[i].UpRefTy->getDescription());
916 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
917 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
918 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
920 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
921 --i; // Do not skip the next element...
927 UR_OUT(" * Resolving upreference for "
928 << UpRefs[i].second->getDescription() << "\n";
929 std::string OldName = TypeToResolve->getDescription());
930 TypeToResolve->refineAbstractTypeTo(Ty);
936 //===----------------------------------------------------------------------===//
937 // RunVMAsmParser - Define an interface to this parser
938 //===----------------------------------------------------------------------===//
940 static Module* RunParser(Module * M);
942 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
944 Module *M = RunParser(new Module(LLLgetFilename()));
952 llvm::Module *ModuleVal;
953 llvm::Function *FunctionVal;
954 llvm::BasicBlock *BasicBlockVal;
955 llvm::TerminatorInst *TermInstVal;
956 llvm::Instruction *InstVal;
957 llvm::Constant *ConstVal;
959 const llvm::Type *PrimType;
960 std::list<llvm::PATypeHolder> *TypeList;
961 llvm::PATypeHolder *TypeVal;
962 llvm::Value *ValueVal;
963 std::vector<llvm::Value*> *ValueList;
964 llvm::ArgListType *ArgList;
965 llvm::TypeWithAttrs TypeWithAttrs;
966 llvm::TypeWithAttrsList *TypeWithAttrsList;
967 llvm::ParamList *ParamList;
969 // Represent the RHS of PHI node
970 std::list<std::pair<llvm::Value*,
971 llvm::BasicBlock*> > *PHIList;
972 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
973 std::vector<llvm::Constant*> *ConstVector;
975 llvm::GlobalValue::LinkageTypes Linkage;
976 llvm::GlobalValue::VisibilityTypes Visibility;
978 llvm::APInt *APIntVal;
983 llvm::APFloat *FPVal;
986 std::string *StrVal; // This memory must be deleted
987 llvm::ValID ValIDVal;
989 llvm::Instruction::BinaryOps BinaryOpVal;
990 llvm::Instruction::TermOps TermOpVal;
991 llvm::Instruction::MemoryOps MemOpVal;
992 llvm::Instruction::CastOps CastOpVal;
993 llvm::Instruction::OtherOps OtherOpVal;
994 llvm::ICmpInst::Predicate IPredicate;
995 llvm::FCmpInst::Predicate FPredicate;
998 %type <ModuleVal> Module
999 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1000 %type <BasicBlockVal> BasicBlock InstructionList
1001 %type <TermInstVal> BBTerminatorInst
1002 %type <InstVal> Inst InstVal MemoryInst
1003 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1004 %type <ConstVector> ConstVector
1005 %type <ArgList> ArgList ArgListH
1006 %type <PHIList> PHIList
1007 %type <ParamList> ParamList // For call param lists & GEP indices
1008 %type <ValueList> IndexList // For GEP indices
1009 %type <TypeList> TypeListI
1010 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1011 %type <TypeWithAttrs> ArgType
1012 %type <JumpTable> JumpTable
1013 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1014 %type <BoolVal> ThreadLocal // 'thread_local' or not
1015 %type <BoolVal> OptVolatile // 'volatile' or not
1016 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1017 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1018 %type <Linkage> GVInternalLinkage GVExternalLinkage
1019 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1020 %type <Linkage> AliasLinkage
1021 %type <Visibility> GVVisibilityStyle
1023 // ValueRef - Unresolved reference to a definition or BB
1024 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1025 %type <ValueVal> ResolvedVal // <type> <valref> pair
1026 // Tokens and types for handling constant integer values
1028 // ESINT64VAL - A negative number within long long range
1029 %token <SInt64Val> ESINT64VAL
1031 // EUINT64VAL - A positive number within uns. long long range
1032 %token <UInt64Val> EUINT64VAL
1034 // ESAPINTVAL - A negative number with arbitrary precision
1035 %token <APIntVal> ESAPINTVAL
1037 // EUAPINTVAL - A positive number with arbitrary precision
1038 %token <APIntVal> EUAPINTVAL
1040 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1041 %token <FPVal> FPVAL // Float or Double constant
1043 // Built in types...
1044 %type <TypeVal> Types ResultTypes
1045 %type <PrimType> IntType FPType PrimType // Classifications
1046 %token <PrimType> VOID INTTYPE
1047 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1051 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1052 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1053 %type <StrVal> LocalName OptLocalName OptLocalAssign
1054 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1055 %type <StrVal> OptSection SectionString OptGC
1057 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1059 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1060 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1061 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1062 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1063 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1064 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1065 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1067 %type <UIntVal> OptCallingConv
1068 %type <ParamAttrs> OptParamAttrs ParamAttr
1069 %type <ParamAttrs> OptFuncAttrs FuncAttr
1071 // Basic Block Terminating Operators
1072 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1075 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1076 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1077 %token <BinaryOpVal> SHL LSHR ASHR
1079 %token <OtherOpVal> ICMP FCMP
1080 %type <IPredicate> IPredicates
1081 %type <FPredicate> FPredicates
1082 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1083 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1085 // Memory Instructions
1086 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1089 %type <CastOpVal> CastOps
1090 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1091 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1094 %token <OtherOpVal> PHI_TOK SELECT VAARG
1095 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1097 // Function Attributes
1098 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1099 %token READNONE READONLY GC
1101 // Visibility Styles
1102 %token DEFAULT HIDDEN PROTECTED
1108 // Operations that are notably excluded from this list include:
1109 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1111 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1112 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1113 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1114 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1117 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1118 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1119 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1120 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1121 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1125 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1126 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1127 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1128 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1129 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1130 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1131 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1132 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1133 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1136 // These are some types that allow classification if we only want a particular
1137 // thing... for example, only a signed, unsigned, or integral type.
1139 FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1141 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1142 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1144 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1145 | /*empty*/ { $$=0; };
1147 /// OptLocalAssign - Value producing statements have an optional assignment
1149 OptLocalAssign : LocalName '=' {
1158 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1160 OptGlobalAssign : GlobalAssign
1166 GlobalAssign : GlobalName '=' {
1172 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1173 | WEAK { $$ = GlobalValue::WeakLinkage; }
1174 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1175 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1176 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1180 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1181 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1182 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1186 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1187 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1188 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1189 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1192 FunctionDeclareLinkage
1193 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1194 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1195 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1198 FunctionDefineLinkage
1199 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1200 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1201 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1202 | WEAK { $$ = GlobalValue::WeakLinkage; }
1203 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1207 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1208 | WEAK { $$ = GlobalValue::WeakLinkage; }
1209 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1212 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1213 CCC_TOK { $$ = CallingConv::C; } |
1214 FASTCC_TOK { $$ = CallingConv::Fast; } |
1215 COLDCC_TOK { $$ = CallingConv::Cold; } |
1216 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1217 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1219 if ((unsigned)$2 != $2)
1220 GEN_ERROR("Calling conv too large");
1225 ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1226 | ZEXT { $$ = ParamAttr::ZExt; }
1227 | SIGNEXT { $$ = ParamAttr::SExt; }
1228 | SEXT { $$ = ParamAttr::SExt; }
1229 | INREG { $$ = ParamAttr::InReg; }
1230 | SRET { $$ = ParamAttr::StructRet; }
1231 | NOALIAS { $$ = ParamAttr::NoAlias; }
1232 | BYVAL { $$ = ParamAttr::ByVal; }
1233 | NEST { $$ = ParamAttr::Nest; }
1236 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1237 | OptParamAttrs ParamAttr {
1242 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1243 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1244 | ZEROEXT { $$ = ParamAttr::ZExt; }
1245 | SIGNEXT { $$ = ParamAttr::SExt; }
1246 | READNONE { $$ = ParamAttr::ReadNone; }
1247 | READONLY { $$ = ParamAttr::ReadOnly; }
1250 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1251 | OptFuncAttrs FuncAttr {
1256 OptGC : /* empty */ { $$ = 0; }
1257 | GC STRINGCONSTANT {
1262 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1263 // a comma before it.
1264 OptAlign : /*empty*/ { $$ = 0; } |
1267 if ($$ != 0 && !isPowerOf2_32($$))
1268 GEN_ERROR("Alignment must be a power of two");
1271 OptCAlign : /*empty*/ { $$ = 0; } |
1272 ',' ALIGN EUINT64VAL {
1274 if ($$ != 0 && !isPowerOf2_32($$))
1275 GEN_ERROR("Alignment must be a power of two");
1281 SectionString : SECTION STRINGCONSTANT {
1282 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1283 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1284 GEN_ERROR("Invalid character in section name");
1289 OptSection : /*empty*/ { $$ = 0; } |
1290 SectionString { $$ = $1; };
1292 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1293 // is set to be the global we are processing.
1295 GlobalVarAttributes : /* empty */ {} |
1296 ',' GlobalVarAttribute GlobalVarAttributes {};
1297 GlobalVarAttribute : SectionString {
1298 CurGV->setSection(*$1);
1302 | ALIGN EUINT64VAL {
1303 if ($2 != 0 && !isPowerOf2_32($2))
1304 GEN_ERROR("Alignment must be a power of two");
1305 CurGV->setAlignment($2);
1309 //===----------------------------------------------------------------------===//
1310 // Types includes all predefined types... except void, because it can only be
1311 // used in specific contexts (function returning void for example).
1313 // Derived types are added later...
1315 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1319 $$ = new PATypeHolder(OpaqueType::get());
1323 $$ = new PATypeHolder($1);
1326 | Types OptAddrSpace '*' { // Pointer type?
1327 if (*$1 == Type::LabelTy)
1328 GEN_ERROR("Cannot form a pointer to a basic block");
1329 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1333 | SymbolicValueRef { // Named types are also simple types...
1334 const Type* tmp = getTypeVal($1);
1336 $$ = new PATypeHolder(tmp);
1338 | '\\' EUINT64VAL { // Type UpReference
1339 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1340 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1341 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1342 $$ = new PATypeHolder(OT);
1343 UR_OUT("New Upreference!\n");
1346 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1347 // Allow but ignore attributes on function types; this permits auto-upgrade.
1348 // FIXME: remove in LLVM 3.0.
1349 const Type* RetTy = *$1;
1350 if (!(RetTy->isFirstClassType() || RetTy == Type::VoidTy ||
1351 isa<OpaqueType>(RetTy)))
1352 GEN_ERROR("LLVM Functions cannot return aggregates");
1354 std::vector<const Type*> Params;
1355 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1356 for (; I != E; ++I ) {
1357 const Type *Ty = I->Ty->get();
1358 Params.push_back(Ty);
1361 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1362 if (isVarArg) Params.pop_back();
1364 for (unsigned i = 0; i != Params.size(); ++i)
1365 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1366 GEN_ERROR("Function arguments must be value types!");
1370 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1371 delete $3; // Delete the argument list
1372 delete $1; // Delete the return type handle
1373 $$ = new PATypeHolder(HandleUpRefs(FT));
1376 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1377 // Allow but ignore attributes on function types; this permits auto-upgrade.
1378 // FIXME: remove in LLVM 3.0.
1379 std::vector<const Type*> Params;
1380 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1381 for ( ; I != E; ++I ) {
1382 const Type* Ty = I->Ty->get();
1383 Params.push_back(Ty);
1386 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1387 if (isVarArg) Params.pop_back();
1389 for (unsigned i = 0; i != Params.size(); ++i)
1390 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1391 GEN_ERROR("Function arguments must be value types!");
1395 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1396 delete $3; // Delete the argument list
1397 $$ = new PATypeHolder(HandleUpRefs(FT));
1401 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1402 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1406 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1407 const llvm::Type* ElemTy = $4->get();
1408 if ((unsigned)$2 != $2)
1409 GEN_ERROR("Unsigned result not equal to signed result");
1410 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1411 GEN_ERROR("Element type of a VectorType must be primitive");
1412 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1416 | '{' TypeListI '}' { // Structure type?
1417 std::vector<const Type*> Elements;
1418 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1419 E = $2->end(); I != E; ++I)
1420 Elements.push_back(*I);
1422 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1426 | '{' '}' { // Empty structure type?
1427 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1430 | '<' '{' TypeListI '}' '>' {
1431 std::vector<const Type*> Elements;
1432 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1433 E = $3->end(); I != E; ++I)
1434 Elements.push_back(*I);
1436 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1440 | '<' '{' '}' '>' { // Empty structure type?
1441 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1447 : Types OptParamAttrs {
1448 // Allow but ignore attributes on function types; this permits auto-upgrade.
1449 // FIXME: remove in LLVM 3.0.
1451 $$.Attrs = ParamAttr::None;
1457 if (!UpRefs.empty())
1458 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1459 if (!(*$1)->isFirstClassType())
1460 GEN_ERROR("LLVM functions cannot return aggregate types");
1464 $$ = new PATypeHolder(Type::VoidTy);
1468 ArgTypeList : ArgType {
1469 $$ = new TypeWithAttrsList();
1473 | ArgTypeList ',' ArgType {
1474 ($$=$1)->push_back($3);
1481 | ArgTypeList ',' DOTDOTDOT {
1483 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1484 TWA.Ty = new PATypeHolder(Type::VoidTy);
1489 $$ = new TypeWithAttrsList;
1490 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1491 TWA.Ty = new PATypeHolder(Type::VoidTy);
1496 $$ = new TypeWithAttrsList();
1500 // TypeList - Used for struct declarations and as a basis for function type
1501 // declaration type lists
1504 $$ = new std::list<PATypeHolder>();
1509 | TypeListI ',' Types {
1510 ($$=$1)->push_back(*$3);
1515 // ConstVal - The various declarations that go into the constant pool. This
1516 // production is used ONLY to represent constants that show up AFTER a 'const',
1517 // 'constant' or 'global' token at global scope. Constants that can be inlined
1518 // into other expressions (such as integers and constexprs) are handled by the
1519 // ResolvedVal, ValueRef and ConstValueRef productions.
1521 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1522 if (!UpRefs.empty())
1523 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1524 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1526 GEN_ERROR("Cannot make array constant with type: '" +
1527 (*$1)->getDescription() + "'");
1528 const Type *ETy = ATy->getElementType();
1529 int NumElements = ATy->getNumElements();
1531 // Verify that we have the correct size...
1532 if (NumElements != -1 && NumElements != (int)$3->size())
1533 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1534 utostr($3->size()) + " arguments, but has size of " +
1535 itostr(NumElements) + "");
1537 // Verify all elements are correct type!
1538 for (unsigned i = 0; i < $3->size(); i++) {
1539 if (ETy != (*$3)[i]->getType())
1540 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1541 ETy->getDescription() +"' as required!\nIt is of type '"+
1542 (*$3)[i]->getType()->getDescription() + "'.");
1545 $$ = ConstantArray::get(ATy, *$3);
1546 delete $1; delete $3;
1550 if (!UpRefs.empty())
1551 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1552 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1554 GEN_ERROR("Cannot make array constant with type: '" +
1555 (*$1)->getDescription() + "'");
1557 int NumElements = ATy->getNumElements();
1558 if (NumElements != -1 && NumElements != 0)
1559 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1560 " arguments, but has size of " + itostr(NumElements) +"");
1561 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1565 | Types 'c' STRINGCONSTANT {
1566 if (!UpRefs.empty())
1567 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1568 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1570 GEN_ERROR("Cannot make array constant with type: '" +
1571 (*$1)->getDescription() + "'");
1573 int NumElements = ATy->getNumElements();
1574 const Type *ETy = ATy->getElementType();
1575 if (NumElements != -1 && NumElements != int($3->length()))
1576 GEN_ERROR("Can't build string constant of size " +
1577 itostr((int)($3->length())) +
1578 " when array has size " + itostr(NumElements) + "");
1579 std::vector<Constant*> Vals;
1580 if (ETy == Type::Int8Ty) {
1581 for (unsigned i = 0; i < $3->length(); ++i)
1582 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1585 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1588 $$ = ConstantArray::get(ATy, Vals);
1592 | Types '<' ConstVector '>' { // Nonempty unsized arr
1593 if (!UpRefs.empty())
1594 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1595 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1597 GEN_ERROR("Cannot make packed constant with type: '" +
1598 (*$1)->getDescription() + "'");
1599 const Type *ETy = PTy->getElementType();
1600 int NumElements = PTy->getNumElements();
1602 // Verify that we have the correct size...
1603 if (NumElements != -1 && NumElements != (int)$3->size())
1604 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1605 utostr($3->size()) + " arguments, but has size of " +
1606 itostr(NumElements) + "");
1608 // Verify all elements are correct type!
1609 for (unsigned i = 0; i < $3->size(); i++) {
1610 if (ETy != (*$3)[i]->getType())
1611 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1612 ETy->getDescription() +"' as required!\nIt is of type '"+
1613 (*$3)[i]->getType()->getDescription() + "'.");
1616 $$ = ConstantVector::get(PTy, *$3);
1617 delete $1; delete $3;
1620 | Types '{' ConstVector '}' {
1621 const StructType *STy = dyn_cast<StructType>($1->get());
1623 GEN_ERROR("Cannot make struct constant with type: '" +
1624 (*$1)->getDescription() + "'");
1626 if ($3->size() != STy->getNumContainedTypes())
1627 GEN_ERROR("Illegal number of initializers for structure type");
1629 // Check to ensure that constants are compatible with the type initializer!
1630 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1631 if ((*$3)[i]->getType() != STy->getElementType(i))
1632 GEN_ERROR("Expected type '" +
1633 STy->getElementType(i)->getDescription() +
1634 "' for element #" + utostr(i) +
1635 " of structure initializer");
1637 // Check to ensure that Type is not packed
1638 if (STy->isPacked())
1639 GEN_ERROR("Unpacked Initializer to vector type '" +
1640 STy->getDescription() + "'");
1642 $$ = ConstantStruct::get(STy, *$3);
1643 delete $1; delete $3;
1647 if (!UpRefs.empty())
1648 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1649 const StructType *STy = dyn_cast<StructType>($1->get());
1651 GEN_ERROR("Cannot make struct constant with type: '" +
1652 (*$1)->getDescription() + "'");
1654 if (STy->getNumContainedTypes() != 0)
1655 GEN_ERROR("Illegal number of initializers for structure type");
1657 // Check to ensure that Type is not packed
1658 if (STy->isPacked())
1659 GEN_ERROR("Unpacked Initializer to vector type '" +
1660 STy->getDescription() + "'");
1662 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1666 | Types '<' '{' ConstVector '}' '>' {
1667 const StructType *STy = dyn_cast<StructType>($1->get());
1669 GEN_ERROR("Cannot make struct constant with type: '" +
1670 (*$1)->getDescription() + "'");
1672 if ($4->size() != STy->getNumContainedTypes())
1673 GEN_ERROR("Illegal number of initializers for structure type");
1675 // Check to ensure that constants are compatible with the type initializer!
1676 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1677 if ((*$4)[i]->getType() != STy->getElementType(i))
1678 GEN_ERROR("Expected type '" +
1679 STy->getElementType(i)->getDescription() +
1680 "' for element #" + utostr(i) +
1681 " of structure initializer");
1683 // Check to ensure that Type is packed
1684 if (!STy->isPacked())
1685 GEN_ERROR("Vector initializer to non-vector type '" +
1686 STy->getDescription() + "'");
1688 $$ = ConstantStruct::get(STy, *$4);
1689 delete $1; delete $4;
1692 | Types '<' '{' '}' '>' {
1693 if (!UpRefs.empty())
1694 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1695 const StructType *STy = dyn_cast<StructType>($1->get());
1697 GEN_ERROR("Cannot make struct constant with type: '" +
1698 (*$1)->getDescription() + "'");
1700 if (STy->getNumContainedTypes() != 0)
1701 GEN_ERROR("Illegal number of initializers for structure type");
1703 // Check to ensure that Type is packed
1704 if (!STy->isPacked())
1705 GEN_ERROR("Vector initializer to non-vector type '" +
1706 STy->getDescription() + "'");
1708 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1713 if (!UpRefs.empty())
1714 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1715 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1717 GEN_ERROR("Cannot make null pointer constant with type: '" +
1718 (*$1)->getDescription() + "'");
1720 $$ = ConstantPointerNull::get(PTy);
1725 if (!UpRefs.empty())
1726 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1727 $$ = UndefValue::get($1->get());
1731 | Types SymbolicValueRef {
1732 if (!UpRefs.empty())
1733 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1734 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1736 GEN_ERROR("Global const reference must be a pointer type");
1738 // ConstExprs can exist in the body of a function, thus creating
1739 // GlobalValues whenever they refer to a variable. Because we are in
1740 // the context of a function, getExistingVal will search the functions
1741 // symbol table instead of the module symbol table for the global symbol,
1742 // which throws things all off. To get around this, we just tell
1743 // getExistingVal that we are at global scope here.
1745 Function *SavedCurFn = CurFun.CurrentFunction;
1746 CurFun.CurrentFunction = 0;
1748 Value *V = getExistingVal(Ty, $2);
1751 CurFun.CurrentFunction = SavedCurFn;
1753 // If this is an initializer for a constant pointer, which is referencing a
1754 // (currently) undefined variable, create a stub now that shall be replaced
1755 // in the future with the right type of variable.
1758 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1759 const PointerType *PT = cast<PointerType>(Ty);
1761 // First check to see if the forward references value is already created!
1762 PerModuleInfo::GlobalRefsType::iterator I =
1763 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1765 if (I != CurModule.GlobalRefs.end()) {
1766 V = I->second; // Placeholder already exists, use it...
1770 if ($2.Type == ValID::GlobalName)
1771 Name = $2.getName();
1772 else if ($2.Type != ValID::GlobalID)
1773 GEN_ERROR("Invalid reference to global");
1775 // Create the forward referenced global.
1777 if (const FunctionType *FTy =
1778 dyn_cast<FunctionType>(PT->getElementType())) {
1779 GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1780 CurModule.CurrentModule);
1782 GV = new GlobalVariable(PT->getElementType(), false,
1783 GlobalValue::ExternalWeakLinkage, 0,
1784 Name, CurModule.CurrentModule);
1787 // Keep track of the fact that we have a forward ref to recycle it
1788 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1793 $$ = cast<GlobalValue>(V);
1794 delete $1; // Free the type handle
1798 if (!UpRefs.empty())
1799 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1800 if ($1->get() != $2->getType())
1801 GEN_ERROR("Mismatched types for constant expression: " +
1802 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1807 | Types ZEROINITIALIZER {
1808 if (!UpRefs.empty())
1809 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1810 const Type *Ty = $1->get();
1811 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1812 GEN_ERROR("Cannot create a null initialized value of this type");
1813 $$ = Constant::getNullValue(Ty);
1817 | IntType ESINT64VAL { // integral constants
1818 if (!ConstantInt::isValueValidForType($1, $2))
1819 GEN_ERROR("Constant value doesn't fit in type");
1820 $$ = ConstantInt::get($1, $2, true);
1823 | IntType ESAPINTVAL { // arbitrary precision integer constants
1824 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1825 if ($2->getBitWidth() > BitWidth) {
1826 GEN_ERROR("Constant value does not fit in type");
1828 $2->sextOrTrunc(BitWidth);
1829 $$ = ConstantInt::get(*$2);
1833 | IntType EUINT64VAL { // integral constants
1834 if (!ConstantInt::isValueValidForType($1, $2))
1835 GEN_ERROR("Constant value doesn't fit in type");
1836 $$ = ConstantInt::get($1, $2, false);
1839 | IntType EUAPINTVAL { // arbitrary precision integer constants
1840 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1841 if ($2->getBitWidth() > BitWidth) {
1842 GEN_ERROR("Constant value does not fit in type");
1844 $2->zextOrTrunc(BitWidth);
1845 $$ = ConstantInt::get(*$2);
1849 | INTTYPE TRUETOK { // Boolean constants
1850 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1851 $$ = ConstantInt::getTrue();
1854 | INTTYPE FALSETOK { // Boolean constants
1855 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1856 $$ = ConstantInt::getFalse();
1859 | FPType FPVAL { // Floating point constants
1860 if (!ConstantFP::isValueValidForType($1, *$2))
1861 GEN_ERROR("Floating point constant invalid for type");
1862 // Lexer has no type info, so builds all float and double FP constants
1863 // as double. Fix this here. Long double is done right.
1864 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1865 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1866 $$ = ConstantFP::get($1, *$2);
1872 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1873 if (!UpRefs.empty())
1874 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1876 const Type *DestTy = $5->get();
1877 if (!CastInst::castIsValid($1, $3, DestTy))
1878 GEN_ERROR("invalid cast opcode for cast from '" +
1879 Val->getType()->getDescription() + "' to '" +
1880 DestTy->getDescription() + "'");
1881 $$ = ConstantExpr::getCast($1, $3, DestTy);
1884 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1885 if (!isa<PointerType>($3->getType()))
1886 GEN_ERROR("GetElementPtr requires a pointer operand");
1889 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
1892 GEN_ERROR("Index list invalid for constant getelementptr");
1894 SmallVector<Constant*, 8> IdxVec;
1895 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1896 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1897 IdxVec.push_back(C);
1899 GEN_ERROR("Indices to constant getelementptr must be constants");
1903 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1906 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1907 if ($3->getType() != Type::Int1Ty)
1908 GEN_ERROR("Select condition must be of boolean type");
1909 if ($5->getType() != $7->getType())
1910 GEN_ERROR("Select operand types must match");
1911 $$ = ConstantExpr::getSelect($3, $5, $7);
1914 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1915 if ($3->getType() != $5->getType())
1916 GEN_ERROR("Binary operator types must match");
1918 $$ = ConstantExpr::get($1, $3, $5);
1920 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1921 if ($3->getType() != $5->getType())
1922 GEN_ERROR("Logical operator types must match");
1923 if (!$3->getType()->isInteger()) {
1924 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1925 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1926 GEN_ERROR("Logical operator requires integral operands");
1928 $$ = ConstantExpr::get($1, $3, $5);
1931 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1932 if ($4->getType() != $6->getType())
1933 GEN_ERROR("icmp operand types must match");
1934 $$ = ConstantExpr::getICmp($2, $4, $6);
1936 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1937 if ($4->getType() != $6->getType())
1938 GEN_ERROR("fcmp operand types must match");
1939 $$ = ConstantExpr::getFCmp($2, $4, $6);
1941 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1942 if (!ExtractElementInst::isValidOperands($3, $5))
1943 GEN_ERROR("Invalid extractelement operands");
1944 $$ = ConstantExpr::getExtractElement($3, $5);
1947 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1948 if (!InsertElementInst::isValidOperands($3, $5, $7))
1949 GEN_ERROR("Invalid insertelement operands");
1950 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1953 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1954 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1955 GEN_ERROR("Invalid shufflevector operands");
1956 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1961 // ConstVector - A list of comma separated constants.
1962 ConstVector : ConstVector ',' ConstVal {
1963 ($$ = $1)->push_back($3);
1967 $$ = new std::vector<Constant*>();
1973 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1974 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1977 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1979 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1980 AliaseeRef : ResultTypes SymbolicValueRef {
1981 const Type* VTy = $1->get();
1982 Value *V = getVal(VTy, $2);
1984 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1986 GEN_ERROR("Aliases can be created only to global values");
1992 | BITCAST '(' AliaseeRef TO Types ')' {
1994 const Type *DestTy = $5->get();
1995 if (!CastInst::castIsValid($1, $3, DestTy))
1996 GEN_ERROR("invalid cast opcode for cast from '" +
1997 Val->getType()->getDescription() + "' to '" +
1998 DestTy->getDescription() + "'");
2000 $$ = ConstantExpr::getCast($1, $3, DestTy);
2005 //===----------------------------------------------------------------------===//
2006 // Rules to match Modules
2007 //===----------------------------------------------------------------------===//
2009 // Module rule: Capture the result of parsing the whole file into a result
2014 $$ = ParserResult = CurModule.CurrentModule;
2015 CurModule.ModuleDone();
2019 $$ = ParserResult = CurModule.CurrentModule;
2020 CurModule.ModuleDone();
2027 | DefinitionList Definition
2031 : DEFINE { CurFun.isDeclare = false; } Function {
2032 CurFun.FunctionDone();
2035 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2038 | MODULE ASM_TOK AsmBlock {
2041 | OptLocalAssign TYPE Types {
2042 if (!UpRefs.empty())
2043 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2044 // Eagerly resolve types. This is not an optimization, this is a
2045 // requirement that is due to the fact that we could have this:
2047 // %list = type { %list * }
2048 // %list = type { %list * } ; repeated type decl
2050 // If types are not resolved eagerly, then the two types will not be
2051 // determined to be the same type!
2053 ResolveTypeTo($1, *$3);
2055 if (!setTypeName(*$3, $1) && !$1) {
2057 // If this is a named type that is not a redefinition, add it to the slot
2059 CurModule.Types.push_back(*$3);
2065 | OptLocalAssign TYPE VOID {
2066 ResolveTypeTo($1, $3);
2068 if (!setTypeName($3, $1) && !$1) {
2070 // If this is a named type that is not a redefinition, add it to the slot
2072 CurModule.Types.push_back($3);
2076 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2078 /* "Externally Visible" Linkage */
2080 GEN_ERROR("Global value initializer is not a constant");
2081 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2082 $2, $4, $5->getType(), $5, $3, $6);
2084 } GlobalVarAttributes {
2087 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2088 ConstVal OptAddrSpace {
2090 GEN_ERROR("Global value initializer is not a constant");
2091 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2093 } GlobalVarAttributes {
2096 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2097 Types OptAddrSpace {
2098 if (!UpRefs.empty())
2099 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2100 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2103 } GlobalVarAttributes {
2107 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2114 GEN_ERROR("Alias name cannot be empty");
2116 Constant* Aliasee = $5;
2118 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2120 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2121 CurModule.CurrentModule);
2122 GA->setVisibility($2);
2123 InsertValue(GA, CurModule.Values);
2126 // If there was a forward reference of this alias, resolve it now.
2130 ID = ValID::createGlobalName(Name);
2132 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2134 if (GlobalValue *FWGV =
2135 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2136 // Replace uses of the fwdref with the actual alias.
2137 FWGV->replaceAllUsesWith(GA);
2138 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2139 GV->eraseFromParent();
2141 cast<Function>(FWGV)->eraseFromParent();
2147 | TARGET TargetDefinition {
2150 | DEPLIBS '=' LibrariesDefinition {
2156 AsmBlock : STRINGCONSTANT {
2157 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2158 if (AsmSoFar.empty())
2159 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2161 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2166 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2167 CurModule.CurrentModule->setTargetTriple(*$3);
2170 | DATALAYOUT '=' STRINGCONSTANT {
2171 CurModule.CurrentModule->setDataLayout(*$3);
2175 LibrariesDefinition : '[' LibList ']';
2177 LibList : LibList ',' STRINGCONSTANT {
2178 CurModule.CurrentModule->addLibrary(*$3);
2183 CurModule.CurrentModule->addLibrary(*$1);
2187 | /* empty: end of list */ {
2192 //===----------------------------------------------------------------------===//
2193 // Rules to match Function Headers
2194 //===----------------------------------------------------------------------===//
2196 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2197 if (!UpRefs.empty())
2198 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2199 if (*$3 == Type::VoidTy)
2200 GEN_ERROR("void typed arguments are invalid");
2201 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2206 | Types OptParamAttrs OptLocalName {
2207 if (!UpRefs.empty())
2208 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2209 if (*$1 == Type::VoidTy)
2210 GEN_ERROR("void typed arguments are invalid");
2211 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2212 $$ = new ArgListType;
2217 ArgList : ArgListH {
2221 | ArgListH ',' DOTDOTDOT {
2223 struct ArgListEntry E;
2224 E.Ty = new PATypeHolder(Type::VoidTy);
2226 E.Attrs = ParamAttr::None;
2231 $$ = new ArgListType;
2232 struct ArgListEntry E;
2233 E.Ty = new PATypeHolder(Type::VoidTy);
2235 E.Attrs = ParamAttr::None;
2244 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2245 OptFuncAttrs OptSection OptAlign OptGC {
2246 std::string FunctionName(*$3);
2247 delete $3; // Free strdup'd memory!
2249 // Check the function result for abstractness if this is a define. We should
2250 // have no abstract types at this point
2251 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2252 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2254 std::vector<const Type*> ParamTypeList;
2255 ParamAttrsVector Attrs;
2256 if ($7 != ParamAttr::None) {
2257 ParamAttrsWithIndex PAWI;
2260 Attrs.push_back(PAWI);
2262 if ($5) { // If there are arguments...
2264 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2265 const Type* Ty = I->Ty->get();
2266 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2267 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2268 ParamTypeList.push_back(Ty);
2269 if (Ty != Type::VoidTy)
2270 if (I->Attrs != ParamAttr::None) {
2271 ParamAttrsWithIndex PAWI;
2273 PAWI.attrs = I->Attrs;
2274 Attrs.push_back(PAWI);
2279 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2280 if (isVarArg) ParamTypeList.pop_back();
2282 const ParamAttrsList *PAL = 0;
2284 PAL = ParamAttrsList::get(Attrs);
2286 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2287 const PointerType *PFT = PointerType::getUnqual(FT);
2291 if (!FunctionName.empty()) {
2292 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2294 ID = ValID::createGlobalID(CurModule.Values.size());
2298 // See if this function was forward referenced. If so, recycle the object.
2299 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2300 // Move the function to the end of the list, from whereever it was
2301 // previously inserted.
2302 Fn = cast<Function>(FWRef);
2303 assert(!Fn->getParamAttrs() && "Forward reference has parameter attributes!");
2304 CurModule.CurrentModule->getFunctionList().remove(Fn);
2305 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2306 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2307 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2308 if (Fn->getFunctionType() != FT ) {
2309 // The existing function doesn't have the same type. This is an overload
2311 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2312 } else if (Fn->getParamAttrs() != PAL) {
2313 // The existing function doesn't have the same parameter attributes.
2314 // This is an overload error.
2315 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2316 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2317 // Neither the existing or the current function is a declaration and they
2318 // have the same name and same type. Clearly this is a redefinition.
2319 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2320 } else if (Fn->isDeclaration()) {
2321 // Make sure to strip off any argument names so we can't get conflicts.
2322 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2326 } else { // Not already defined?
2327 Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2328 CurModule.CurrentModule);
2329 InsertValue(Fn, CurModule.Values);
2332 CurFun.FunctionStart(Fn);
2334 if (CurFun.isDeclare) {
2335 // If we have declaration, always overwrite linkage. This will allow us to
2336 // correctly handle cases, when pointer to function is passed as argument to
2337 // another function.
2338 Fn->setLinkage(CurFun.Linkage);
2339 Fn->setVisibility(CurFun.Visibility);
2341 Fn->setCallingConv($1);
2342 Fn->setParamAttrs(PAL);
2343 Fn->setAlignment($9);
2345 Fn->setSection(*$8);
2349 Fn->setCollector($10->c_str());
2353 // Add all of the arguments we parsed to the function...
2354 if ($5) { // Is null if empty...
2355 if (isVarArg) { // Nuke the last entry
2356 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2357 "Not a varargs marker!");
2358 delete $5->back().Ty;
2359 $5->pop_back(); // Delete the last entry
2361 Function::arg_iterator ArgIt = Fn->arg_begin();
2362 Function::arg_iterator ArgEnd = Fn->arg_end();
2364 for (ArgListType::iterator I = $5->begin();
2365 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2366 delete I->Ty; // Delete the typeholder...
2367 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2373 delete $5; // We're now done with the argument list
2378 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2380 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2381 $$ = CurFun.CurrentFunction;
2383 // Make sure that we keep track of the linkage type even if there was a
2384 // previous "declare".
2386 $$->setVisibility($2);
2389 END : ENDTOK | '}'; // Allow end of '}' to end a function
2391 Function : BasicBlockList END {
2396 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2397 CurFun.CurrentFunction->setLinkage($1);
2398 CurFun.CurrentFunction->setVisibility($2);
2399 $$ = CurFun.CurrentFunction;
2400 CurFun.FunctionDone();
2404 //===----------------------------------------------------------------------===//
2405 // Rules to match Basic Blocks
2406 //===----------------------------------------------------------------------===//
2408 OptSideEffect : /* empty */ {
2417 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2418 $$ = ValID::create($1);
2422 $$ = ValID::create($1);
2425 | FPVAL { // Perhaps it's an FP constant?
2426 $$ = ValID::create($1);
2430 $$ = ValID::create(ConstantInt::getTrue());
2434 $$ = ValID::create(ConstantInt::getFalse());
2438 $$ = ValID::createNull();
2442 $$ = ValID::createUndef();
2445 | ZEROINITIALIZER { // A vector zero constant.
2446 $$ = ValID::createZeroInit();
2449 | '<' ConstVector '>' { // Nonempty unsized packed vector
2450 const Type *ETy = (*$2)[0]->getType();
2451 int NumElements = $2->size();
2453 VectorType* pt = VectorType::get(ETy, NumElements);
2454 PATypeHolder* PTy = new PATypeHolder(
2462 // Verify all elements are correct type!
2463 for (unsigned i = 0; i < $2->size(); i++) {
2464 if (ETy != (*$2)[i]->getType())
2465 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2466 ETy->getDescription() +"' as required!\nIt is of type '" +
2467 (*$2)[i]->getType()->getDescription() + "'.");
2470 $$ = ValID::create(ConstantVector::get(pt, *$2));
2471 delete PTy; delete $2;
2475 $$ = ValID::create($1);
2478 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2479 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2485 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2488 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2489 $$ = ValID::createLocalID($1);
2493 $$ = ValID::createGlobalID($1);
2496 | LocalName { // Is it a named reference...?
2497 $$ = ValID::createLocalName(*$1);
2501 | GlobalName { // Is it a named reference...?
2502 $$ = ValID::createGlobalName(*$1);
2507 // ValueRef - A reference to a definition... either constant or symbolic
2508 ValueRef : SymbolicValueRef | ConstValueRef;
2511 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2512 // type immediately preceeds the value reference, and allows complex constant
2513 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2514 ResolvedVal : Types ValueRef {
2515 if (!UpRefs.empty())
2516 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2517 $$ = getVal(*$1, $2);
2523 BasicBlockList : BasicBlockList BasicBlock {
2527 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2533 // Basic blocks are terminated by branching instructions:
2534 // br, br/cc, switch, ret
2536 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2537 setValueName($3, $2);
2540 $1->getInstList().push_back($3);
2545 InstructionList : InstructionList Inst {
2546 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2547 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2548 if (CI2->getParent() == 0)
2549 $1->getInstList().push_back(CI2);
2550 $1->getInstList().push_back($2);
2554 | /* empty */ { // Empty space between instruction lists
2555 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2558 | LABELSTR { // Labelled (named) basic block
2559 $$ = defineBBVal(ValID::createLocalName(*$1));
2565 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2566 $$ = new ReturnInst($2);
2569 | RET VOID { // Return with no result...
2570 $$ = new ReturnInst();
2573 | BR LABEL ValueRef { // Unconditional Branch...
2574 BasicBlock* tmpBB = getBBVal($3);
2576 $$ = new BranchInst(tmpBB);
2577 } // Conditional Branch...
2578 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2579 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2580 BasicBlock* tmpBBA = getBBVal($6);
2582 BasicBlock* tmpBBB = getBBVal($9);
2584 Value* tmpVal = getVal(Type::Int1Ty, $3);
2586 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2588 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2589 Value* tmpVal = getVal($2, $3);
2591 BasicBlock* tmpBB = getBBVal($6);
2593 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2596 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2598 for (; I != E; ++I) {
2599 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2600 S->addCase(CI, I->second);
2602 GEN_ERROR("Switch case is constant, but not a simple integer");
2607 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2608 Value* tmpVal = getVal($2, $3);
2610 BasicBlock* tmpBB = getBBVal($6);
2612 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2616 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2617 TO LABEL ValueRef UNWIND LABEL ValueRef {
2619 // Handle the short syntax
2620 const PointerType *PFTy = 0;
2621 const FunctionType *Ty = 0;
2622 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2623 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2624 // Pull out the types of all of the arguments...
2625 std::vector<const Type*> ParamTypes;
2626 ParamList::iterator I = $6->begin(), E = $6->end();
2627 for (; I != E; ++I) {
2628 const Type *Ty = I->Val->getType();
2629 if (Ty == Type::VoidTy)
2630 GEN_ERROR("Short call syntax cannot be used with varargs");
2631 ParamTypes.push_back(Ty);
2633 Ty = FunctionType::get($3->get(), ParamTypes, false);
2634 PFTy = PointerType::getUnqual(Ty);
2639 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2641 BasicBlock *Normal = getBBVal($11);
2643 BasicBlock *Except = getBBVal($14);
2646 ParamAttrsVector Attrs;
2647 if ($8 != ParamAttr::None) {
2648 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2649 Attrs.push_back(PAWI);
2652 // Check the arguments
2654 if ($6->empty()) { // Has no arguments?
2655 // Make sure no arguments is a good thing!
2656 if (Ty->getNumParams() != 0)
2657 GEN_ERROR("No arguments passed to a function that "
2658 "expects arguments");
2659 } else { // Has arguments?
2660 // Loop through FunctionType's arguments and ensure they are specified
2662 FunctionType::param_iterator I = Ty->param_begin();
2663 FunctionType::param_iterator E = Ty->param_end();
2664 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2667 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2668 if (ArgI->Val->getType() != *I)
2669 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2670 (*I)->getDescription() + "'");
2671 Args.push_back(ArgI->Val);
2672 if (ArgI->Attrs != ParamAttr::None) {
2673 ParamAttrsWithIndex PAWI;
2675 PAWI.attrs = ArgI->Attrs;
2676 Attrs.push_back(PAWI);
2680 if (Ty->isVarArg()) {
2682 for (; ArgI != ArgE; ++ArgI, ++index) {
2683 Args.push_back(ArgI->Val); // push the remaining varargs
2684 if (ArgI->Attrs != ParamAttr::None) {
2685 ParamAttrsWithIndex PAWI;
2687 PAWI.attrs = ArgI->Attrs;
2688 Attrs.push_back(PAWI);
2691 } else if (I != E || ArgI != ArgE)
2692 GEN_ERROR("Invalid number of parameters detected");
2695 const ParamAttrsList *PAL = 0;
2697 PAL = ParamAttrsList::get(Attrs);
2699 // Create the InvokeInst
2700 InvokeInst *II = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
2701 II->setCallingConv($2);
2702 II->setParamAttrs(PAL);
2708 $$ = new UnwindInst();
2712 $$ = new UnreachableInst();
2718 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2720 Constant *V = cast<Constant>(getExistingVal($2, $3));
2723 GEN_ERROR("May only switch on a constant pool value");
2725 BasicBlock* tmpBB = getBBVal($6);
2727 $$->push_back(std::make_pair(V, tmpBB));
2729 | IntType ConstValueRef ',' LABEL ValueRef {
2730 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2731 Constant *V = cast<Constant>(getExistingVal($1, $2));
2735 GEN_ERROR("May only switch on a constant pool value");
2737 BasicBlock* tmpBB = getBBVal($5);
2739 $$->push_back(std::make_pair(V, tmpBB));
2742 Inst : OptLocalAssign InstVal {
2743 // Is this definition named?? if so, assign the name...
2744 setValueName($2, $1);
2752 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2753 if (!UpRefs.empty())
2754 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2755 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2756 Value* tmpVal = getVal(*$1, $3);
2758 BasicBlock* tmpBB = getBBVal($5);
2760 $$->push_back(std::make_pair(tmpVal, tmpBB));
2763 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2765 Value* tmpVal = getVal($1->front().first->getType(), $4);
2767 BasicBlock* tmpBB = getBBVal($6);
2769 $1->push_back(std::make_pair(tmpVal, tmpBB));
2773 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2774 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2775 if (!UpRefs.empty())
2776 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2777 // Used for call and invoke instructions
2778 $$ = new ParamList();
2779 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
2784 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2785 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2786 // Labels are only valid in ASMs
2787 $$ = new ParamList();
2788 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
2792 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2793 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2794 if (!UpRefs.empty())
2795 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2797 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
2802 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2803 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2805 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
2809 | /*empty*/ { $$ = new ParamList(); };
2811 IndexList // Used for gep instructions and constant expressions
2812 : /*empty*/ { $$ = new std::vector<Value*>(); }
2813 | IndexList ',' ResolvedVal {
2820 OptTailCall : TAIL CALL {
2829 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2830 if (!UpRefs.empty())
2831 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2832 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2833 !isa<VectorType>((*$2).get()))
2835 "Arithmetic operator requires integer, FP, or packed operands");
2836 Value* val1 = getVal(*$2, $3);
2838 Value* val2 = getVal(*$2, $5);
2840 $$ = BinaryOperator::create($1, val1, val2);
2842 GEN_ERROR("binary operator returned null");
2845 | LogicalOps Types ValueRef ',' ValueRef {
2846 if (!UpRefs.empty())
2847 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2848 if (!(*$2)->isInteger()) {
2849 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2850 !cast<VectorType>($2->get())->getElementType()->isInteger())
2851 GEN_ERROR("Logical operator requires integral operands");
2853 Value* tmpVal1 = getVal(*$2, $3);
2855 Value* tmpVal2 = getVal(*$2, $5);
2857 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2859 GEN_ERROR("binary operator returned null");
2862 | ICMP IPredicates Types ValueRef ',' ValueRef {
2863 if (!UpRefs.empty())
2864 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2865 if (isa<VectorType>((*$3).get()))
2866 GEN_ERROR("Vector types not supported by icmp instruction");
2867 Value* tmpVal1 = getVal(*$3, $4);
2869 Value* tmpVal2 = getVal(*$3, $6);
2871 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2873 GEN_ERROR("icmp operator returned null");
2876 | FCMP FPredicates Types ValueRef ',' ValueRef {
2877 if (!UpRefs.empty())
2878 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2879 if (isa<VectorType>((*$3).get()))
2880 GEN_ERROR("Vector types not supported by fcmp instruction");
2881 Value* tmpVal1 = getVal(*$3, $4);
2883 Value* tmpVal2 = getVal(*$3, $6);
2885 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2887 GEN_ERROR("fcmp operator returned null");
2890 | CastOps ResolvedVal TO Types {
2891 if (!UpRefs.empty())
2892 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2894 const Type* DestTy = $4->get();
2895 if (!CastInst::castIsValid($1, Val, DestTy))
2896 GEN_ERROR("invalid cast opcode for cast from '" +
2897 Val->getType()->getDescription() + "' to '" +
2898 DestTy->getDescription() + "'");
2899 $$ = CastInst::create($1, Val, DestTy);
2902 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2903 if ($2->getType() != Type::Int1Ty)
2904 GEN_ERROR("select condition must be boolean");
2905 if ($4->getType() != $6->getType())
2906 GEN_ERROR("select value types should match");
2907 $$ = new SelectInst($2, $4, $6);
2910 | VAARG ResolvedVal ',' Types {
2911 if (!UpRefs.empty())
2912 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2913 $$ = new VAArgInst($2, *$4);
2917 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2918 if (!ExtractElementInst::isValidOperands($2, $4))
2919 GEN_ERROR("Invalid extractelement operands");
2920 $$ = new ExtractElementInst($2, $4);
2923 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2924 if (!InsertElementInst::isValidOperands($2, $4, $6))
2925 GEN_ERROR("Invalid insertelement operands");
2926 $$ = new InsertElementInst($2, $4, $6);
2929 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2930 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2931 GEN_ERROR("Invalid shufflevector operands");
2932 $$ = new ShuffleVectorInst($2, $4, $6);
2936 const Type *Ty = $2->front().first->getType();
2937 if (!Ty->isFirstClassType())
2938 GEN_ERROR("PHI node operands must be of first class type");
2939 $$ = new PHINode(Ty);
2940 ((PHINode*)$$)->reserveOperandSpace($2->size());
2941 while ($2->begin() != $2->end()) {
2942 if ($2->front().first->getType() != Ty)
2943 GEN_ERROR("All elements of a PHI node must be of the same type");
2944 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2947 delete $2; // Free the list...
2950 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
2953 // Handle the short syntax
2954 const PointerType *PFTy = 0;
2955 const FunctionType *Ty = 0;
2956 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2957 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2958 // Pull out the types of all of the arguments...
2959 std::vector<const Type*> ParamTypes;
2960 ParamList::iterator I = $6->begin(), E = $6->end();
2961 for (; I != E; ++I) {
2962 const Type *Ty = I->Val->getType();
2963 if (Ty == Type::VoidTy)
2964 GEN_ERROR("Short call syntax cannot be used with varargs");
2965 ParamTypes.push_back(Ty);
2967 Ty = FunctionType::get($3->get(), ParamTypes, false);
2968 PFTy = PointerType::getUnqual(Ty);
2971 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2974 // Check for call to invalid intrinsic to avoid crashing later.
2975 if (Function *theF = dyn_cast<Function>(V)) {
2976 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2977 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2978 !theF->getIntrinsicID(true))
2979 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
2980 theF->getName() + "'");
2983 // Set up the ParamAttrs for the function
2984 ParamAttrsVector Attrs;
2985 if ($8 != ParamAttr::None) {
2986 ParamAttrsWithIndex PAWI;
2989 Attrs.push_back(PAWI);
2991 // Check the arguments
2993 if ($6->empty()) { // Has no arguments?
2994 // Make sure no arguments is a good thing!
2995 if (Ty->getNumParams() != 0)
2996 GEN_ERROR("No arguments passed to a function that "
2997 "expects arguments");
2998 } else { // Has arguments?
2999 // Loop through FunctionType's arguments and ensure they are specified
3000 // correctly. Also, gather any parameter attributes.
3001 FunctionType::param_iterator I = Ty->param_begin();
3002 FunctionType::param_iterator E = Ty->param_end();
3003 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
3006 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3007 if (ArgI->Val->getType() != *I)
3008 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3009 (*I)->getDescription() + "'");
3010 Args.push_back(ArgI->Val);
3011 if (ArgI->Attrs != ParamAttr::None) {
3012 ParamAttrsWithIndex PAWI;
3014 PAWI.attrs = ArgI->Attrs;
3015 Attrs.push_back(PAWI);
3018 if (Ty->isVarArg()) {
3020 for (; ArgI != ArgE; ++ArgI, ++index) {
3021 Args.push_back(ArgI->Val); // push the remaining varargs
3022 if (ArgI->Attrs != ParamAttr::None) {
3023 ParamAttrsWithIndex PAWI;
3025 PAWI.attrs = ArgI->Attrs;
3026 Attrs.push_back(PAWI);
3029 } else if (I != E || ArgI != ArgE)
3030 GEN_ERROR("Invalid number of parameters detected");
3033 // Finish off the ParamAttrs and check them
3034 const ParamAttrsList *PAL = 0;
3036 PAL = ParamAttrsList::get(Attrs);
3038 // Create the call node
3039 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
3040 CI->setTailCall($1);
3041 CI->setCallingConv($2);
3042 CI->setParamAttrs(PAL);
3053 OptVolatile : VOLATILE {
3064 MemoryInst : MALLOC Types OptCAlign {
3065 if (!UpRefs.empty())
3066 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3067 $$ = new MallocInst(*$2, 0, $3);
3071 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3072 if (!UpRefs.empty())
3073 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3074 Value* tmpVal = getVal($4, $5);
3076 $$ = new MallocInst(*$2, tmpVal, $6);
3079 | ALLOCA Types OptCAlign {
3080 if (!UpRefs.empty())
3081 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3082 $$ = new AllocaInst(*$2, 0, $3);
3086 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3087 if (!UpRefs.empty())
3088 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3089 Value* tmpVal = getVal($4, $5);
3091 $$ = new AllocaInst(*$2, tmpVal, $6);
3094 | FREE ResolvedVal {
3095 if (!isa<PointerType>($2->getType()))
3096 GEN_ERROR("Trying to free nonpointer type " +
3097 $2->getType()->getDescription() + "");
3098 $$ = new FreeInst($2);
3102 | OptVolatile LOAD Types ValueRef OptCAlign {
3103 if (!UpRefs.empty())
3104 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3105 if (!isa<PointerType>($3->get()))
3106 GEN_ERROR("Can't load from nonpointer type: " +
3107 (*$3)->getDescription());
3108 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3109 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3110 (*$3)->getDescription());
3111 Value* tmpVal = getVal(*$3, $4);
3113 $$ = new LoadInst(tmpVal, "", $1, $5);
3116 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3117 if (!UpRefs.empty())
3118 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3119 const PointerType *PT = dyn_cast<PointerType>($5->get());
3121 GEN_ERROR("Can't store to a nonpointer type: " +
3122 (*$5)->getDescription());
3123 const Type *ElTy = PT->getElementType();
3124 if (ElTy != $3->getType())
3125 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3126 "' into space of type '" + ElTy->getDescription() + "'");
3128 Value* tmpVal = getVal(*$5, $6);
3130 $$ = new StoreInst($3, tmpVal, $1, $7);
3133 | GETELEMENTPTR Types ValueRef IndexList {
3134 if (!UpRefs.empty())
3135 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3136 if (!isa<PointerType>($2->get()))
3137 GEN_ERROR("getelementptr insn requires pointer operand");
3139 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
3140 GEN_ERROR("Invalid getelementptr indices for type '" +
3141 (*$2)->getDescription()+ "'");
3142 Value* tmpVal = getVal(*$2, $3);
3144 $$ = new GetElementPtrInst(tmpVal, $4->begin(), $4->end());
3152 // common code from the two 'RunVMAsmParser' functions
3153 static Module* RunParser(Module * M) {
3154 CurModule.CurrentModule = M;
3155 // Check to make sure the parser succeeded
3158 delete ParserResult;
3162 // Emit an error if there are any unresolved types left.
3163 if (!CurModule.LateResolveTypes.empty()) {
3164 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3165 if (DID.Type == ValID::LocalName) {
3166 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3168 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3171 delete ParserResult;
3175 // Emit an error if there are any unresolved values left.
3176 if (!CurModule.LateResolveValues.empty()) {
3177 Value *V = CurModule.LateResolveValues.back();
3178 std::map<Value*, std::pair<ValID, int> >::iterator I =
3179 CurModule.PlaceHolderInfo.find(V);
3181 if (I != CurModule.PlaceHolderInfo.end()) {
3182 ValID &DID = I->second.first;
3183 if (DID.Type == ValID::LocalName) {
3184 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3186 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3189 delete ParserResult;
3194 // Check to make sure that parsing produced a result
3198 // Reset ParserResult variable while saving its value for the result.
3199 Module *Result = ParserResult;
3205 void llvm::GenerateError(const std::string &message, int LineNo) {
3206 if (LineNo == -1) LineNo = LLLgetLineNo();
3207 // TODO: column number in exception
3209 TheParseError->setError(LLLgetFilename(), message, LineNo);
3213 int yyerror(const char *ErrorMsg) {
3214 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3215 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3216 if (yychar != YYEMPTY && yychar != 0) {
3217 errMsg += " while reading token: '";
3218 errMsg += std::string(LLLgetTokenStart(),
3219 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3221 GenerateError(errMsg);