1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
33 // The following is a gross hack. In order to rid the libAsmParser library of
34 // exceptions, we have to have a way of getting the yyparse function to go into
35 // an error situation. So, whenever we want an error to occur, the GenerateError
36 // function (see bottom of file) sets TriggerError. Then, at the end of each
37 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
38 // (a goto) to put YACC in error state. Furthermore, several calls to
39 // GenerateError are made from inside productions and they must simulate the
40 // previous exception behavior by exiting the production immediately. We have
41 // replaced these with the GEN_ERROR macro which calls GeneratError and then
42 // immediately invokes YYERROR. This would be so much cleaner if it was a
43 // recursive descent parser.
44 static bool TriggerError = false;
45 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
48 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49 int yylex(); // declaration" of xxx warnings.
53 static Module *ParserResult;
55 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56 // relating to upreferences in the input stream.
58 //#define DEBUG_UPREFS 1
60 #define UR_OUT(X) cerr << X
65 #define YYERROR_VERBOSE 1
67 static GlobalVariable *CurGV;
70 // This contains info used when building the body of a function. It is
71 // destroyed when the function is completed.
73 typedef std::vector<Value *> ValueList; // Numbered defs
76 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
78 static struct PerModuleInfo {
79 Module *CurrentModule;
80 ValueList Values; // Module level numbered definitions
81 ValueList LateResolveValues;
82 std::vector<PATypeHolder> Types;
83 std::map<ValID, PATypeHolder> LateResolveTypes;
85 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86 /// how they were referenced and on which line of the input they came from so
87 /// that we can resolve them later and print error messages as appropriate.
88 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
90 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91 // references to global values. Global values may be referenced before they
92 // are defined, and if so, the temporary object that they represent is held
93 // here. This is used for forward references of GlobalValues.
95 typedef std::map<std::pair<const PointerType *,
96 ValID>, GlobalValue*> GlobalRefsType;
97 GlobalRefsType GlobalRefs;
100 // If we could not resolve some functions at function compilation time
101 // (calls to functions before they are defined), resolve them now... Types
102 // are resolved when the constant pool has been completely parsed.
104 ResolveDefinitions(LateResolveValues);
108 // Check to make sure that all global value forward references have been
111 if (!GlobalRefs.empty()) {
112 std::string UndefinedReferences = "Unresolved global references exist:\n";
114 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
116 UndefinedReferences += " " + I->first.first->getDescription() + " " +
117 I->first.second.getName() + "\n";
119 GenerateError(UndefinedReferences);
123 // Look for intrinsic functions and CallInst that need to be upgraded
124 for (Module::iterator FI = CurrentModule->begin(),
125 FE = CurrentModule->end(); FI != FE; )
126 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
128 Values.clear(); // Clear out function local definitions
133 // GetForwardRefForGlobal - Check to see if there is a forward reference
134 // for this global. If so, remove it from the GlobalRefs map and return it.
135 // If not, just return null.
136 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
137 // Check to see if there is a forward reference to this global variable...
138 // if there is, eliminate it and patch the reference to use the new def'n.
139 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
140 GlobalValue *Ret = 0;
141 if (I != GlobalRefs.end()) {
148 bool TypeIsUnresolved(PATypeHolder* PATy) {
149 // If it isn't abstract, its resolved
150 const Type* Ty = PATy->get();
151 if (!Ty->isAbstract())
153 // Traverse the type looking for abstract types. If it isn't abstract then
154 // we don't need to traverse that leg of the type.
155 std::vector<const Type*> WorkList, SeenList;
156 WorkList.push_back(Ty);
157 while (!WorkList.empty()) {
158 const Type* Ty = WorkList.back();
159 SeenList.push_back(Ty);
161 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
162 // Check to see if this is an unresolved type
163 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
164 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
165 for ( ; I != E; ++I) {
166 if (I->second.get() == OpTy)
169 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
170 const Type* TheTy = SeqTy->getElementType();
171 if (TheTy->isAbstract() && TheTy != Ty) {
172 std::vector<const Type*>::iterator I = SeenList.begin(),
178 WorkList.push_back(TheTy);
180 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
181 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
182 const Type* TheTy = StrTy->getElementType(i);
183 if (TheTy->isAbstract() && TheTy != Ty) {
184 std::vector<const Type*>::iterator I = SeenList.begin(),
190 WorkList.push_back(TheTy);
199 static struct PerFunctionInfo {
200 Function *CurrentFunction; // Pointer to current function being created
202 ValueList Values; // Keep track of #'d definitions
204 ValueList LateResolveValues;
205 bool isDeclare; // Is this function a forward declararation?
206 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
207 GlobalValue::VisibilityTypes Visibility;
209 /// BBForwardRefs - When we see forward references to basic blocks, keep
210 /// track of them here.
211 std::map<ValID, BasicBlock*> BBForwardRefs;
213 inline PerFunctionInfo() {
216 Linkage = GlobalValue::ExternalLinkage;
217 Visibility = GlobalValue::DefaultVisibility;
220 inline void FunctionStart(Function *M) {
225 void FunctionDone() {
226 // Any forward referenced blocks left?
227 if (!BBForwardRefs.empty()) {
228 GenerateError("Undefined reference to label " +
229 BBForwardRefs.begin()->second->getName());
233 // Resolve all forward references now.
234 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
236 Values.clear(); // Clear out function local definitions
237 BBForwardRefs.clear();
240 Linkage = GlobalValue::ExternalLinkage;
241 Visibility = GlobalValue::DefaultVisibility;
243 } CurFun; // Info for the current function...
245 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
248 //===----------------------------------------------------------------------===//
249 // Code to handle definitions of all the types
250 //===----------------------------------------------------------------------===//
252 static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
253 // Things that have names or are void typed don't get slot numbers
254 if (V->hasName() || (V->getType() == Type::VoidTy))
257 // In the case of function values, we have to allow for the forward reference
258 // of basic blocks, which are included in the numbering. Consequently, we keep
259 // track of the next insertion location with NextValNum. When a BB gets
260 // inserted, it could change the size of the CurFun.Values vector.
261 if (&ValueTab == &CurFun.Values) {
262 if (ValueTab.size() <= CurFun.NextValNum)
263 ValueTab.resize(CurFun.NextValNum+1);
264 ValueTab[CurFun.NextValNum++] = V;
267 // For all other lists, its okay to just tack it on the back of the vector.
268 ValueTab.push_back(V);
271 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
273 case ValID::LocalID: // Is it a numbered definition?
274 // Module constants occupy the lowest numbered slots...
275 if (D.Num < CurModule.Types.size())
276 return CurModule.Types[D.Num];
278 case ValID::LocalName: // Is it a named definition?
279 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
280 D.destroy(); // Free old strdup'd memory...
285 GenerateError("Internal parser error: Invalid symbol type reference");
289 // If we reached here, we referenced either a symbol that we don't know about
290 // or an id number that hasn't been read yet. We may be referencing something
291 // forward, so just create an entry to be resolved later and get to it...
293 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
296 if (inFunctionScope()) {
297 if (D.Type == ValID::LocalName) {
298 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
301 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
306 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
307 if (I != CurModule.LateResolveTypes.end())
310 Type *Typ = OpaqueType::get();
311 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
315 // getExistingVal - Look up the value specified by the provided type and
316 // the provided ValID. If the value exists and has already been defined, return
317 // it. Otherwise return null.
319 static Value *getExistingVal(const Type *Ty, const ValID &D) {
320 if (isa<FunctionType>(Ty)) {
321 GenerateError("Functions are not values and "
322 "must be referenced as pointers");
327 case ValID::LocalID: { // Is it a numbered definition?
328 // Check that the number is within bounds.
329 if (D.Num >= CurFun.Values.size())
331 Value *Result = CurFun.Values[D.Num];
332 if (Ty != Result->getType()) {
333 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
334 Result->getType()->getDescription() + "' does not match "
335 "expected type, '" + Ty->getDescription() + "'");
340 case ValID::GlobalID: { // Is it a numbered definition?
341 if (D.Num >= CurModule.Values.size())
343 Value *Result = CurModule.Values[D.Num];
344 if (Ty != Result->getType()) {
345 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
346 Result->getType()->getDescription() + "' does not match "
347 "expected type, '" + Ty->getDescription() + "'");
353 case ValID::LocalName: { // Is it a named definition?
354 if (!inFunctionScope())
356 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
357 Value *N = SymTab.lookup(D.getName());
360 if (N->getType() != Ty)
363 D.destroy(); // Free old strdup'd memory...
366 case ValID::GlobalName: { // Is it a named definition?
367 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
368 Value *N = SymTab.lookup(D.getName());
371 if (N->getType() != Ty)
374 D.destroy(); // Free old strdup'd memory...
378 // Check to make sure that "Ty" is an integral type, and that our
379 // value will fit into the specified type...
380 case ValID::ConstSIntVal: // Is it a constant pool reference??
381 if (!isa<IntegerType>(Ty) ||
382 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
383 GenerateError("Signed integral constant '" +
384 itostr(D.ConstPool64) + "' is invalid for type '" +
385 Ty->getDescription() + "'");
388 return ConstantInt::get(Ty, D.ConstPool64, true);
390 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
391 if (isa<IntegerType>(Ty) &&
392 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
393 return ConstantInt::get(Ty, D.UConstPool64);
395 if (!isa<IntegerType>(Ty) ||
396 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
397 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
398 "' is invalid or out of range for type '" +
399 Ty->getDescription() + "'");
402 // This is really a signed reference. Transmogrify.
403 return ConstantInt::get(Ty, D.ConstPool64, true);
405 case ValID::ConstAPInt: // Is it an unsigned const pool reference?
406 if (!isa<IntegerType>(Ty)) {
407 GenerateError("Integral constant '" + D.getName() +
408 "' is invalid or out of range for type '" +
409 Ty->getDescription() + "'");
414 APSInt Tmp = *D.ConstPoolInt;
415 Tmp.extOrTrunc(Ty->getPrimitiveSizeInBits());
416 return ConstantInt::get(Tmp);
419 case ValID::ConstFPVal: // Is it a floating point const pool reference?
420 if (!Ty->isFloatingPoint() ||
421 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
422 GenerateError("FP constant invalid for type");
425 // Lexer has no type info, so builds all float and double FP constants
426 // as double. Fix this here. Long double does not need this.
427 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
429 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
430 return ConstantFP::get(*D.ConstPoolFP);
432 case ValID::ConstNullVal: // Is it a null value?
433 if (!isa<PointerType>(Ty)) {
434 GenerateError("Cannot create a a non pointer null");
437 return ConstantPointerNull::get(cast<PointerType>(Ty));
439 case ValID::ConstUndefVal: // Is it an undef value?
440 return UndefValue::get(Ty);
442 case ValID::ConstZeroVal: // Is it a zero value?
443 return Constant::getNullValue(Ty);
445 case ValID::ConstantVal: // Fully resolved constant?
446 if (D.ConstantValue->getType() != Ty) {
447 GenerateError("Constant expression type different from required type");
450 return D.ConstantValue;
452 case ValID::InlineAsmVal: { // Inline asm expression
453 const PointerType *PTy = dyn_cast<PointerType>(Ty);
454 const FunctionType *FTy =
455 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
456 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
457 GenerateError("Invalid type for asm constraint string");
460 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
461 D.IAD->HasSideEffects);
462 D.destroy(); // Free InlineAsmDescriptor.
466 assert(0 && "Unhandled case!");
470 assert(0 && "Unhandled case!");
474 // getVal - This function is identical to getExistingVal, except that if a
475 // value is not already defined, it "improvises" by creating a placeholder var
476 // that looks and acts just like the requested variable. When the value is
477 // defined later, all uses of the placeholder variable are replaced with the
480 static Value *getVal(const Type *Ty, const ValID &ID) {
481 if (Ty == Type::LabelTy) {
482 GenerateError("Cannot use a basic block here");
486 // See if the value has already been defined.
487 Value *V = getExistingVal(Ty, ID);
489 if (TriggerError) return 0;
491 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
492 GenerateError("Invalid use of a non-first-class type");
496 // If we reached here, we referenced either a symbol that we don't know about
497 // or an id number that hasn't been read yet. We may be referencing something
498 // forward, so just create an entry to be resolved later and get to it...
501 case ValID::GlobalName:
502 case ValID::GlobalID: {
503 const PointerType *PTy = dyn_cast<PointerType>(Ty);
505 GenerateError("Invalid type for reference to global" );
508 const Type* ElTy = PTy->getElementType();
509 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
510 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
512 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
513 (Module*)0, false, PTy->getAddressSpace());
517 V = new Argument(Ty);
520 // Remember where this forward reference came from. FIXME, shouldn't we try
521 // to recycle these things??
522 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
525 if (inFunctionScope())
526 InsertValue(V, CurFun.LateResolveValues);
528 InsertValue(V, CurModule.LateResolveValues);
532 /// defineBBVal - This is a definition of a new basic block with the specified
533 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
534 static BasicBlock *defineBBVal(const ValID &ID) {
535 assert(inFunctionScope() && "Can't get basic block at global scope!");
539 // First, see if this was forward referenced
541 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
542 if (BBI != CurFun.BBForwardRefs.end()) {
544 // The forward declaration could have been inserted anywhere in the
545 // function: insert it into the correct place now.
546 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
547 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
549 // We're about to erase the entry, save the key so we can clean it up.
550 ValID Tmp = BBI->first;
552 // Erase the forward ref from the map as its no longer "forward"
553 CurFun.BBForwardRefs.erase(ID);
555 // The key has been removed from the map but so we don't want to leave
556 // strdup'd memory around so destroy it too.
559 // If its a numbered definition, bump the number and set the BB value.
560 if (ID.Type == ValID::LocalID) {
561 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
565 // We haven't seen this BB before and its first mention is a definition.
566 // Just create it and return it.
567 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
568 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
569 if (ID.Type == ValID::LocalID) {
570 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
579 /// getBBVal - get an existing BB value or create a forward reference for it.
581 static BasicBlock *getBBVal(const ValID &ID) {
582 assert(inFunctionScope() && "Can't get basic block at global scope!");
586 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
587 if (BBI != CurFun.BBForwardRefs.end()) {
589 } if (ID.Type == ValID::LocalName) {
590 std::string Name = ID.getName();
591 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
593 if (N->getType()->getTypeID() == Type::LabelTyID)
594 BB = cast<BasicBlock>(N);
596 GenerateError("Reference to label '" + Name + "' is actually of type '"+
597 N->getType()->getDescription() + "'");
599 } else if (ID.Type == ValID::LocalID) {
600 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
601 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
602 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
604 GenerateError("Reference to label '%" + utostr(ID.Num) +
605 "' is actually of type '"+
606 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
609 GenerateError("Illegal label reference " + ID.getName());
613 // If its already been defined, return it now.
615 ID.destroy(); // Free strdup'd memory.
619 // Otherwise, this block has not been seen before, create it.
621 if (ID.Type == ValID::LocalName)
623 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
625 // Insert it in the forward refs map.
626 CurFun.BBForwardRefs[ID] = BB;
632 //===----------------------------------------------------------------------===//
633 // Code to handle forward references in instructions
634 //===----------------------------------------------------------------------===//
636 // This code handles the late binding needed with statements that reference
637 // values not defined yet... for example, a forward branch, or the PHI node for
640 // This keeps a table (CurFun.LateResolveValues) of all such forward references
641 // and back patchs after we are done.
644 // ResolveDefinitions - If we could not resolve some defs at parsing
645 // time (forward branches, phi functions for loops, etc...) resolve the
649 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
650 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
651 while (!LateResolvers.empty()) {
652 Value *V = LateResolvers.back();
653 LateResolvers.pop_back();
655 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
656 CurModule.PlaceHolderInfo.find(V);
657 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
659 ValID &DID = PHI->second.first;
661 Value *TheRealValue = getExistingVal(V->getType(), DID);
665 V->replaceAllUsesWith(TheRealValue);
667 CurModule.PlaceHolderInfo.erase(PHI);
668 } else if (FutureLateResolvers) {
669 // Functions have their unresolved items forwarded to the module late
671 InsertValue(V, *FutureLateResolvers);
673 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
674 GenerateError("Reference to an invalid definition: '" +DID.getName()+
675 "' of type '" + V->getType()->getDescription() + "'",
679 GenerateError("Reference to an invalid definition: #" +
680 itostr(DID.Num) + " of type '" +
681 V->getType()->getDescription() + "'",
687 LateResolvers.clear();
690 // ResolveTypeTo - A brand new type was just declared. This means that (if
691 // name is not null) things referencing Name can be resolved. Otherwise, things
692 // refering to the number can be resolved. Do this now.
694 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
697 D = ValID::createLocalName(*Name);
699 D = ValID::createLocalID(CurModule.Types.size());
701 std::map<ValID, PATypeHolder>::iterator I =
702 CurModule.LateResolveTypes.find(D);
703 if (I != CurModule.LateResolveTypes.end()) {
704 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
705 CurModule.LateResolveTypes.erase(I);
709 // setValueName - Set the specified value to the name given. The name may be
710 // null potentially, in which case this is a noop. The string passed in is
711 // assumed to be a malloc'd string buffer, and is free'd by this function.
713 static void setValueName(Value *V, std::string *NameStr) {
714 if (!NameStr) return;
715 std::string Name(*NameStr); // Copy string
716 delete NameStr; // Free old string
718 if (V->getType() == Type::VoidTy) {
719 GenerateError("Can't assign name '" + Name+"' to value with void type");
723 assert(inFunctionScope() && "Must be in function scope!");
724 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
725 if (ST.lookup(Name)) {
726 GenerateError("Redefinition of value '" + Name + "' of type '" +
727 V->getType()->getDescription() + "'");
735 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
736 /// this is a declaration, otherwise it is a definition.
737 static GlobalVariable *
738 ParseGlobalVariable(std::string *NameStr,
739 GlobalValue::LinkageTypes Linkage,
740 GlobalValue::VisibilityTypes Visibility,
741 bool isConstantGlobal, const Type *Ty,
742 Constant *Initializer, bool IsThreadLocal,
743 unsigned AddressSpace = 0) {
744 if (isa<FunctionType>(Ty)) {
745 GenerateError("Cannot declare global vars of function type");
748 if (Ty == Type::LabelTy) {
749 GenerateError("Cannot declare global vars of label type");
753 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
757 Name = *NameStr; // Copy string
758 delete NameStr; // Free old string
761 // See if this global value was forward referenced. If so, recycle the
765 ID = ValID::createGlobalName(Name);
767 ID = ValID::createGlobalID(CurModule.Values.size());
770 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
771 // Move the global to the end of the list, from whereever it was
772 // previously inserted.
773 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
774 CurModule.CurrentModule->getGlobalList().remove(GV);
775 CurModule.CurrentModule->getGlobalList().push_back(GV);
776 GV->setInitializer(Initializer);
777 GV->setLinkage(Linkage);
778 GV->setVisibility(Visibility);
779 GV->setConstant(isConstantGlobal);
780 GV->setThreadLocal(IsThreadLocal);
781 InsertValue(GV, CurModule.Values);
785 // If this global has a name
787 // if the global we're parsing has an initializer (is a definition) and
788 // has external linkage.
789 if (Initializer && Linkage != GlobalValue::InternalLinkage)
790 // If there is already a global with external linkage with this name
791 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
792 // If we allow this GVar to get created, it will be renamed in the
793 // symbol table because it conflicts with an existing GVar. We can't
794 // allow redefinition of GVars whose linking indicates that their name
795 // must stay the same. Issue the error.
796 GenerateError("Redefinition of global variable named '" + Name +
797 "' of type '" + Ty->getDescription() + "'");
802 // Otherwise there is no existing GV to use, create one now.
804 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
805 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
806 GV->setVisibility(Visibility);
807 InsertValue(GV, CurModule.Values);
811 // setTypeName - Set the specified type to the name given. The name may be
812 // null potentially, in which case this is a noop. The string passed in is
813 // assumed to be a malloc'd string buffer, and is freed by this function.
815 // This function returns true if the type has already been defined, but is
816 // allowed to be redefined in the specified context. If the name is a new name
817 // for the type plane, it is inserted and false is returned.
818 static bool setTypeName(const Type *T, std::string *NameStr) {
819 assert(!inFunctionScope() && "Can't give types function-local names!");
820 if (NameStr == 0) return false;
822 std::string Name(*NameStr); // Copy string
823 delete NameStr; // Free old string
825 // We don't allow assigning names to void type
826 if (T == Type::VoidTy) {
827 GenerateError("Can't assign name '" + Name + "' to the void type");
831 // Set the type name, checking for conflicts as we do so.
832 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
834 if (AlreadyExists) { // Inserting a name that is already defined???
835 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
836 assert(Existing && "Conflict but no matching type?!");
838 // There is only one case where this is allowed: when we are refining an
839 // opaque type. In this case, Existing will be an opaque type.
840 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
841 // We ARE replacing an opaque type!
842 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
846 // Otherwise, this is an attempt to redefine a type. That's okay if
847 // the redefinition is identical to the original. This will be so if
848 // Existing and T point to the same Type object. In this one case we
849 // allow the equivalent redefinition.
850 if (Existing == T) return true; // Yes, it's equal.
852 // Any other kind of (non-equivalent) redefinition is an error.
853 GenerateError("Redefinition of type named '" + Name + "' of type '" +
854 T->getDescription() + "'");
860 //===----------------------------------------------------------------------===//
861 // Code for handling upreferences in type names...
864 // TypeContains - Returns true if Ty directly contains E in it.
866 static bool TypeContains(const Type *Ty, const Type *E) {
867 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
868 E) != Ty->subtype_end();
873 // NestingLevel - The number of nesting levels that need to be popped before
874 // this type is resolved.
875 unsigned NestingLevel;
877 // LastContainedTy - This is the type at the current binding level for the
878 // type. Every time we reduce the nesting level, this gets updated.
879 const Type *LastContainedTy;
881 // UpRefTy - This is the actual opaque type that the upreference is
885 UpRefRecord(unsigned NL, OpaqueType *URTy)
886 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
890 // UpRefs - A list of the outstanding upreferences that need to be resolved.
891 static std::vector<UpRefRecord> UpRefs;
893 /// HandleUpRefs - Every time we finish a new layer of types, this function is
894 /// called. It loops through the UpRefs vector, which is a list of the
895 /// currently active types. For each type, if the up reference is contained in
896 /// the newly completed type, we decrement the level count. When the level
897 /// count reaches zero, the upreferenced type is the type that is passed in:
898 /// thus we can complete the cycle.
900 static PATypeHolder HandleUpRefs(const Type *ty) {
901 // If Ty isn't abstract, or if there are no up-references in it, then there is
902 // nothing to resolve here.
903 if (!ty->isAbstract() || UpRefs.empty()) return ty;
906 UR_OUT("Type '" << Ty->getDescription() <<
907 "' newly formed. Resolving upreferences.\n" <<
908 UpRefs.size() << " upreferences active!\n");
910 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
911 // to zero), we resolve them all together before we resolve them to Ty. At
912 // the end of the loop, if there is anything to resolve to Ty, it will be in
914 OpaqueType *TypeToResolve = 0;
916 for (unsigned i = 0; i != UpRefs.size(); ++i) {
917 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
918 << UpRefs[i].second->getDescription() << ") = "
919 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
920 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
921 // Decrement level of upreference
922 unsigned Level = --UpRefs[i].NestingLevel;
923 UpRefs[i].LastContainedTy = Ty;
924 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
925 if (Level == 0) { // Upreference should be resolved!
926 if (!TypeToResolve) {
927 TypeToResolve = UpRefs[i].UpRefTy;
929 UR_OUT(" * Resolving upreference for "
930 << UpRefs[i].second->getDescription() << "\n";
931 std::string OldName = UpRefs[i].UpRefTy->getDescription());
932 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
933 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
934 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
936 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
937 --i; // Do not skip the next element...
943 UR_OUT(" * Resolving upreference for "
944 << UpRefs[i].second->getDescription() << "\n";
945 std::string OldName = TypeToResolve->getDescription());
946 TypeToResolve->refineAbstractTypeTo(Ty);
952 //===----------------------------------------------------------------------===//
953 // RunVMAsmParser - Define an interface to this parser
954 //===----------------------------------------------------------------------===//
956 static Module* RunParser(Module * M);
958 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
960 Module *M = RunParser(new Module(LLLgetFilename()));
968 llvm::Module *ModuleVal;
969 llvm::Function *FunctionVal;
970 llvm::BasicBlock *BasicBlockVal;
971 llvm::TerminatorInst *TermInstVal;
972 llvm::Instruction *InstVal;
973 llvm::Constant *ConstVal;
975 const llvm::Type *PrimType;
976 std::list<llvm::PATypeHolder> *TypeList;
977 llvm::PATypeHolder *TypeVal;
978 llvm::Value *ValueVal;
979 std::vector<llvm::Value*> *ValueList;
980 std::vector<unsigned> *ConstantList;
981 llvm::ArgListType *ArgList;
982 llvm::TypeWithAttrs TypeWithAttrs;
983 llvm::TypeWithAttrsList *TypeWithAttrsList;
984 llvm::ParamList *ParamList;
986 // Represent the RHS of PHI node
987 std::list<std::pair<llvm::Value*,
988 llvm::BasicBlock*> > *PHIList;
989 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
990 std::vector<llvm::Constant*> *ConstVector;
992 llvm::GlobalValue::LinkageTypes Linkage;
993 llvm::GlobalValue::VisibilityTypes Visibility;
994 llvm::ParameterAttributes ParamAttrs;
995 llvm::APInt *APIntVal;
1000 llvm::APFloat *FPVal;
1003 std::string *StrVal; // This memory must be deleted
1004 llvm::ValID ValIDVal;
1006 llvm::Instruction::BinaryOps BinaryOpVal;
1007 llvm::Instruction::TermOps TermOpVal;
1008 llvm::Instruction::MemoryOps MemOpVal;
1009 llvm::Instruction::CastOps CastOpVal;
1010 llvm::Instruction::OtherOps OtherOpVal;
1011 llvm::ICmpInst::Predicate IPredicate;
1012 llvm::FCmpInst::Predicate FPredicate;
1015 %type <ModuleVal> Module
1016 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1017 %type <BasicBlockVal> BasicBlock InstructionList
1018 %type <TermInstVal> BBTerminatorInst
1019 %type <InstVal> Inst InstVal MemoryInst
1020 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1021 %type <ConstVector> ConstVector
1022 %type <ArgList> ArgList ArgListH
1023 %type <PHIList> PHIList
1024 %type <ParamList> ParamList // For call param lists & GEP indices
1025 %type <ValueList> IndexList // For GEP indices
1026 %type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
1027 %type <TypeList> TypeListI
1028 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1029 %type <TypeWithAttrs> ArgType
1030 %type <JumpTable> JumpTable
1031 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1032 %type <BoolVal> ThreadLocal // 'thread_local' or not
1033 %type <BoolVal> OptVolatile // 'volatile' or not
1034 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1035 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1036 %type <Linkage> GVInternalLinkage GVExternalLinkage
1037 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1038 %type <Linkage> AliasLinkage
1039 %type <Visibility> GVVisibilityStyle
1041 // ValueRef - Unresolved reference to a definition or BB
1042 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1043 %type <ValueVal> ResolvedVal // <type> <valref> pair
1044 %type <ValueList> ReturnedVal
1045 // Tokens and types for handling constant integer values
1047 // ESINT64VAL - A negative number within long long range
1048 %token <SInt64Val> ESINT64VAL
1050 // EUINT64VAL - A positive number within uns. long long range
1051 %token <UInt64Val> EUINT64VAL
1053 // ESAPINTVAL - A negative number with arbitrary precision
1054 %token <APIntVal> ESAPINTVAL
1056 // EUAPINTVAL - A positive number with arbitrary precision
1057 %token <APIntVal> EUAPINTVAL
1059 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1060 %token <FPVal> FPVAL // Float or Double constant
1062 // Built in types...
1063 %type <TypeVal> Types ResultTypes
1064 %type <PrimType> IntType FPType PrimType // Classifications
1065 %token <PrimType> VOID INTTYPE
1066 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1070 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1071 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1072 %type <StrVal> LocalName OptLocalName OptLocalAssign
1073 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1074 %type <StrVal> OptSection SectionString OptGC
1076 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1078 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1079 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1080 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1081 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1082 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1083 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1084 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1086 %type <UIntVal> OptCallingConv
1087 %type <ParamAttrs> OptParamAttrs ParamAttr
1088 %type <ParamAttrs> OptFuncAttrs FuncAttr
1090 // Basic Block Terminating Operators
1091 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1094 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1095 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1096 %token <BinaryOpVal> SHL LSHR ASHR
1098 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1099 %type <IPredicate> IPredicates
1100 %type <FPredicate> FPredicates
1101 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1102 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1104 // Memory Instructions
1105 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1108 %type <CastOpVal> CastOps
1109 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1110 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1113 %token <OtherOpVal> PHI_TOK SELECT VAARG
1114 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1115 %token <OtherOpVal> GETRESULT
1116 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1118 // Function Attributes
1119 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1120 %token READNONE READONLY GC
1122 // Visibility Styles
1123 %token DEFAULT HIDDEN PROTECTED
1129 // Operations that are notably excluded from this list include:
1130 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1132 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1133 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1134 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1135 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1138 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1139 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1140 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1141 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1142 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1146 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1147 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1148 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1149 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1150 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1151 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1152 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1153 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1154 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1157 // These are some types that allow classification if we only want a particular
1158 // thing... for example, only a signed, unsigned, or integral type.
1160 FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1162 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1163 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1165 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1166 | /*empty*/ { $$=0; };
1168 /// OptLocalAssign - Value producing statements have an optional assignment
1170 OptLocalAssign : LocalName '=' {
1179 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1181 OptGlobalAssign : GlobalAssign
1187 GlobalAssign : GlobalName '=' {
1193 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1194 | WEAK { $$ = GlobalValue::WeakLinkage; }
1195 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1196 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1197 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1198 | COMMON { $$ = GlobalValue::CommonLinkage; }
1202 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1203 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1204 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1208 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1209 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1210 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1211 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1214 FunctionDeclareLinkage
1215 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1216 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1217 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1220 FunctionDefineLinkage
1221 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1222 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1223 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1224 | WEAK { $$ = GlobalValue::WeakLinkage; }
1225 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1229 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1230 | WEAK { $$ = GlobalValue::WeakLinkage; }
1231 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1234 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1235 CCC_TOK { $$ = CallingConv::C; } |
1236 FASTCC_TOK { $$ = CallingConv::Fast; } |
1237 COLDCC_TOK { $$ = CallingConv::Cold; } |
1238 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1239 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1241 if ((unsigned)$2 != $2)
1242 GEN_ERROR("Calling conv too large");
1247 ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1248 | ZEXT { $$ = ParamAttr::ZExt; }
1249 | SIGNEXT { $$ = ParamAttr::SExt; }
1250 | SEXT { $$ = ParamAttr::SExt; }
1251 | INREG { $$ = ParamAttr::InReg; }
1252 | SRET { $$ = ParamAttr::StructRet; }
1253 | NOALIAS { $$ = ParamAttr::NoAlias; }
1254 | BYVAL { $$ = ParamAttr::ByVal; }
1255 | NEST { $$ = ParamAttr::Nest; }
1256 | ALIGN EUINT64VAL { $$ =
1257 ParamAttr::constructAlignmentFromInt($2); }
1260 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1261 | OptParamAttrs ParamAttr {
1266 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1267 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1268 | ZEROEXT { $$ = ParamAttr::ZExt; }
1269 | SIGNEXT { $$ = ParamAttr::SExt; }
1270 | READNONE { $$ = ParamAttr::ReadNone; }
1271 | READONLY { $$ = ParamAttr::ReadOnly; }
1274 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1275 | OptFuncAttrs FuncAttr {
1280 OptGC : /* empty */ { $$ = 0; }
1281 | GC STRINGCONSTANT {
1286 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1287 // a comma before it.
1288 OptAlign : /*empty*/ { $$ = 0; } |
1291 if ($$ != 0 && !isPowerOf2_32($$))
1292 GEN_ERROR("Alignment must be a power of two");
1295 OptCAlign : /*empty*/ { $$ = 0; } |
1296 ',' ALIGN EUINT64VAL {
1298 if ($$ != 0 && !isPowerOf2_32($$))
1299 GEN_ERROR("Alignment must be a power of two");
1305 SectionString : SECTION STRINGCONSTANT {
1306 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1307 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1308 GEN_ERROR("Invalid character in section name");
1313 OptSection : /*empty*/ { $$ = 0; } |
1314 SectionString { $$ = $1; };
1316 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1317 // is set to be the global we are processing.
1319 GlobalVarAttributes : /* empty */ {} |
1320 ',' GlobalVarAttribute GlobalVarAttributes {};
1321 GlobalVarAttribute : SectionString {
1322 CurGV->setSection(*$1);
1326 | ALIGN EUINT64VAL {
1327 if ($2 != 0 && !isPowerOf2_32($2))
1328 GEN_ERROR("Alignment must be a power of two");
1329 CurGV->setAlignment($2);
1333 //===----------------------------------------------------------------------===//
1334 // Types includes all predefined types... except void, because it can only be
1335 // used in specific contexts (function returning void for example).
1337 // Derived types are added later...
1339 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1343 $$ = new PATypeHolder(OpaqueType::get());
1347 $$ = new PATypeHolder($1);
1350 | Types OptAddrSpace '*' { // Pointer type?
1351 if (*$1 == Type::LabelTy)
1352 GEN_ERROR("Cannot form a pointer to a basic block");
1353 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1357 | SymbolicValueRef { // Named types are also simple types...
1358 const Type* tmp = getTypeVal($1);
1360 $$ = new PATypeHolder(tmp);
1362 | '\\' EUINT64VAL { // Type UpReference
1363 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1364 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1365 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1366 $$ = new PATypeHolder(OT);
1367 UR_OUT("New Upreference!\n");
1370 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1371 // Allow but ignore attributes on function types; this permits auto-upgrade.
1372 // FIXME: remove in LLVM 3.0.
1373 const Type *RetTy = *$1;
1374 if (!FunctionType::isValidReturnType(RetTy))
1375 GEN_ERROR("Invalid result type for LLVM function");
1377 std::vector<const Type*> Params;
1378 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1379 for (; I != E; ++I ) {
1380 const Type *Ty = I->Ty->get();
1381 Params.push_back(Ty);
1384 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1385 if (isVarArg) Params.pop_back();
1387 for (unsigned i = 0; i != Params.size(); ++i)
1388 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1389 GEN_ERROR("Function arguments must be value types!");
1393 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1394 delete $3; // Delete the argument list
1395 delete $1; // Delete the return type handle
1396 $$ = new PATypeHolder(HandleUpRefs(FT));
1399 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1400 // Allow but ignore attributes on function types; this permits auto-upgrade.
1401 // FIXME: remove in LLVM 3.0.
1402 std::vector<const Type*> Params;
1403 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1404 for ( ; I != E; ++I ) {
1405 const Type* Ty = I->Ty->get();
1406 Params.push_back(Ty);
1409 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1410 if (isVarArg) Params.pop_back();
1412 for (unsigned i = 0; i != Params.size(); ++i)
1413 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1414 GEN_ERROR("Function arguments must be value types!");
1418 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1419 delete $3; // Delete the argument list
1420 $$ = new PATypeHolder(HandleUpRefs(FT));
1424 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1425 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1429 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1430 const llvm::Type* ElemTy = $4->get();
1431 if ((unsigned)$2 != $2)
1432 GEN_ERROR("Unsigned result not equal to signed result");
1433 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1434 GEN_ERROR("Element type of a VectorType must be primitive");
1435 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1439 | '{' TypeListI '}' { // Structure type?
1440 std::vector<const Type*> Elements;
1441 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1442 E = $2->end(); I != E; ++I)
1443 Elements.push_back(*I);
1445 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1449 | '{' '}' { // Empty structure type?
1450 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1453 | '<' '{' TypeListI '}' '>' {
1454 std::vector<const Type*> Elements;
1455 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1456 E = $3->end(); I != E; ++I)
1457 Elements.push_back(*I);
1459 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1463 | '<' '{' '}' '>' { // Empty structure type?
1464 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1470 : Types OptParamAttrs {
1471 // Allow but ignore attributes on function types; this permits auto-upgrade.
1472 // FIXME: remove in LLVM 3.0.
1474 $$.Attrs = ParamAttr::None;
1480 if (!UpRefs.empty())
1481 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1482 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1483 GEN_ERROR("LLVM functions cannot return aggregate types");
1487 $$ = new PATypeHolder(Type::VoidTy);
1491 ArgTypeList : ArgType {
1492 $$ = new TypeWithAttrsList();
1496 | ArgTypeList ',' ArgType {
1497 ($$=$1)->push_back($3);
1504 | ArgTypeList ',' DOTDOTDOT {
1506 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1507 TWA.Ty = new PATypeHolder(Type::VoidTy);
1512 $$ = new TypeWithAttrsList;
1513 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1514 TWA.Ty = new PATypeHolder(Type::VoidTy);
1519 $$ = new TypeWithAttrsList();
1523 // TypeList - Used for struct declarations and as a basis for function type
1524 // declaration type lists
1527 $$ = new std::list<PATypeHolder>();
1532 | TypeListI ',' Types {
1533 ($$=$1)->push_back(*$3);
1538 // ConstVal - The various declarations that go into the constant pool. This
1539 // production is used ONLY to represent constants that show up AFTER a 'const',
1540 // 'constant' or 'global' token at global scope. Constants that can be inlined
1541 // into other expressions (such as integers and constexprs) are handled by the
1542 // ResolvedVal, ValueRef and ConstValueRef productions.
1544 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1545 if (!UpRefs.empty())
1546 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1547 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1549 GEN_ERROR("Cannot make array constant with type: '" +
1550 (*$1)->getDescription() + "'");
1551 const Type *ETy = ATy->getElementType();
1552 uint64_t NumElements = ATy->getNumElements();
1554 // Verify that we have the correct size...
1555 if (NumElements != uint64_t(-1) && NumElements != $3->size())
1556 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1557 utostr($3->size()) + " arguments, but has size of " +
1558 utostr(NumElements) + "");
1560 // Verify all elements are correct type!
1561 for (unsigned i = 0; i < $3->size(); i++) {
1562 if (ETy != (*$3)[i]->getType())
1563 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1564 ETy->getDescription() +"' as required!\nIt is of type '"+
1565 (*$3)[i]->getType()->getDescription() + "'.");
1568 $$ = ConstantArray::get(ATy, *$3);
1569 delete $1; delete $3;
1573 if (!UpRefs.empty())
1574 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1575 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1577 GEN_ERROR("Cannot make array constant with type: '" +
1578 (*$1)->getDescription() + "'");
1580 uint64_t NumElements = ATy->getNumElements();
1581 if (NumElements != uint64_t(-1) && NumElements != 0)
1582 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1583 " arguments, but has size of " + utostr(NumElements) +"");
1584 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1588 | Types 'c' STRINGCONSTANT {
1589 if (!UpRefs.empty())
1590 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1591 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1593 GEN_ERROR("Cannot make array constant with type: '" +
1594 (*$1)->getDescription() + "'");
1596 uint64_t NumElements = ATy->getNumElements();
1597 const Type *ETy = ATy->getElementType();
1598 if (NumElements != uint64_t(-1) && NumElements != $3->length())
1599 GEN_ERROR("Can't build string constant of size " +
1600 utostr($3->length()) +
1601 " when array has size " + utostr(NumElements) + "");
1602 std::vector<Constant*> Vals;
1603 if (ETy == Type::Int8Ty) {
1604 for (uint64_t i = 0; i < $3->length(); ++i)
1605 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1608 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1611 $$ = ConstantArray::get(ATy, Vals);
1615 | Types '<' ConstVector '>' { // Nonempty unsized arr
1616 if (!UpRefs.empty())
1617 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1618 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1620 GEN_ERROR("Cannot make packed constant with type: '" +
1621 (*$1)->getDescription() + "'");
1622 const Type *ETy = PTy->getElementType();
1623 unsigned NumElements = PTy->getNumElements();
1625 // Verify that we have the correct size...
1626 if (NumElements != unsigned(-1) && NumElements != (unsigned)$3->size())
1627 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1628 utostr($3->size()) + " arguments, but has size of " +
1629 utostr(NumElements) + "");
1631 // Verify all elements are correct type!
1632 for (unsigned i = 0; i < $3->size(); i++) {
1633 if (ETy != (*$3)[i]->getType())
1634 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1635 ETy->getDescription() +"' as required!\nIt is of type '"+
1636 (*$3)[i]->getType()->getDescription() + "'.");
1639 $$ = ConstantVector::get(PTy, *$3);
1640 delete $1; delete $3;
1643 | Types '{' ConstVector '}' {
1644 const StructType *STy = dyn_cast<StructType>($1->get());
1646 GEN_ERROR("Cannot make struct constant with type: '" +
1647 (*$1)->getDescription() + "'");
1649 if ($3->size() != STy->getNumContainedTypes())
1650 GEN_ERROR("Illegal number of initializers for structure type");
1652 // Check to ensure that constants are compatible with the type initializer!
1653 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1654 if ((*$3)[i]->getType() != STy->getElementType(i))
1655 GEN_ERROR("Expected type '" +
1656 STy->getElementType(i)->getDescription() +
1657 "' for element #" + utostr(i) +
1658 " of structure initializer");
1660 // Check to ensure that Type is not packed
1661 if (STy->isPacked())
1662 GEN_ERROR("Unpacked Initializer to vector type '" +
1663 STy->getDescription() + "'");
1665 $$ = ConstantStruct::get(STy, *$3);
1666 delete $1; delete $3;
1670 if (!UpRefs.empty())
1671 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1672 const StructType *STy = dyn_cast<StructType>($1->get());
1674 GEN_ERROR("Cannot make struct constant with type: '" +
1675 (*$1)->getDescription() + "'");
1677 if (STy->getNumContainedTypes() != 0)
1678 GEN_ERROR("Illegal number of initializers for structure type");
1680 // Check to ensure that Type is not packed
1681 if (STy->isPacked())
1682 GEN_ERROR("Unpacked Initializer to vector type '" +
1683 STy->getDescription() + "'");
1685 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1689 | Types '<' '{' ConstVector '}' '>' {
1690 const StructType *STy = dyn_cast<StructType>($1->get());
1692 GEN_ERROR("Cannot make struct constant with type: '" +
1693 (*$1)->getDescription() + "'");
1695 if ($4->size() != STy->getNumContainedTypes())
1696 GEN_ERROR("Illegal number of initializers for structure type");
1698 // Check to ensure that constants are compatible with the type initializer!
1699 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1700 if ((*$4)[i]->getType() != STy->getElementType(i))
1701 GEN_ERROR("Expected type '" +
1702 STy->getElementType(i)->getDescription() +
1703 "' for element #" + utostr(i) +
1704 " of structure initializer");
1706 // Check to ensure that Type is packed
1707 if (!STy->isPacked())
1708 GEN_ERROR("Vector initializer to non-vector type '" +
1709 STy->getDescription() + "'");
1711 $$ = ConstantStruct::get(STy, *$4);
1712 delete $1; delete $4;
1715 | Types '<' '{' '}' '>' {
1716 if (!UpRefs.empty())
1717 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1718 const StructType *STy = dyn_cast<StructType>($1->get());
1720 GEN_ERROR("Cannot make struct constant with type: '" +
1721 (*$1)->getDescription() + "'");
1723 if (STy->getNumContainedTypes() != 0)
1724 GEN_ERROR("Illegal number of initializers for structure type");
1726 // Check to ensure that Type is packed
1727 if (!STy->isPacked())
1728 GEN_ERROR("Vector initializer to non-vector type '" +
1729 STy->getDescription() + "'");
1731 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1736 if (!UpRefs.empty())
1737 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1738 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1740 GEN_ERROR("Cannot make null pointer constant with type: '" +
1741 (*$1)->getDescription() + "'");
1743 $$ = ConstantPointerNull::get(PTy);
1748 if (!UpRefs.empty())
1749 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1750 $$ = UndefValue::get($1->get());
1754 | Types SymbolicValueRef {
1755 if (!UpRefs.empty())
1756 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1757 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1759 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1761 // ConstExprs can exist in the body of a function, thus creating
1762 // GlobalValues whenever they refer to a variable. Because we are in
1763 // the context of a function, getExistingVal will search the functions
1764 // symbol table instead of the module symbol table for the global symbol,
1765 // which throws things all off. To get around this, we just tell
1766 // getExistingVal that we are at global scope here.
1768 Function *SavedCurFn = CurFun.CurrentFunction;
1769 CurFun.CurrentFunction = 0;
1771 Value *V = getExistingVal(Ty, $2);
1774 CurFun.CurrentFunction = SavedCurFn;
1776 // If this is an initializer for a constant pointer, which is referencing a
1777 // (currently) undefined variable, create a stub now that shall be replaced
1778 // in the future with the right type of variable.
1781 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1782 const PointerType *PT = cast<PointerType>(Ty);
1784 // First check to see if the forward references value is already created!
1785 PerModuleInfo::GlobalRefsType::iterator I =
1786 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1788 if (I != CurModule.GlobalRefs.end()) {
1789 V = I->second; // Placeholder already exists, use it...
1793 if ($2.Type == ValID::GlobalName)
1794 Name = $2.getName();
1795 else if ($2.Type != ValID::GlobalID)
1796 GEN_ERROR("Invalid reference to global");
1798 // Create the forward referenced global.
1800 if (const FunctionType *FTy =
1801 dyn_cast<FunctionType>(PT->getElementType())) {
1802 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1803 CurModule.CurrentModule);
1805 GV = new GlobalVariable(PT->getElementType(), false,
1806 GlobalValue::ExternalWeakLinkage, 0,
1807 Name, CurModule.CurrentModule);
1810 // Keep track of the fact that we have a forward ref to recycle it
1811 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1816 $$ = cast<GlobalValue>(V);
1817 delete $1; // Free the type handle
1821 if (!UpRefs.empty())
1822 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1823 if ($1->get() != $2->getType())
1824 GEN_ERROR("Mismatched types for constant expression: " +
1825 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1830 | Types ZEROINITIALIZER {
1831 if (!UpRefs.empty())
1832 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1833 const Type *Ty = $1->get();
1834 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1835 GEN_ERROR("Cannot create a null initialized value of this type");
1836 $$ = Constant::getNullValue(Ty);
1840 | IntType ESINT64VAL { // integral constants
1841 if (!ConstantInt::isValueValidForType($1, $2))
1842 GEN_ERROR("Constant value doesn't fit in type");
1843 $$ = ConstantInt::get($1, $2, true);
1846 | IntType ESAPINTVAL { // arbitrary precision integer constants
1847 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1848 if ($2->getBitWidth() > BitWidth) {
1849 GEN_ERROR("Constant value does not fit in type");
1851 $2->sextOrTrunc(BitWidth);
1852 $$ = ConstantInt::get(*$2);
1856 | IntType EUINT64VAL { // integral constants
1857 if (!ConstantInt::isValueValidForType($1, $2))
1858 GEN_ERROR("Constant value doesn't fit in type");
1859 $$ = ConstantInt::get($1, $2, false);
1862 | IntType EUAPINTVAL { // arbitrary precision integer constants
1863 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1864 if ($2->getBitWidth() > BitWidth) {
1865 GEN_ERROR("Constant value does not fit in type");
1867 $2->zextOrTrunc(BitWidth);
1868 $$ = ConstantInt::get(*$2);
1872 | INTTYPE TRUETOK { // Boolean constants
1873 if (cast<IntegerType>($1)->getBitWidth() != 1)
1874 GEN_ERROR("Constant true must have type i1");
1875 $$ = ConstantInt::getTrue();
1878 | INTTYPE FALSETOK { // Boolean constants
1879 if (cast<IntegerType>($1)->getBitWidth() != 1)
1880 GEN_ERROR("Constant false must have type i1");
1881 $$ = ConstantInt::getFalse();
1884 | FPType FPVAL { // Floating point constants
1885 if (!ConstantFP::isValueValidForType($1, *$2))
1886 GEN_ERROR("Floating point constant invalid for type");
1887 // Lexer has no type info, so builds all float and double FP constants
1888 // as double. Fix this here. Long double is done right.
1889 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1890 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1891 $$ = ConstantFP::get(*$2);
1897 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1898 if (!UpRefs.empty())
1899 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1901 const Type *DestTy = $5->get();
1902 if (!CastInst::castIsValid($1, $3, DestTy))
1903 GEN_ERROR("invalid cast opcode for cast from '" +
1904 Val->getType()->getDescription() + "' to '" +
1905 DestTy->getDescription() + "'");
1906 $$ = ConstantExpr::getCast($1, $3, DestTy);
1909 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1910 if (!isa<PointerType>($3->getType()))
1911 GEN_ERROR("GetElementPtr requires a pointer operand");
1914 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1916 GEN_ERROR("Index list invalid for constant getelementptr");
1918 SmallVector<Constant*, 8> IdxVec;
1919 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1920 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1921 IdxVec.push_back(C);
1923 GEN_ERROR("Indices to constant getelementptr must be constants");
1927 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1930 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1931 if ($3->getType() != Type::Int1Ty)
1932 GEN_ERROR("Select condition must be of boolean type");
1933 if ($5->getType() != $7->getType())
1934 GEN_ERROR("Select operand types must match");
1935 $$ = ConstantExpr::getSelect($3, $5, $7);
1938 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1939 if ($3->getType() != $5->getType())
1940 GEN_ERROR("Binary operator types must match");
1942 $$ = ConstantExpr::get($1, $3, $5);
1944 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1945 if ($3->getType() != $5->getType())
1946 GEN_ERROR("Logical operator types must match");
1947 if (!$3->getType()->isInteger()) {
1948 if (!isa<VectorType>($3->getType()) ||
1949 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1950 GEN_ERROR("Logical operator requires integral operands");
1952 $$ = ConstantExpr::get($1, $3, $5);
1955 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1956 if ($4->getType() != $6->getType())
1957 GEN_ERROR("icmp operand types must match");
1958 $$ = ConstantExpr::getICmp($2, $4, $6);
1960 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1961 if ($4->getType() != $6->getType())
1962 GEN_ERROR("fcmp operand types must match");
1963 $$ = ConstantExpr::getFCmp($2, $4, $6);
1965 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1966 if ($4->getType() != $6->getType())
1967 GEN_ERROR("vicmp operand types must match");
1968 $$ = ConstantExpr::getVICmp($2, $4, $6);
1970 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1971 if ($4->getType() != $6->getType())
1972 GEN_ERROR("vfcmp operand types must match");
1973 $$ = ConstantExpr::getVFCmp($2, $4, $6);
1975 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1976 if (!ExtractElementInst::isValidOperands($3, $5))
1977 GEN_ERROR("Invalid extractelement operands");
1978 $$ = ConstantExpr::getExtractElement($3, $5);
1981 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1982 if (!InsertElementInst::isValidOperands($3, $5, $7))
1983 GEN_ERROR("Invalid insertelement operands");
1984 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1987 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1988 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1989 GEN_ERROR("Invalid shufflevector operands");
1990 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1993 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
1994 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
1995 GEN_ERROR("ExtractValue requires an aggregate operand");
1997 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
2001 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
2002 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
2003 GEN_ERROR("InsertValue requires an aggregate operand");
2005 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
2011 // ConstVector - A list of comma separated constants.
2012 ConstVector : ConstVector ',' ConstVal {
2013 ($$ = $1)->push_back($3);
2017 $$ = new std::vector<Constant*>();
2023 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2024 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2027 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2029 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2030 AliaseeRef : ResultTypes SymbolicValueRef {
2031 const Type* VTy = $1->get();
2032 Value *V = getVal(VTy, $2);
2034 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2036 GEN_ERROR("Aliases can be created only to global values");
2042 | BITCAST '(' AliaseeRef TO Types ')' {
2044 const Type *DestTy = $5->get();
2045 if (!CastInst::castIsValid($1, $3, DestTy))
2046 GEN_ERROR("invalid cast opcode for cast from '" +
2047 Val->getType()->getDescription() + "' to '" +
2048 DestTy->getDescription() + "'");
2050 $$ = ConstantExpr::getCast($1, $3, DestTy);
2055 //===----------------------------------------------------------------------===//
2056 // Rules to match Modules
2057 //===----------------------------------------------------------------------===//
2059 // Module rule: Capture the result of parsing the whole file into a result
2064 $$ = ParserResult = CurModule.CurrentModule;
2065 CurModule.ModuleDone();
2069 $$ = ParserResult = CurModule.CurrentModule;
2070 CurModule.ModuleDone();
2077 | DefinitionList Definition
2081 : DEFINE { CurFun.isDeclare = false; } Function {
2082 CurFun.FunctionDone();
2085 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2088 | MODULE ASM_TOK AsmBlock {
2091 | OptLocalAssign TYPE Types {
2092 if (!UpRefs.empty())
2093 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2094 // Eagerly resolve types. This is not an optimization, this is a
2095 // requirement that is due to the fact that we could have this:
2097 // %list = type { %list * }
2098 // %list = type { %list * } ; repeated type decl
2100 // If types are not resolved eagerly, then the two types will not be
2101 // determined to be the same type!
2103 ResolveTypeTo($1, *$3);
2105 if (!setTypeName(*$3, $1) && !$1) {
2107 // If this is a named type that is not a redefinition, add it to the slot
2109 CurModule.Types.push_back(*$3);
2115 | OptLocalAssign TYPE VOID {
2116 ResolveTypeTo($1, $3);
2118 if (!setTypeName($3, $1) && !$1) {
2120 // If this is a named type that is not a redefinition, add it to the slot
2122 CurModule.Types.push_back($3);
2126 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2128 /* "Externally Visible" Linkage */
2130 GEN_ERROR("Global value initializer is not a constant");
2131 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2132 $2, $4, $5->getType(), $5, $3, $6);
2134 } GlobalVarAttributes {
2137 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2138 ConstVal OptAddrSpace {
2140 GEN_ERROR("Global value initializer is not a constant");
2141 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2143 } GlobalVarAttributes {
2146 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2147 Types OptAddrSpace {
2148 if (!UpRefs.empty())
2149 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2150 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2153 } GlobalVarAttributes {
2157 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2164 GEN_ERROR("Alias name cannot be empty");
2166 Constant* Aliasee = $5;
2168 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2170 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2171 CurModule.CurrentModule);
2172 GA->setVisibility($2);
2173 InsertValue(GA, CurModule.Values);
2176 // If there was a forward reference of this alias, resolve it now.
2180 ID = ValID::createGlobalName(Name);
2182 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2184 if (GlobalValue *FWGV =
2185 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2186 // Replace uses of the fwdref with the actual alias.
2187 FWGV->replaceAllUsesWith(GA);
2188 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2189 GV->eraseFromParent();
2191 cast<Function>(FWGV)->eraseFromParent();
2197 | TARGET TargetDefinition {
2200 | DEPLIBS '=' LibrariesDefinition {
2206 AsmBlock : STRINGCONSTANT {
2207 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2208 if (AsmSoFar.empty())
2209 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2211 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2216 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2217 CurModule.CurrentModule->setTargetTriple(*$3);
2220 | DATALAYOUT '=' STRINGCONSTANT {
2221 CurModule.CurrentModule->setDataLayout(*$3);
2225 LibrariesDefinition : '[' LibList ']';
2227 LibList : LibList ',' STRINGCONSTANT {
2228 CurModule.CurrentModule->addLibrary(*$3);
2233 CurModule.CurrentModule->addLibrary(*$1);
2237 | /* empty: end of list */ {
2242 //===----------------------------------------------------------------------===//
2243 // Rules to match Function Headers
2244 //===----------------------------------------------------------------------===//
2246 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2247 if (!UpRefs.empty())
2248 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2249 if (!(*$3)->isFirstClassType())
2250 GEN_ERROR("Argument types must be first-class");
2251 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2256 | Types OptParamAttrs OptLocalName {
2257 if (!UpRefs.empty())
2258 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2259 if (!(*$1)->isFirstClassType())
2260 GEN_ERROR("Argument types must be first-class");
2261 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2262 $$ = new ArgListType;
2267 ArgList : ArgListH {
2271 | ArgListH ',' DOTDOTDOT {
2273 struct ArgListEntry E;
2274 E.Ty = new PATypeHolder(Type::VoidTy);
2276 E.Attrs = ParamAttr::None;
2281 $$ = new ArgListType;
2282 struct ArgListEntry E;
2283 E.Ty = new PATypeHolder(Type::VoidTy);
2285 E.Attrs = ParamAttr::None;
2294 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2295 OptFuncAttrs OptSection OptAlign OptGC {
2296 std::string FunctionName(*$3);
2297 delete $3; // Free strdup'd memory!
2299 // Check the function result for abstractness if this is a define. We should
2300 // have no abstract types at this point
2301 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2302 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2304 if (!FunctionType::isValidReturnType(*$2))
2305 GEN_ERROR("Invalid result type for LLVM function");
2307 std::vector<const Type*> ParamTypeList;
2308 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2309 if ($7 != ParamAttr::None)
2310 Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
2311 if ($5) { // If there are arguments...
2313 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2314 const Type* Ty = I->Ty->get();
2315 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2316 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2317 ParamTypeList.push_back(Ty);
2318 if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2319 Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
2323 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2324 if (isVarArg) ParamTypeList.pop_back();
2328 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2330 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2331 const PointerType *PFT = PointerType::getUnqual(FT);
2335 if (!FunctionName.empty()) {
2336 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2338 ID = ValID::createGlobalID(CurModule.Values.size());
2342 // See if this function was forward referenced. If so, recycle the object.
2343 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2344 // Move the function to the end of the list, from whereever it was
2345 // previously inserted.
2346 Fn = cast<Function>(FWRef);
2347 assert(Fn->getParamAttrs().isEmpty() &&
2348 "Forward reference has parameter attributes!");
2349 CurModule.CurrentModule->getFunctionList().remove(Fn);
2350 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2351 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2352 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2353 if (Fn->getFunctionType() != FT ) {
2354 // The existing function doesn't have the same type. This is an overload
2356 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2357 } else if (Fn->getParamAttrs() != PAL) {
2358 // The existing function doesn't have the same parameter attributes.
2359 // This is an overload error.
2360 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2361 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2362 // Neither the existing or the current function is a declaration and they
2363 // have the same name and same type. Clearly this is a redefinition.
2364 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2365 } else if (Fn->isDeclaration()) {
2366 // Make sure to strip off any argument names so we can't get conflicts.
2367 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2371 } else { // Not already defined?
2372 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2373 CurModule.CurrentModule);
2374 InsertValue(Fn, CurModule.Values);
2377 CurFun.FunctionStart(Fn);
2379 if (CurFun.isDeclare) {
2380 // If we have declaration, always overwrite linkage. This will allow us to
2381 // correctly handle cases, when pointer to function is passed as argument to
2382 // another function.
2383 Fn->setLinkage(CurFun.Linkage);
2384 Fn->setVisibility(CurFun.Visibility);
2386 Fn->setCallingConv($1);
2387 Fn->setParamAttrs(PAL);
2388 Fn->setAlignment($9);
2390 Fn->setSection(*$8);
2394 Fn->setCollector($10->c_str());
2398 // Add all of the arguments we parsed to the function...
2399 if ($5) { // Is null if empty...
2400 if (isVarArg) { // Nuke the last entry
2401 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2402 "Not a varargs marker!");
2403 delete $5->back().Ty;
2404 $5->pop_back(); // Delete the last entry
2406 Function::arg_iterator ArgIt = Fn->arg_begin();
2407 Function::arg_iterator ArgEnd = Fn->arg_end();
2409 for (ArgListType::iterator I = $5->begin();
2410 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2411 delete I->Ty; // Delete the typeholder...
2412 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2418 delete $5; // We're now done with the argument list
2423 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2425 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2426 $$ = CurFun.CurrentFunction;
2428 // Make sure that we keep track of the linkage type even if there was a
2429 // previous "declare".
2431 $$->setVisibility($2);
2434 END : ENDTOK | '}'; // Allow end of '}' to end a function
2436 Function : BasicBlockList END {
2441 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2442 CurFun.CurrentFunction->setLinkage($1);
2443 CurFun.CurrentFunction->setVisibility($2);
2444 $$ = CurFun.CurrentFunction;
2445 CurFun.FunctionDone();
2449 //===----------------------------------------------------------------------===//
2450 // Rules to match Basic Blocks
2451 //===----------------------------------------------------------------------===//
2453 OptSideEffect : /* empty */ {
2462 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2463 $$ = ValID::create($1);
2467 $$ = ValID::create($1);
2470 | ESAPINTVAL { // arbitrary precision integer constants
2471 $$ = ValID::create(*$1, true);
2475 | EUAPINTVAL { // arbitrary precision integer constants
2476 $$ = ValID::create(*$1, false);
2480 | FPVAL { // Perhaps it's an FP constant?
2481 $$ = ValID::create($1);
2485 $$ = ValID::create(ConstantInt::getTrue());
2489 $$ = ValID::create(ConstantInt::getFalse());
2493 $$ = ValID::createNull();
2497 $$ = ValID::createUndef();
2500 | ZEROINITIALIZER { // A vector zero constant.
2501 $$ = ValID::createZeroInit();
2504 | '<' ConstVector '>' { // Nonempty unsized packed vector
2505 const Type *ETy = (*$2)[0]->getType();
2506 unsigned NumElements = $2->size();
2508 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2509 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2511 VectorType* pt = VectorType::get(ETy, NumElements);
2512 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2514 // Verify all elements are correct type!
2515 for (unsigned i = 0; i < $2->size(); i++) {
2516 if (ETy != (*$2)[i]->getType())
2517 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2518 ETy->getDescription() +"' as required!\nIt is of type '" +
2519 (*$2)[i]->getType()->getDescription() + "'.");
2522 $$ = ValID::create(ConstantVector::get(pt, *$2));
2523 delete PTy; delete $2;
2526 | '[' ConstVector ']' { // Nonempty unsized arr
2527 const Type *ETy = (*$2)[0]->getType();
2528 uint64_t NumElements = $2->size();
2530 if (!ETy->isFirstClassType())
2531 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2533 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2534 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2536 // Verify all elements are correct type!
2537 for (unsigned i = 0; i < $2->size(); i++) {
2538 if (ETy != (*$2)[i]->getType())
2539 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2540 ETy->getDescription() +"' as required!\nIt is of type '"+
2541 (*$2)[i]->getType()->getDescription() + "'.");
2544 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2545 delete PTy; delete $2;
2549 // Use undef instead of an array because it's inconvenient to determine
2550 // the element type at this point, there being no elements to examine.
2551 $$ = ValID::createUndef();
2554 | 'c' STRINGCONSTANT {
2555 uint64_t NumElements = $2->length();
2556 const Type *ETy = Type::Int8Ty;
2558 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2560 std::vector<Constant*> Vals;
2561 for (unsigned i = 0; i < $2->length(); ++i)
2562 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2564 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2567 | '{' ConstVector '}' {
2568 std::vector<const Type*> Elements($2->size());
2569 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2570 Elements[i] = (*$2)[i]->getType();
2572 const StructType *STy = StructType::get(Elements);
2573 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2575 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2576 delete PTy; delete $2;
2580 const StructType *STy = StructType::get(std::vector<const Type*>());
2581 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2584 | '<' '{' ConstVector '}' '>' {
2585 std::vector<const Type*> Elements($3->size());
2586 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2587 Elements[i] = (*$3)[i]->getType();
2589 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2590 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2592 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2593 delete PTy; delete $3;
2597 const StructType *STy = StructType::get(std::vector<const Type*>(),
2599 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2603 $$ = ValID::create($1);
2606 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2607 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2613 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2616 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2617 $$ = ValID::createLocalID($1);
2621 $$ = ValID::createGlobalID($1);
2624 | LocalName { // Is it a named reference...?
2625 $$ = ValID::createLocalName(*$1);
2629 | GlobalName { // Is it a named reference...?
2630 $$ = ValID::createGlobalName(*$1);
2635 // ValueRef - A reference to a definition... either constant or symbolic
2636 ValueRef : SymbolicValueRef | ConstValueRef;
2639 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2640 // type immediately preceeds the value reference, and allows complex constant
2641 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2642 ResolvedVal : Types ValueRef {
2643 if (!UpRefs.empty())
2644 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2645 $$ = getVal(*$1, $2);
2651 ReturnedVal : ResolvedVal {
2652 $$ = new std::vector<Value *>();
2656 | ReturnedVal ',' ResolvedVal {
2657 ($$=$1)->push_back($3);
2661 BasicBlockList : BasicBlockList BasicBlock {
2665 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2671 // Basic blocks are terminated by branching instructions:
2672 // br, br/cc, switch, ret
2674 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2675 setValueName($3, $2);
2678 $1->getInstList().push_back($3);
2683 InstructionList : InstructionList Inst {
2684 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2685 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2686 if (CI2->getParent() == 0)
2687 $1->getInstList().push_back(CI2);
2688 $1->getInstList().push_back($2);
2692 | /* empty */ { // Empty space between instruction lists
2693 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2696 | LABELSTR { // Labelled (named) basic block
2697 $$ = defineBBVal(ValID::createLocalName(*$1));
2704 RET ReturnedVal { // Return with a result...
2705 ValueList &VL = *$2;
2706 assert(!VL.empty() && "Invalid ret operands!");
2707 const Type *ReturnType = CurFun.CurrentFunction->getReturnType();
2708 if (VL.size() > 1 ||
2709 (isa<StructType>(ReturnType) &&
2710 (VL.empty() || VL[0]->getType() != ReturnType))) {
2711 Value *RV = UndefValue::get(ReturnType);
2712 for (unsigned i = 0, e = VL.size(); i != e; ++i) {
2713 Instruction *I = InsertValueInst::Create(RV, VL[i], i, "mrv");
2714 ($<BasicBlockVal>-1)->getInstList().push_back(I);
2717 $$ = ReturnInst::Create(RV);
2719 $$ = ReturnInst::Create(VL[0]);
2724 | RET VOID { // Return with no result...
2725 $$ = ReturnInst::Create();
2728 | BR LABEL ValueRef { // Unconditional Branch...
2729 BasicBlock* tmpBB = getBBVal($3);
2731 $$ = BranchInst::Create(tmpBB);
2732 } // Conditional Branch...
2733 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2734 if (cast<IntegerType>($2)->getBitWidth() != 1)
2735 GEN_ERROR("Branch condition must have type i1");
2736 BasicBlock* tmpBBA = getBBVal($6);
2738 BasicBlock* tmpBBB = getBBVal($9);
2740 Value* tmpVal = getVal(Type::Int1Ty, $3);
2742 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2744 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2745 Value* tmpVal = getVal($2, $3);
2747 BasicBlock* tmpBB = getBBVal($6);
2749 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2752 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2754 for (; I != E; ++I) {
2755 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2756 S->addCase(CI, I->second);
2758 GEN_ERROR("Switch case is constant, but not a simple integer");
2763 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2764 Value* tmpVal = getVal($2, $3);
2766 BasicBlock* tmpBB = getBBVal($6);
2768 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2772 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2773 TO LABEL ValueRef UNWIND LABEL ValueRef {
2775 // Handle the short syntax
2776 const PointerType *PFTy = 0;
2777 const FunctionType *Ty = 0;
2778 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2779 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2780 // Pull out the types of all of the arguments...
2781 std::vector<const Type*> ParamTypes;
2782 ParamList::iterator I = $6->begin(), E = $6->end();
2783 for (; I != E; ++I) {
2784 const Type *Ty = I->Val->getType();
2785 if (Ty == Type::VoidTy)
2786 GEN_ERROR("Short call syntax cannot be used with varargs");
2787 ParamTypes.push_back(Ty);
2790 if (!FunctionType::isValidReturnType(*$3))
2791 GEN_ERROR("Invalid result type for LLVM function");
2793 Ty = FunctionType::get($3->get(), ParamTypes, false);
2794 PFTy = PointerType::getUnqual(Ty);
2799 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2801 BasicBlock *Normal = getBBVal($11);
2803 BasicBlock *Except = getBBVal($14);
2806 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2807 if ($8 != ParamAttr::None)
2808 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
2810 // Check the arguments
2812 if ($6->empty()) { // Has no arguments?
2813 // Make sure no arguments is a good thing!
2814 if (Ty->getNumParams() != 0)
2815 GEN_ERROR("No arguments passed to a function that "
2816 "expects arguments");
2817 } else { // Has arguments?
2818 // Loop through FunctionType's arguments and ensure they are specified
2820 FunctionType::param_iterator I = Ty->param_begin();
2821 FunctionType::param_iterator E = Ty->param_end();
2822 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2825 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2826 if (ArgI->Val->getType() != *I)
2827 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2828 (*I)->getDescription() + "'");
2829 Args.push_back(ArgI->Val);
2830 if (ArgI->Attrs != ParamAttr::None)
2831 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2834 if (Ty->isVarArg()) {
2836 for (; ArgI != ArgE; ++ArgI, ++index) {
2837 Args.push_back(ArgI->Val); // push the remaining varargs
2838 if (ArgI->Attrs != ParamAttr::None)
2839 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2841 } else if (I != E || ArgI != ArgE)
2842 GEN_ERROR("Invalid number of parameters detected");
2847 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2849 // Create the InvokeInst
2850 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2851 Args.begin(), Args.end());
2852 II->setCallingConv($2);
2853 II->setParamAttrs(PAL);
2859 $$ = new UnwindInst();
2863 $$ = new UnreachableInst();
2869 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2871 Constant *V = cast<Constant>(getExistingVal($2, $3));
2874 GEN_ERROR("May only switch on a constant pool value");
2876 BasicBlock* tmpBB = getBBVal($6);
2878 $$->push_back(std::make_pair(V, tmpBB));
2880 | IntType ConstValueRef ',' LABEL ValueRef {
2881 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2882 Constant *V = cast<Constant>(getExistingVal($1, $2));
2886 GEN_ERROR("May only switch on a constant pool value");
2888 BasicBlock* tmpBB = getBBVal($5);
2890 $$->push_back(std::make_pair(V, tmpBB));
2893 Inst : OptLocalAssign InstVal {
2894 // Is this definition named?? if so, assign the name...
2895 setValueName($2, $1);
2903 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2904 if (!UpRefs.empty())
2905 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2906 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2907 Value* tmpVal = getVal(*$1, $3);
2909 BasicBlock* tmpBB = getBBVal($5);
2911 $$->push_back(std::make_pair(tmpVal, tmpBB));
2914 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2916 Value* tmpVal = getVal($1->front().first->getType(), $4);
2918 BasicBlock* tmpBB = getBBVal($6);
2920 $1->push_back(std::make_pair(tmpVal, tmpBB));
2924 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2925 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2926 if (!UpRefs.empty())
2927 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2928 // Used for call and invoke instructions
2929 $$ = new ParamList();
2930 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
2935 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2936 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2937 // Labels are only valid in ASMs
2938 $$ = new ParamList();
2939 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
2943 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2944 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2945 if (!UpRefs.empty())
2946 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2948 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
2953 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2954 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2956 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
2960 | /*empty*/ { $$ = new ParamList(); };
2962 IndexList // Used for gep instructions and constant expressions
2963 : /*empty*/ { $$ = new std::vector<Value*>(); }
2964 | IndexList ',' ResolvedVal {
2971 ConstantIndexList // Used for insertvalue and extractvalue instructions
2973 $$ = new std::vector<unsigned>();
2974 if ((unsigned)$2 != $2)
2975 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
2978 | ConstantIndexList ',' EUINT64VAL {
2980 if ((unsigned)$3 != $3)
2981 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
2987 OptTailCall : TAIL CALL {
2996 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2997 if (!UpRefs.empty())
2998 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2999 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
3000 !isa<VectorType>((*$2).get()))
3002 "Arithmetic operator requires integer, FP, or packed operands");
3003 Value* val1 = getVal(*$2, $3);
3005 Value* val2 = getVal(*$2, $5);
3007 $$ = BinaryOperator::Create($1, val1, val2);
3009 GEN_ERROR("binary operator returned null");
3012 | LogicalOps Types ValueRef ',' ValueRef {
3013 if (!UpRefs.empty())
3014 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3015 if (!(*$2)->isInteger()) {
3016 if (!isa<VectorType>($2->get()) ||
3017 !cast<VectorType>($2->get())->getElementType()->isInteger())
3018 GEN_ERROR("Logical operator requires integral operands");
3020 Value* tmpVal1 = getVal(*$2, $3);
3022 Value* tmpVal2 = getVal(*$2, $5);
3024 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
3026 GEN_ERROR("binary operator returned null");
3029 | ICMP IPredicates Types ValueRef ',' ValueRef {
3030 if (!UpRefs.empty())
3031 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3032 if (isa<VectorType>((*$3).get()))
3033 GEN_ERROR("Vector types not supported by icmp instruction");
3034 Value* tmpVal1 = getVal(*$3, $4);
3036 Value* tmpVal2 = getVal(*$3, $6);
3038 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3040 GEN_ERROR("icmp operator returned null");
3043 | FCMP FPredicates Types ValueRef ',' ValueRef {
3044 if (!UpRefs.empty())
3045 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3046 if (isa<VectorType>((*$3).get()))
3047 GEN_ERROR("Vector types not supported by fcmp instruction");
3048 Value* tmpVal1 = getVal(*$3, $4);
3050 Value* tmpVal2 = getVal(*$3, $6);
3052 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3054 GEN_ERROR("fcmp operator returned null");
3057 | VICMP IPredicates Types ValueRef ',' ValueRef {
3058 if (!UpRefs.empty())
3059 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3060 if (!isa<VectorType>((*$3).get()))
3061 GEN_ERROR("Scalar types not supported by vicmp instruction");
3062 Value* tmpVal1 = getVal(*$3, $4);
3064 Value* tmpVal2 = getVal(*$3, $6);
3066 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3068 GEN_ERROR("icmp operator returned null");
3071 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3072 if (!UpRefs.empty())
3073 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3074 if (!isa<VectorType>((*$3).get()))
3075 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3076 Value* tmpVal1 = getVal(*$3, $4);
3078 Value* tmpVal2 = getVal(*$3, $6);
3080 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3082 GEN_ERROR("fcmp operator returned null");
3085 | CastOps ResolvedVal TO Types {
3086 if (!UpRefs.empty())
3087 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3089 const Type* DestTy = $4->get();
3090 if (!CastInst::castIsValid($1, Val, DestTy))
3091 GEN_ERROR("invalid cast opcode for cast from '" +
3092 Val->getType()->getDescription() + "' to '" +
3093 DestTy->getDescription() + "'");
3094 $$ = CastInst::Create($1, Val, DestTy);
3097 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3098 if ($2->getType() != Type::Int1Ty)
3099 GEN_ERROR("select condition must be boolean");
3100 if ($4->getType() != $6->getType())
3101 GEN_ERROR("select value types should match");
3102 $$ = SelectInst::Create($2, $4, $6);
3105 | VAARG ResolvedVal ',' Types {
3106 if (!UpRefs.empty())
3107 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3108 $$ = new VAArgInst($2, *$4);
3112 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3113 if (!ExtractElementInst::isValidOperands($2, $4))
3114 GEN_ERROR("Invalid extractelement operands");
3115 $$ = new ExtractElementInst($2, $4);
3118 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3119 if (!InsertElementInst::isValidOperands($2, $4, $6))
3120 GEN_ERROR("Invalid insertelement operands");
3121 $$ = InsertElementInst::Create($2, $4, $6);
3124 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3125 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3126 GEN_ERROR("Invalid shufflevector operands");
3127 $$ = new ShuffleVectorInst($2, $4, $6);
3131 const Type *Ty = $2->front().first->getType();
3132 if (!Ty->isFirstClassType())
3133 GEN_ERROR("PHI node operands must be of first class type");
3134 $$ = PHINode::Create(Ty);
3135 ((PHINode*)$$)->reserveOperandSpace($2->size());
3136 while ($2->begin() != $2->end()) {
3137 if ($2->front().first->getType() != Ty)
3138 GEN_ERROR("All elements of a PHI node must be of the same type");
3139 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3142 delete $2; // Free the list...
3145 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
3148 // Handle the short syntax
3149 const PointerType *PFTy = 0;
3150 const FunctionType *Ty = 0;
3151 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3152 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3153 // Pull out the types of all of the arguments...
3154 std::vector<const Type*> ParamTypes;
3155 ParamList::iterator I = $6->begin(), E = $6->end();
3156 for (; I != E; ++I) {
3157 const Type *Ty = I->Val->getType();
3158 if (Ty == Type::VoidTy)
3159 GEN_ERROR("Short call syntax cannot be used with varargs");
3160 ParamTypes.push_back(Ty);
3163 if (!FunctionType::isValidReturnType(*$3))
3164 GEN_ERROR("Invalid result type for LLVM function");
3166 Ty = FunctionType::get($3->get(), ParamTypes, false);
3167 PFTy = PointerType::getUnqual(Ty);
3170 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3173 // Check for call to invalid intrinsic to avoid crashing later.
3174 if (Function *theF = dyn_cast<Function>(V)) {
3175 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3176 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3177 !theF->getIntrinsicID(true))
3178 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3179 theF->getName() + "'");
3182 // Set up the ParamAttrs for the function
3183 SmallVector<ParamAttrsWithIndex, 8> Attrs;
3184 if ($8 != ParamAttr::None)
3185 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
3186 // Check the arguments
3188 if ($6->empty()) { // Has no arguments?
3189 // Make sure no arguments is a good thing!
3190 if (Ty->getNumParams() != 0)
3191 GEN_ERROR("No arguments passed to a function that "
3192 "expects arguments");
3193 } else { // Has arguments?
3194 // Loop through FunctionType's arguments and ensure they are specified
3195 // correctly. Also, gather any parameter attributes.
3196 FunctionType::param_iterator I = Ty->param_begin();
3197 FunctionType::param_iterator E = Ty->param_end();
3198 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
3201 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3202 if (ArgI->Val->getType() != *I)
3203 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3204 (*I)->getDescription() + "'");
3205 Args.push_back(ArgI->Val);
3206 if (ArgI->Attrs != ParamAttr::None)
3207 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3209 if (Ty->isVarArg()) {
3211 for (; ArgI != ArgE; ++ArgI, ++index) {
3212 Args.push_back(ArgI->Val); // push the remaining varargs
3213 if (ArgI->Attrs != ParamAttr::None)
3214 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3216 } else if (I != E || ArgI != ArgE)
3217 GEN_ERROR("Invalid number of parameters detected");
3220 // Finish off the ParamAttrs and check them
3223 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
3225 // Create the call node
3226 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3227 CI->setTailCall($1);
3228 CI->setCallingConv($2);
3229 CI->setParamAttrs(PAL);
3240 OptVolatile : VOLATILE {
3251 MemoryInst : MALLOC Types OptCAlign {
3252 if (!UpRefs.empty())
3253 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3254 $$ = new MallocInst(*$2, 0, $3);
3258 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3259 if (!UpRefs.empty())
3260 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3261 if ($4 != Type::Int32Ty)
3262 GEN_ERROR("Malloc array size is not a 32-bit integer!");
3263 Value* tmpVal = getVal($4, $5);
3265 $$ = new MallocInst(*$2, tmpVal, $6);
3268 | ALLOCA Types OptCAlign {
3269 if (!UpRefs.empty())
3270 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3271 $$ = new AllocaInst(*$2, 0, $3);
3275 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3276 if (!UpRefs.empty())
3277 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3278 if ($4 != Type::Int32Ty)
3279 GEN_ERROR("Alloca array size is not a 32-bit integer!");
3280 Value* tmpVal = getVal($4, $5);
3282 $$ = new AllocaInst(*$2, tmpVal, $6);
3285 | FREE ResolvedVal {
3286 if (!isa<PointerType>($2->getType()))
3287 GEN_ERROR("Trying to free nonpointer type " +
3288 $2->getType()->getDescription() + "");
3289 $$ = new FreeInst($2);
3293 | OptVolatile LOAD Types ValueRef OptCAlign {
3294 if (!UpRefs.empty())
3295 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3296 if (!isa<PointerType>($3->get()))
3297 GEN_ERROR("Can't load from nonpointer type: " +
3298 (*$3)->getDescription());
3299 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3300 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3301 (*$3)->getDescription());
3302 Value* tmpVal = getVal(*$3, $4);
3304 $$ = new LoadInst(tmpVal, "", $1, $5);
3307 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3308 if (!UpRefs.empty())
3309 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3310 const PointerType *PT = dyn_cast<PointerType>($5->get());
3312 GEN_ERROR("Can't store to a nonpointer type: " +
3313 (*$5)->getDescription());
3314 const Type *ElTy = PT->getElementType();
3315 if (ElTy != $3->getType())
3316 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3317 "' into space of type '" + ElTy->getDescription() + "'");
3319 Value* tmpVal = getVal(*$5, $6);
3321 $$ = new StoreInst($3, tmpVal, $1, $7);
3324 | GETRESULT Types ValueRef ',' EUINT64VAL {
3325 if (!UpRefs.empty())
3326 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3327 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3328 GEN_ERROR("getresult insn requires an aggregate operand");
3329 if (!ExtractValueInst::getIndexedType(*$2, $5))
3330 GEN_ERROR("Invalid getresult index for type '" +
3331 (*$2)->getDescription()+ "'");
3333 Value *tmpVal = getVal(*$2, $3);
3335 $$ = ExtractValueInst::Create(tmpVal, $5);
3338 | GETELEMENTPTR Types ValueRef IndexList {
3339 if (!UpRefs.empty())
3340 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3341 if (!isa<PointerType>($2->get()))
3342 GEN_ERROR("getelementptr insn requires pointer operand");
3344 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3345 GEN_ERROR("Invalid getelementptr indices for type '" +
3346 (*$2)->getDescription()+ "'");
3347 Value* tmpVal = getVal(*$2, $3);
3349 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3353 | EXTRACTVALUE Types ValueRef ConstantIndexList {
3354 if (!UpRefs.empty())
3355 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3356 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3357 GEN_ERROR("extractvalue insn requires an aggregate operand");
3359 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3360 GEN_ERROR("Invalid extractvalue indices for type '" +
3361 (*$2)->getDescription()+ "'");
3362 Value* tmpVal = getVal(*$2, $3);
3364 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3368 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3369 if (!UpRefs.empty())
3370 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3371 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3372 GEN_ERROR("extractvalue insn requires an aggregate operand");
3374 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3375 GEN_ERROR("Invalid insertvalue indices for type '" +
3376 (*$2)->getDescription()+ "'");
3377 Value* aggVal = getVal(*$2, $3);
3378 Value* tmpVal = getVal(*$5, $6);
3380 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3389 // common code from the two 'RunVMAsmParser' functions
3390 static Module* RunParser(Module * M) {
3391 CurModule.CurrentModule = M;
3392 // Check to make sure the parser succeeded
3395 delete ParserResult;
3399 // Emit an error if there are any unresolved types left.
3400 if (!CurModule.LateResolveTypes.empty()) {
3401 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3402 if (DID.Type == ValID::LocalName) {
3403 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3405 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3408 delete ParserResult;
3412 // Emit an error if there are any unresolved values left.
3413 if (!CurModule.LateResolveValues.empty()) {
3414 Value *V = CurModule.LateResolveValues.back();
3415 std::map<Value*, std::pair<ValID, int> >::iterator I =
3416 CurModule.PlaceHolderInfo.find(V);
3418 if (I != CurModule.PlaceHolderInfo.end()) {
3419 ValID &DID = I->second.first;
3420 if (DID.Type == ValID::LocalName) {
3421 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3423 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3426 delete ParserResult;
3431 // Check to make sure that parsing produced a result
3435 // Reset ParserResult variable while saving its value for the result.
3436 Module *Result = ParserResult;
3442 void llvm::GenerateError(const std::string &message, int LineNo) {
3443 if (LineNo == -1) LineNo = LLLgetLineNo();
3444 // TODO: column number in exception
3446 TheParseError->setError(LLLgetFilename(), message, LineNo);
3450 int yyerror(const char *ErrorMsg) {
3451 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3452 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3453 if (yychar != YYEMPTY && yychar != 0) {
3454 errMsg += " while reading token: '";
3455 errMsg += std::string(LLLgetTokenStart(),
3456 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3458 GenerateError(errMsg);