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"
28 #include "llvm/ParamAttrsList.h"
34 // The following is a gross hack. In order to rid the libAsmParser library of
35 // exceptions, we have to have a way of getting the yyparse function to go into
36 // an error situation. So, whenever we want an error to occur, the GenerateError
37 // function (see bottom of file) sets TriggerError. Then, at the end of each
38 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
39 // (a goto) to put YACC in error state. Furthermore, several calls to
40 // GenerateError are made from inside productions and they must simulate the
41 // previous exception behavior by exiting the production immediately. We have
42 // replaced these with the GEN_ERROR macro which calls GeneratError and then
43 // immediately invokes YYERROR. This would be so much cleaner if it was a
44 // recursive descent parser.
45 static bool TriggerError = false;
46 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
47 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
49 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
50 int yylex(); // declaration" of xxx warnings.
54 static Module *ParserResult;
56 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
57 // relating to upreferences in the input stream.
59 //#define DEBUG_UPREFS 1
61 #define UR_OUT(X) cerr << X
66 #define YYERROR_VERBOSE 1
68 static GlobalVariable *CurGV;
71 // This contains info used when building the body of a function. It is
72 // destroyed when the function is completed.
74 typedef std::vector<Value *> ValueList; // Numbered defs
77 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
79 static struct PerModuleInfo {
80 Module *CurrentModule;
81 ValueList Values; // Module level numbered definitions
82 ValueList LateResolveValues;
83 std::vector<PATypeHolder> Types;
84 std::map<ValID, PATypeHolder> LateResolveTypes;
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
96 typedef std::map<std::pair<const PointerType *,
97 ValID>, GlobalValue*> GlobalRefsType;
98 GlobalRefsType GlobalRefs;
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
105 ResolveDefinitions(LateResolveValues);
109 // Check to make sure that all global value forward references have been
112 if (!GlobalRefs.empty()) {
113 std::string UndefinedReferences = "Unresolved global references exist:\n";
115 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
117 UndefinedReferences += " " + I->first.first->getDescription() + " " +
118 I->first.second.getName() + "\n";
120 GenerateError(UndefinedReferences);
124 // Look for intrinsic functions and CallInst that need to be upgraded
125 for (Module::iterator FI = CurrentModule->begin(),
126 FE = CurrentModule->end(); FI != FE; )
127 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
129 Values.clear(); // Clear out function local definitions
134 // GetForwardRefForGlobal - Check to see if there is a forward reference
135 // for this global. If so, remove it from the GlobalRefs map and return it.
136 // If not, just return null.
137 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
138 // Check to see if there is a forward reference to this global variable...
139 // if there is, eliminate it and patch the reference to use the new def'n.
140 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
141 GlobalValue *Ret = 0;
142 if (I != GlobalRefs.end()) {
149 bool TypeIsUnresolved(PATypeHolder* PATy) {
150 // If it isn't abstract, its resolved
151 const Type* Ty = PATy->get();
152 if (!Ty->isAbstract())
154 // Traverse the type looking for abstract types. If it isn't abstract then
155 // we don't need to traverse that leg of the type.
156 std::vector<const Type*> WorkList, SeenList;
157 WorkList.push_back(Ty);
158 while (!WorkList.empty()) {
159 const Type* Ty = WorkList.back();
160 SeenList.push_back(Ty);
162 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
163 // Check to see if this is an unresolved type
164 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
165 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
166 for ( ; I != E; ++I) {
167 if (I->second.get() == OpTy)
170 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
171 const Type* TheTy = SeqTy->getElementType();
172 if (TheTy->isAbstract() && TheTy != Ty) {
173 std::vector<const Type*>::iterator I = SeenList.begin(),
179 WorkList.push_back(TheTy);
181 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
182 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
183 const Type* TheTy = StrTy->getElementType(i);
184 if (TheTy->isAbstract() && TheTy != Ty) {
185 std::vector<const Type*>::iterator I = SeenList.begin(),
191 WorkList.push_back(TheTy);
200 static struct PerFunctionInfo {
201 Function *CurrentFunction; // Pointer to current function being created
203 ValueList Values; // Keep track of #'d definitions
205 ValueList LateResolveValues;
206 bool isDeclare; // Is this function a forward declararation?
207 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
208 GlobalValue::VisibilityTypes Visibility;
210 /// BBForwardRefs - When we see forward references to basic blocks, keep
211 /// track of them here.
212 std::map<ValID, BasicBlock*> BBForwardRefs;
214 inline PerFunctionInfo() {
217 Linkage = GlobalValue::ExternalLinkage;
218 Visibility = GlobalValue::DefaultVisibility;
221 inline void FunctionStart(Function *M) {
226 void FunctionDone() {
227 // Any forward referenced blocks left?
228 if (!BBForwardRefs.empty()) {
229 GenerateError("Undefined reference to label " +
230 BBForwardRefs.begin()->second->getName());
234 // Resolve all forward references now.
235 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
237 Values.clear(); // Clear out function local definitions
238 BBForwardRefs.clear();
241 Linkage = GlobalValue::ExternalLinkage;
242 Visibility = GlobalValue::DefaultVisibility;
244 } CurFun; // Info for the current function...
246 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
249 //===----------------------------------------------------------------------===//
250 // Code to handle definitions of all the types
251 //===----------------------------------------------------------------------===//
253 static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
254 // Things that have names or are void typed don't get slot numbers
255 if (V->hasName() || (V->getType() == Type::VoidTy))
258 // In the case of function values, we have to allow for the forward reference
259 // of basic blocks, which are included in the numbering. Consequently, we keep
260 // track of the next insertion location with NextValNum. When a BB gets
261 // inserted, it could change the size of the CurFun.Values vector.
262 if (&ValueTab == &CurFun.Values) {
263 if (ValueTab.size() <= CurFun.NextValNum)
264 ValueTab.resize(CurFun.NextValNum+1);
265 ValueTab[CurFun.NextValNum++] = V;
268 // For all other lists, its okay to just tack it on the back of the vector.
269 ValueTab.push_back(V);
272 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
274 case ValID::LocalID: // Is it a numbered definition?
275 // Module constants occupy the lowest numbered slots...
276 if (D.Num < CurModule.Types.size())
277 return CurModule.Types[D.Num];
279 case ValID::LocalName: // Is it a named definition?
280 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
281 D.destroy(); // Free old strdup'd memory...
286 GenerateError("Internal parser error: Invalid symbol type reference");
290 // If we reached here, we referenced either a symbol that we don't know about
291 // or an id number that hasn't been read yet. We may be referencing something
292 // forward, so just create an entry to be resolved later and get to it...
294 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
297 if (inFunctionScope()) {
298 if (D.Type == ValID::LocalName) {
299 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
302 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
307 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
308 if (I != CurModule.LateResolveTypes.end())
311 Type *Typ = OpaqueType::get();
312 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
316 // getExistingVal - Look up the value specified by the provided type and
317 // the provided ValID. If the value exists and has already been defined, return
318 // it. Otherwise return null.
320 static Value *getExistingVal(const Type *Ty, const ValID &D) {
321 if (isa<FunctionType>(Ty)) {
322 GenerateError("Functions are not values and "
323 "must be referenced as pointers");
328 case ValID::LocalID: { // Is it a numbered definition?
329 // Check that the number is within bounds.
330 if (D.Num >= CurFun.Values.size())
332 Value *Result = CurFun.Values[D.Num];
333 if (Ty != Result->getType()) {
334 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
335 Result->getType()->getDescription() + "' does not match "
336 "expected type, '" + Ty->getDescription() + "'");
341 case ValID::GlobalID: { // Is it a numbered definition?
342 if (D.Num >= CurModule.Values.size())
344 Value *Result = CurModule.Values[D.Num];
345 if (Ty != Result->getType()) {
346 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
347 Result->getType()->getDescription() + "' does not match "
348 "expected type, '" + Ty->getDescription() + "'");
354 case ValID::LocalName: { // Is it a named definition?
355 if (!inFunctionScope())
357 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
358 Value *N = SymTab.lookup(D.getName());
361 if (N->getType() != Ty)
364 D.destroy(); // Free old strdup'd memory...
367 case ValID::GlobalName: { // Is it a named definition?
368 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
369 Value *N = SymTab.lookup(D.getName());
372 if (N->getType() != Ty)
375 D.destroy(); // Free old strdup'd memory...
379 // Check to make sure that "Ty" is an integral type, and that our
380 // value will fit into the specified type...
381 case ValID::ConstSIntVal: // Is it a constant pool reference??
382 if (!isa<IntegerType>(Ty) ||
383 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
384 GenerateError("Signed integral constant '" +
385 itostr(D.ConstPool64) + "' is invalid for type '" +
386 Ty->getDescription() + "'");
389 return ConstantInt::get(Ty, D.ConstPool64, true);
391 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
392 if (isa<IntegerType>(Ty) &&
393 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
394 return ConstantInt::get(Ty, D.UConstPool64);
396 if (!isa<IntegerType>(Ty) ||
397 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
398 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
399 "' is invalid or out of range for type '" +
400 Ty->getDescription() + "'");
403 // This is really a signed reference. Transmogrify.
404 return ConstantInt::get(Ty, D.ConstPool64, true);
406 case ValID::ConstFPVal: // Is it a floating point const pool reference?
407 if (!Ty->isFloatingPoint() ||
408 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
409 GenerateError("FP constant invalid for type");
412 // Lexer has no type info, so builds all float and double FP constants
413 // as double. Fix this here. Long double does not need this.
414 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
416 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
417 return ConstantFP::get(Ty, *D.ConstPoolFP);
419 case ValID::ConstNullVal: // Is it a null value?
420 if (!isa<PointerType>(Ty)) {
421 GenerateError("Cannot create a a non pointer null");
424 return ConstantPointerNull::get(cast<PointerType>(Ty));
426 case ValID::ConstUndefVal: // Is it an undef value?
427 return UndefValue::get(Ty);
429 case ValID::ConstZeroVal: // Is it a zero value?
430 return Constant::getNullValue(Ty);
432 case ValID::ConstantVal: // Fully resolved constant?
433 if (D.ConstantValue->getType() != Ty) {
434 GenerateError("Constant expression type different from required type");
437 return D.ConstantValue;
439 case ValID::InlineAsmVal: { // Inline asm expression
440 const PointerType *PTy = dyn_cast<PointerType>(Ty);
441 const FunctionType *FTy =
442 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
443 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
444 GenerateError("Invalid type for asm constraint string");
447 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
448 D.IAD->HasSideEffects);
449 D.destroy(); // Free InlineAsmDescriptor.
453 assert(0 && "Unhandled case!");
457 assert(0 && "Unhandled case!");
461 // getVal - This function is identical to getExistingVal, except that if a
462 // value is not already defined, it "improvises" by creating a placeholder var
463 // that looks and acts just like the requested variable. When the value is
464 // defined later, all uses of the placeholder variable are replaced with the
467 static Value *getVal(const Type *Ty, const ValID &ID) {
468 if (Ty == Type::LabelTy) {
469 GenerateError("Cannot use a basic block here");
473 // See if the value has already been defined.
474 Value *V = getExistingVal(Ty, ID);
476 if (TriggerError) return 0;
478 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
479 GenerateError("Invalid use of a composite type");
483 // If we reached here, we referenced either a symbol that we don't know about
484 // or an id number that hasn't been read yet. We may be referencing something
485 // forward, so just create an entry to be resolved later and get to it...
488 case ValID::GlobalName:
489 case ValID::GlobalID: {
490 const PointerType *PTy = dyn_cast<PointerType>(Ty);
492 GenerateError("Invalid type for reference to global" );
495 const Type* ElTy = PTy->getElementType();
496 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
497 V = new Function(FTy, GlobalValue::ExternalLinkage);
499 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
500 (Module*)0, false, PTy->getAddressSpace());
504 V = new Argument(Ty);
507 // Remember where this forward reference came from. FIXME, shouldn't we try
508 // to recycle these things??
509 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
512 if (inFunctionScope())
513 InsertValue(V, CurFun.LateResolveValues);
515 InsertValue(V, CurModule.LateResolveValues);
519 /// defineBBVal - This is a definition of a new basic block with the specified
520 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
521 static BasicBlock *defineBBVal(const ValID &ID, BasicBlock *unwindDest) {
522 assert(inFunctionScope() && "Can't get basic block at global scope!");
526 // First, see if this was forward referenced
528 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
529 if (BBI != CurFun.BBForwardRefs.end()) {
531 // The forward declaration could have been inserted anywhere in the
532 // function: insert it into the correct place now.
533 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
534 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
536 // We're about to erase the entry, save the key so we can clean it up.
537 ValID Tmp = BBI->first;
539 // Erase the forward ref from the map as its no longer "forward"
540 CurFun.BBForwardRefs.erase(ID);
542 // The key has been removed from the map but so we don't want to leave
543 // strdup'd memory around so destroy it too.
546 // If its a numbered definition, bump the number and set the BB value.
547 if (ID.Type == ValID::LocalID) {
548 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
552 // We haven't seen this BB before and its first mention is a definition.
553 // Just create it and return it.
554 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
555 BB = new BasicBlock(Name, CurFun.CurrentFunction);
556 if (ID.Type == ValID::LocalID) {
557 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
563 BB->setUnwindDest(unwindDest);
567 /// getBBVal - get an existing BB value or create a forward reference for it.
569 static BasicBlock *getBBVal(const ValID &ID) {
570 assert(inFunctionScope() && "Can't get basic block at global scope!");
574 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
575 if (BBI != CurFun.BBForwardRefs.end()) {
577 } if (ID.Type == ValID::LocalName) {
578 std::string Name = ID.getName();
579 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
581 if (N->getType()->getTypeID() == Type::LabelTyID)
582 BB = cast<BasicBlock>(N);
584 GenerateError("Reference to label '" + Name + "' is actually of type '"+
585 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;
977 llvm::ParameterAttributes ParamAttrs;
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 %type <ValueList> ReturnedVal
1027 // Tokens and types for handling constant integer values
1029 // ESINT64VAL - A negative number within long long range
1030 %token <SInt64Val> ESINT64VAL
1032 // EUINT64VAL - A positive number within uns. long long range
1033 %token <UInt64Val> EUINT64VAL
1035 // ESAPINTVAL - A negative number with arbitrary precision
1036 %token <APIntVal> ESAPINTVAL
1038 // EUAPINTVAL - A positive number with arbitrary precision
1039 %token <APIntVal> EUAPINTVAL
1041 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1042 %token <FPVal> FPVAL // Float or Double constant
1044 // Built in types...
1045 %type <TypeVal> Types ResultTypes
1046 %type <PrimType> IntType FPType PrimType // Classifications
1047 %token <PrimType> VOID INTTYPE
1048 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1052 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1053 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1054 %type <StrVal> LocalName OptLocalName OptLocalAssign
1055 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1056 %type <StrVal> OptSection SectionString OptGC
1058 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1060 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1061 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1062 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1063 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1064 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1065 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1066 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1067 %token DATALAYOUT UNWIND_TO
1068 %type <UIntVal> OptCallingConv
1069 %type <ParamAttrs> OptParamAttrs ParamAttr
1070 %type <ParamAttrs> OptFuncAttrs FuncAttr
1072 // Basic Block Terminating Operators
1073 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1076 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1077 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1078 %token <BinaryOpVal> SHL LSHR ASHR
1080 %token <OtherOpVal> ICMP FCMP
1081 %type <IPredicate> IPredicates
1082 %type <FPredicate> FPredicates
1083 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1084 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1086 // Memory Instructions
1087 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1090 %type <CastOpVal> CastOps
1091 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1092 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1095 %token <OtherOpVal> PHI_TOK SELECT VAARG
1096 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1097 %token <OtherOpVal> GETRESULT
1099 // Function Attributes
1100 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1101 %token READNONE READONLY GC
1103 // Visibility Styles
1104 %token DEFAULT HIDDEN PROTECTED
1110 // Operations that are notably excluded from this list include:
1111 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1113 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1114 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1115 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1116 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1119 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1120 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1121 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1122 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1123 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1127 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1128 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1129 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1130 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1131 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1132 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1133 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1134 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1135 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1138 // These are some types that allow classification if we only want a particular
1139 // thing... for example, only a signed, unsigned, or integral type.
1141 FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1143 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1144 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1146 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1147 | /*empty*/ { $$=0; };
1149 /// OptLocalAssign - Value producing statements have an optional assignment
1151 OptLocalAssign : LocalName '=' {
1160 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1162 OptGlobalAssign : GlobalAssign
1168 GlobalAssign : GlobalName '=' {
1174 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1175 | WEAK { $$ = GlobalValue::WeakLinkage; }
1176 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1177 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1178 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1182 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1183 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1184 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1188 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1189 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1190 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1191 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1194 FunctionDeclareLinkage
1195 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1196 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1197 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1200 FunctionDefineLinkage
1201 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1202 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1203 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1204 | WEAK { $$ = GlobalValue::WeakLinkage; }
1205 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1209 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1210 | WEAK { $$ = GlobalValue::WeakLinkage; }
1211 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1214 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1215 CCC_TOK { $$ = CallingConv::C; } |
1216 FASTCC_TOK { $$ = CallingConv::Fast; } |
1217 COLDCC_TOK { $$ = CallingConv::Cold; } |
1218 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1219 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1221 if ((unsigned)$2 != $2)
1222 GEN_ERROR("Calling conv too large");
1227 ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1228 | ZEXT { $$ = ParamAttr::ZExt; }
1229 | SIGNEXT { $$ = ParamAttr::SExt; }
1230 | SEXT { $$ = ParamAttr::SExt; }
1231 | INREG { $$ = ParamAttr::InReg; }
1232 | SRET { $$ = ParamAttr::StructRet; }
1233 | NOALIAS { $$ = ParamAttr::NoAlias; }
1234 | BYVAL { $$ = ParamAttr::ByVal; }
1235 | NEST { $$ = ParamAttr::Nest; }
1236 | ALIGN EUINT64VAL { $$ =
1237 ParamAttr::constructAlignmentFromInt($2); }
1240 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1241 | OptParamAttrs ParamAttr {
1246 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1247 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1248 | ZEROEXT { $$ = ParamAttr::ZExt; }
1249 | SIGNEXT { $$ = ParamAttr::SExt; }
1250 | READNONE { $$ = ParamAttr::ReadNone; }
1251 | READONLY { $$ = ParamAttr::ReadOnly; }
1254 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1255 | OptFuncAttrs FuncAttr {
1260 OptGC : /* empty */ { $$ = 0; }
1261 | GC STRINGCONSTANT {
1266 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1267 // a comma before it.
1268 OptAlign : /*empty*/ { $$ = 0; } |
1271 if ($$ != 0 && !isPowerOf2_32($$))
1272 GEN_ERROR("Alignment must be a power of two");
1275 OptCAlign : /*empty*/ { $$ = 0; } |
1276 ',' ALIGN EUINT64VAL {
1278 if ($$ != 0 && !isPowerOf2_32($$))
1279 GEN_ERROR("Alignment must be a power of two");
1285 SectionString : SECTION STRINGCONSTANT {
1286 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1287 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1288 GEN_ERROR("Invalid character in section name");
1293 OptSection : /*empty*/ { $$ = 0; } |
1294 SectionString { $$ = $1; };
1296 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1297 // is set to be the global we are processing.
1299 GlobalVarAttributes : /* empty */ {} |
1300 ',' GlobalVarAttribute GlobalVarAttributes {};
1301 GlobalVarAttribute : SectionString {
1302 CurGV->setSection(*$1);
1306 | ALIGN EUINT64VAL {
1307 if ($2 != 0 && !isPowerOf2_32($2))
1308 GEN_ERROR("Alignment must be a power of two");
1309 CurGV->setAlignment($2);
1313 //===----------------------------------------------------------------------===//
1314 // Types includes all predefined types... except void, because it can only be
1315 // used in specific contexts (function returning void for example).
1317 // Derived types are added later...
1319 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1323 $$ = new PATypeHolder(OpaqueType::get());
1327 $$ = new PATypeHolder($1);
1330 | Types OptAddrSpace '*' { // Pointer type?
1331 if (*$1 == Type::LabelTy)
1332 GEN_ERROR("Cannot form a pointer to a basic block");
1333 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1337 | SymbolicValueRef { // Named types are also simple types...
1338 const Type* tmp = getTypeVal($1);
1340 $$ = new PATypeHolder(tmp);
1342 | '\\' EUINT64VAL { // Type UpReference
1343 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1344 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1345 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1346 $$ = new PATypeHolder(OT);
1347 UR_OUT("New Upreference!\n");
1350 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1351 // Allow but ignore attributes on function types; this permits auto-upgrade.
1352 // FIXME: remove in LLVM 3.0.
1353 const Type* RetTy = *$1;
1354 if (!(RetTy->isFirstClassType() || RetTy == Type::VoidTy ||
1355 isa<OpaqueType>(RetTy)))
1356 GEN_ERROR("LLVM Functions cannot return aggregates");
1358 std::vector<const Type*> Params;
1359 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1360 for (; I != E; ++I ) {
1361 const Type *Ty = I->Ty->get();
1362 Params.push_back(Ty);
1365 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1366 if (isVarArg) Params.pop_back();
1368 for (unsigned i = 0; i != Params.size(); ++i)
1369 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1370 GEN_ERROR("Function arguments must be value types!");
1374 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1375 delete $3; // Delete the argument list
1376 delete $1; // Delete the return type handle
1377 $$ = new PATypeHolder(HandleUpRefs(FT));
1380 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1381 // Allow but ignore attributes on function types; this permits auto-upgrade.
1382 // FIXME: remove in LLVM 3.0.
1383 std::vector<const Type*> Params;
1384 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1385 for ( ; I != E; ++I ) {
1386 const Type* Ty = I->Ty->get();
1387 Params.push_back(Ty);
1390 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1391 if (isVarArg) Params.pop_back();
1393 for (unsigned i = 0; i != Params.size(); ++i)
1394 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1395 GEN_ERROR("Function arguments must be value types!");
1399 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1400 delete $3; // Delete the argument list
1401 $$ = new PATypeHolder(HandleUpRefs(FT));
1405 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1406 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1410 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1411 const llvm::Type* ElemTy = $4->get();
1412 if ((unsigned)$2 != $2)
1413 GEN_ERROR("Unsigned result not equal to signed result");
1414 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1415 GEN_ERROR("Element type of a VectorType must be primitive");
1416 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1420 | '{' TypeListI '}' { // Structure type?
1421 std::vector<const Type*> Elements;
1422 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1423 E = $2->end(); I != E; ++I)
1424 Elements.push_back(*I);
1426 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1430 | '{' '}' { // Empty structure type?
1431 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1434 | '<' '{' TypeListI '}' '>' {
1435 std::vector<const Type*> Elements;
1436 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1437 E = $3->end(); I != E; ++I)
1438 Elements.push_back(*I);
1440 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1444 | '<' '{' '}' '>' { // Empty structure type?
1445 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1451 : Types OptParamAttrs {
1452 // Allow but ignore attributes on function types; this permits auto-upgrade.
1453 // FIXME: remove in LLVM 3.0.
1455 $$.Attrs = ParamAttr::None;
1461 if (!UpRefs.empty())
1462 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1463 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1464 GEN_ERROR("LLVM functions cannot return aggregate types");
1468 $$ = new PATypeHolder(Type::VoidTy);
1472 ArgTypeList : ArgType {
1473 $$ = new TypeWithAttrsList();
1477 | ArgTypeList ',' ArgType {
1478 ($$=$1)->push_back($3);
1485 | ArgTypeList ',' DOTDOTDOT {
1487 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1488 TWA.Ty = new PATypeHolder(Type::VoidTy);
1493 $$ = new TypeWithAttrsList;
1494 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1495 TWA.Ty = new PATypeHolder(Type::VoidTy);
1500 $$ = new TypeWithAttrsList();
1504 // TypeList - Used for struct declarations and as a basis for function type
1505 // declaration type lists
1508 $$ = new std::list<PATypeHolder>();
1513 | TypeListI ',' Types {
1514 ($$=$1)->push_back(*$3);
1519 // ConstVal - The various declarations that go into the constant pool. This
1520 // production is used ONLY to represent constants that show up AFTER a 'const',
1521 // 'constant' or 'global' token at global scope. Constants that can be inlined
1522 // into other expressions (such as integers and constexprs) are handled by the
1523 // ResolvedVal, ValueRef and ConstValueRef productions.
1525 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1526 if (!UpRefs.empty())
1527 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1528 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1530 GEN_ERROR("Cannot make array constant with type: '" +
1531 (*$1)->getDescription() + "'");
1532 const Type *ETy = ATy->getElementType();
1533 int NumElements = ATy->getNumElements();
1535 // Verify that we have the correct size...
1536 if (NumElements != -1 && NumElements != (int)$3->size())
1537 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1538 utostr($3->size()) + " arguments, but has size of " +
1539 itostr(NumElements) + "");
1541 // Verify all elements are correct type!
1542 for (unsigned i = 0; i < $3->size(); i++) {
1543 if (ETy != (*$3)[i]->getType())
1544 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1545 ETy->getDescription() +"' as required!\nIt is of type '"+
1546 (*$3)[i]->getType()->getDescription() + "'.");
1549 $$ = ConstantArray::get(ATy, *$3);
1550 delete $1; delete $3;
1554 if (!UpRefs.empty())
1555 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1556 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1558 GEN_ERROR("Cannot make array constant with type: '" +
1559 (*$1)->getDescription() + "'");
1561 int NumElements = ATy->getNumElements();
1562 if (NumElements != -1 && NumElements != 0)
1563 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1564 " arguments, but has size of " + itostr(NumElements) +"");
1565 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1569 | Types 'c' STRINGCONSTANT {
1570 if (!UpRefs.empty())
1571 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1572 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1574 GEN_ERROR("Cannot make array constant with type: '" +
1575 (*$1)->getDescription() + "'");
1577 int NumElements = ATy->getNumElements();
1578 const Type *ETy = ATy->getElementType();
1579 if (NumElements != -1 && NumElements != int($3->length()))
1580 GEN_ERROR("Can't build string constant of size " +
1581 itostr((int)($3->length())) +
1582 " when array has size " + itostr(NumElements) + "");
1583 std::vector<Constant*> Vals;
1584 if (ETy == Type::Int8Ty) {
1585 for (unsigned i = 0; i < $3->length(); ++i)
1586 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1589 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1592 $$ = ConstantArray::get(ATy, Vals);
1596 | Types '<' ConstVector '>' { // Nonempty unsized arr
1597 if (!UpRefs.empty())
1598 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1599 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1601 GEN_ERROR("Cannot make packed constant with type: '" +
1602 (*$1)->getDescription() + "'");
1603 const Type *ETy = PTy->getElementType();
1604 int NumElements = PTy->getNumElements();
1606 // Verify that we have the correct size...
1607 if (NumElements != -1 && NumElements != (int)$3->size())
1608 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1609 utostr($3->size()) + " arguments, but has size of " +
1610 itostr(NumElements) + "");
1612 // Verify all elements are correct type!
1613 for (unsigned i = 0; i < $3->size(); i++) {
1614 if (ETy != (*$3)[i]->getType())
1615 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1616 ETy->getDescription() +"' as required!\nIt is of type '"+
1617 (*$3)[i]->getType()->getDescription() + "'.");
1620 $$ = ConstantVector::get(PTy, *$3);
1621 delete $1; delete $3;
1624 | Types '{' ConstVector '}' {
1625 const StructType *STy = dyn_cast<StructType>($1->get());
1627 GEN_ERROR("Cannot make struct constant with type: '" +
1628 (*$1)->getDescription() + "'");
1630 if ($3->size() != STy->getNumContainedTypes())
1631 GEN_ERROR("Illegal number of initializers for structure type");
1633 // Check to ensure that constants are compatible with the type initializer!
1634 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1635 if ((*$3)[i]->getType() != STy->getElementType(i))
1636 GEN_ERROR("Expected type '" +
1637 STy->getElementType(i)->getDescription() +
1638 "' for element #" + utostr(i) +
1639 " of structure initializer");
1641 // Check to ensure that Type is not packed
1642 if (STy->isPacked())
1643 GEN_ERROR("Unpacked Initializer to vector type '" +
1644 STy->getDescription() + "'");
1646 $$ = ConstantStruct::get(STy, *$3);
1647 delete $1; delete $3;
1651 if (!UpRefs.empty())
1652 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1653 const StructType *STy = dyn_cast<StructType>($1->get());
1655 GEN_ERROR("Cannot make struct constant with type: '" +
1656 (*$1)->getDescription() + "'");
1658 if (STy->getNumContainedTypes() != 0)
1659 GEN_ERROR("Illegal number of initializers for structure type");
1661 // Check to ensure that Type is not packed
1662 if (STy->isPacked())
1663 GEN_ERROR("Unpacked Initializer to vector type '" +
1664 STy->getDescription() + "'");
1666 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1670 | Types '<' '{' ConstVector '}' '>' {
1671 const StructType *STy = dyn_cast<StructType>($1->get());
1673 GEN_ERROR("Cannot make struct constant with type: '" +
1674 (*$1)->getDescription() + "'");
1676 if ($4->size() != STy->getNumContainedTypes())
1677 GEN_ERROR("Illegal number of initializers for structure type");
1679 // Check to ensure that constants are compatible with the type initializer!
1680 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1681 if ((*$4)[i]->getType() != STy->getElementType(i))
1682 GEN_ERROR("Expected type '" +
1683 STy->getElementType(i)->getDescription() +
1684 "' for element #" + utostr(i) +
1685 " of structure initializer");
1687 // Check to ensure that Type is packed
1688 if (!STy->isPacked())
1689 GEN_ERROR("Vector initializer to non-vector type '" +
1690 STy->getDescription() + "'");
1692 $$ = ConstantStruct::get(STy, *$4);
1693 delete $1; delete $4;
1696 | Types '<' '{' '}' '>' {
1697 if (!UpRefs.empty())
1698 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1699 const StructType *STy = dyn_cast<StructType>($1->get());
1701 GEN_ERROR("Cannot make struct constant with type: '" +
1702 (*$1)->getDescription() + "'");
1704 if (STy->getNumContainedTypes() != 0)
1705 GEN_ERROR("Illegal number of initializers for structure type");
1707 // Check to ensure that Type is packed
1708 if (!STy->isPacked())
1709 GEN_ERROR("Vector initializer to non-vector type '" +
1710 STy->getDescription() + "'");
1712 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1717 if (!UpRefs.empty())
1718 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1719 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1721 GEN_ERROR("Cannot make null pointer constant with type: '" +
1722 (*$1)->getDescription() + "'");
1724 $$ = ConstantPointerNull::get(PTy);
1729 if (!UpRefs.empty())
1730 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1731 $$ = UndefValue::get($1->get());
1735 | Types SymbolicValueRef {
1736 if (!UpRefs.empty())
1737 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1738 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1740 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1742 // ConstExprs can exist in the body of a function, thus creating
1743 // GlobalValues whenever they refer to a variable. Because we are in
1744 // the context of a function, getExistingVal will search the functions
1745 // symbol table instead of the module symbol table for the global symbol,
1746 // which throws things all off. To get around this, we just tell
1747 // getExistingVal that we are at global scope here.
1749 Function *SavedCurFn = CurFun.CurrentFunction;
1750 CurFun.CurrentFunction = 0;
1752 Value *V = getExistingVal(Ty, $2);
1755 CurFun.CurrentFunction = SavedCurFn;
1757 // If this is an initializer for a constant pointer, which is referencing a
1758 // (currently) undefined variable, create a stub now that shall be replaced
1759 // in the future with the right type of variable.
1762 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1763 const PointerType *PT = cast<PointerType>(Ty);
1765 // First check to see if the forward references value is already created!
1766 PerModuleInfo::GlobalRefsType::iterator I =
1767 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1769 if (I != CurModule.GlobalRefs.end()) {
1770 V = I->second; // Placeholder already exists, use it...
1774 if ($2.Type == ValID::GlobalName)
1775 Name = $2.getName();
1776 else if ($2.Type != ValID::GlobalID)
1777 GEN_ERROR("Invalid reference to global");
1779 // Create the forward referenced global.
1781 if (const FunctionType *FTy =
1782 dyn_cast<FunctionType>(PT->getElementType())) {
1783 GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1784 CurModule.CurrentModule);
1786 GV = new GlobalVariable(PT->getElementType(), false,
1787 GlobalValue::ExternalWeakLinkage, 0,
1788 Name, CurModule.CurrentModule);
1791 // Keep track of the fact that we have a forward ref to recycle it
1792 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1797 $$ = cast<GlobalValue>(V);
1798 delete $1; // Free the type handle
1802 if (!UpRefs.empty())
1803 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1804 if ($1->get() != $2->getType())
1805 GEN_ERROR("Mismatched types for constant expression: " +
1806 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1811 | Types ZEROINITIALIZER {
1812 if (!UpRefs.empty())
1813 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1814 const Type *Ty = $1->get();
1815 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1816 GEN_ERROR("Cannot create a null initialized value of this type");
1817 $$ = Constant::getNullValue(Ty);
1821 | IntType ESINT64VAL { // integral constants
1822 if (!ConstantInt::isValueValidForType($1, $2))
1823 GEN_ERROR("Constant value doesn't fit in type");
1824 $$ = ConstantInt::get($1, $2, true);
1827 | IntType ESAPINTVAL { // arbitrary precision integer constants
1828 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1829 if ($2->getBitWidth() > BitWidth) {
1830 GEN_ERROR("Constant value does not fit in type");
1832 $2->sextOrTrunc(BitWidth);
1833 $$ = ConstantInt::get(*$2);
1837 | IntType EUINT64VAL { // integral constants
1838 if (!ConstantInt::isValueValidForType($1, $2))
1839 GEN_ERROR("Constant value doesn't fit in type");
1840 $$ = ConstantInt::get($1, $2, false);
1843 | IntType EUAPINTVAL { // arbitrary precision integer constants
1844 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1845 if ($2->getBitWidth() > BitWidth) {
1846 GEN_ERROR("Constant value does not fit in type");
1848 $2->zextOrTrunc(BitWidth);
1849 $$ = ConstantInt::get(*$2);
1853 | INTTYPE TRUETOK { // Boolean constants
1854 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1855 $$ = ConstantInt::getTrue();
1858 | INTTYPE FALSETOK { // Boolean constants
1859 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1860 $$ = ConstantInt::getFalse();
1863 | FPType FPVAL { // Floating point constants
1864 if (!ConstantFP::isValueValidForType($1, *$2))
1865 GEN_ERROR("Floating point constant invalid for type");
1866 // Lexer has no type info, so builds all float and double FP constants
1867 // as double. Fix this here. Long double is done right.
1868 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1869 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1870 $$ = ConstantFP::get($1, *$2);
1876 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1877 if (!UpRefs.empty())
1878 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1880 const Type *DestTy = $5->get();
1881 if (!CastInst::castIsValid($1, $3, DestTy))
1882 GEN_ERROR("invalid cast opcode for cast from '" +
1883 Val->getType()->getDescription() + "' to '" +
1884 DestTy->getDescription() + "'");
1885 $$ = ConstantExpr::getCast($1, $3, DestTy);
1888 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1889 if (!isa<PointerType>($3->getType()))
1890 GEN_ERROR("GetElementPtr requires a pointer operand");
1893 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
1896 GEN_ERROR("Index list invalid for constant getelementptr");
1898 SmallVector<Constant*, 8> IdxVec;
1899 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1900 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1901 IdxVec.push_back(C);
1903 GEN_ERROR("Indices to constant getelementptr must be constants");
1907 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1910 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1911 if ($3->getType() != Type::Int1Ty)
1912 GEN_ERROR("Select condition must be of boolean type");
1913 if ($5->getType() != $7->getType())
1914 GEN_ERROR("Select operand types must match");
1915 $$ = ConstantExpr::getSelect($3, $5, $7);
1918 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1919 if ($3->getType() != $5->getType())
1920 GEN_ERROR("Binary operator types must match");
1922 $$ = ConstantExpr::get($1, $3, $5);
1924 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1925 if ($3->getType() != $5->getType())
1926 GEN_ERROR("Logical operator types must match");
1927 if (!$3->getType()->isInteger()) {
1928 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1929 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1930 GEN_ERROR("Logical operator requires integral operands");
1932 $$ = ConstantExpr::get($1, $3, $5);
1935 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1936 if ($4->getType() != $6->getType())
1937 GEN_ERROR("icmp operand types must match");
1938 $$ = ConstantExpr::getICmp($2, $4, $6);
1940 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1941 if ($4->getType() != $6->getType())
1942 GEN_ERROR("fcmp operand types must match");
1943 $$ = ConstantExpr::getFCmp($2, $4, $6);
1945 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1946 if (!ExtractElementInst::isValidOperands($3, $5))
1947 GEN_ERROR("Invalid extractelement operands");
1948 $$ = ConstantExpr::getExtractElement($3, $5);
1951 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1952 if (!InsertElementInst::isValidOperands($3, $5, $7))
1953 GEN_ERROR("Invalid insertelement operands");
1954 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1957 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1958 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1959 GEN_ERROR("Invalid shufflevector operands");
1960 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1965 // ConstVector - A list of comma separated constants.
1966 ConstVector : ConstVector ',' ConstVal {
1967 ($$ = $1)->push_back($3);
1971 $$ = new std::vector<Constant*>();
1977 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1978 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1981 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1983 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1984 AliaseeRef : ResultTypes SymbolicValueRef {
1985 const Type* VTy = $1->get();
1986 Value *V = getVal(VTy, $2);
1988 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1990 GEN_ERROR("Aliases can be created only to global values");
1996 | BITCAST '(' AliaseeRef TO Types ')' {
1998 const Type *DestTy = $5->get();
1999 if (!CastInst::castIsValid($1, $3, DestTy))
2000 GEN_ERROR("invalid cast opcode for cast from '" +
2001 Val->getType()->getDescription() + "' to '" +
2002 DestTy->getDescription() + "'");
2004 $$ = ConstantExpr::getCast($1, $3, DestTy);
2009 //===----------------------------------------------------------------------===//
2010 // Rules to match Modules
2011 //===----------------------------------------------------------------------===//
2013 // Module rule: Capture the result of parsing the whole file into a result
2018 $$ = ParserResult = CurModule.CurrentModule;
2019 CurModule.ModuleDone();
2023 $$ = ParserResult = CurModule.CurrentModule;
2024 CurModule.ModuleDone();
2031 | DefinitionList Definition
2035 : DEFINE { CurFun.isDeclare = false; } Function {
2036 CurFun.FunctionDone();
2039 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2042 | MODULE ASM_TOK AsmBlock {
2045 | OptLocalAssign TYPE Types {
2046 if (!UpRefs.empty())
2047 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2048 // Eagerly resolve types. This is not an optimization, this is a
2049 // requirement that is due to the fact that we could have this:
2051 // %list = type { %list * }
2052 // %list = type { %list * } ; repeated type decl
2054 // If types are not resolved eagerly, then the two types will not be
2055 // determined to be the same type!
2057 ResolveTypeTo($1, *$3);
2059 if (!setTypeName(*$3, $1) && !$1) {
2061 // If this is a named type that is not a redefinition, add it to the slot
2063 CurModule.Types.push_back(*$3);
2069 | OptLocalAssign TYPE VOID {
2070 ResolveTypeTo($1, $3);
2072 if (!setTypeName($3, $1) && !$1) {
2074 // If this is a named type that is not a redefinition, add it to the slot
2076 CurModule.Types.push_back($3);
2080 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2082 /* "Externally Visible" Linkage */
2084 GEN_ERROR("Global value initializer is not a constant");
2085 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2086 $2, $4, $5->getType(), $5, $3, $6);
2088 } GlobalVarAttributes {
2091 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2092 ConstVal OptAddrSpace {
2094 GEN_ERROR("Global value initializer is not a constant");
2095 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2097 } GlobalVarAttributes {
2100 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2101 Types OptAddrSpace {
2102 if (!UpRefs.empty())
2103 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2104 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2107 } GlobalVarAttributes {
2111 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2118 GEN_ERROR("Alias name cannot be empty");
2120 Constant* Aliasee = $5;
2122 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2124 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2125 CurModule.CurrentModule);
2126 GA->setVisibility($2);
2127 InsertValue(GA, CurModule.Values);
2130 // If there was a forward reference of this alias, resolve it now.
2134 ID = ValID::createGlobalName(Name);
2136 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2138 if (GlobalValue *FWGV =
2139 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2140 // Replace uses of the fwdref with the actual alias.
2141 FWGV->replaceAllUsesWith(GA);
2142 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2143 GV->eraseFromParent();
2145 cast<Function>(FWGV)->eraseFromParent();
2151 | TARGET TargetDefinition {
2154 | DEPLIBS '=' LibrariesDefinition {
2160 AsmBlock : STRINGCONSTANT {
2161 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2162 if (AsmSoFar.empty())
2163 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2165 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2170 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2171 CurModule.CurrentModule->setTargetTriple(*$3);
2174 | DATALAYOUT '=' STRINGCONSTANT {
2175 CurModule.CurrentModule->setDataLayout(*$3);
2179 LibrariesDefinition : '[' LibList ']';
2181 LibList : LibList ',' STRINGCONSTANT {
2182 CurModule.CurrentModule->addLibrary(*$3);
2187 CurModule.CurrentModule->addLibrary(*$1);
2191 | /* empty: end of list */ {
2196 //===----------------------------------------------------------------------===//
2197 // Rules to match Function Headers
2198 //===----------------------------------------------------------------------===//
2200 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2201 if (!UpRefs.empty())
2202 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2203 if (*$3 == Type::VoidTy)
2204 GEN_ERROR("void typed arguments are invalid");
2205 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2210 | Types OptParamAttrs OptLocalName {
2211 if (!UpRefs.empty())
2212 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2213 if (*$1 == Type::VoidTy)
2214 GEN_ERROR("void typed arguments are invalid");
2215 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2216 $$ = new ArgListType;
2221 ArgList : ArgListH {
2225 | ArgListH ',' DOTDOTDOT {
2227 struct ArgListEntry E;
2228 E.Ty = new PATypeHolder(Type::VoidTy);
2230 E.Attrs = ParamAttr::None;
2235 $$ = new ArgListType;
2236 struct ArgListEntry E;
2237 E.Ty = new PATypeHolder(Type::VoidTy);
2239 E.Attrs = ParamAttr::None;
2248 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2249 OptFuncAttrs OptSection OptAlign OptGC {
2250 std::string FunctionName(*$3);
2251 delete $3; // Free strdup'd memory!
2253 // Check the function result for abstractness if this is a define. We should
2254 // have no abstract types at this point
2255 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2256 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2258 std::vector<const Type*> ParamTypeList;
2259 ParamAttrsVector Attrs;
2260 if ($7 != ParamAttr::None) {
2261 ParamAttrsWithIndex PAWI;
2264 Attrs.push_back(PAWI);
2266 if ($5) { // If there are arguments...
2268 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2269 const Type* Ty = I->Ty->get();
2270 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2271 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2272 ParamTypeList.push_back(Ty);
2273 if (Ty != Type::VoidTy)
2274 if (I->Attrs != ParamAttr::None) {
2275 ParamAttrsWithIndex PAWI;
2277 PAWI.attrs = I->Attrs;
2278 Attrs.push_back(PAWI);
2283 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2284 if (isVarArg) ParamTypeList.pop_back();
2286 const ParamAttrsList *PAL = 0;
2288 PAL = ParamAttrsList::get(Attrs);
2290 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2291 const PointerType *PFT = PointerType::getUnqual(FT);
2295 if (!FunctionName.empty()) {
2296 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2298 ID = ValID::createGlobalID(CurModule.Values.size());
2302 // See if this function was forward referenced. If so, recycle the object.
2303 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2304 // Move the function to the end of the list, from whereever it was
2305 // previously inserted.
2306 Fn = cast<Function>(FWRef);
2307 assert(!Fn->getParamAttrs() && "Forward reference has parameter attributes!");
2308 CurModule.CurrentModule->getFunctionList().remove(Fn);
2309 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2310 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2311 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2312 if (Fn->getFunctionType() != FT ) {
2313 // The existing function doesn't have the same type. This is an overload
2315 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2316 } else if (Fn->getParamAttrs() != PAL) {
2317 // The existing function doesn't have the same parameter attributes.
2318 // This is an overload error.
2319 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2320 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2321 // Neither the existing or the current function is a declaration and they
2322 // have the same name and same type. Clearly this is a redefinition.
2323 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2324 } else if (Fn->isDeclaration()) {
2325 // Make sure to strip off any argument names so we can't get conflicts.
2326 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2330 } else { // Not already defined?
2331 Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2332 CurModule.CurrentModule);
2333 InsertValue(Fn, CurModule.Values);
2336 CurFun.FunctionStart(Fn);
2338 if (CurFun.isDeclare) {
2339 // If we have declaration, always overwrite linkage. This will allow us to
2340 // correctly handle cases, when pointer to function is passed as argument to
2341 // another function.
2342 Fn->setLinkage(CurFun.Linkage);
2343 Fn->setVisibility(CurFun.Visibility);
2345 Fn->setCallingConv($1);
2346 Fn->setParamAttrs(PAL);
2347 Fn->setAlignment($9);
2349 Fn->setSection(*$8);
2353 Fn->setCollector($10->c_str());
2357 // Add all of the arguments we parsed to the function...
2358 if ($5) { // Is null if empty...
2359 if (isVarArg) { // Nuke the last entry
2360 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2361 "Not a varargs marker!");
2362 delete $5->back().Ty;
2363 $5->pop_back(); // Delete the last entry
2365 Function::arg_iterator ArgIt = Fn->arg_begin();
2366 Function::arg_iterator ArgEnd = Fn->arg_end();
2368 for (ArgListType::iterator I = $5->begin();
2369 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2370 delete I->Ty; // Delete the typeholder...
2371 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2377 delete $5; // We're now done with the argument list
2382 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2384 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2385 $$ = CurFun.CurrentFunction;
2387 // Make sure that we keep track of the linkage type even if there was a
2388 // previous "declare".
2390 $$->setVisibility($2);
2393 END : ENDTOK | '}'; // Allow end of '}' to end a function
2395 Function : BasicBlockList END {
2400 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2401 CurFun.CurrentFunction->setLinkage($1);
2402 CurFun.CurrentFunction->setVisibility($2);
2403 $$ = CurFun.CurrentFunction;
2404 CurFun.FunctionDone();
2408 //===----------------------------------------------------------------------===//
2409 // Rules to match Basic Blocks
2410 //===----------------------------------------------------------------------===//
2412 OptSideEffect : /* empty */ {
2421 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2422 $$ = ValID::create($1);
2426 $$ = ValID::create($1);
2429 | FPVAL { // Perhaps it's an FP constant?
2430 $$ = ValID::create($1);
2434 $$ = ValID::create(ConstantInt::getTrue());
2438 $$ = ValID::create(ConstantInt::getFalse());
2442 $$ = ValID::createNull();
2446 $$ = ValID::createUndef();
2449 | ZEROINITIALIZER { // A vector zero constant.
2450 $$ = ValID::createZeroInit();
2453 | '<' ConstVector '>' { // Nonempty unsized packed vector
2454 const Type *ETy = (*$2)[0]->getType();
2455 int NumElements = $2->size();
2457 VectorType* pt = VectorType::get(ETy, NumElements);
2458 PATypeHolder* PTy = new PATypeHolder(
2466 // Verify all elements are correct type!
2467 for (unsigned i = 0; i < $2->size(); i++) {
2468 if (ETy != (*$2)[i]->getType())
2469 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2470 ETy->getDescription() +"' as required!\nIt is of type '" +
2471 (*$2)[i]->getType()->getDescription() + "'.");
2474 $$ = ValID::create(ConstantVector::get(pt, *$2));
2475 delete PTy; delete $2;
2479 $$ = ValID::create($1);
2482 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2483 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2489 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2492 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2493 $$ = ValID::createLocalID($1);
2497 $$ = ValID::createGlobalID($1);
2500 | LocalName { // Is it a named reference...?
2501 $$ = ValID::createLocalName(*$1);
2505 | GlobalName { // Is it a named reference...?
2506 $$ = ValID::createGlobalName(*$1);
2511 // ValueRef - A reference to a definition... either constant or symbolic
2512 ValueRef : SymbolicValueRef | ConstValueRef;
2515 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2516 // type immediately preceeds the value reference, and allows complex constant
2517 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2518 ResolvedVal : Types ValueRef {
2519 if (!UpRefs.empty())
2520 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2521 $$ = getVal(*$1, $2);
2527 ReturnedVal : ResolvedVal {
2528 $$ = new std::vector<Value *>();
2532 | ReturnedVal ',' ResolvedVal {
2533 ($$=$1)->push_back($3);
2537 BasicBlockList : BasicBlockList BasicBlock {
2541 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2547 // Basic blocks are terminated by branching instructions:
2548 // br, br/cc, switch, ret
2550 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2551 setValueName($3, $2);
2554 $1->getInstList().push_back($3);
2559 InstructionList : InstructionList Inst {
2560 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2561 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2562 if (CI2->getParent() == 0)
2563 $1->getInstList().push_back(CI2);
2564 $1->getInstList().push_back($2);
2568 | /* empty */ { // Empty space between instruction lists
2569 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum), 0);
2572 | UNWIND_TO ValueRef { // Only the unwind to block
2573 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum), getBBVal($2));
2576 | LABELSTR { // Labelled (named) basic block
2577 $$ = defineBBVal(ValID::createLocalName(*$1), 0);
2581 | LABELSTR UNWIND_TO ValueRef {
2582 $$ = defineBBVal(ValID::createLocalName(*$1), getBBVal($3));
2588 RET ReturnedVal { // Return with a result...
2589 ValueList &VL = *$2;
2590 assert(!VL.empty() && "Invalid ret operands!");
2591 $$ = new ReturnInst(&VL[0], VL.size());
2595 | RET VOID { // Return with no result...
2596 $$ = new ReturnInst();
2599 | BR LABEL ValueRef { // Unconditional Branch...
2600 BasicBlock* tmpBB = getBBVal($3);
2602 $$ = new BranchInst(tmpBB);
2603 } // Conditional Branch...
2604 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2605 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2606 BasicBlock* tmpBBA = getBBVal($6);
2608 BasicBlock* tmpBBB = getBBVal($9);
2610 Value* tmpVal = getVal(Type::Int1Ty, $3);
2612 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2614 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2615 Value* tmpVal = getVal($2, $3);
2617 BasicBlock* tmpBB = getBBVal($6);
2619 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2622 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2624 for (; I != E; ++I) {
2625 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2626 S->addCase(CI, I->second);
2628 GEN_ERROR("Switch case is constant, but not a simple integer");
2633 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2634 Value* tmpVal = getVal($2, $3);
2636 BasicBlock* tmpBB = getBBVal($6);
2638 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2642 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2643 TO LABEL ValueRef UNWIND LABEL ValueRef {
2645 // Handle the short syntax
2646 const PointerType *PFTy = 0;
2647 const FunctionType *Ty = 0;
2648 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2649 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2650 // Pull out the types of all of the arguments...
2651 std::vector<const Type*> ParamTypes;
2652 ParamList::iterator I = $6->begin(), E = $6->end();
2653 for (; I != E; ++I) {
2654 const Type *Ty = I->Val->getType();
2655 if (Ty == Type::VoidTy)
2656 GEN_ERROR("Short call syntax cannot be used with varargs");
2657 ParamTypes.push_back(Ty);
2659 Ty = FunctionType::get($3->get(), ParamTypes, false);
2660 PFTy = PointerType::getUnqual(Ty);
2665 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2667 BasicBlock *Normal = getBBVal($11);
2669 BasicBlock *Except = getBBVal($14);
2672 ParamAttrsVector Attrs;
2673 if ($8 != ParamAttr::None) {
2674 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2675 Attrs.push_back(PAWI);
2678 // Check the arguments
2680 if ($6->empty()) { // Has no arguments?
2681 // Make sure no arguments is a good thing!
2682 if (Ty->getNumParams() != 0)
2683 GEN_ERROR("No arguments passed to a function that "
2684 "expects arguments");
2685 } else { // Has arguments?
2686 // Loop through FunctionType's arguments and ensure they are specified
2688 FunctionType::param_iterator I = Ty->param_begin();
2689 FunctionType::param_iterator E = Ty->param_end();
2690 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2693 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2694 if (ArgI->Val->getType() != *I)
2695 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2696 (*I)->getDescription() + "'");
2697 Args.push_back(ArgI->Val);
2698 if (ArgI->Attrs != ParamAttr::None) {
2699 ParamAttrsWithIndex PAWI;
2701 PAWI.attrs = ArgI->Attrs;
2702 Attrs.push_back(PAWI);
2706 if (Ty->isVarArg()) {
2708 for (; ArgI != ArgE; ++ArgI, ++index) {
2709 Args.push_back(ArgI->Val); // push the remaining varargs
2710 if (ArgI->Attrs != ParamAttr::None) {
2711 ParamAttrsWithIndex PAWI;
2713 PAWI.attrs = ArgI->Attrs;
2714 Attrs.push_back(PAWI);
2717 } else if (I != E || ArgI != ArgE)
2718 GEN_ERROR("Invalid number of parameters detected");
2721 const ParamAttrsList *PAL = 0;
2723 PAL = ParamAttrsList::get(Attrs);
2725 // Create the InvokeInst
2726 InvokeInst *II = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
2727 II->setCallingConv($2);
2728 II->setParamAttrs(PAL);
2734 $$ = new UnwindInst();
2738 $$ = new UnreachableInst();
2744 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2746 Constant *V = cast<Constant>(getExistingVal($2, $3));
2749 GEN_ERROR("May only switch on a constant pool value");
2751 BasicBlock* tmpBB = getBBVal($6);
2753 $$->push_back(std::make_pair(V, tmpBB));
2755 | IntType ConstValueRef ',' LABEL ValueRef {
2756 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2757 Constant *V = cast<Constant>(getExistingVal($1, $2));
2761 GEN_ERROR("May only switch on a constant pool value");
2763 BasicBlock* tmpBB = getBBVal($5);
2765 $$->push_back(std::make_pair(V, tmpBB));
2768 Inst : OptLocalAssign InstVal {
2769 // Is this definition named?? if so, assign the name...
2770 setValueName($2, $1);
2778 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2779 if (!UpRefs.empty())
2780 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2781 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2782 Value* tmpVal = getVal(*$1, $3);
2784 BasicBlock* tmpBB = getBBVal($5);
2786 $$->push_back(std::make_pair(tmpVal, tmpBB));
2789 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2791 Value* tmpVal = getVal($1->front().first->getType(), $4);
2793 BasicBlock* tmpBB = getBBVal($6);
2795 $1->push_back(std::make_pair(tmpVal, tmpBB));
2799 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2800 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2801 if (!UpRefs.empty())
2802 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2803 // Used for call and invoke instructions
2804 $$ = new ParamList();
2805 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
2810 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2811 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2812 // Labels are only valid in ASMs
2813 $$ = new ParamList();
2814 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
2818 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2819 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2820 if (!UpRefs.empty())
2821 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2823 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
2828 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2829 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2831 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
2835 | /*empty*/ { $$ = new ParamList(); };
2837 IndexList // Used for gep instructions and constant expressions
2838 : /*empty*/ { $$ = new std::vector<Value*>(); }
2839 | IndexList ',' ResolvedVal {
2846 OptTailCall : TAIL CALL {
2855 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2856 if (!UpRefs.empty())
2857 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2858 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2859 !isa<VectorType>((*$2).get()))
2861 "Arithmetic operator requires integer, FP, or packed operands");
2862 Value* val1 = getVal(*$2, $3);
2864 Value* val2 = getVal(*$2, $5);
2866 $$ = BinaryOperator::create($1, val1, val2);
2868 GEN_ERROR("binary operator returned null");
2871 | LogicalOps Types ValueRef ',' ValueRef {
2872 if (!UpRefs.empty())
2873 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2874 if (!(*$2)->isInteger()) {
2875 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2876 !cast<VectorType>($2->get())->getElementType()->isInteger())
2877 GEN_ERROR("Logical operator requires integral operands");
2879 Value* tmpVal1 = getVal(*$2, $3);
2881 Value* tmpVal2 = getVal(*$2, $5);
2883 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2885 GEN_ERROR("binary operator returned null");
2888 | ICMP IPredicates Types ValueRef ',' ValueRef {
2889 if (!UpRefs.empty())
2890 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2891 if (isa<VectorType>((*$3).get()))
2892 GEN_ERROR("Vector types not supported by icmp instruction");
2893 Value* tmpVal1 = getVal(*$3, $4);
2895 Value* tmpVal2 = getVal(*$3, $6);
2897 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2899 GEN_ERROR("icmp operator returned null");
2902 | FCMP FPredicates Types ValueRef ',' ValueRef {
2903 if (!UpRefs.empty())
2904 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2905 if (isa<VectorType>((*$3).get()))
2906 GEN_ERROR("Vector types not supported by fcmp instruction");
2907 Value* tmpVal1 = getVal(*$3, $4);
2909 Value* tmpVal2 = getVal(*$3, $6);
2911 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2913 GEN_ERROR("fcmp operator returned null");
2916 | CastOps ResolvedVal TO Types {
2917 if (!UpRefs.empty())
2918 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2920 const Type* DestTy = $4->get();
2921 if (!CastInst::castIsValid($1, Val, DestTy))
2922 GEN_ERROR("invalid cast opcode for cast from '" +
2923 Val->getType()->getDescription() + "' to '" +
2924 DestTy->getDescription() + "'");
2925 $$ = CastInst::create($1, Val, DestTy);
2928 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2929 if ($2->getType() != Type::Int1Ty)
2930 GEN_ERROR("select condition must be boolean");
2931 if ($4->getType() != $6->getType())
2932 GEN_ERROR("select value types should match");
2933 $$ = new SelectInst($2, $4, $6);
2936 | VAARG ResolvedVal ',' Types {
2937 if (!UpRefs.empty())
2938 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2939 $$ = new VAArgInst($2, *$4);
2943 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2944 if (!ExtractElementInst::isValidOperands($2, $4))
2945 GEN_ERROR("Invalid extractelement operands");
2946 $$ = new ExtractElementInst($2, $4);
2949 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2950 if (!InsertElementInst::isValidOperands($2, $4, $6))
2951 GEN_ERROR("Invalid insertelement operands");
2952 $$ = new InsertElementInst($2, $4, $6);
2955 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2956 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2957 GEN_ERROR("Invalid shufflevector operands");
2958 $$ = new ShuffleVectorInst($2, $4, $6);
2962 const Type *Ty = $2->front().first->getType();
2963 if (!Ty->isFirstClassType())
2964 GEN_ERROR("PHI node operands must be of first class type");
2965 $$ = new PHINode(Ty);
2966 ((PHINode*)$$)->reserveOperandSpace($2->size());
2967 while ($2->begin() != $2->end()) {
2968 if ($2->front().first->getType() != Ty)
2969 GEN_ERROR("All elements of a PHI node must be of the same type");
2970 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2973 delete $2; // Free the list...
2976 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
2979 // Handle the short syntax
2980 const PointerType *PFTy = 0;
2981 const FunctionType *Ty = 0;
2982 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2983 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2984 // Pull out the types of all of the arguments...
2985 std::vector<const Type*> ParamTypes;
2986 ParamList::iterator I = $6->begin(), E = $6->end();
2987 for (; I != E; ++I) {
2988 const Type *Ty = I->Val->getType();
2989 if (Ty == Type::VoidTy)
2990 GEN_ERROR("Short call syntax cannot be used with varargs");
2991 ParamTypes.push_back(Ty);
2993 Ty = FunctionType::get($3->get(), ParamTypes, false);
2994 PFTy = PointerType::getUnqual(Ty);
2997 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3000 // Check for call to invalid intrinsic to avoid crashing later.
3001 if (Function *theF = dyn_cast<Function>(V)) {
3002 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3003 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3004 !theF->getIntrinsicID(true))
3005 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3006 theF->getName() + "'");
3009 // Set up the ParamAttrs for the function
3010 ParamAttrsVector Attrs;
3011 if ($8 != ParamAttr::None) {
3012 ParamAttrsWithIndex PAWI;
3015 Attrs.push_back(PAWI);
3017 // Check the arguments
3019 if ($6->empty()) { // Has no arguments?
3020 // Make sure no arguments is a good thing!
3021 if (Ty->getNumParams() != 0)
3022 GEN_ERROR("No arguments passed to a function that "
3023 "expects arguments");
3024 } else { // Has arguments?
3025 // Loop through FunctionType's arguments and ensure they are specified
3026 // correctly. Also, gather any parameter attributes.
3027 FunctionType::param_iterator I = Ty->param_begin();
3028 FunctionType::param_iterator E = Ty->param_end();
3029 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
3032 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3033 if (ArgI->Val->getType() != *I)
3034 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3035 (*I)->getDescription() + "'");
3036 Args.push_back(ArgI->Val);
3037 if (ArgI->Attrs != ParamAttr::None) {
3038 ParamAttrsWithIndex PAWI;
3040 PAWI.attrs = ArgI->Attrs;
3041 Attrs.push_back(PAWI);
3044 if (Ty->isVarArg()) {
3046 for (; ArgI != ArgE; ++ArgI, ++index) {
3047 Args.push_back(ArgI->Val); // push the remaining varargs
3048 if (ArgI->Attrs != ParamAttr::None) {
3049 ParamAttrsWithIndex PAWI;
3051 PAWI.attrs = ArgI->Attrs;
3052 Attrs.push_back(PAWI);
3055 } else if (I != E || ArgI != ArgE)
3056 GEN_ERROR("Invalid number of parameters detected");
3059 // Finish off the ParamAttrs and check them
3060 const ParamAttrsList *PAL = 0;
3062 PAL = ParamAttrsList::get(Attrs);
3064 // Create the call node
3065 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
3066 CI->setTailCall($1);
3067 CI->setCallingConv($2);
3068 CI->setParamAttrs(PAL);
3079 OptVolatile : VOLATILE {
3090 MemoryInst : MALLOC Types OptCAlign {
3091 if (!UpRefs.empty())
3092 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3093 $$ = new MallocInst(*$2, 0, $3);
3097 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3098 if (!UpRefs.empty())
3099 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3100 Value* tmpVal = getVal($4, $5);
3102 $$ = new MallocInst(*$2, tmpVal, $6);
3105 | ALLOCA Types OptCAlign {
3106 if (!UpRefs.empty())
3107 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3108 $$ = new AllocaInst(*$2, 0, $3);
3112 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3113 if (!UpRefs.empty())
3114 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3115 Value* tmpVal = getVal($4, $5);
3117 $$ = new AllocaInst(*$2, tmpVal, $6);
3120 | FREE ResolvedVal {
3121 if (!isa<PointerType>($2->getType()))
3122 GEN_ERROR("Trying to free nonpointer type " +
3123 $2->getType()->getDescription() + "");
3124 $$ = new FreeInst($2);
3128 | OptVolatile LOAD Types ValueRef OptCAlign {
3129 if (!UpRefs.empty())
3130 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3131 if (!isa<PointerType>($3->get()))
3132 GEN_ERROR("Can't load from nonpointer type: " +
3133 (*$3)->getDescription());
3134 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3135 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3136 (*$3)->getDescription());
3137 Value* tmpVal = getVal(*$3, $4);
3139 $$ = new LoadInst(tmpVal, "", $1, $5);
3142 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3143 if (!UpRefs.empty())
3144 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3145 const PointerType *PT = dyn_cast<PointerType>($5->get());
3147 GEN_ERROR("Can't store to a nonpointer type: " +
3148 (*$5)->getDescription());
3149 const Type *ElTy = PT->getElementType();
3150 if (ElTy != $3->getType())
3151 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3152 "' into space of type '" + ElTy->getDescription() + "'");
3154 Value* tmpVal = getVal(*$5, $6);
3156 $$ = new StoreInst($3, tmpVal, $1, $7);
3159 | GETRESULT Types SymbolicValueRef ',' EUINT64VAL {
3160 Value *TmpVal = getVal($2->get(), $3);
3161 if (!GetResultInst::isValidOperands(TmpVal, $5))
3162 GEN_ERROR("Invalid getresult operands");
3163 $$ = new GetResultInst(TmpVal, $5);
3167 | GETELEMENTPTR Types ValueRef IndexList {
3168 if (!UpRefs.empty())
3169 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3170 if (!isa<PointerType>($2->get()))
3171 GEN_ERROR("getelementptr insn requires pointer operand");
3173 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
3174 GEN_ERROR("Invalid getelementptr indices for type '" +
3175 (*$2)->getDescription()+ "'");
3176 Value* tmpVal = getVal(*$2, $3);
3178 $$ = new GetElementPtrInst(tmpVal, $4->begin(), $4->end());
3186 // common code from the two 'RunVMAsmParser' functions
3187 static Module* RunParser(Module * M) {
3188 CurModule.CurrentModule = M;
3189 // Check to make sure the parser succeeded
3192 delete ParserResult;
3196 // Emit an error if there are any unresolved types left.
3197 if (!CurModule.LateResolveTypes.empty()) {
3198 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3199 if (DID.Type == ValID::LocalName) {
3200 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3202 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3205 delete ParserResult;
3209 // Emit an error if there are any unresolved values left.
3210 if (!CurModule.LateResolveValues.empty()) {
3211 Value *V = CurModule.LateResolveValues.back();
3212 std::map<Value*, std::pair<ValID, int> >::iterator I =
3213 CurModule.PlaceHolderInfo.find(V);
3215 if (I != CurModule.PlaceHolderInfo.end()) {
3216 ValID &DID = I->second.first;
3217 if (DID.Type == ValID::LocalName) {
3218 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3220 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3223 delete ParserResult;
3228 // Check to make sure that parsing produced a result
3232 // Reset ParserResult variable while saving its value for the result.
3233 Module *Result = ParserResult;
3239 void llvm::GenerateError(const std::string &message, int LineNo) {
3240 if (LineNo == -1) LineNo = LLLgetLineNo();
3241 // TODO: column number in exception
3243 TheParseError->setError(LLLgetFilename(), message, LineNo);
3247 int yyerror(const char *ErrorMsg) {
3248 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3249 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3250 if (yychar != YYEMPTY && yychar != 0) {
3251 errMsg += " while reading token: '";
3252 errMsg += std::string(LLLgetTokenStart(),
3253 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3255 GenerateError(errMsg);