1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/SymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/Support/MathExtras.h"
25 #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 std::string CurFilename;
56 Debug("debug-yacc", cl::desc("Print yacc debug state changes"),
57 cl::Hidden, cl::init(false));
62 static Module *ParserResult;
64 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
65 // relating to upreferences in the input stream.
67 //#define DEBUG_UPREFS 1
69 #define UR_OUT(X) cerr << X
74 #define YYERROR_VERBOSE 1
76 static GlobalVariable *CurGV;
79 // This contains info used when building the body of a function. It is
80 // destroyed when the function is completed.
82 typedef std::vector<Value *> ValueList; // Numbered defs
85 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
86 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
88 static struct PerModuleInfo {
89 Module *CurrentModule;
90 std::map<const Type *, ValueList> Values; // Module level numbered definitions
91 std::map<const Type *,ValueList> LateResolveValues;
92 std::vector<PATypeHolder> Types;
93 std::map<ValID, PATypeHolder> LateResolveTypes;
95 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
96 /// how they were referenced and on which line of the input they came from so
97 /// that we can resolve them later and print error messages as appropriate.
98 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
100 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
101 // references to global values. Global values may be referenced before they
102 // are defined, and if so, the temporary object that they represent is held
103 // here. This is used for forward references of GlobalValues.
105 typedef std::map<std::pair<const PointerType *,
106 ValID>, GlobalValue*> GlobalRefsType;
107 GlobalRefsType GlobalRefs;
110 // If we could not resolve some functions at function compilation time
111 // (calls to functions before they are defined), resolve them now... Types
112 // are resolved when the constant pool has been completely parsed.
114 ResolveDefinitions(LateResolveValues);
118 // Check to make sure that all global value forward references have been
121 if (!GlobalRefs.empty()) {
122 std::string UndefinedReferences = "Unresolved global references exist:\n";
124 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
126 UndefinedReferences += " " + I->first.first->getDescription() + " " +
127 I->first.second.getName() + "\n";
129 GenerateError(UndefinedReferences);
133 Values.clear(); // Clear out function local definitions
138 // GetForwardRefForGlobal - Check to see if there is a forward reference
139 // for this global. If so, remove it from the GlobalRefs map and return it.
140 // If not, just return null.
141 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
142 // Check to see if there is a forward reference to this global variable...
143 // if there is, eliminate it and patch the reference to use the new def'n.
144 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
145 GlobalValue *Ret = 0;
146 if (I != GlobalRefs.end()) {
153 bool TypeIsUnresolved(PATypeHolder* PATy) {
154 // If it isn't abstract, its resolved
155 const Type* Ty = PATy->get();
156 if (!Ty->isAbstract())
158 // Traverse the type looking for abstract types. If it isn't abstract then
159 // we don't need to traverse that leg of the type.
160 std::vector<const Type*> WorkList, SeenList;
161 WorkList.push_back(Ty);
162 while (!WorkList.empty()) {
163 const Type* Ty = WorkList.back();
164 SeenList.push_back(Ty);
166 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
167 // Check to see if this is an unresolved type
168 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
169 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
170 for ( ; I != E; ++I) {
171 if (I->second.get() == OpTy)
174 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
175 const Type* TheTy = SeqTy->getElementType();
176 if (TheTy->isAbstract() && TheTy != Ty) {
177 std::vector<const Type*>::iterator I = SeenList.begin(),
183 WorkList.push_back(TheTy);
185 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
186 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
187 const Type* TheTy = StrTy->getElementType(i);
188 if (TheTy->isAbstract() && TheTy != Ty) {
189 std::vector<const Type*>::iterator I = SeenList.begin(),
195 WorkList.push_back(TheTy);
206 static struct PerFunctionInfo {
207 Function *CurrentFunction; // Pointer to current function being created
209 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
210 std::map<const Type*, ValueList> LateResolveValues;
211 bool isDeclare; // Is this function a forward declararation?
212 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
213 GlobalValue::VisibilityTypes Visibility;
215 /// BBForwardRefs - When we see forward references to basic blocks, keep
216 /// track of them here.
217 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
218 std::vector<BasicBlock*> NumberedBlocks;
221 inline PerFunctionInfo() {
224 Linkage = GlobalValue::ExternalLinkage;
225 Visibility = GlobalValue::DefaultVisibility;
228 inline void FunctionStart(Function *M) {
233 void FunctionDone() {
234 NumberedBlocks.clear();
236 // Any forward referenced blocks left?
237 if (!BBForwardRefs.empty()) {
238 GenerateError("Undefined reference to label " +
239 BBForwardRefs.begin()->first->getName());
243 // Resolve all forward references now.
244 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
246 Values.clear(); // Clear out function local definitions
249 Linkage = GlobalValue::ExternalLinkage;
250 Visibility = GlobalValue::DefaultVisibility;
252 } CurFun; // Info for the current function...
254 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
257 //===----------------------------------------------------------------------===//
258 // Code to handle definitions of all the types
259 //===----------------------------------------------------------------------===//
261 static int InsertValue(Value *V,
262 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
263 if (V->hasName()) return -1; // Is this a numbered definition?
265 // Yes, insert the value into the value table...
266 ValueList &List = ValueTab[V->getType()];
268 return List.size()-1;
271 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
273 case ValID::NumberVal: // Is it a numbered definition?
274 // Module constants occupy the lowest numbered slots...
275 if ((unsigned)D.Num < CurModule.Types.size())
276 return CurModule.Types[(unsigned)D.Num];
278 case ValID::NameVal: // Is it a named definition?
279 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
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::NameVal) {
298 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
301 GenerateError("Reference to an undefined type: #" + itostr(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 static Value *lookupInSymbolTable(const Type *Ty, const std::string &Name) {
316 SymbolTable &SymTab =
317 inFunctionScope() ? CurFun.CurrentFunction->getValueSymbolTable() :
318 CurModule.CurrentModule->getValueSymbolTable();
319 return SymTab.lookup(Ty, Name);
322 // getValNonImprovising - Look up the value specified by the provided type and
323 // the provided ValID. If the value exists and has already been defined, return
324 // it. Otherwise return null.
326 static Value *getValNonImprovising(const Type *Ty, const ValID &D) {
327 if (isa<FunctionType>(Ty)) {
328 GenerateError("Functions are not values and "
329 "must be referenced as pointers");
334 case ValID::NumberVal: { // Is it a numbered definition?
335 unsigned Num = (unsigned)D.Num;
337 // Module constants occupy the lowest numbered slots...
338 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
339 if (VI != CurModule.Values.end()) {
340 if (Num < VI->second.size())
341 return VI->second[Num];
342 Num -= VI->second.size();
345 // Make sure that our type is within bounds
346 VI = CurFun.Values.find(Ty);
347 if (VI == CurFun.Values.end()) return 0;
349 // Check that the number is within bounds...
350 if (VI->second.size() <= Num) return 0;
352 return VI->second[Num];
355 case ValID::NameVal: { // Is it a named definition?
356 Value *N = lookupInSymbolTable(Ty, std::string(D.Name));
357 if (N == 0) return 0;
359 D.destroy(); // Free old strdup'd memory...
363 // Check to make sure that "Ty" is an integral type, and that our
364 // value will fit into the specified type...
365 case ValID::ConstSIntVal: // Is it a constant pool reference??
366 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
367 GenerateError("Signed integral constant '" +
368 itostr(D.ConstPool64) + "' is invalid for type '" +
369 Ty->getDescription() + "'!");
372 return ConstantInt::get(Ty, D.ConstPool64);
374 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
375 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
376 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
377 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
378 "' is invalid or out of range!");
380 } else { // This is really a signed reference. Transmogrify.
381 return ConstantInt::get(Ty, D.ConstPool64);
384 return ConstantInt::get(Ty, D.UConstPool64);
387 case ValID::ConstFPVal: // Is it a floating point const pool reference?
388 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
389 GenerateError("FP constant invalid for type!!");
392 return ConstantFP::get(Ty, D.ConstPoolFP);
394 case ValID::ConstNullVal: // Is it a null value?
395 if (!isa<PointerType>(Ty)) {
396 GenerateError("Cannot create a a non pointer null!");
399 return ConstantPointerNull::get(cast<PointerType>(Ty));
401 case ValID::ConstUndefVal: // Is it an undef value?
402 return UndefValue::get(Ty);
404 case ValID::ConstZeroVal: // Is it a zero value?
405 return Constant::getNullValue(Ty);
407 case ValID::ConstantVal: // Fully resolved constant?
408 if (D.ConstantValue->getType() != Ty) {
409 GenerateError("Constant expression type different from required type!");
412 return D.ConstantValue;
414 case ValID::InlineAsmVal: { // Inline asm expression
415 const PointerType *PTy = dyn_cast<PointerType>(Ty);
416 const FunctionType *FTy =
417 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
418 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
419 GenerateError("Invalid type for asm constraint string!");
422 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
423 D.IAD->HasSideEffects);
424 D.destroy(); // Free InlineAsmDescriptor.
428 assert(0 && "Unhandled case!");
432 assert(0 && "Unhandled case!");
436 // getVal - This function is identical to getValNonImprovising, except that if a
437 // value is not already defined, it "improvises" by creating a placeholder var
438 // that looks and acts just like the requested variable. When the value is
439 // defined later, all uses of the placeholder variable are replaced with the
442 static Value *getVal(const Type *Ty, const ValID &ID) {
443 if (Ty == Type::LabelTy) {
444 GenerateError("Cannot use a basic block here");
448 // See if the value has already been defined.
449 Value *V = getValNonImprovising(Ty, ID);
451 if (TriggerError) return 0;
453 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
454 GenerateError("Invalid use of a composite type!");
458 // If we reached here, we referenced either a symbol that we don't know about
459 // or an id number that hasn't been read yet. We may be referencing something
460 // forward, so just create an entry to be resolved later and get to it...
462 V = new Argument(Ty);
464 // Remember where this forward reference came from. FIXME, shouldn't we try
465 // to recycle these things??
466 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
469 if (inFunctionScope())
470 InsertValue(V, CurFun.LateResolveValues);
472 InsertValue(V, CurModule.LateResolveValues);
476 /// getBBVal - This is used for two purposes:
477 /// * If isDefinition is true, a new basic block with the specified ID is being
479 /// * If isDefinition is true, this is a reference to a basic block, which may
480 /// or may not be a forward reference.
482 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
483 assert(inFunctionScope() && "Can't get basic block at global scope!");
489 GenerateError("Illegal label reference " + ID.getName());
491 case ValID::NumberVal: // Is it a numbered definition?
492 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
493 CurFun.NumberedBlocks.resize(ID.Num+1);
494 BB = CurFun.NumberedBlocks[ID.Num];
496 case ValID::NameVal: // Is it a named definition?
498 if (Value *N = CurFun.CurrentFunction->
499 getValueSymbolTable().lookup(Type::LabelTy, Name))
500 BB = cast<BasicBlock>(N);
504 // See if the block has already been defined.
506 // If this is the definition of the block, make sure the existing value was
507 // just a forward reference. If it was a forward reference, there will be
508 // an entry for it in the PlaceHolderInfo map.
509 if (isDefinition && !CurFun.BBForwardRefs.erase(BB)) {
510 // The existing value was a definition, not a forward reference.
511 GenerateError("Redefinition of label " + ID.getName());
515 ID.destroy(); // Free strdup'd memory.
519 // Otherwise this block has not been seen before.
520 BB = new BasicBlock("", CurFun.CurrentFunction);
521 if (ID.Type == ValID::NameVal) {
522 BB->setName(ID.Name);
524 CurFun.NumberedBlocks[ID.Num] = BB;
527 // If this is not a definition, keep track of it so we can use it as a forward
530 // Remember where this forward reference came from.
531 CurFun.BBForwardRefs[BB] = std::make_pair(ID, llvmAsmlineno);
533 // The forward declaration could have been inserted anywhere in the
534 // function: insert it into the correct place now.
535 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
536 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
543 //===----------------------------------------------------------------------===//
544 // Code to handle forward references in instructions
545 //===----------------------------------------------------------------------===//
547 // This code handles the late binding needed with statements that reference
548 // values not defined yet... for example, a forward branch, or the PHI node for
551 // This keeps a table (CurFun.LateResolveValues) of all such forward references
552 // and back patchs after we are done.
555 // ResolveDefinitions - If we could not resolve some defs at parsing
556 // time (forward branches, phi functions for loops, etc...) resolve the
560 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
561 std::map<const Type*,ValueList> *FutureLateResolvers) {
562 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
563 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
564 E = LateResolvers.end(); LRI != E; ++LRI) {
565 ValueList &List = LRI->second;
566 while (!List.empty()) {
567 Value *V = List.back();
570 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
571 CurModule.PlaceHolderInfo.find(V);
572 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
574 ValID &DID = PHI->second.first;
576 Value *TheRealValue = getValNonImprovising(LRI->first, DID);
580 V->replaceAllUsesWith(TheRealValue);
582 CurModule.PlaceHolderInfo.erase(PHI);
583 } else if (FutureLateResolvers) {
584 // Functions have their unresolved items forwarded to the module late
586 InsertValue(V, *FutureLateResolvers);
588 if (DID.Type == ValID::NameVal) {
589 GenerateError("Reference to an invalid definition: '" +DID.getName()+
590 "' of type '" + V->getType()->getDescription() + "'",
594 GenerateError("Reference to an invalid definition: #" +
595 itostr(DID.Num) + " of type '" +
596 V->getType()->getDescription() + "'",
604 LateResolvers.clear();
607 // ResolveTypeTo - A brand new type was just declared. This means that (if
608 // name is not null) things referencing Name can be resolved. Otherwise, things
609 // refering to the number can be resolved. Do this now.
611 static void ResolveTypeTo(char *Name, const Type *ToTy) {
613 if (Name) D = ValID::create(Name);
614 else D = ValID::create((int)CurModule.Types.size());
616 std::map<ValID, PATypeHolder>::iterator I =
617 CurModule.LateResolveTypes.find(D);
618 if (I != CurModule.LateResolveTypes.end()) {
619 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
620 CurModule.LateResolveTypes.erase(I);
624 // setValueName - Set the specified value to the name given. The name may be
625 // null potentially, in which case this is a noop. The string passed in is
626 // assumed to be a malloc'd string buffer, and is free'd by this function.
628 static void setValueName(Value *V, char *NameStr) {
630 std::string Name(NameStr); // Copy string
631 free(NameStr); // Free old string
633 if (V->getType() == Type::VoidTy) {
634 GenerateError("Can't assign name '" + Name+"' to value with void type!");
638 assert(inFunctionScope() && "Must be in function scope!");
639 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
640 if (ST.lookup(V->getType(), Name)) {
641 GenerateError("Redefinition of value '" + Name + "' of type '" +
642 V->getType()->getDescription() + "'!");
651 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
652 /// this is a declaration, otherwise it is a definition.
653 static GlobalVariable *
654 ParseGlobalVariable(char *NameStr,
655 GlobalValue::LinkageTypes Linkage,
656 GlobalValue::VisibilityTypes Visibility,
657 bool isConstantGlobal, const Type *Ty,
658 Constant *Initializer) {
659 if (isa<FunctionType>(Ty)) {
660 GenerateError("Cannot declare global vars of function type!");
664 const PointerType *PTy = PointerType::get(Ty);
668 Name = NameStr; // Copy string
669 free(NameStr); // Free old string
672 // See if this global value was forward referenced. If so, recycle the
676 ID = ValID::create((char*)Name.c_str());
678 ID = ValID::create((int)CurModule.Values[PTy].size());
681 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
682 // Move the global to the end of the list, from whereever it was
683 // previously inserted.
684 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
685 CurModule.CurrentModule->getGlobalList().remove(GV);
686 CurModule.CurrentModule->getGlobalList().push_back(GV);
687 GV->setInitializer(Initializer);
688 GV->setLinkage(Linkage);
689 GV->setVisibility(Visibility);
690 GV->setConstant(isConstantGlobal);
691 InsertValue(GV, CurModule.Values);
695 // If this global has a name, check to see if there is already a definition
696 // of this global in the module. If so, it is an error.
698 // We are a simple redefinition of a value, check to see if it is defined
699 // the same as the old one.
700 if (CurModule.CurrentModule->getGlobalVariable(Name, Ty)) {
701 GenerateError("Redefinition of global variable named '" + Name +
702 "' of type '" + Ty->getDescription() + "'!");
707 // Otherwise there is no existing GV to use, create one now.
709 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
710 CurModule.CurrentModule);
711 GV->setVisibility(Visibility);
712 InsertValue(GV, CurModule.Values);
716 // setTypeName - Set the specified type to the name given. The name may be
717 // null potentially, in which case this is a noop. The string passed in is
718 // assumed to be a malloc'd string buffer, and is freed by this function.
720 // This function returns true if the type has already been defined, but is
721 // allowed to be redefined in the specified context. If the name is a new name
722 // for the type plane, it is inserted and false is returned.
723 static bool setTypeName(const Type *T, char *NameStr) {
724 assert(!inFunctionScope() && "Can't give types function-local names!");
725 if (NameStr == 0) return false;
727 std::string Name(NameStr); // Copy string
728 free(NameStr); // Free old string
730 // We don't allow assigning names to void type
731 if (T == Type::VoidTy) {
732 GenerateError("Can't assign name '" + Name + "' to the void type!");
736 // Set the type name, checking for conflicts as we do so.
737 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
739 if (AlreadyExists) { // Inserting a name that is already defined???
740 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
741 assert(Existing && "Conflict but no matching type?");
743 // There is only one case where this is allowed: when we are refining an
744 // opaque type. In this case, Existing will be an opaque type.
745 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
746 // We ARE replacing an opaque type!
747 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
751 // Otherwise, this is an attempt to redefine a type. That's okay if
752 // the redefinition is identical to the original. This will be so if
753 // Existing and T point to the same Type object. In this one case we
754 // allow the equivalent redefinition.
755 if (Existing == T) return true; // Yes, it's equal.
757 // Any other kind of (non-equivalent) redefinition is an error.
758 GenerateError("Redefinition of type named '" + Name + "' of type '" +
759 T->getDescription() + "'!");
765 //===----------------------------------------------------------------------===//
766 // Code for handling upreferences in type names...
769 // TypeContains - Returns true if Ty directly contains E in it.
771 static bool TypeContains(const Type *Ty, const Type *E) {
772 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
773 E) != Ty->subtype_end();
778 // NestingLevel - The number of nesting levels that need to be popped before
779 // this type is resolved.
780 unsigned NestingLevel;
782 // LastContainedTy - This is the type at the current binding level for the
783 // type. Every time we reduce the nesting level, this gets updated.
784 const Type *LastContainedTy;
786 // UpRefTy - This is the actual opaque type that the upreference is
790 UpRefRecord(unsigned NL, OpaqueType *URTy)
791 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
795 // UpRefs - A list of the outstanding upreferences that need to be resolved.
796 static std::vector<UpRefRecord> UpRefs;
798 /// HandleUpRefs - Every time we finish a new layer of types, this function is
799 /// called. It loops through the UpRefs vector, which is a list of the
800 /// currently active types. For each type, if the up reference is contained in
801 /// the newly completed type, we decrement the level count. When the level
802 /// count reaches zero, the upreferenced type is the type that is passed in:
803 /// thus we can complete the cycle.
805 static PATypeHolder HandleUpRefs(const Type *ty) {
806 // If Ty isn't abstract, or if there are no up-references in it, then there is
807 // nothing to resolve here.
808 if (!ty->isAbstract() || UpRefs.empty()) return ty;
811 UR_OUT("Type '" << Ty->getDescription() <<
812 "' newly formed. Resolving upreferences.\n" <<
813 UpRefs.size() << " upreferences active!\n");
815 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
816 // to zero), we resolve them all together before we resolve them to Ty. At
817 // the end of the loop, if there is anything to resolve to Ty, it will be in
819 OpaqueType *TypeToResolve = 0;
821 for (unsigned i = 0; i != UpRefs.size(); ++i) {
822 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
823 << UpRefs[i].second->getDescription() << ") = "
824 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
825 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
826 // Decrement level of upreference
827 unsigned Level = --UpRefs[i].NestingLevel;
828 UpRefs[i].LastContainedTy = Ty;
829 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
830 if (Level == 0) { // Upreference should be resolved!
831 if (!TypeToResolve) {
832 TypeToResolve = UpRefs[i].UpRefTy;
834 UR_OUT(" * Resolving upreference for "
835 << UpRefs[i].second->getDescription() << "\n";
836 std::string OldName = UpRefs[i].UpRefTy->getDescription());
837 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
838 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
839 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
841 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
842 --i; // Do not skip the next element...
848 UR_OUT(" * Resolving upreference for "
849 << UpRefs[i].second->getDescription() << "\n";
850 std::string OldName = TypeToResolve->getDescription());
851 TypeToResolve->refineAbstractTypeTo(Ty);
857 //===----------------------------------------------------------------------===//
858 // RunVMAsmParser - Define an interface to this parser
859 //===----------------------------------------------------------------------===//
861 static Module* RunParser(Module * M);
863 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
866 CurFilename = Filename;
867 return RunParser(new Module(CurFilename));
870 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
871 set_scan_string(AsmString);
873 CurFilename = "from_memory";
875 return RunParser(new Module (CurFilename));
884 llvm::Module *ModuleVal;
885 llvm::Function *FunctionVal;
886 llvm::BasicBlock *BasicBlockVal;
887 llvm::TerminatorInst *TermInstVal;
888 llvm::Instruction *InstVal;
889 llvm::Constant *ConstVal;
891 const llvm::Type *PrimType;
892 std::list<llvm::PATypeHolder> *TypeList;
893 llvm::PATypeHolder *TypeVal;
894 llvm::Value *ValueVal;
895 std::vector<llvm::Value*> *ValueList;
896 llvm::ArgListType *ArgList;
897 llvm::TypeWithAttrs TypeWithAttrs;
898 llvm::TypeWithAttrsList *TypeWithAttrsList;
899 llvm::ValueRefList *ValueRefList;
901 // Represent the RHS of PHI node
902 std::list<std::pair<llvm::Value*,
903 llvm::BasicBlock*> > *PHIList;
904 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
905 std::vector<llvm::Constant*> *ConstVector;
907 llvm::GlobalValue::LinkageTypes Linkage;
908 llvm::GlobalValue::VisibilityTypes Visibility;
909 llvm::FunctionType::ParameterAttributes ParamAttrs;
917 char *StrVal; // This memory is strdup'd!
918 llvm::ValID ValIDVal; // strdup'd memory maybe!
920 llvm::Instruction::BinaryOps BinaryOpVal;
921 llvm::Instruction::TermOps TermOpVal;
922 llvm::Instruction::MemoryOps MemOpVal;
923 llvm::Instruction::CastOps CastOpVal;
924 llvm::Instruction::OtherOps OtherOpVal;
925 llvm::Module::Endianness Endianness;
926 llvm::ICmpInst::Predicate IPredicate;
927 llvm::FCmpInst::Predicate FPredicate;
930 %type <ModuleVal> Module
931 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
932 %type <BasicBlockVal> BasicBlock InstructionList
933 %type <TermInstVal> BBTerminatorInst
934 %type <InstVal> Inst InstVal MemoryInst
935 %type <ConstVal> ConstVal ConstExpr
936 %type <ConstVector> ConstVector
937 %type <ArgList> ArgList ArgListH
938 %type <PHIList> PHIList
939 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
940 %type <ValueList> IndexList // For GEP indices
941 %type <TypeList> TypeListI
942 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
943 %type <TypeWithAttrs> ArgType
944 %type <JumpTable> JumpTable
945 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
946 %type <BoolVal> OptVolatile // 'volatile' or not
947 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
948 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
949 %type <Linkage> GVInternalLinkage GVExternalLinkage
950 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
951 %type <Visibility> GVVisibilityStyle
952 %type <Endianness> BigOrLittle
954 // ValueRef - Unresolved reference to a definition or BB
955 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
956 %type <ValueVal> ResolvedVal // <type> <valref> pair
957 // Tokens and types for handling constant integer values
959 // ESINT64VAL - A negative number within long long range
960 %token <SInt64Val> ESINT64VAL
962 // EUINT64VAL - A positive number within uns. long long range
963 %token <UInt64Val> EUINT64VAL
965 %token <SIntVal> SINTVAL // Signed 32 bit ints...
966 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
967 %type <SIntVal> INTVAL
968 %token <FPVal> FPVAL // Float or Double constant
971 %type <TypeVal> Types ResultTypes
972 %type <PrimType> IntType FPType PrimType // Classifications
973 %token <PrimType> VOID INTTYPE
974 %token <PrimType> FLOAT DOUBLE LABEL
977 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
978 %type <StrVal> Name OptName OptAssign
979 %type <UIntVal> OptAlign OptCAlign
980 %type <StrVal> OptSection SectionString
982 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
983 %token DECLARE DEFINE GLOBAL CONSTANT SECTION VOLATILE
984 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
985 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
986 %token OPAQUE EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
987 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
988 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
989 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
991 %type <UIntVal> OptCallingConv
992 %type <ParamAttrs> OptParamAttrs ParamAttr
993 %type <ParamAttrs> OptFuncAttrs FuncAttr
995 // Basic Block Terminating Operators
996 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
999 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1000 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1001 %token <OtherOpVal> ICMP FCMP
1002 %type <IPredicate> IPredicates
1003 %type <FPredicate> FPredicates
1004 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1005 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1007 // Memory Instructions
1008 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1011 %type <CastOpVal> CastOps
1012 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1013 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1016 %type <OtherOpVal> ShiftOps
1017 %token <OtherOpVal> PHI_TOK SELECT SHL LSHR ASHR VAARG
1018 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1020 // Function Attributes
1023 // Visibility Styles
1024 %token DEFAULT HIDDEN
1029 // Handle constant integer size restriction and conversion...
1033 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1034 GEN_ERROR("Value too large for type!");
1039 // Operations that are notably excluded from this list include:
1040 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1042 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1043 LogicalOps : AND | OR | XOR;
1044 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1045 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1046 ShiftOps : SHL | LSHR | ASHR;
1048 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1049 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1050 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1051 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1052 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1056 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1057 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1058 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1059 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1060 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1061 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1062 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1063 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1064 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1067 // These are some types that allow classification if we only want a particular
1068 // thing... for example, only a signed, unsigned, or integral type.
1070 FPType : FLOAT | DOUBLE;
1072 // OptAssign - Value producing statements have an optional assignment component
1073 OptAssign : Name '=' {
1083 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1084 | WEAK { $$ = GlobalValue::WeakLinkage; }
1085 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1086 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1087 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1091 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1092 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1093 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1097 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1098 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1101 FunctionDeclareLinkage
1102 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1103 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1104 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1107 FunctionDefineLinkage
1108 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1109 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1110 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1111 | WEAK { $$ = GlobalValue::WeakLinkage; }
1112 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1115 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1116 CCC_TOK { $$ = CallingConv::C; } |
1117 CSRETCC_TOK { $$ = CallingConv::CSRet; } |
1118 FASTCC_TOK { $$ = CallingConv::Fast; } |
1119 COLDCC_TOK { $$ = CallingConv::Cold; } |
1120 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1121 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1123 if ((unsigned)$2 != $2)
1124 GEN_ERROR("Calling conv too large!");
1129 ParamAttr : ZEXT { $$ = FunctionType::ZExtAttribute; }
1130 | SEXT { $$ = FunctionType::SExtAttribute; }
1133 OptParamAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1134 | OptParamAttrs ParamAttr {
1135 $$ = FunctionType::ParameterAttributes($1 | $2);
1139 FuncAttr : NORETURN { $$ = FunctionType::NoReturnAttribute; }
1143 OptFuncAttrs : /* empty */ { $$ = FunctionType::NoAttributeSet; }
1144 | OptFuncAttrs FuncAttr {
1145 $$ = FunctionType::ParameterAttributes($1 | $2);
1149 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1150 // a comma before it.
1151 OptAlign : /*empty*/ { $$ = 0; } |
1154 if ($$ != 0 && !isPowerOf2_32($$))
1155 GEN_ERROR("Alignment must be a power of two!");
1158 OptCAlign : /*empty*/ { $$ = 0; } |
1159 ',' ALIGN EUINT64VAL {
1161 if ($$ != 0 && !isPowerOf2_32($$))
1162 GEN_ERROR("Alignment must be a power of two!");
1167 SectionString : SECTION STRINGCONSTANT {
1168 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1169 if ($2[i] == '"' || $2[i] == '\\')
1170 GEN_ERROR("Invalid character in section name!");
1175 OptSection : /*empty*/ { $$ = 0; } |
1176 SectionString { $$ = $1; };
1178 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1179 // is set to be the global we are processing.
1181 GlobalVarAttributes : /* empty */ {} |
1182 ',' GlobalVarAttribute GlobalVarAttributes {};
1183 GlobalVarAttribute : SectionString {
1184 CurGV->setSection($1);
1188 | ALIGN EUINT64VAL {
1189 if ($2 != 0 && !isPowerOf2_32($2))
1190 GEN_ERROR("Alignment must be a power of two!");
1191 CurGV->setAlignment($2);
1195 //===----------------------------------------------------------------------===//
1196 // Types includes all predefined types... except void, because it can only be
1197 // used in specific contexts (function returning void for example).
1199 // Derived types are added later...
1201 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1205 $$ = new PATypeHolder(OpaqueType::get());
1209 $$ = new PATypeHolder($1);
1212 | Types '*' { // Pointer type?
1213 if (*$1 == Type::LabelTy)
1214 GEN_ERROR("Cannot form a pointer to a basic block");
1215 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1219 | SymbolicValueRef { // Named types are also simple types...
1220 const Type* tmp = getTypeVal($1);
1222 $$ = new PATypeHolder(tmp);
1224 | '\\' EUINT64VAL { // Type UpReference
1225 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range!");
1226 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1227 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1228 $$ = new PATypeHolder(OT);
1229 UR_OUT("New Upreference!\n");
1232 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1233 std::vector<const Type*> Params;
1234 std::vector<FunctionType::ParameterAttributes> Attrs;
1235 Attrs.push_back($5);
1236 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1237 Params.push_back(I->Ty->get());
1238 if (I->Ty->get() != Type::VoidTy)
1239 Attrs.push_back(I->Attrs);
1241 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1242 if (isVarArg) Params.pop_back();
1244 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg, Attrs);
1245 delete $3; // Delete the argument list
1246 delete $1; // Delete the return type handle
1247 $$ = new PATypeHolder(HandleUpRefs(FT));
1250 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1251 std::vector<const Type*> Params;
1252 std::vector<FunctionType::ParameterAttributes> Attrs;
1253 Attrs.push_back($5);
1254 for (TypeWithAttrsList::iterator I=$3->begin(), E=$3->end(); I != E; ++I) {
1255 Params.push_back(I->Ty->get());
1256 if (I->Ty->get() != Type::VoidTy)
1257 Attrs.push_back(I->Attrs);
1259 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1260 if (isVarArg) Params.pop_back();
1262 FunctionType *FT = FunctionType::get($1, Params, isVarArg, Attrs);
1263 delete $3; // Delete the argument list
1264 $$ = new PATypeHolder(HandleUpRefs(FT));
1268 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1269 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1273 | '<' EUINT64VAL 'x' Types '>' { // Packed array type?
1274 const llvm::Type* ElemTy = $4->get();
1275 if ((unsigned)$2 != $2)
1276 GEN_ERROR("Unsigned result not equal to signed result");
1277 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1278 GEN_ERROR("Element type of a PackedType must be primitive");
1279 if (!isPowerOf2_32($2))
1280 GEN_ERROR("Vector length should be a power of 2!");
1281 $$ = new PATypeHolder(HandleUpRefs(PackedType::get(*$4, (unsigned)$2)));
1285 | '{' TypeListI '}' { // Structure type?
1286 std::vector<const Type*> Elements;
1287 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1288 E = $2->end(); I != E; ++I)
1289 Elements.push_back(*I);
1291 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1295 | '{' '}' { // Empty structure type?
1296 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1299 | '<' '{' TypeListI '}' '>' {
1300 std::vector<const Type*> Elements;
1301 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1302 E = $3->end(); I != E; ++I)
1303 Elements.push_back(*I);
1305 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1309 | '<' '{' '}' '>' { // Empty structure type?
1310 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1316 : Types OptParamAttrs {
1324 if (!UpRefs.empty())
1325 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1326 if (!(*$1)->isFirstClassType())
1327 GEN_ERROR("LLVM functions cannot return aggregate types!");
1331 $$ = new PATypeHolder(Type::VoidTy);
1335 ArgTypeList : ArgType {
1336 $$ = new TypeWithAttrsList();
1340 | ArgTypeList ',' ArgType {
1341 ($$=$1)->push_back($3);
1348 | ArgTypeList ',' DOTDOTDOT {
1350 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1351 TWA.Ty = new PATypeHolder(Type::VoidTy);
1356 $$ = new TypeWithAttrsList;
1357 TypeWithAttrs TWA; TWA.Attrs = FunctionType::NoAttributeSet;
1358 TWA.Ty = new PATypeHolder(Type::VoidTy);
1363 $$ = new TypeWithAttrsList();
1367 // TypeList - Used for struct declarations and as a basis for function type
1368 // declaration type lists
1371 $$ = new std::list<PATypeHolder>();
1372 $$->push_back(*$1); delete $1;
1375 | TypeListI ',' Types {
1376 ($$=$1)->push_back(*$3); delete $3;
1380 // ConstVal - The various declarations that go into the constant pool. This
1381 // production is used ONLY to represent constants that show up AFTER a 'const',
1382 // 'constant' or 'global' token at global scope. Constants that can be inlined
1383 // into other expressions (such as integers and constexprs) are handled by the
1384 // ResolvedVal, ValueRef and ConstValueRef productions.
1386 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1387 if (!UpRefs.empty())
1388 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1389 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1391 GEN_ERROR("Cannot make array constant with type: '" +
1392 (*$1)->getDescription() + "'!");
1393 const Type *ETy = ATy->getElementType();
1394 int NumElements = ATy->getNumElements();
1396 // Verify that we have the correct size...
1397 if (NumElements != -1 && NumElements != (int)$3->size())
1398 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1399 utostr($3->size()) + " arguments, but has size of " +
1400 itostr(NumElements) + "!");
1402 // Verify all elements are correct type!
1403 for (unsigned i = 0; i < $3->size(); i++) {
1404 if (ETy != (*$3)[i]->getType())
1405 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1406 ETy->getDescription() +"' as required!\nIt is of type '"+
1407 (*$3)[i]->getType()->getDescription() + "'.");
1410 $$ = ConstantArray::get(ATy, *$3);
1411 delete $1; delete $3;
1415 if (!UpRefs.empty())
1416 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1417 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1419 GEN_ERROR("Cannot make array constant with type: '" +
1420 (*$1)->getDescription() + "'!");
1422 int NumElements = ATy->getNumElements();
1423 if (NumElements != -1 && NumElements != 0)
1424 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1425 " arguments, but has size of " + itostr(NumElements) +"!");
1426 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1430 | Types 'c' STRINGCONSTANT {
1431 if (!UpRefs.empty())
1432 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1433 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1435 GEN_ERROR("Cannot make array constant with type: '" +
1436 (*$1)->getDescription() + "'!");
1438 int NumElements = ATy->getNumElements();
1439 const Type *ETy = ATy->getElementType();
1440 char *EndStr = UnEscapeLexed($3, true);
1441 if (NumElements != -1 && NumElements != (EndStr-$3))
1442 GEN_ERROR("Can't build string constant of size " +
1443 itostr((int)(EndStr-$3)) +
1444 " when array has size " + itostr(NumElements) + "!");
1445 std::vector<Constant*> Vals;
1446 if (ETy == Type::Int8Ty) {
1447 for (unsigned char *C = (unsigned char *)$3;
1448 C != (unsigned char*)EndStr; ++C)
1449 Vals.push_back(ConstantInt::get(ETy, *C));
1452 GEN_ERROR("Cannot build string arrays of non byte sized elements!");
1455 $$ = ConstantArray::get(ATy, Vals);
1459 | Types '<' ConstVector '>' { // Nonempty unsized arr
1460 if (!UpRefs.empty())
1461 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1462 const PackedType *PTy = dyn_cast<PackedType>($1->get());
1464 GEN_ERROR("Cannot make packed constant with type: '" +
1465 (*$1)->getDescription() + "'!");
1466 const Type *ETy = PTy->getElementType();
1467 int NumElements = PTy->getNumElements();
1469 // Verify that we have the correct size...
1470 if (NumElements != -1 && NumElements != (int)$3->size())
1471 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1472 utostr($3->size()) + " arguments, but has size of " +
1473 itostr(NumElements) + "!");
1475 // Verify all elements are correct type!
1476 for (unsigned i = 0; i < $3->size(); i++) {
1477 if (ETy != (*$3)[i]->getType())
1478 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1479 ETy->getDescription() +"' as required!\nIt is of type '"+
1480 (*$3)[i]->getType()->getDescription() + "'.");
1483 $$ = ConstantPacked::get(PTy, *$3);
1484 delete $1; delete $3;
1487 | Types '{' ConstVector '}' {
1488 const StructType *STy = dyn_cast<StructType>($1->get());
1490 GEN_ERROR("Cannot make struct constant with type: '" +
1491 (*$1)->getDescription() + "'!");
1493 if ($3->size() != STy->getNumContainedTypes())
1494 GEN_ERROR("Illegal number of initializers for structure type!");
1496 // Check to ensure that constants are compatible with the type initializer!
1497 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1498 if ((*$3)[i]->getType() != STy->getElementType(i))
1499 GEN_ERROR("Expected type '" +
1500 STy->getElementType(i)->getDescription() +
1501 "' for element #" + utostr(i) +
1502 " of structure initializer!");
1504 // Check to ensure that Type is not packed
1505 if (STy->isPacked())
1506 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1508 $$ = ConstantStruct::get(STy, *$3);
1509 delete $1; delete $3;
1513 if (!UpRefs.empty())
1514 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1515 const StructType *STy = dyn_cast<StructType>($1->get());
1517 GEN_ERROR("Cannot make struct constant with type: '" +
1518 (*$1)->getDescription() + "'!");
1520 if (STy->getNumContainedTypes() != 0)
1521 GEN_ERROR("Illegal number of initializers for structure type!");
1523 // Check to ensure that Type is not packed
1524 if (STy->isPacked())
1525 GEN_ERROR("Unpacked Initializer to packed type '" + STy->getDescription() + "'");
1527 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1531 | Types '<' '{' ConstVector '}' '>' {
1532 const StructType *STy = dyn_cast<StructType>($1->get());
1534 GEN_ERROR("Cannot make struct constant with type: '" +
1535 (*$1)->getDescription() + "'!");
1537 if ($4->size() != STy->getNumContainedTypes())
1538 GEN_ERROR("Illegal number of initializers for structure type!");
1540 // Check to ensure that constants are compatible with the type initializer!
1541 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1542 if ((*$4)[i]->getType() != STy->getElementType(i))
1543 GEN_ERROR("Expected type '" +
1544 STy->getElementType(i)->getDescription() +
1545 "' for element #" + utostr(i) +
1546 " of structure initializer!");
1548 // Check to ensure that Type is packed
1549 if (!STy->isPacked())
1550 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1552 $$ = ConstantStruct::get(STy, *$4);
1553 delete $1; delete $4;
1556 | Types '<' '{' '}' '>' {
1557 if (!UpRefs.empty())
1558 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1559 const StructType *STy = dyn_cast<StructType>($1->get());
1561 GEN_ERROR("Cannot make struct constant with type: '" +
1562 (*$1)->getDescription() + "'!");
1564 if (STy->getNumContainedTypes() != 0)
1565 GEN_ERROR("Illegal number of initializers for structure type!");
1567 // Check to ensure that Type is packed
1568 if (!STy->isPacked())
1569 GEN_ERROR("Packed Initializer to unpacked type '" + STy->getDescription() + "'");
1571 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1576 if (!UpRefs.empty())
1577 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1578 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1580 GEN_ERROR("Cannot make null pointer constant with type: '" +
1581 (*$1)->getDescription() + "'!");
1583 $$ = ConstantPointerNull::get(PTy);
1588 if (!UpRefs.empty())
1589 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1590 $$ = UndefValue::get($1->get());
1594 | Types SymbolicValueRef {
1595 if (!UpRefs.empty())
1596 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1597 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1599 GEN_ERROR("Global const reference must be a pointer type!");
1601 // ConstExprs can exist in the body of a function, thus creating
1602 // GlobalValues whenever they refer to a variable. Because we are in
1603 // the context of a function, getValNonImprovising will search the functions
1604 // symbol table instead of the module symbol table for the global symbol,
1605 // which throws things all off. To get around this, we just tell
1606 // getValNonImprovising that we are at global scope here.
1608 Function *SavedCurFn = CurFun.CurrentFunction;
1609 CurFun.CurrentFunction = 0;
1611 Value *V = getValNonImprovising(Ty, $2);
1614 CurFun.CurrentFunction = SavedCurFn;
1616 // If this is an initializer for a constant pointer, which is referencing a
1617 // (currently) undefined variable, create a stub now that shall be replaced
1618 // in the future with the right type of variable.
1621 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1622 const PointerType *PT = cast<PointerType>(Ty);
1624 // First check to see if the forward references value is already created!
1625 PerModuleInfo::GlobalRefsType::iterator I =
1626 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1628 if (I != CurModule.GlobalRefs.end()) {
1629 V = I->second; // Placeholder already exists, use it...
1633 if ($2.Type == ValID::NameVal) Name = $2.Name;
1635 // Create the forward referenced global.
1637 if (const FunctionType *FTy =
1638 dyn_cast<FunctionType>(PT->getElementType())) {
1639 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
1640 CurModule.CurrentModule);
1642 GV = new GlobalVariable(PT->getElementType(), false,
1643 GlobalValue::ExternalLinkage, 0,
1644 Name, CurModule.CurrentModule);
1647 // Keep track of the fact that we have a forward ref to recycle it
1648 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1653 $$ = cast<GlobalValue>(V);
1654 delete $1; // Free the type handle
1658 if (!UpRefs.empty())
1659 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1660 if ($1->get() != $2->getType())
1661 GEN_ERROR("Mismatched types for constant expression: " +
1662 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1667 | Types ZEROINITIALIZER {
1668 if (!UpRefs.empty())
1669 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1670 const Type *Ty = $1->get();
1671 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1672 GEN_ERROR("Cannot create a null initialized value of this type!");
1673 $$ = Constant::getNullValue(Ty);
1677 | IntType ESINT64VAL { // integral constants
1678 if (!ConstantInt::isValueValidForType($1, $2))
1679 GEN_ERROR("Constant value doesn't fit in type!");
1680 $$ = ConstantInt::get($1, $2);
1683 | IntType EUINT64VAL { // integral constants
1684 if (!ConstantInt::isValueValidForType($1, $2))
1685 GEN_ERROR("Constant value doesn't fit in type!");
1686 $$ = ConstantInt::get($1, $2);
1689 | INTTYPE TRUETOK { // Boolean constants
1690 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1691 $$ = ConstantInt::getTrue();
1694 | INTTYPE FALSETOK { // Boolean constants
1695 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1696 $$ = ConstantInt::getFalse();
1699 | FPType FPVAL { // Float & Double constants
1700 if (!ConstantFP::isValueValidForType($1, $2))
1701 GEN_ERROR("Floating point constant invalid for type!!");
1702 $$ = ConstantFP::get($1, $2);
1707 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1708 if (!UpRefs.empty())
1709 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1711 const Type *Ty = $5->get();
1712 if (!Val->getType()->isFirstClassType())
1713 GEN_ERROR("cast constant expression from a non-primitive type: '" +
1714 Val->getType()->getDescription() + "'!");
1715 if (!Ty->isFirstClassType())
1716 GEN_ERROR("cast constant expression to a non-primitive type: '" +
1717 Ty->getDescription() + "'!");
1718 $$ = ConstantExpr::getCast($1, $3, $5->get());
1721 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1722 if (!isa<PointerType>($3->getType()))
1723 GEN_ERROR("GetElementPtr requires a pointer operand!");
1726 GetElementPtrInst::getIndexedType($3->getType(), *$4, true);
1728 GEN_ERROR("Index list invalid for constant getelementptr!");
1730 std::vector<Constant*> IdxVec;
1731 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1732 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1733 IdxVec.push_back(C);
1735 GEN_ERROR("Indices to constant getelementptr must be constants!");
1739 $$ = ConstantExpr::getGetElementPtr($3, IdxVec);
1742 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1743 if ($3->getType() != Type::Int1Ty)
1744 GEN_ERROR("Select condition must be of boolean type!");
1745 if ($5->getType() != $7->getType())
1746 GEN_ERROR("Select operand types must match!");
1747 $$ = ConstantExpr::getSelect($3, $5, $7);
1750 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1751 if ($3->getType() != $5->getType())
1752 GEN_ERROR("Binary operator types must match!");
1754 $$ = ConstantExpr::get($1, $3, $5);
1756 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1757 if ($3->getType() != $5->getType())
1758 GEN_ERROR("Logical operator types must match!");
1759 if (!$3->getType()->isIntegral()) {
1760 if (!isa<PackedType>($3->getType()) ||
1761 !cast<PackedType>($3->getType())->getElementType()->isIntegral())
1762 GEN_ERROR("Logical operator requires integral operands!");
1764 $$ = ConstantExpr::get($1, $3, $5);
1767 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1768 if ($4->getType() != $6->getType())
1769 GEN_ERROR("icmp operand types must match!");
1770 $$ = ConstantExpr::getICmp($2, $4, $6);
1772 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1773 if ($4->getType() != $6->getType())
1774 GEN_ERROR("fcmp operand types must match!");
1775 $$ = ConstantExpr::getFCmp($2, $4, $6);
1777 | ShiftOps '(' ConstVal ',' ConstVal ')' {
1778 if ($5->getType() != Type::Int8Ty)
1779 GEN_ERROR("Shift count for shift constant must be i8 type!");
1780 if (!$3->getType()->isInteger())
1781 GEN_ERROR("Shift constant expression requires integer operand!");
1783 $$ = ConstantExpr::get($1, $3, $5);
1786 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1787 if (!ExtractElementInst::isValidOperands($3, $5))
1788 GEN_ERROR("Invalid extractelement operands!");
1789 $$ = ConstantExpr::getExtractElement($3, $5);
1792 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1793 if (!InsertElementInst::isValidOperands($3, $5, $7))
1794 GEN_ERROR("Invalid insertelement operands!");
1795 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1798 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1799 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1800 GEN_ERROR("Invalid shufflevector operands!");
1801 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1806 // ConstVector - A list of comma separated constants.
1807 ConstVector : ConstVector ',' ConstVal {
1808 ($$ = $1)->push_back($3);
1812 $$ = new std::vector<Constant*>();
1818 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1819 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1822 //===----------------------------------------------------------------------===//
1823 // Rules to match Modules
1824 //===----------------------------------------------------------------------===//
1826 // Module rule: Capture the result of parsing the whole file into a result
1831 $$ = ParserResult = CurModule.CurrentModule;
1832 CurModule.ModuleDone();
1836 $$ = ParserResult = CurModule.CurrentModule;
1837 CurModule.ModuleDone();
1844 | DefinitionList Definition
1848 : DEFINE { CurFun.isDeclare = false } Function {
1849 CurFun.FunctionDone();
1852 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1855 | MODULE ASM_TOK AsmBlock {
1859 // Emit an error if there are any unresolved types left.
1860 if (!CurModule.LateResolveTypes.empty()) {
1861 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
1862 if (DID.Type == ValID::NameVal) {
1863 GEN_ERROR("Reference to an undefined type: '"+DID.getName() + "'");
1865 GEN_ERROR("Reference to an undefined type: #" + itostr(DID.Num));
1870 | OptAssign TYPE Types {
1871 if (!UpRefs.empty())
1872 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
1873 // Eagerly resolve types. This is not an optimization, this is a
1874 // requirement that is due to the fact that we could have this:
1876 // %list = type { %list * }
1877 // %list = type { %list * } ; repeated type decl
1879 // If types are not resolved eagerly, then the two types will not be
1880 // determined to be the same type!
1882 ResolveTypeTo($1, *$3);
1884 if (!setTypeName(*$3, $1) && !$1) {
1886 // If this is a named type that is not a redefinition, add it to the slot
1888 CurModule.Types.push_back(*$3);
1894 | OptAssign TYPE VOID {
1895 ResolveTypeTo($1, $3);
1897 if (!setTypeName($3, $1) && !$1) {
1899 // If this is a named type that is not a redefinition, add it to the slot
1901 CurModule.Types.push_back($3);
1905 | OptAssign GVVisibilityStyle GlobalType ConstVal { /* "Externally Visible" Linkage */
1907 GEN_ERROR("Global value initializer is not a constant!");
1908 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
1909 $2, $3, $4->getType(), $4);
1911 } GlobalVarAttributes {
1914 | OptAssign GVInternalLinkage GVVisibilityStyle GlobalType ConstVal {
1916 GEN_ERROR("Global value initializer is not a constant!");
1917 CurGV = ParseGlobalVariable($1, $2, $3, $4, $5->getType(), $5);
1919 } GlobalVarAttributes {
1922 | OptAssign GVExternalLinkage GVVisibilityStyle GlobalType Types {
1923 if (!UpRefs.empty())
1924 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1925 CurGV = ParseGlobalVariable($1, $2, $3, $4, *$5, 0);
1928 } GlobalVarAttributes {
1932 | TARGET TargetDefinition {
1935 | DEPLIBS '=' LibrariesDefinition {
1941 AsmBlock : STRINGCONSTANT {
1942 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
1943 char *EndStr = UnEscapeLexed($1, true);
1944 std::string NewAsm($1, EndStr);
1947 if (AsmSoFar.empty())
1948 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
1950 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
1954 BigOrLittle : BIG { $$ = Module::BigEndian; };
1955 BigOrLittle : LITTLE { $$ = Module::LittleEndian; };
1957 TargetDefinition : ENDIAN '=' BigOrLittle {
1958 CurModule.CurrentModule->setEndianness($3);
1961 | POINTERSIZE '=' EUINT64VAL {
1963 CurModule.CurrentModule->setPointerSize(Module::Pointer32);
1965 CurModule.CurrentModule->setPointerSize(Module::Pointer64);
1967 GEN_ERROR("Invalid pointer size: '" + utostr($3) + "'!");
1970 | TRIPLE '=' STRINGCONSTANT {
1971 CurModule.CurrentModule->setTargetTriple($3);
1974 | DATALAYOUT '=' STRINGCONSTANT {
1975 CurModule.CurrentModule->setDataLayout($3);
1979 LibrariesDefinition : '[' LibList ']';
1981 LibList : LibList ',' STRINGCONSTANT {
1982 CurModule.CurrentModule->addLibrary($3);
1987 CurModule.CurrentModule->addLibrary($1);
1991 | /* empty: end of list */ {
1996 //===----------------------------------------------------------------------===//
1997 // Rules to match Function Headers
1998 //===----------------------------------------------------------------------===//
2000 Name : VAR_ID | STRINGCONSTANT;
2001 OptName : Name | /*empty*/ { $$ = 0; };
2003 ArgListH : ArgListH ',' Types OptParamAttrs OptName {
2004 if (!UpRefs.empty())
2005 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2006 if (*$3 == Type::VoidTy)
2007 GEN_ERROR("void typed arguments are invalid!");
2008 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2013 | Types OptParamAttrs OptName {
2014 if (!UpRefs.empty())
2015 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2016 if (*$1 == Type::VoidTy)
2017 GEN_ERROR("void typed arguments are invalid!");
2018 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2019 $$ = new ArgListType;
2024 ArgList : ArgListH {
2028 | ArgListH ',' DOTDOTDOT {
2030 struct ArgListEntry E;
2031 E.Ty = new PATypeHolder(Type::VoidTy);
2033 E.Attrs = FunctionType::NoAttributeSet;
2038 $$ = new ArgListType;
2039 struct ArgListEntry E;
2040 E.Ty = new PATypeHolder(Type::VoidTy);
2042 E.Attrs = FunctionType::NoAttributeSet;
2051 FunctionHeaderH : OptCallingConv ResultTypes Name '(' ArgList ')'
2052 OptFuncAttrs OptSection OptAlign {
2054 std::string FunctionName($3);
2055 free($3); // Free strdup'd memory!
2057 // Check the function result for abstractness if this is a define. We should
2058 // have no abstract types at this point
2059 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2060 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2062 std::vector<const Type*> ParamTypeList;
2063 std::vector<FunctionType::ParameterAttributes> ParamAttrs;
2064 ParamAttrs.push_back($7);
2065 if ($5) { // If there are arguments...
2066 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I) {
2067 const Type* Ty = I->Ty->get();
2068 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2069 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2070 ParamTypeList.push_back(Ty);
2071 if (Ty != Type::VoidTy)
2072 ParamAttrs.push_back(I->Attrs);
2076 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2077 if (isVarArg) ParamTypeList.pop_back();
2079 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg,
2081 const PointerType *PFT = PointerType::get(FT);
2085 if (!FunctionName.empty()) {
2086 ID = ValID::create((char*)FunctionName.c_str());
2088 ID = ValID::create((int)CurModule.Values[PFT].size());
2092 // See if this function was forward referenced. If so, recycle the object.
2093 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2094 // Move the function to the end of the list, from whereever it was
2095 // previously inserted.
2096 Fn = cast<Function>(FWRef);
2097 CurModule.CurrentModule->getFunctionList().remove(Fn);
2098 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2099 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2100 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2101 // If this is the case, either we need to be a forward decl, or it needs
2103 if (!CurFun.isDeclare && !Fn->isExternal())
2104 GEN_ERROR("Redefinition of function '" + FunctionName + "'!");
2106 // Make sure to strip off any argument names so we can't get conflicts.
2107 if (Fn->isExternal())
2108 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2111 } else { // Not already defined?
2112 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2113 CurModule.CurrentModule);
2115 InsertValue(Fn, CurModule.Values);
2118 CurFun.FunctionStart(Fn);
2120 if (CurFun.isDeclare) {
2121 // If we have declaration, always overwrite linkage. This will allow us to
2122 // correctly handle cases, when pointer to function is passed as argument to
2123 // another function.
2124 Fn->setLinkage(CurFun.Linkage);
2125 Fn->setVisibility(CurFun.Visibility);
2127 Fn->setCallingConv($1);
2128 Fn->setAlignment($9);
2134 // Add all of the arguments we parsed to the function...
2135 if ($5) { // Is null if empty...
2136 if (isVarArg) { // Nuke the last entry
2137 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0&&
2138 "Not a varargs marker!");
2139 delete $5->back().Ty;
2140 $5->pop_back(); // Delete the last entry
2142 Function::arg_iterator ArgIt = Fn->arg_begin();
2144 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++ArgIt) {
2145 delete I->Ty; // Delete the typeholder...
2146 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2152 delete $5; // We're now done with the argument list
2157 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2159 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2160 $$ = CurFun.CurrentFunction;
2162 // Make sure that we keep track of the linkage type even if there was a
2163 // previous "declare".
2165 $$->setVisibility($2);
2168 END : ENDTOK | '}'; // Allow end of '}' to end a function
2170 Function : BasicBlockList END {
2175 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2176 CurFun.CurrentFunction->setLinkage($1);
2177 CurFun.CurrentFunction->setVisibility($2);
2178 $$ = CurFun.CurrentFunction;
2179 CurFun.FunctionDone();
2183 //===----------------------------------------------------------------------===//
2184 // Rules to match Basic Blocks
2185 //===----------------------------------------------------------------------===//
2187 OptSideEffect : /* empty */ {
2196 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2197 $$ = ValID::create($1);
2201 $$ = ValID::create($1);
2204 | FPVAL { // Perhaps it's an FP constant?
2205 $$ = ValID::create($1);
2209 $$ = ValID::create(ConstantInt::getTrue());
2213 $$ = ValID::create(ConstantInt::getFalse());
2217 $$ = ValID::createNull();
2221 $$ = ValID::createUndef();
2224 | ZEROINITIALIZER { // A vector zero constant.
2225 $$ = ValID::createZeroInit();
2228 | '<' ConstVector '>' { // Nonempty unsized packed vector
2229 const Type *ETy = (*$2)[0]->getType();
2230 int NumElements = $2->size();
2232 PackedType* pt = PackedType::get(ETy, NumElements);
2233 PATypeHolder* PTy = new PATypeHolder(
2241 // Verify all elements are correct type!
2242 for (unsigned i = 0; i < $2->size(); i++) {
2243 if (ETy != (*$2)[i]->getType())
2244 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2245 ETy->getDescription() +"' as required!\nIt is of type '" +
2246 (*$2)[i]->getType()->getDescription() + "'.");
2249 $$ = ValID::create(ConstantPacked::get(pt, *$2));
2250 delete PTy; delete $2;
2254 $$ = ValID::create($1);
2257 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2258 char *End = UnEscapeLexed($3, true);
2259 std::string AsmStr = std::string($3, End);
2260 End = UnEscapeLexed($5, true);
2261 std::string Constraints = std::string($5, End);
2262 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2268 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2271 SymbolicValueRef : INTVAL { // Is it an integer reference...?
2272 $$ = ValID::create($1);
2275 | Name { // Is it a named reference...?
2276 $$ = ValID::create($1);
2280 // ValueRef - A reference to a definition... either constant or symbolic
2281 ValueRef : SymbolicValueRef | ConstValueRef;
2284 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2285 // type immediately preceeds the value reference, and allows complex constant
2286 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2287 ResolvedVal : Types ValueRef {
2288 if (!UpRefs.empty())
2289 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2290 $$ = getVal(*$1, $2);
2296 BasicBlockList : BasicBlockList BasicBlock {
2300 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2306 // Basic blocks are terminated by branching instructions:
2307 // br, br/cc, switch, ret
2309 BasicBlock : InstructionList OptAssign BBTerminatorInst {
2310 setValueName($3, $2);
2314 $1->getInstList().push_back($3);
2320 InstructionList : InstructionList Inst {
2321 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2322 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2323 if (CI2->getParent() == 0)
2324 $1->getInstList().push_back(CI2);
2325 $1->getInstList().push_back($2);
2330 $$ = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2333 // Make sure to move the basic block to the correct location in the
2334 // function, instead of leaving it inserted wherever it was first
2336 Function::BasicBlockListType &BBL =
2337 CurFun.CurrentFunction->getBasicBlockList();
2338 BBL.splice(BBL.end(), BBL, $$);
2342 $$ = getBBVal(ValID::create($1), true);
2345 // Make sure to move the basic block to the correct location in the
2346 // function, instead of leaving it inserted wherever it was first
2348 Function::BasicBlockListType &BBL =
2349 CurFun.CurrentFunction->getBasicBlockList();
2350 BBL.splice(BBL.end(), BBL, $$);
2354 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2355 $$ = new ReturnInst($2);
2358 | RET VOID { // Return with no result...
2359 $$ = new ReturnInst();
2362 | BR LABEL ValueRef { // Unconditional Branch...
2363 BasicBlock* tmpBB = getBBVal($3);
2365 $$ = new BranchInst(tmpBB);
2366 } // Conditional Branch...
2367 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2368 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2369 BasicBlock* tmpBBA = getBBVal($6);
2371 BasicBlock* tmpBBB = getBBVal($9);
2373 Value* tmpVal = getVal(Type::Int1Ty, $3);
2375 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2377 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2378 Value* tmpVal = getVal($2, $3);
2380 BasicBlock* tmpBB = getBBVal($6);
2382 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2385 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2387 for (; I != E; ++I) {
2388 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2389 S->addCase(CI, I->second);
2391 GEN_ERROR("Switch case is constant, but not a simple integer!");
2396 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2397 Value* tmpVal = getVal($2, $3);
2399 BasicBlock* tmpBB = getBBVal($6);
2401 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2405 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2406 TO LABEL ValueRef UNWIND LABEL ValueRef {
2408 // Handle the short syntax
2409 const PointerType *PFTy = 0;
2410 const FunctionType *Ty = 0;
2411 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2412 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2413 // Pull out the types of all of the arguments...
2414 std::vector<const Type*> ParamTypes;
2415 FunctionType::ParamAttrsList ParamAttrs;
2416 ParamAttrs.push_back($8);
2417 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2418 const Type *Ty = I->Val->getType();
2419 if (Ty == Type::VoidTy)
2420 GEN_ERROR("Short call syntax cannot be used with varargs");
2421 ParamTypes.push_back(Ty);
2422 ParamAttrs.push_back(I->Attrs);
2425 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2426 PFTy = PointerType::get(Ty);
2429 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2431 BasicBlock *Normal = getBBVal($11);
2433 BasicBlock *Except = getBBVal($14);
2436 // Check the arguments
2438 if ($6->empty()) { // Has no arguments?
2439 // Make sure no arguments is a good thing!
2440 if (Ty->getNumParams() != 0)
2441 GEN_ERROR("No arguments passed to a function that "
2442 "expects arguments!");
2443 } else { // Has arguments?
2444 // Loop through FunctionType's arguments and ensure they are specified
2446 FunctionType::param_iterator I = Ty->param_begin();
2447 FunctionType::param_iterator E = Ty->param_end();
2448 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2450 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2451 if (ArgI->Val->getType() != *I)
2452 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2453 (*I)->getDescription() + "'!");
2454 Args.push_back(ArgI->Val);
2457 if (Ty->isVarArg()) {
2459 for (; ArgI != ArgE; ++ArgI)
2460 Args.push_back(ArgI->Val); // push the remaining varargs
2461 } else if (I != E || ArgI != ArgE)
2462 GEN_ERROR("Invalid number of parameters detected!");
2465 // Create the InvokeInst
2466 InvokeInst *II = new InvokeInst(V, Normal, Except, Args);
2467 II->setCallingConv($2);
2473 $$ = new UnwindInst();
2477 $$ = new UnreachableInst();
2483 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2485 Constant *V = cast<Constant>(getValNonImprovising($2, $3));
2488 GEN_ERROR("May only switch on a constant pool value!");
2490 BasicBlock* tmpBB = getBBVal($6);
2492 $$->push_back(std::make_pair(V, tmpBB));
2494 | IntType ConstValueRef ',' LABEL ValueRef {
2495 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2496 Constant *V = cast<Constant>(getValNonImprovising($1, $2));
2500 GEN_ERROR("May only switch on a constant pool value!");
2502 BasicBlock* tmpBB = getBBVal($5);
2504 $$->push_back(std::make_pair(V, tmpBB));
2507 Inst : OptAssign InstVal {
2508 // Is this definition named?? if so, assign the name...
2509 setValueName($2, $1);
2516 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2517 if (!UpRefs.empty())
2518 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2519 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2520 Value* tmpVal = getVal(*$1, $3);
2522 BasicBlock* tmpBB = getBBVal($5);
2524 $$->push_back(std::make_pair(tmpVal, tmpBB));
2527 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2529 Value* tmpVal = getVal($1->front().first->getType(), $4);
2531 BasicBlock* tmpBB = getBBVal($6);
2533 $1->push_back(std::make_pair(tmpVal, tmpBB));
2537 ValueRefList : Types ValueRef OptParamAttrs {
2538 if (!UpRefs.empty())
2539 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2540 // Used for call and invoke instructions
2541 $$ = new ValueRefList();
2542 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2545 | ValueRefList ',' Types ValueRef OptParamAttrs {
2546 if (!UpRefs.empty())
2547 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2549 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2553 | /*empty*/ { $$ = new ValueRefList(); };
2555 IndexList // Used for gep instructions and constant expressions
2556 : /*empty*/ { $$ = new std::vector<Value*>(); }
2557 | IndexList ',' ResolvedVal {
2564 OptTailCall : TAIL CALL {
2573 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2574 if (!UpRefs.empty())
2575 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2576 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2577 !isa<PackedType>((*$2).get()))
2579 "Arithmetic operator requires integer, FP, or packed operands!");
2580 if (isa<PackedType>((*$2).get()) &&
2581 ($1 == Instruction::URem ||
2582 $1 == Instruction::SRem ||
2583 $1 == Instruction::FRem))
2584 GEN_ERROR("U/S/FRem not supported on packed types!");
2585 Value* val1 = getVal(*$2, $3);
2587 Value* val2 = getVal(*$2, $5);
2589 $$ = BinaryOperator::create($1, val1, val2);
2591 GEN_ERROR("binary operator returned null!");
2594 | LogicalOps Types ValueRef ',' ValueRef {
2595 if (!UpRefs.empty())
2596 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2597 if (!(*$2)->isIntegral()) {
2598 if (!isa<PackedType>($2->get()) ||
2599 !cast<PackedType>($2->get())->getElementType()->isIntegral())
2600 GEN_ERROR("Logical operator requires integral operands!");
2602 Value* tmpVal1 = getVal(*$2, $3);
2604 Value* tmpVal2 = getVal(*$2, $5);
2606 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2608 GEN_ERROR("binary operator returned null!");
2611 | ICMP IPredicates Types ValueRef ',' ValueRef {
2612 if (!UpRefs.empty())
2613 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2614 if (isa<PackedType>((*$3).get()))
2615 GEN_ERROR("Packed types not supported by icmp instruction");
2616 Value* tmpVal1 = getVal(*$3, $4);
2618 Value* tmpVal2 = getVal(*$3, $6);
2620 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2622 GEN_ERROR("icmp operator returned null!");
2624 | FCMP FPredicates Types ValueRef ',' ValueRef {
2625 if (!UpRefs.empty())
2626 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2627 if (isa<PackedType>((*$3).get()))
2628 GEN_ERROR("Packed types not supported by fcmp instruction");
2629 Value* tmpVal1 = getVal(*$3, $4);
2631 Value* tmpVal2 = getVal(*$3, $6);
2633 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2635 GEN_ERROR("fcmp operator returned null!");
2637 | ShiftOps ResolvedVal ',' ResolvedVal {
2638 if ($4->getType() != Type::Int8Ty)
2639 GEN_ERROR("Shift amount must be i8 type!");
2640 if (!$2->getType()->isInteger())
2641 GEN_ERROR("Shift constant expression requires integer operand!");
2643 $$ = new ShiftInst($1, $2, $4);
2646 | CastOps ResolvedVal TO Types {
2647 if (!UpRefs.empty())
2648 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2650 const Type* Ty = $4->get();
2651 if (!Val->getType()->isFirstClassType())
2652 GEN_ERROR("cast from a non-primitive type: '" +
2653 Val->getType()->getDescription() + "'!");
2654 if (!Ty->isFirstClassType())
2655 GEN_ERROR("cast to a non-primitive type: '" + Ty->getDescription() +"'!");
2656 $$ = CastInst::create($1, Val, $4->get());
2659 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2660 if ($2->getType() != Type::Int1Ty)
2661 GEN_ERROR("select condition must be boolean!");
2662 if ($4->getType() != $6->getType())
2663 GEN_ERROR("select value types should match!");
2664 $$ = new SelectInst($2, $4, $6);
2667 | VAARG ResolvedVal ',' Types {
2668 if (!UpRefs.empty())
2669 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2670 $$ = new VAArgInst($2, *$4);
2674 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2675 if (!ExtractElementInst::isValidOperands($2, $4))
2676 GEN_ERROR("Invalid extractelement operands!");
2677 $$ = new ExtractElementInst($2, $4);
2680 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2681 if (!InsertElementInst::isValidOperands($2, $4, $6))
2682 GEN_ERROR("Invalid insertelement operands!");
2683 $$ = new InsertElementInst($2, $4, $6);
2686 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2687 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2688 GEN_ERROR("Invalid shufflevector operands!");
2689 $$ = new ShuffleVectorInst($2, $4, $6);
2693 const Type *Ty = $2->front().first->getType();
2694 if (!Ty->isFirstClassType())
2695 GEN_ERROR("PHI node operands must be of first class type!");
2696 $$ = new PHINode(Ty);
2697 ((PHINode*)$$)->reserveOperandSpace($2->size());
2698 while ($2->begin() != $2->end()) {
2699 if ($2->front().first->getType() != Ty)
2700 GEN_ERROR("All elements of a PHI node must be of the same type!");
2701 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2704 delete $2; // Free the list...
2707 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2710 // Handle the short syntax
2711 const PointerType *PFTy = 0;
2712 const FunctionType *Ty = 0;
2713 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2714 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2715 // Pull out the types of all of the arguments...
2716 std::vector<const Type*> ParamTypes;
2717 FunctionType::ParamAttrsList ParamAttrs;
2718 ParamAttrs.push_back($8);
2719 for (ValueRefList::iterator I = $6->begin(), E = $6->end(); I != E; ++I) {
2720 const Type *Ty = I->Val->getType();
2721 if (Ty == Type::VoidTy)
2722 GEN_ERROR("Short call syntax cannot be used with varargs");
2723 ParamTypes.push_back(Ty);
2724 ParamAttrs.push_back(I->Attrs);
2727 Ty = FunctionType::get($3->get(), ParamTypes, false, ParamAttrs);
2728 PFTy = PointerType::get(Ty);
2731 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2734 // Check the arguments
2736 if ($6->empty()) { // Has no arguments?
2737 // Make sure no arguments is a good thing!
2738 if (Ty->getNumParams() != 0)
2739 GEN_ERROR("No arguments passed to a function that "
2740 "expects arguments!");
2741 } else { // Has arguments?
2742 // Loop through FunctionType's arguments and ensure they are specified
2745 FunctionType::param_iterator I = Ty->param_begin();
2746 FunctionType::param_iterator E = Ty->param_end();
2747 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2749 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2750 if (ArgI->Val->getType() != *I)
2751 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2752 (*I)->getDescription() + "'!");
2753 Args.push_back(ArgI->Val);
2755 if (Ty->isVarArg()) {
2757 for (; ArgI != ArgE; ++ArgI)
2758 Args.push_back(ArgI->Val); // push the remaining varargs
2759 } else if (I != E || ArgI != ArgE)
2760 GEN_ERROR("Invalid number of parameters detected!");
2762 // Create the call node
2763 CallInst *CI = new CallInst(V, Args);
2764 CI->setTailCall($1);
2765 CI->setCallingConv($2);
2775 OptVolatile : VOLATILE {
2786 MemoryInst : MALLOC Types OptCAlign {
2787 if (!UpRefs.empty())
2788 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2789 $$ = new MallocInst(*$2, 0, $3);
2793 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2794 if (!UpRefs.empty())
2795 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2796 Value* tmpVal = getVal($4, $5);
2798 $$ = new MallocInst(*$2, tmpVal, $6);
2801 | ALLOCA Types OptCAlign {
2802 if (!UpRefs.empty())
2803 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2804 $$ = new AllocaInst(*$2, 0, $3);
2808 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2809 if (!UpRefs.empty())
2810 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2811 Value* tmpVal = getVal($4, $5);
2813 $$ = new AllocaInst(*$2, tmpVal, $6);
2816 | FREE ResolvedVal {
2817 if (!isa<PointerType>($2->getType()))
2818 GEN_ERROR("Trying to free nonpointer type " +
2819 $2->getType()->getDescription() + "!");
2820 $$ = new FreeInst($2);
2824 | OptVolatile LOAD Types ValueRef {
2825 if (!UpRefs.empty())
2826 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2827 if (!isa<PointerType>($3->get()))
2828 GEN_ERROR("Can't load from nonpointer type: " +
2829 (*$3)->getDescription());
2830 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
2831 GEN_ERROR("Can't load from pointer of non-first-class type: " +
2832 (*$3)->getDescription());
2833 Value* tmpVal = getVal(*$3, $4);
2835 $$ = new LoadInst(tmpVal, "", $1);
2838 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
2839 if (!UpRefs.empty())
2840 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
2841 const PointerType *PT = dyn_cast<PointerType>($5->get());
2843 GEN_ERROR("Can't store to a nonpointer type: " +
2844 (*$5)->getDescription());
2845 const Type *ElTy = PT->getElementType();
2846 if (ElTy != $3->getType())
2847 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
2848 "' into space of type '" + ElTy->getDescription() + "'!");
2850 Value* tmpVal = getVal(*$5, $6);
2852 $$ = new StoreInst($3, tmpVal, $1);
2855 | GETELEMENTPTR Types ValueRef IndexList {
2856 if (!UpRefs.empty())
2857 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2858 if (!isa<PointerType>($2->get()))
2859 GEN_ERROR("getelementptr insn requires pointer operand!");
2861 if (!GetElementPtrInst::getIndexedType(*$2, *$4, true))
2862 GEN_ERROR("Invalid getelementptr indices for type '" +
2863 (*$2)->getDescription()+ "'!");
2864 Value* tmpVal = getVal(*$2, $3);
2866 $$ = new GetElementPtrInst(tmpVal, *$4);
2874 // common code from the two 'RunVMAsmParser' functions
2875 static Module* RunParser(Module * M) {
2877 llvmAsmlineno = 1; // Reset the current line number...
2878 CurModule.CurrentModule = M;
2883 // Check to make sure the parser succeeded
2886 delete ParserResult;
2890 // Check to make sure that parsing produced a result
2894 // Reset ParserResult variable while saving its value for the result.
2895 Module *Result = ParserResult;
2901 void llvm::GenerateError(const std::string &message, int LineNo) {
2902 if (LineNo == -1) LineNo = llvmAsmlineno;
2903 // TODO: column number in exception
2905 TheParseError->setError(CurFilename, message, LineNo);
2909 int yyerror(const char *ErrorMsg) {
2911 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
2912 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
2913 std::string errMsg = std::string(ErrorMsg) + "\n" + where + " while reading ";
2914 if (yychar == YYEMPTY || yychar == 0)
2915 errMsg += "end-of-file.";
2917 errMsg += "token: '" + std::string(llvmAsmtext, llvmAsmleng) + "'";
2918 GenerateError(errMsg);