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 (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
382 GenerateError("Signed integral constant '" +
383 itostr(D.ConstPool64) + "' is invalid for type '" +
384 Ty->getDescription() + "'");
387 return ConstantInt::get(Ty, D.ConstPool64, true);
389 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
390 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
391 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
392 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
393 "' is invalid or out of range");
395 } else { // This is really a signed reference. Transmogrify.
396 return ConstantInt::get(Ty, D.ConstPool64, true);
399 return ConstantInt::get(Ty, D.UConstPool64);
402 case ValID::ConstFPVal: // Is it a floating point const pool reference?
403 if (!ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
404 GenerateError("FP constant invalid for type");
407 // Lexer has no type info, so builds all float and double FP constants
408 // as double. Fix this here. Long double does not need this.
409 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
411 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
412 return ConstantFP::get(Ty, *D.ConstPoolFP);
414 case ValID::ConstNullVal: // Is it a null value?
415 if (!isa<PointerType>(Ty)) {
416 GenerateError("Cannot create a a non pointer null");
419 return ConstantPointerNull::get(cast<PointerType>(Ty));
421 case ValID::ConstUndefVal: // Is it an undef value?
422 return UndefValue::get(Ty);
424 case ValID::ConstZeroVal: // Is it a zero value?
425 return Constant::getNullValue(Ty);
427 case ValID::ConstantVal: // Fully resolved constant?
428 if (D.ConstantValue->getType() != Ty) {
429 GenerateError("Constant expression type different from required type");
432 return D.ConstantValue;
434 case ValID::InlineAsmVal: { // Inline asm expression
435 const PointerType *PTy = dyn_cast<PointerType>(Ty);
436 const FunctionType *FTy =
437 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
438 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
439 GenerateError("Invalid type for asm constraint string");
442 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
443 D.IAD->HasSideEffects);
444 D.destroy(); // Free InlineAsmDescriptor.
448 assert(0 && "Unhandled case!");
452 assert(0 && "Unhandled case!");
456 // getVal - This function is identical to getExistingVal, except that if a
457 // value is not already defined, it "improvises" by creating a placeholder var
458 // that looks and acts just like the requested variable. When the value is
459 // defined later, all uses of the placeholder variable are replaced with the
462 static Value *getVal(const Type *Ty, const ValID &ID) {
463 if (Ty == Type::LabelTy) {
464 GenerateError("Cannot use a basic block here");
468 // See if the value has already been defined.
469 Value *V = getExistingVal(Ty, ID);
471 if (TriggerError) return 0;
473 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
474 GenerateError("Invalid use of a composite type");
478 // If we reached here, we referenced either a symbol that we don't know about
479 // or an id number that hasn't been read yet. We may be referencing something
480 // forward, so just create an entry to be resolved later and get to it...
483 case ValID::GlobalName:
484 case ValID::GlobalID: {
485 const PointerType *PTy = dyn_cast<PointerType>(Ty);
487 GenerateError("Invalid type for reference to global" );
490 const Type* ElTy = PTy->getElementType();
491 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
492 V = new Function(FTy, GlobalValue::ExternalLinkage);
494 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
495 (Module*)0, false, PTy->getAddressSpace());
499 V = new Argument(Ty);
502 // Remember where this forward reference came from. FIXME, shouldn't we try
503 // to recycle these things??
504 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
507 if (inFunctionScope())
508 InsertValue(V, CurFun.LateResolveValues);
510 InsertValue(V, CurModule.LateResolveValues);
514 /// defineBBVal - This is a definition of a new basic block with the specified
515 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
516 static BasicBlock *defineBBVal(const ValID &ID) {
517 assert(inFunctionScope() && "Can't get basic block at global scope!");
521 // First, see if this was forward referenced
523 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
524 if (BBI != CurFun.BBForwardRefs.end()) {
526 // The forward declaration could have been inserted anywhere in the
527 // function: insert it into the correct place now.
528 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
529 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
531 // We're about to erase the entry, save the key so we can clean it up.
532 ValID Tmp = BBI->first;
534 // Erase the forward ref from the map as its no longer "forward"
535 CurFun.BBForwardRefs.erase(ID);
537 // The key has been removed from the map but so we don't want to leave
538 // strdup'd memory around so destroy it too.
541 // If its a numbered definition, bump the number and set the BB value.
542 if (ID.Type == ValID::LocalID) {
543 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
551 // We haven't seen this BB before and its first mention is a definition.
552 // Just create it and return it.
553 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
554 BB = new BasicBlock(Name, CurFun.CurrentFunction);
555 if (ID.Type == ValID::LocalID) {
556 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
560 ID.destroy(); // Free strdup'd memory
564 /// getBBVal - get an existing BB value or create a forward reference for it.
566 static BasicBlock *getBBVal(const ValID &ID) {
567 assert(inFunctionScope() && "Can't get basic block at global scope!");
571 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
572 if (BBI != CurFun.BBForwardRefs.end()) {
574 } if (ID.Type == ValID::LocalName) {
575 std::string Name = ID.getName();
576 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
578 if (N->getType()->getTypeID() == Type::LabelTyID)
579 BB = cast<BasicBlock>(N);
581 GenerateError("Reference to label '" + Name + "' is actually of type '"+
582 N->getType()->getDescription() + "'");
583 } else if (ID.Type == ValID::LocalID) {
584 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
585 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
586 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
588 GenerateError("Reference to label '%" + utostr(ID.Num) +
589 "' is actually of type '"+
590 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
593 GenerateError("Illegal label reference " + ID.getName());
597 // If its already been defined, return it now.
599 ID.destroy(); // Free strdup'd memory.
603 // Otherwise, this block has not been seen before, create it.
605 if (ID.Type == ValID::LocalName)
607 BB = new BasicBlock(Name, CurFun.CurrentFunction);
609 // Insert it in the forward refs map.
610 CurFun.BBForwardRefs[ID] = BB;
616 //===----------------------------------------------------------------------===//
617 // Code to handle forward references in instructions
618 //===----------------------------------------------------------------------===//
620 // This code handles the late binding needed with statements that reference
621 // values not defined yet... for example, a forward branch, or the PHI node for
624 // This keeps a table (CurFun.LateResolveValues) of all such forward references
625 // and back patchs after we are done.
628 // ResolveDefinitions - If we could not resolve some defs at parsing
629 // time (forward branches, phi functions for loops, etc...) resolve the
633 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
634 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
635 while (!LateResolvers.empty()) {
636 Value *V = LateResolvers.back();
637 LateResolvers.pop_back();
639 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
640 CurModule.PlaceHolderInfo.find(V);
641 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
643 ValID &DID = PHI->second.first;
645 Value *TheRealValue = getExistingVal(V->getType(), DID);
649 V->replaceAllUsesWith(TheRealValue);
651 CurModule.PlaceHolderInfo.erase(PHI);
652 } else if (FutureLateResolvers) {
653 // Functions have their unresolved items forwarded to the module late
655 InsertValue(V, *FutureLateResolvers);
657 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
658 GenerateError("Reference to an invalid definition: '" +DID.getName()+
659 "' of type '" + V->getType()->getDescription() + "'",
663 GenerateError("Reference to an invalid definition: #" +
664 itostr(DID.Num) + " of type '" +
665 V->getType()->getDescription() + "'",
671 LateResolvers.clear();
674 // ResolveTypeTo - A brand new type was just declared. This means that (if
675 // name is not null) things referencing Name can be resolved. Otherwise, things
676 // refering to the number can be resolved. Do this now.
678 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
681 D = ValID::createLocalName(*Name);
683 D = ValID::createLocalID(CurModule.Types.size());
685 std::map<ValID, PATypeHolder>::iterator I =
686 CurModule.LateResolveTypes.find(D);
687 if (I != CurModule.LateResolveTypes.end()) {
688 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
689 CurModule.LateResolveTypes.erase(I);
693 // setValueName - Set the specified value to the name given. The name may be
694 // null potentially, in which case this is a noop. The string passed in is
695 // assumed to be a malloc'd string buffer, and is free'd by this function.
697 static void setValueName(Value *V, std::string *NameStr) {
698 if (!NameStr) return;
699 std::string Name(*NameStr); // Copy string
700 delete NameStr; // Free old string
702 if (V->getType() == Type::VoidTy) {
703 GenerateError("Can't assign name '" + Name+"' to value with void type");
707 assert(inFunctionScope() && "Must be in function scope!");
708 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
709 if (ST.lookup(Name)) {
710 GenerateError("Redefinition of value '" + Name + "' of type '" +
711 V->getType()->getDescription() + "'");
719 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
720 /// this is a declaration, otherwise it is a definition.
721 static GlobalVariable *
722 ParseGlobalVariable(std::string *NameStr,
723 GlobalValue::LinkageTypes Linkage,
724 GlobalValue::VisibilityTypes Visibility,
725 bool isConstantGlobal, const Type *Ty,
726 Constant *Initializer, bool IsThreadLocal,
727 unsigned AddressSpace = 0) {
728 if (isa<FunctionType>(Ty)) {
729 GenerateError("Cannot declare global vars of function type");
733 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
737 Name = *NameStr; // Copy string
738 delete NameStr; // Free old string
741 // See if this global value was forward referenced. If so, recycle the
745 ID = ValID::createGlobalName(Name);
747 ID = ValID::createGlobalID(CurModule.Values.size());
750 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
751 // Move the global to the end of the list, from whereever it was
752 // previously inserted.
753 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
754 CurModule.CurrentModule->getGlobalList().remove(GV);
755 CurModule.CurrentModule->getGlobalList().push_back(GV);
756 GV->setInitializer(Initializer);
757 GV->setLinkage(Linkage);
758 GV->setVisibility(Visibility);
759 GV->setConstant(isConstantGlobal);
760 GV->setThreadLocal(IsThreadLocal);
761 InsertValue(GV, CurModule.Values);
765 // If this global has a name
767 // if the global we're parsing has an initializer (is a definition) and
768 // has external linkage.
769 if (Initializer && Linkage != GlobalValue::InternalLinkage)
770 // If there is already a global with external linkage with this name
771 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
772 // If we allow this GVar to get created, it will be renamed in the
773 // symbol table because it conflicts with an existing GVar. We can't
774 // allow redefinition of GVars whose linking indicates that their name
775 // must stay the same. Issue the error.
776 GenerateError("Redefinition of global variable named '" + Name +
777 "' of type '" + Ty->getDescription() + "'");
782 // Otherwise there is no existing GV to use, create one now.
784 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
785 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
786 GV->setVisibility(Visibility);
787 InsertValue(GV, CurModule.Values);
791 // setTypeName - Set the specified type to the name given. The name may be
792 // null potentially, in which case this is a noop. The string passed in is
793 // assumed to be a malloc'd string buffer, and is freed by this function.
795 // This function returns true if the type has already been defined, but is
796 // allowed to be redefined in the specified context. If the name is a new name
797 // for the type plane, it is inserted and false is returned.
798 static bool setTypeName(const Type *T, std::string *NameStr) {
799 assert(!inFunctionScope() && "Can't give types function-local names!");
800 if (NameStr == 0) return false;
802 std::string Name(*NameStr); // Copy string
803 delete NameStr; // Free old string
805 // We don't allow assigning names to void type
806 if (T == Type::VoidTy) {
807 GenerateError("Can't assign name '" + Name + "' to the void type");
811 // Set the type name, checking for conflicts as we do so.
812 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
814 if (AlreadyExists) { // Inserting a name that is already defined???
815 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
816 assert(Existing && "Conflict but no matching type?!");
818 // There is only one case where this is allowed: when we are refining an
819 // opaque type. In this case, Existing will be an opaque type.
820 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
821 // We ARE replacing an opaque type!
822 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
826 // Otherwise, this is an attempt to redefine a type. That's okay if
827 // the redefinition is identical to the original. This will be so if
828 // Existing and T point to the same Type object. In this one case we
829 // allow the equivalent redefinition.
830 if (Existing == T) return true; // Yes, it's equal.
832 // Any other kind of (non-equivalent) redefinition is an error.
833 GenerateError("Redefinition of type named '" + Name + "' of type '" +
834 T->getDescription() + "'");
840 //===----------------------------------------------------------------------===//
841 // Code for handling upreferences in type names...
844 // TypeContains - Returns true if Ty directly contains E in it.
846 static bool TypeContains(const Type *Ty, const Type *E) {
847 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
848 E) != Ty->subtype_end();
853 // NestingLevel - The number of nesting levels that need to be popped before
854 // this type is resolved.
855 unsigned NestingLevel;
857 // LastContainedTy - This is the type at the current binding level for the
858 // type. Every time we reduce the nesting level, this gets updated.
859 const Type *LastContainedTy;
861 // UpRefTy - This is the actual opaque type that the upreference is
865 UpRefRecord(unsigned NL, OpaqueType *URTy)
866 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
870 // UpRefs - A list of the outstanding upreferences that need to be resolved.
871 static std::vector<UpRefRecord> UpRefs;
873 /// HandleUpRefs - Every time we finish a new layer of types, this function is
874 /// called. It loops through the UpRefs vector, which is a list of the
875 /// currently active types. For each type, if the up reference is contained in
876 /// the newly completed type, we decrement the level count. When the level
877 /// count reaches zero, the upreferenced type is the type that is passed in:
878 /// thus we can complete the cycle.
880 static PATypeHolder HandleUpRefs(const Type *ty) {
881 // If Ty isn't abstract, or if there are no up-references in it, then there is
882 // nothing to resolve here.
883 if (!ty->isAbstract() || UpRefs.empty()) return ty;
886 UR_OUT("Type '" << Ty->getDescription() <<
887 "' newly formed. Resolving upreferences.\n" <<
888 UpRefs.size() << " upreferences active!\n");
890 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
891 // to zero), we resolve them all together before we resolve them to Ty. At
892 // the end of the loop, if there is anything to resolve to Ty, it will be in
894 OpaqueType *TypeToResolve = 0;
896 for (unsigned i = 0; i != UpRefs.size(); ++i) {
897 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
898 << UpRefs[i].second->getDescription() << ") = "
899 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
900 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
901 // Decrement level of upreference
902 unsigned Level = --UpRefs[i].NestingLevel;
903 UpRefs[i].LastContainedTy = Ty;
904 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
905 if (Level == 0) { // Upreference should be resolved!
906 if (!TypeToResolve) {
907 TypeToResolve = UpRefs[i].UpRefTy;
909 UR_OUT(" * Resolving upreference for "
910 << UpRefs[i].second->getDescription() << "\n";
911 std::string OldName = UpRefs[i].UpRefTy->getDescription());
912 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
913 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
914 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
916 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
917 --i; // Do not skip the next element...
923 UR_OUT(" * Resolving upreference for "
924 << UpRefs[i].second->getDescription() << "\n";
925 std::string OldName = TypeToResolve->getDescription());
926 TypeToResolve->refineAbstractTypeTo(Ty);
932 //===----------------------------------------------------------------------===//
933 // RunVMAsmParser - Define an interface to this parser
934 //===----------------------------------------------------------------------===//
936 static Module* RunParser(Module * M);
938 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
940 Module *M = RunParser(new Module(LLLgetFilename()));
948 llvm::Module *ModuleVal;
949 llvm::Function *FunctionVal;
950 llvm::BasicBlock *BasicBlockVal;
951 llvm::TerminatorInst *TermInstVal;
952 llvm::Instruction *InstVal;
953 llvm::Constant *ConstVal;
955 const llvm::Type *PrimType;
956 std::list<llvm::PATypeHolder> *TypeList;
957 llvm::PATypeHolder *TypeVal;
958 llvm::Value *ValueVal;
959 std::vector<llvm::Value*> *ValueList;
960 llvm::ArgListType *ArgList;
961 llvm::TypeWithAttrs TypeWithAttrs;
962 llvm::TypeWithAttrsList *TypeWithAttrsList;
963 llvm::ParamList *ParamList;
965 // Represent the RHS of PHI node
966 std::list<std::pair<llvm::Value*,
967 llvm::BasicBlock*> > *PHIList;
968 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
969 std::vector<llvm::Constant*> *ConstVector;
971 llvm::GlobalValue::LinkageTypes Linkage;
972 llvm::GlobalValue::VisibilityTypes Visibility;
974 llvm::APInt *APIntVal;
979 llvm::APFloat *FPVal;
982 std::string *StrVal; // This memory must be deleted
983 llvm::ValID ValIDVal;
985 llvm::Instruction::BinaryOps BinaryOpVal;
986 llvm::Instruction::TermOps TermOpVal;
987 llvm::Instruction::MemoryOps MemOpVal;
988 llvm::Instruction::CastOps CastOpVal;
989 llvm::Instruction::OtherOps OtherOpVal;
990 llvm::ICmpInst::Predicate IPredicate;
991 llvm::FCmpInst::Predicate FPredicate;
994 %type <ModuleVal> Module
995 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
996 %type <BasicBlockVal> BasicBlock InstructionList
997 %type <TermInstVal> BBTerminatorInst
998 %type <InstVal> Inst InstVal MemoryInst
999 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1000 %type <ConstVector> ConstVector
1001 %type <ArgList> ArgList ArgListH
1002 %type <PHIList> PHIList
1003 %type <ParamList> ParamList // For call param lists & GEP indices
1004 %type <ValueList> IndexList // For GEP indices
1005 %type <TypeList> TypeListI
1006 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1007 %type <TypeWithAttrs> ArgType
1008 %type <JumpTable> JumpTable
1009 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1010 %type <BoolVal> ThreadLocal // 'thread_local' or not
1011 %type <BoolVal> OptVolatile // 'volatile' or not
1012 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1013 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1014 %type <Linkage> GVInternalLinkage GVExternalLinkage
1015 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1016 %type <Linkage> AliasLinkage
1017 %type <Visibility> GVVisibilityStyle
1019 // ValueRef - Unresolved reference to a definition or BB
1020 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1021 %type <ValueVal> ResolvedVal // <type> <valref> pair
1022 // Tokens and types for handling constant integer values
1024 // ESINT64VAL - A negative number within long long range
1025 %token <SInt64Val> ESINT64VAL
1027 // EUINT64VAL - A positive number within uns. long long range
1028 %token <UInt64Val> EUINT64VAL
1030 // ESAPINTVAL - A negative number with arbitrary precision
1031 %token <APIntVal> ESAPINTVAL
1033 // EUAPINTVAL - A positive number with arbitrary precision
1034 %token <APIntVal> EUAPINTVAL
1036 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1037 %token <FPVal> FPVAL // Float or Double constant
1039 // Built in types...
1040 %type <TypeVal> Types ResultTypes
1041 %type <PrimType> IntType FPType PrimType // Classifications
1042 %token <PrimType> VOID INTTYPE
1043 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1047 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1048 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1049 %type <StrVal> LocalName OptLocalName OptLocalAssign
1050 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1051 %type <StrVal> OptSection SectionString OptGC
1053 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1055 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1056 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1057 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1058 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1059 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1060 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1061 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1063 %type <UIntVal> OptCallingConv
1064 %type <ParamAttrs> OptParamAttrs ParamAttr
1065 %type <ParamAttrs> OptFuncAttrs FuncAttr
1067 // Basic Block Terminating Operators
1068 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1071 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1072 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1073 %token <BinaryOpVal> SHL LSHR ASHR
1075 %token <OtherOpVal> ICMP FCMP
1076 %type <IPredicate> IPredicates
1077 %type <FPredicate> FPredicates
1078 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1079 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1081 // Memory Instructions
1082 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1085 %type <CastOpVal> CastOps
1086 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1087 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1090 %token <OtherOpVal> PHI_TOK SELECT VAARG
1091 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1093 // Function Attributes
1094 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1095 %token READNONE READONLY GC
1097 // Visibility Styles
1098 %token DEFAULT HIDDEN PROTECTED
1104 // Operations that are notably excluded from this list include:
1105 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1107 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1108 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1109 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1110 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1113 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1114 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1115 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1116 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1117 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1121 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1122 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1123 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1124 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1125 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1126 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1127 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1128 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1129 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1132 // These are some types that allow classification if we only want a particular
1133 // thing... for example, only a signed, unsigned, or integral type.
1135 FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1137 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1138 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1140 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1141 | /*empty*/ { $$=0; };
1143 /// OptLocalAssign - Value producing statements have an optional assignment
1145 OptLocalAssign : LocalName '=' {
1154 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1156 OptGlobalAssign : GlobalAssign
1162 GlobalAssign : GlobalName '=' {
1168 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1169 | WEAK { $$ = GlobalValue::WeakLinkage; }
1170 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1171 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1172 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1176 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1177 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1178 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1182 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1183 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1184 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1185 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1188 FunctionDeclareLinkage
1189 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1190 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1191 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1194 FunctionDefineLinkage
1195 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1196 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1197 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1198 | WEAK { $$ = GlobalValue::WeakLinkage; }
1199 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1203 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1204 | WEAK { $$ = GlobalValue::WeakLinkage; }
1205 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1208 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1209 CCC_TOK { $$ = CallingConv::C; } |
1210 FASTCC_TOK { $$ = CallingConv::Fast; } |
1211 COLDCC_TOK { $$ = CallingConv::Cold; } |
1212 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1213 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1215 if ((unsigned)$2 != $2)
1216 GEN_ERROR("Calling conv too large");
1221 ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1222 | ZEXT { $$ = ParamAttr::ZExt; }
1223 | SIGNEXT { $$ = ParamAttr::SExt; }
1224 | SEXT { $$ = ParamAttr::SExt; }
1225 | INREG { $$ = ParamAttr::InReg; }
1226 | SRET { $$ = ParamAttr::StructRet; }
1227 | NOALIAS { $$ = ParamAttr::NoAlias; }
1228 | BYVAL { $$ = ParamAttr::ByVal; }
1229 | NEST { $$ = ParamAttr::Nest; }
1232 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1233 | OptParamAttrs ParamAttr {
1238 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1239 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1240 | ZEROEXT { $$ = ParamAttr::ZExt; }
1241 | SIGNEXT { $$ = ParamAttr::SExt; }
1242 | READNONE { $$ = ParamAttr::ReadNone; }
1243 | READONLY { $$ = ParamAttr::ReadOnly; }
1246 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1247 | OptFuncAttrs FuncAttr {
1252 OptGC : /* empty */ { $$ = 0; }
1253 | GC STRINGCONSTANT {
1258 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1259 // a comma before it.
1260 OptAlign : /*empty*/ { $$ = 0; } |
1263 if ($$ != 0 && !isPowerOf2_32($$))
1264 GEN_ERROR("Alignment must be a power of two");
1267 OptCAlign : /*empty*/ { $$ = 0; } |
1268 ',' ALIGN EUINT64VAL {
1270 if ($$ != 0 && !isPowerOf2_32($$))
1271 GEN_ERROR("Alignment must be a power of two");
1277 SectionString : SECTION STRINGCONSTANT {
1278 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1279 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1280 GEN_ERROR("Invalid character in section name");
1285 OptSection : /*empty*/ { $$ = 0; } |
1286 SectionString { $$ = $1; };
1288 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1289 // is set to be the global we are processing.
1291 GlobalVarAttributes : /* empty */ {} |
1292 ',' GlobalVarAttribute GlobalVarAttributes {};
1293 GlobalVarAttribute : SectionString {
1294 CurGV->setSection(*$1);
1298 | ALIGN EUINT64VAL {
1299 if ($2 != 0 && !isPowerOf2_32($2))
1300 GEN_ERROR("Alignment must be a power of two");
1301 CurGV->setAlignment($2);
1305 //===----------------------------------------------------------------------===//
1306 // Types includes all predefined types... except void, because it can only be
1307 // used in specific contexts (function returning void for example).
1309 // Derived types are added later...
1311 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1315 $$ = new PATypeHolder(OpaqueType::get());
1319 $$ = new PATypeHolder($1);
1322 | Types OptAddrSpace '*' { // Pointer type?
1323 if (*$1 == Type::LabelTy)
1324 GEN_ERROR("Cannot form a pointer to a basic block");
1325 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1329 | SymbolicValueRef { // Named types are also simple types...
1330 const Type* tmp = getTypeVal($1);
1332 $$ = new PATypeHolder(tmp);
1334 | '\\' EUINT64VAL { // Type UpReference
1335 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1336 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1337 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1338 $$ = new PATypeHolder(OT);
1339 UR_OUT("New Upreference!\n");
1342 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1343 // Allow but ignore attributes on function types; this permits auto-upgrade.
1344 // FIXME: remove in LLVM 3.0.
1345 const Type* RetTy = *$1;
1346 if (!(RetTy->isFirstClassType() || RetTy == Type::VoidTy ||
1347 isa<OpaqueType>(RetTy)))
1348 GEN_ERROR("LLVM Functions cannot return aggregates");
1350 std::vector<const Type*> Params;
1351 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1352 for (; I != E; ++I ) {
1353 const Type *Ty = I->Ty->get();
1354 Params.push_back(Ty);
1357 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1358 if (isVarArg) Params.pop_back();
1360 for (unsigned i = 0; i != Params.size(); ++i)
1361 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1362 GEN_ERROR("Function arguments must be value types!");
1366 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1367 delete $3; // Delete the argument list
1368 delete $1; // Delete the return type handle
1369 $$ = new PATypeHolder(HandleUpRefs(FT));
1372 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1373 // Allow but ignore attributes on function types; this permits auto-upgrade.
1374 // FIXME: remove in LLVM 3.0.
1375 std::vector<const Type*> Params;
1376 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1377 for ( ; I != E; ++I ) {
1378 const Type* Ty = I->Ty->get();
1379 Params.push_back(Ty);
1382 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1383 if (isVarArg) Params.pop_back();
1385 for (unsigned i = 0; i != Params.size(); ++i)
1386 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1387 GEN_ERROR("Function arguments must be value types!");
1391 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1392 delete $3; // Delete the argument list
1393 $$ = new PATypeHolder(HandleUpRefs(FT));
1397 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1398 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1402 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1403 const llvm::Type* ElemTy = $4->get();
1404 if ((unsigned)$2 != $2)
1405 GEN_ERROR("Unsigned result not equal to signed result");
1406 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1407 GEN_ERROR("Element type of a VectorType must be primitive");
1408 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1412 | '{' TypeListI '}' { // Structure type?
1413 std::vector<const Type*> Elements;
1414 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1415 E = $2->end(); I != E; ++I)
1416 Elements.push_back(*I);
1418 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1422 | '{' '}' { // Empty structure type?
1423 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1426 | '<' '{' TypeListI '}' '>' {
1427 std::vector<const Type*> Elements;
1428 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1429 E = $3->end(); I != E; ++I)
1430 Elements.push_back(*I);
1432 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1436 | '<' '{' '}' '>' { // Empty structure type?
1437 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1443 : Types OptParamAttrs {
1444 // Allow but ignore attributes on function types; this permits auto-upgrade.
1445 // FIXME: remove in LLVM 3.0.
1447 $$.Attrs = ParamAttr::None;
1453 if (!UpRefs.empty())
1454 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1455 if (!(*$1)->isFirstClassType())
1456 GEN_ERROR("LLVM functions cannot return aggregate types");
1460 $$ = new PATypeHolder(Type::VoidTy);
1464 ArgTypeList : ArgType {
1465 $$ = new TypeWithAttrsList();
1469 | ArgTypeList ',' ArgType {
1470 ($$=$1)->push_back($3);
1477 | ArgTypeList ',' DOTDOTDOT {
1479 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1480 TWA.Ty = new PATypeHolder(Type::VoidTy);
1485 $$ = new TypeWithAttrsList;
1486 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1487 TWA.Ty = new PATypeHolder(Type::VoidTy);
1492 $$ = new TypeWithAttrsList();
1496 // TypeList - Used for struct declarations and as a basis for function type
1497 // declaration type lists
1500 $$ = new std::list<PATypeHolder>();
1505 | TypeListI ',' Types {
1506 ($$=$1)->push_back(*$3);
1511 // ConstVal - The various declarations that go into the constant pool. This
1512 // production is used ONLY to represent constants that show up AFTER a 'const',
1513 // 'constant' or 'global' token at global scope. Constants that can be inlined
1514 // into other expressions (such as integers and constexprs) are handled by the
1515 // ResolvedVal, ValueRef and ConstValueRef productions.
1517 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1518 if (!UpRefs.empty())
1519 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1520 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1522 GEN_ERROR("Cannot make array constant with type: '" +
1523 (*$1)->getDescription() + "'");
1524 const Type *ETy = ATy->getElementType();
1525 int NumElements = ATy->getNumElements();
1527 // Verify that we have the correct size...
1528 if (NumElements != -1 && NumElements != (int)$3->size())
1529 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1530 utostr($3->size()) + " arguments, but has size of " +
1531 itostr(NumElements) + "");
1533 // Verify all elements are correct type!
1534 for (unsigned i = 0; i < $3->size(); i++) {
1535 if (ETy != (*$3)[i]->getType())
1536 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1537 ETy->getDescription() +"' as required!\nIt is of type '"+
1538 (*$3)[i]->getType()->getDescription() + "'.");
1541 $$ = ConstantArray::get(ATy, *$3);
1542 delete $1; delete $3;
1546 if (!UpRefs.empty())
1547 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1548 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1550 GEN_ERROR("Cannot make array constant with type: '" +
1551 (*$1)->getDescription() + "'");
1553 int NumElements = ATy->getNumElements();
1554 if (NumElements != -1 && NumElements != 0)
1555 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1556 " arguments, but has size of " + itostr(NumElements) +"");
1557 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1561 | Types 'c' STRINGCONSTANT {
1562 if (!UpRefs.empty())
1563 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1564 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1566 GEN_ERROR("Cannot make array constant with type: '" +
1567 (*$1)->getDescription() + "'");
1569 int NumElements = ATy->getNumElements();
1570 const Type *ETy = ATy->getElementType();
1571 if (NumElements != -1 && NumElements != int($3->length()))
1572 GEN_ERROR("Can't build string constant of size " +
1573 itostr((int)($3->length())) +
1574 " when array has size " + itostr(NumElements) + "");
1575 std::vector<Constant*> Vals;
1576 if (ETy == Type::Int8Ty) {
1577 for (unsigned i = 0; i < $3->length(); ++i)
1578 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1581 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1584 $$ = ConstantArray::get(ATy, Vals);
1588 | Types '<' ConstVector '>' { // Nonempty unsized arr
1589 if (!UpRefs.empty())
1590 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1591 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1593 GEN_ERROR("Cannot make packed constant with type: '" +
1594 (*$1)->getDescription() + "'");
1595 const Type *ETy = PTy->getElementType();
1596 int NumElements = PTy->getNumElements();
1598 // Verify that we have the correct size...
1599 if (NumElements != -1 && NumElements != (int)$3->size())
1600 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1601 utostr($3->size()) + " arguments, but has size of " +
1602 itostr(NumElements) + "");
1604 // Verify all elements are correct type!
1605 for (unsigned i = 0; i < $3->size(); i++) {
1606 if (ETy != (*$3)[i]->getType())
1607 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1608 ETy->getDescription() +"' as required!\nIt is of type '"+
1609 (*$3)[i]->getType()->getDescription() + "'.");
1612 $$ = ConstantVector::get(PTy, *$3);
1613 delete $1; delete $3;
1616 | Types '{' ConstVector '}' {
1617 const StructType *STy = dyn_cast<StructType>($1->get());
1619 GEN_ERROR("Cannot make struct constant with type: '" +
1620 (*$1)->getDescription() + "'");
1622 if ($3->size() != STy->getNumContainedTypes())
1623 GEN_ERROR("Illegal number of initializers for structure type");
1625 // Check to ensure that constants are compatible with the type initializer!
1626 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1627 if ((*$3)[i]->getType() != STy->getElementType(i))
1628 GEN_ERROR("Expected type '" +
1629 STy->getElementType(i)->getDescription() +
1630 "' for element #" + utostr(i) +
1631 " of structure initializer");
1633 // Check to ensure that Type is not packed
1634 if (STy->isPacked())
1635 GEN_ERROR("Unpacked Initializer to vector type '" +
1636 STy->getDescription() + "'");
1638 $$ = ConstantStruct::get(STy, *$3);
1639 delete $1; delete $3;
1643 if (!UpRefs.empty())
1644 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1645 const StructType *STy = dyn_cast<StructType>($1->get());
1647 GEN_ERROR("Cannot make struct constant with type: '" +
1648 (*$1)->getDescription() + "'");
1650 if (STy->getNumContainedTypes() != 0)
1651 GEN_ERROR("Illegal number of initializers for structure type");
1653 // Check to ensure that Type is not packed
1654 if (STy->isPacked())
1655 GEN_ERROR("Unpacked Initializer to vector type '" +
1656 STy->getDescription() + "'");
1658 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1662 | Types '<' '{' ConstVector '}' '>' {
1663 const StructType *STy = dyn_cast<StructType>($1->get());
1665 GEN_ERROR("Cannot make struct constant with type: '" +
1666 (*$1)->getDescription() + "'");
1668 if ($4->size() != STy->getNumContainedTypes())
1669 GEN_ERROR("Illegal number of initializers for structure type");
1671 // Check to ensure that constants are compatible with the type initializer!
1672 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1673 if ((*$4)[i]->getType() != STy->getElementType(i))
1674 GEN_ERROR("Expected type '" +
1675 STy->getElementType(i)->getDescription() +
1676 "' for element #" + utostr(i) +
1677 " of structure initializer");
1679 // Check to ensure that Type is packed
1680 if (!STy->isPacked())
1681 GEN_ERROR("Vector initializer to non-vector type '" +
1682 STy->getDescription() + "'");
1684 $$ = ConstantStruct::get(STy, *$4);
1685 delete $1; delete $4;
1688 | Types '<' '{' '}' '>' {
1689 if (!UpRefs.empty())
1690 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1691 const StructType *STy = dyn_cast<StructType>($1->get());
1693 GEN_ERROR("Cannot make struct constant with type: '" +
1694 (*$1)->getDescription() + "'");
1696 if (STy->getNumContainedTypes() != 0)
1697 GEN_ERROR("Illegal number of initializers for structure type");
1699 // Check to ensure that Type is packed
1700 if (!STy->isPacked())
1701 GEN_ERROR("Vector initializer to non-vector type '" +
1702 STy->getDescription() + "'");
1704 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1709 if (!UpRefs.empty())
1710 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1711 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1713 GEN_ERROR("Cannot make null pointer constant with type: '" +
1714 (*$1)->getDescription() + "'");
1716 $$ = ConstantPointerNull::get(PTy);
1721 if (!UpRefs.empty())
1722 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1723 $$ = UndefValue::get($1->get());
1727 | Types SymbolicValueRef {
1728 if (!UpRefs.empty())
1729 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1730 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1732 GEN_ERROR("Global const reference must be a pointer type");
1734 // ConstExprs can exist in the body of a function, thus creating
1735 // GlobalValues whenever they refer to a variable. Because we are in
1736 // the context of a function, getExistingVal will search the functions
1737 // symbol table instead of the module symbol table for the global symbol,
1738 // which throws things all off. To get around this, we just tell
1739 // getExistingVal that we are at global scope here.
1741 Function *SavedCurFn = CurFun.CurrentFunction;
1742 CurFun.CurrentFunction = 0;
1744 Value *V = getExistingVal(Ty, $2);
1747 CurFun.CurrentFunction = SavedCurFn;
1749 // If this is an initializer for a constant pointer, which is referencing a
1750 // (currently) undefined variable, create a stub now that shall be replaced
1751 // in the future with the right type of variable.
1754 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1755 const PointerType *PT = cast<PointerType>(Ty);
1757 // First check to see if the forward references value is already created!
1758 PerModuleInfo::GlobalRefsType::iterator I =
1759 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1761 if (I != CurModule.GlobalRefs.end()) {
1762 V = I->second; // Placeholder already exists, use it...
1766 if ($2.Type == ValID::GlobalName)
1767 Name = $2.getName();
1768 else if ($2.Type != ValID::GlobalID)
1769 GEN_ERROR("Invalid reference to global");
1771 // Create the forward referenced global.
1773 if (const FunctionType *FTy =
1774 dyn_cast<FunctionType>(PT->getElementType())) {
1775 GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1776 CurModule.CurrentModule);
1778 GV = new GlobalVariable(PT->getElementType(), false,
1779 GlobalValue::ExternalWeakLinkage, 0,
1780 Name, CurModule.CurrentModule);
1783 // Keep track of the fact that we have a forward ref to recycle it
1784 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1789 $$ = cast<GlobalValue>(V);
1790 delete $1; // Free the type handle
1794 if (!UpRefs.empty())
1795 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1796 if ($1->get() != $2->getType())
1797 GEN_ERROR("Mismatched types for constant expression: " +
1798 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1803 | Types ZEROINITIALIZER {
1804 if (!UpRefs.empty())
1805 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1806 const Type *Ty = $1->get();
1807 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1808 GEN_ERROR("Cannot create a null initialized value of this type");
1809 $$ = Constant::getNullValue(Ty);
1813 | IntType ESINT64VAL { // integral constants
1814 if (!ConstantInt::isValueValidForType($1, $2))
1815 GEN_ERROR("Constant value doesn't fit in type");
1816 $$ = ConstantInt::get($1, $2, true);
1819 | IntType ESAPINTVAL { // arbitrary precision integer constants
1820 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1821 if ($2->getBitWidth() > BitWidth) {
1822 GEN_ERROR("Constant value does not fit in type");
1824 $2->sextOrTrunc(BitWidth);
1825 $$ = ConstantInt::get(*$2);
1829 | IntType EUINT64VAL { // integral constants
1830 if (!ConstantInt::isValueValidForType($1, $2))
1831 GEN_ERROR("Constant value doesn't fit in type");
1832 $$ = ConstantInt::get($1, $2, false);
1835 | IntType EUAPINTVAL { // arbitrary precision integer constants
1836 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1837 if ($2->getBitWidth() > BitWidth) {
1838 GEN_ERROR("Constant value does not fit in type");
1840 $2->zextOrTrunc(BitWidth);
1841 $$ = ConstantInt::get(*$2);
1845 | INTTYPE TRUETOK { // Boolean constants
1846 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1847 $$ = ConstantInt::getTrue();
1850 | INTTYPE FALSETOK { // Boolean constants
1851 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1852 $$ = ConstantInt::getFalse();
1855 | FPType FPVAL { // Floating point constants
1856 if (!ConstantFP::isValueValidForType($1, *$2))
1857 GEN_ERROR("Floating point constant invalid for type");
1858 // Lexer has no type info, so builds all float and double FP constants
1859 // as double. Fix this here. Long double is done right.
1860 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1861 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1862 $$ = ConstantFP::get($1, *$2);
1868 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1869 if (!UpRefs.empty())
1870 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1872 const Type *DestTy = $5->get();
1873 if (!CastInst::castIsValid($1, $3, DestTy))
1874 GEN_ERROR("invalid cast opcode for cast from '" +
1875 Val->getType()->getDescription() + "' to '" +
1876 DestTy->getDescription() + "'");
1877 $$ = ConstantExpr::getCast($1, $3, DestTy);
1880 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1881 if (!isa<PointerType>($3->getType()))
1882 GEN_ERROR("GetElementPtr requires a pointer operand");
1885 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
1888 GEN_ERROR("Index list invalid for constant getelementptr");
1890 SmallVector<Constant*, 8> IdxVec;
1891 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1892 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1893 IdxVec.push_back(C);
1895 GEN_ERROR("Indices to constant getelementptr must be constants");
1899 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1902 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1903 if ($3->getType() != Type::Int1Ty)
1904 GEN_ERROR("Select condition must be of boolean type");
1905 if ($5->getType() != $7->getType())
1906 GEN_ERROR("Select operand types must match");
1907 $$ = ConstantExpr::getSelect($3, $5, $7);
1910 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1911 if ($3->getType() != $5->getType())
1912 GEN_ERROR("Binary operator types must match");
1914 $$ = ConstantExpr::get($1, $3, $5);
1916 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1917 if ($3->getType() != $5->getType())
1918 GEN_ERROR("Logical operator types must match");
1919 if (!$3->getType()->isInteger()) {
1920 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1921 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1922 GEN_ERROR("Logical operator requires integral operands");
1924 $$ = ConstantExpr::get($1, $3, $5);
1927 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1928 if ($4->getType() != $6->getType())
1929 GEN_ERROR("icmp operand types must match");
1930 $$ = ConstantExpr::getICmp($2, $4, $6);
1932 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1933 if ($4->getType() != $6->getType())
1934 GEN_ERROR("fcmp operand types must match");
1935 $$ = ConstantExpr::getFCmp($2, $4, $6);
1937 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1938 if (!ExtractElementInst::isValidOperands($3, $5))
1939 GEN_ERROR("Invalid extractelement operands");
1940 $$ = ConstantExpr::getExtractElement($3, $5);
1943 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1944 if (!InsertElementInst::isValidOperands($3, $5, $7))
1945 GEN_ERROR("Invalid insertelement operands");
1946 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1949 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1950 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1951 GEN_ERROR("Invalid shufflevector operands");
1952 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1957 // ConstVector - A list of comma separated constants.
1958 ConstVector : ConstVector ',' ConstVal {
1959 ($$ = $1)->push_back($3);
1963 $$ = new std::vector<Constant*>();
1969 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1970 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1973 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1975 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1976 AliaseeRef : ResultTypes SymbolicValueRef {
1977 const Type* VTy = $1->get();
1978 Value *V = getVal(VTy, $2);
1980 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1982 GEN_ERROR("Aliases can be created only to global values");
1988 | BITCAST '(' AliaseeRef TO Types ')' {
1990 const Type *DestTy = $5->get();
1991 if (!CastInst::castIsValid($1, $3, DestTy))
1992 GEN_ERROR("invalid cast opcode for cast from '" +
1993 Val->getType()->getDescription() + "' to '" +
1994 DestTy->getDescription() + "'");
1996 $$ = ConstantExpr::getCast($1, $3, DestTy);
2001 //===----------------------------------------------------------------------===//
2002 // Rules to match Modules
2003 //===----------------------------------------------------------------------===//
2005 // Module rule: Capture the result of parsing the whole file into a result
2010 $$ = ParserResult = CurModule.CurrentModule;
2011 CurModule.ModuleDone();
2015 $$ = ParserResult = CurModule.CurrentModule;
2016 CurModule.ModuleDone();
2023 | DefinitionList Definition
2027 : DEFINE { CurFun.isDeclare = false; } Function {
2028 CurFun.FunctionDone();
2031 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2034 | MODULE ASM_TOK AsmBlock {
2037 | OptLocalAssign TYPE Types {
2038 if (!UpRefs.empty())
2039 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2040 // Eagerly resolve types. This is not an optimization, this is a
2041 // requirement that is due to the fact that we could have this:
2043 // %list = type { %list * }
2044 // %list = type { %list * } ; repeated type decl
2046 // If types are not resolved eagerly, then the two types will not be
2047 // determined to be the same type!
2049 ResolveTypeTo($1, *$3);
2051 if (!setTypeName(*$3, $1) && !$1) {
2053 // If this is a named type that is not a redefinition, add it to the slot
2055 CurModule.Types.push_back(*$3);
2061 | OptLocalAssign TYPE VOID {
2062 ResolveTypeTo($1, $3);
2064 if (!setTypeName($3, $1) && !$1) {
2066 // If this is a named type that is not a redefinition, add it to the slot
2068 CurModule.Types.push_back($3);
2072 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2074 /* "Externally Visible" Linkage */
2076 GEN_ERROR("Global value initializer is not a constant");
2077 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2078 $2, $4, $5->getType(), $5, $3, $6);
2080 } GlobalVarAttributes {
2083 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2084 ConstVal OptAddrSpace {
2086 GEN_ERROR("Global value initializer is not a constant");
2087 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2089 } GlobalVarAttributes {
2092 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2093 Types OptAddrSpace {
2094 if (!UpRefs.empty())
2095 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2096 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2099 } GlobalVarAttributes {
2103 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2110 GEN_ERROR("Alias name cannot be empty");
2112 Constant* Aliasee = $5;
2114 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2116 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2117 CurModule.CurrentModule);
2118 GA->setVisibility($2);
2119 InsertValue(GA, CurModule.Values);
2122 // If there was a forward reference of this alias, resolve it now.
2126 ID = ValID::createGlobalName(Name);
2128 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2130 if (GlobalValue *FWGV =
2131 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2132 // Replace uses of the fwdref with the actual alias.
2133 FWGV->replaceAllUsesWith(GA);
2134 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2135 GV->eraseFromParent();
2137 cast<Function>(FWGV)->eraseFromParent();
2143 | TARGET TargetDefinition {
2146 | DEPLIBS '=' LibrariesDefinition {
2152 AsmBlock : STRINGCONSTANT {
2153 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2154 if (AsmSoFar.empty())
2155 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2157 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2162 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2163 CurModule.CurrentModule->setTargetTriple(*$3);
2166 | DATALAYOUT '=' STRINGCONSTANT {
2167 CurModule.CurrentModule->setDataLayout(*$3);
2171 LibrariesDefinition : '[' LibList ']';
2173 LibList : LibList ',' STRINGCONSTANT {
2174 CurModule.CurrentModule->addLibrary(*$3);
2179 CurModule.CurrentModule->addLibrary(*$1);
2183 | /* empty: end of list */ {
2188 //===----------------------------------------------------------------------===//
2189 // Rules to match Function Headers
2190 //===----------------------------------------------------------------------===//
2192 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2193 if (!UpRefs.empty())
2194 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2195 if (*$3 == Type::VoidTy)
2196 GEN_ERROR("void typed arguments are invalid");
2197 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2202 | Types OptParamAttrs OptLocalName {
2203 if (!UpRefs.empty())
2204 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2205 if (*$1 == Type::VoidTy)
2206 GEN_ERROR("void typed arguments are invalid");
2207 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2208 $$ = new ArgListType;
2213 ArgList : ArgListH {
2217 | ArgListH ',' DOTDOTDOT {
2219 struct ArgListEntry E;
2220 E.Ty = new PATypeHolder(Type::VoidTy);
2222 E.Attrs = ParamAttr::None;
2227 $$ = new ArgListType;
2228 struct ArgListEntry E;
2229 E.Ty = new PATypeHolder(Type::VoidTy);
2231 E.Attrs = ParamAttr::None;
2240 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2241 OptFuncAttrs OptSection OptAlign OptGC {
2242 std::string FunctionName(*$3);
2243 delete $3; // Free strdup'd memory!
2245 // Check the function result for abstractness if this is a define. We should
2246 // have no abstract types at this point
2247 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2248 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2250 std::vector<const Type*> ParamTypeList;
2251 ParamAttrsVector Attrs;
2252 if ($7 != ParamAttr::None) {
2253 ParamAttrsWithIndex PAWI;
2256 Attrs.push_back(PAWI);
2258 if ($5) { // If there are arguments...
2260 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2261 const Type* Ty = I->Ty->get();
2262 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2263 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2264 ParamTypeList.push_back(Ty);
2265 if (Ty != Type::VoidTy)
2266 if (I->Attrs != ParamAttr::None) {
2267 ParamAttrsWithIndex PAWI;
2269 PAWI.attrs = I->Attrs;
2270 Attrs.push_back(PAWI);
2275 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2276 if (isVarArg) ParamTypeList.pop_back();
2278 const ParamAttrsList *PAL = 0;
2280 PAL = ParamAttrsList::get(Attrs);
2282 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2283 const PointerType *PFT = PointerType::getUnqual(FT);
2287 if (!FunctionName.empty()) {
2288 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2290 ID = ValID::createGlobalID(CurModule.Values.size());
2294 // See if this function was forward referenced. If so, recycle the object.
2295 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2296 // Move the function to the end of the list, from whereever it was
2297 // previously inserted.
2298 Fn = cast<Function>(FWRef);
2299 assert(!Fn->getParamAttrs() && "Forward reference has parameter attributes!");
2300 CurModule.CurrentModule->getFunctionList().remove(Fn);
2301 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2302 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2303 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2304 if (Fn->getFunctionType() != FT ) {
2305 // The existing function doesn't have the same type. This is an overload
2307 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2308 } else if (Fn->getParamAttrs() != PAL) {
2309 // The existing function doesn't have the same parameter attributes.
2310 // This is an overload error.
2311 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2312 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2313 // Neither the existing or the current function is a declaration and they
2314 // have the same name and same type. Clearly this is a redefinition.
2315 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2316 } else if (Fn->isDeclaration()) {
2317 // Make sure to strip off any argument names so we can't get conflicts.
2318 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2322 } else { // Not already defined?
2323 Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2324 CurModule.CurrentModule);
2325 InsertValue(Fn, CurModule.Values);
2328 CurFun.FunctionStart(Fn);
2330 if (CurFun.isDeclare) {
2331 // If we have declaration, always overwrite linkage. This will allow us to
2332 // correctly handle cases, when pointer to function is passed as argument to
2333 // another function.
2334 Fn->setLinkage(CurFun.Linkage);
2335 Fn->setVisibility(CurFun.Visibility);
2337 Fn->setCallingConv($1);
2338 Fn->setParamAttrs(PAL);
2339 Fn->setAlignment($9);
2341 Fn->setSection(*$8);
2345 Fn->setCollector($10->c_str());
2349 // Add all of the arguments we parsed to the function...
2350 if ($5) { // Is null if empty...
2351 if (isVarArg) { // Nuke the last entry
2352 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2353 "Not a varargs marker!");
2354 delete $5->back().Ty;
2355 $5->pop_back(); // Delete the last entry
2357 Function::arg_iterator ArgIt = Fn->arg_begin();
2358 Function::arg_iterator ArgEnd = Fn->arg_end();
2360 for (ArgListType::iterator I = $5->begin();
2361 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2362 delete I->Ty; // Delete the typeholder...
2363 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2369 delete $5; // We're now done with the argument list
2374 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2376 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2377 $$ = CurFun.CurrentFunction;
2379 // Make sure that we keep track of the linkage type even if there was a
2380 // previous "declare".
2382 $$->setVisibility($2);
2385 END : ENDTOK | '}'; // Allow end of '}' to end a function
2387 Function : BasicBlockList END {
2392 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2393 CurFun.CurrentFunction->setLinkage($1);
2394 CurFun.CurrentFunction->setVisibility($2);
2395 $$ = CurFun.CurrentFunction;
2396 CurFun.FunctionDone();
2400 //===----------------------------------------------------------------------===//
2401 // Rules to match Basic Blocks
2402 //===----------------------------------------------------------------------===//
2404 OptSideEffect : /* empty */ {
2413 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2414 $$ = ValID::create($1);
2418 $$ = ValID::create($1);
2421 | FPVAL { // Perhaps it's an FP constant?
2422 $$ = ValID::create($1);
2426 $$ = ValID::create(ConstantInt::getTrue());
2430 $$ = ValID::create(ConstantInt::getFalse());
2434 $$ = ValID::createNull();
2438 $$ = ValID::createUndef();
2441 | ZEROINITIALIZER { // A vector zero constant.
2442 $$ = ValID::createZeroInit();
2445 | '<' ConstVector '>' { // Nonempty unsized packed vector
2446 const Type *ETy = (*$2)[0]->getType();
2447 int NumElements = $2->size();
2449 VectorType* pt = VectorType::get(ETy, NumElements);
2450 PATypeHolder* PTy = new PATypeHolder(
2458 // Verify all elements are correct type!
2459 for (unsigned i = 0; i < $2->size(); i++) {
2460 if (ETy != (*$2)[i]->getType())
2461 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2462 ETy->getDescription() +"' as required!\nIt is of type '" +
2463 (*$2)[i]->getType()->getDescription() + "'.");
2466 $$ = ValID::create(ConstantVector::get(pt, *$2));
2467 delete PTy; delete $2;
2471 $$ = ValID::create($1);
2474 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2475 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2481 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2484 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2485 $$ = ValID::createLocalID($1);
2489 $$ = ValID::createGlobalID($1);
2492 | LocalName { // Is it a named reference...?
2493 $$ = ValID::createLocalName(*$1);
2497 | GlobalName { // Is it a named reference...?
2498 $$ = ValID::createGlobalName(*$1);
2503 // ValueRef - A reference to a definition... either constant or symbolic
2504 ValueRef : SymbolicValueRef | ConstValueRef;
2507 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2508 // type immediately preceeds the value reference, and allows complex constant
2509 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2510 ResolvedVal : Types ValueRef {
2511 if (!UpRefs.empty())
2512 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2513 $$ = getVal(*$1, $2);
2519 BasicBlockList : BasicBlockList BasicBlock {
2523 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2529 // Basic blocks are terminated by branching instructions:
2530 // br, br/cc, switch, ret
2532 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2533 setValueName($3, $2);
2536 $1->getInstList().push_back($3);
2541 InstructionList : InstructionList Inst {
2542 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2543 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2544 if (CI2->getParent() == 0)
2545 $1->getInstList().push_back(CI2);
2546 $1->getInstList().push_back($2);
2550 | /* empty */ { // Empty space between instruction lists
2551 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2554 | LABELSTR { // Labelled (named) basic block
2555 $$ = defineBBVal(ValID::createLocalName(*$1));
2561 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2562 $$ = new ReturnInst($2);
2565 | RET VOID { // Return with no result...
2566 $$ = new ReturnInst();
2569 | BR LABEL ValueRef { // Unconditional Branch...
2570 BasicBlock* tmpBB = getBBVal($3);
2572 $$ = new BranchInst(tmpBB);
2573 } // Conditional Branch...
2574 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2575 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2576 BasicBlock* tmpBBA = getBBVal($6);
2578 BasicBlock* tmpBBB = getBBVal($9);
2580 Value* tmpVal = getVal(Type::Int1Ty, $3);
2582 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2584 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2585 Value* tmpVal = getVal($2, $3);
2587 BasicBlock* tmpBB = getBBVal($6);
2589 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2592 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2594 for (; I != E; ++I) {
2595 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2596 S->addCase(CI, I->second);
2598 GEN_ERROR("Switch case is constant, but not a simple integer");
2603 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2604 Value* tmpVal = getVal($2, $3);
2606 BasicBlock* tmpBB = getBBVal($6);
2608 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2612 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2613 TO LABEL ValueRef UNWIND LABEL ValueRef {
2615 // Handle the short syntax
2616 const PointerType *PFTy = 0;
2617 const FunctionType *Ty = 0;
2618 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2619 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2620 // Pull out the types of all of the arguments...
2621 std::vector<const Type*> ParamTypes;
2622 ParamList::iterator I = $6->begin(), E = $6->end();
2623 for (; I != E; ++I) {
2624 const Type *Ty = I->Val->getType();
2625 if (Ty == Type::VoidTy)
2626 GEN_ERROR("Short call syntax cannot be used with varargs");
2627 ParamTypes.push_back(Ty);
2629 Ty = FunctionType::get($3->get(), ParamTypes, false);
2630 PFTy = PointerType::getUnqual(Ty);
2635 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2637 BasicBlock *Normal = getBBVal($11);
2639 BasicBlock *Except = getBBVal($14);
2642 ParamAttrsVector Attrs;
2643 if ($8 != ParamAttr::None) {
2644 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2645 Attrs.push_back(PAWI);
2648 // Check the arguments
2650 if ($6->empty()) { // Has no arguments?
2651 // Make sure no arguments is a good thing!
2652 if (Ty->getNumParams() != 0)
2653 GEN_ERROR("No arguments passed to a function that "
2654 "expects arguments");
2655 } else { // Has arguments?
2656 // Loop through FunctionType's arguments and ensure they are specified
2658 FunctionType::param_iterator I = Ty->param_begin();
2659 FunctionType::param_iterator E = Ty->param_end();
2660 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2663 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2664 if (ArgI->Val->getType() != *I)
2665 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2666 (*I)->getDescription() + "'");
2667 Args.push_back(ArgI->Val);
2668 if (ArgI->Attrs != ParamAttr::None) {
2669 ParamAttrsWithIndex PAWI;
2671 PAWI.attrs = ArgI->Attrs;
2672 Attrs.push_back(PAWI);
2676 if (Ty->isVarArg()) {
2678 for (; ArgI != ArgE; ++ArgI, ++index) {
2679 Args.push_back(ArgI->Val); // push the remaining varargs
2680 if (ArgI->Attrs != ParamAttr::None) {
2681 ParamAttrsWithIndex PAWI;
2683 PAWI.attrs = ArgI->Attrs;
2684 Attrs.push_back(PAWI);
2687 } else if (I != E || ArgI != ArgE)
2688 GEN_ERROR("Invalid number of parameters detected");
2691 const ParamAttrsList *PAL = 0;
2693 PAL = ParamAttrsList::get(Attrs);
2695 // Create the InvokeInst
2696 InvokeInst *II = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
2697 II->setCallingConv($2);
2698 II->setParamAttrs(PAL);
2704 $$ = new UnwindInst();
2708 $$ = new UnreachableInst();
2714 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2716 Constant *V = cast<Constant>(getExistingVal($2, $3));
2719 GEN_ERROR("May only switch on a constant pool value");
2721 BasicBlock* tmpBB = getBBVal($6);
2723 $$->push_back(std::make_pair(V, tmpBB));
2725 | IntType ConstValueRef ',' LABEL ValueRef {
2726 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2727 Constant *V = cast<Constant>(getExistingVal($1, $2));
2731 GEN_ERROR("May only switch on a constant pool value");
2733 BasicBlock* tmpBB = getBBVal($5);
2735 $$->push_back(std::make_pair(V, tmpBB));
2738 Inst : OptLocalAssign InstVal {
2739 // Is this definition named?? if so, assign the name...
2740 setValueName($2, $1);
2748 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2749 if (!UpRefs.empty())
2750 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2751 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2752 Value* tmpVal = getVal(*$1, $3);
2754 BasicBlock* tmpBB = getBBVal($5);
2756 $$->push_back(std::make_pair(tmpVal, tmpBB));
2759 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2761 Value* tmpVal = getVal($1->front().first->getType(), $4);
2763 BasicBlock* tmpBB = getBBVal($6);
2765 $1->push_back(std::make_pair(tmpVal, tmpBB));
2769 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2770 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2771 if (!UpRefs.empty())
2772 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2773 // Used for call and invoke instructions
2774 $$ = new ParamList();
2775 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
2780 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2781 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2782 // Labels are only valid in ASMs
2783 $$ = new ParamList();
2784 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
2788 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2789 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2790 if (!UpRefs.empty())
2791 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2793 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
2798 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2799 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2801 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
2805 | /*empty*/ { $$ = new ParamList(); };
2807 IndexList // Used for gep instructions and constant expressions
2808 : /*empty*/ { $$ = new std::vector<Value*>(); }
2809 | IndexList ',' ResolvedVal {
2816 OptTailCall : TAIL CALL {
2825 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2826 if (!UpRefs.empty())
2827 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2828 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2829 !isa<VectorType>((*$2).get()))
2831 "Arithmetic operator requires integer, FP, or packed operands");
2832 Value* val1 = getVal(*$2, $3);
2834 Value* val2 = getVal(*$2, $5);
2836 $$ = BinaryOperator::create($1, val1, val2);
2838 GEN_ERROR("binary operator returned null");
2841 | LogicalOps Types ValueRef ',' ValueRef {
2842 if (!UpRefs.empty())
2843 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2844 if (!(*$2)->isInteger()) {
2845 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2846 !cast<VectorType>($2->get())->getElementType()->isInteger())
2847 GEN_ERROR("Logical operator requires integral operands");
2849 Value* tmpVal1 = getVal(*$2, $3);
2851 Value* tmpVal2 = getVal(*$2, $5);
2853 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2855 GEN_ERROR("binary operator returned null");
2858 | ICMP IPredicates Types ValueRef ',' ValueRef {
2859 if (!UpRefs.empty())
2860 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2861 if (isa<VectorType>((*$3).get()))
2862 GEN_ERROR("Vector types not supported by icmp instruction");
2863 Value* tmpVal1 = getVal(*$3, $4);
2865 Value* tmpVal2 = getVal(*$3, $6);
2867 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2869 GEN_ERROR("icmp operator returned null");
2872 | FCMP FPredicates Types ValueRef ',' ValueRef {
2873 if (!UpRefs.empty())
2874 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2875 if (isa<VectorType>((*$3).get()))
2876 GEN_ERROR("Vector types not supported by fcmp instruction");
2877 Value* tmpVal1 = getVal(*$3, $4);
2879 Value* tmpVal2 = getVal(*$3, $6);
2881 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2883 GEN_ERROR("fcmp operator returned null");
2886 | CastOps ResolvedVal TO Types {
2887 if (!UpRefs.empty())
2888 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2890 const Type* DestTy = $4->get();
2891 if (!CastInst::castIsValid($1, Val, DestTy))
2892 GEN_ERROR("invalid cast opcode for cast from '" +
2893 Val->getType()->getDescription() + "' to '" +
2894 DestTy->getDescription() + "'");
2895 $$ = CastInst::create($1, Val, DestTy);
2898 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2899 if ($2->getType() != Type::Int1Ty)
2900 GEN_ERROR("select condition must be boolean");
2901 if ($4->getType() != $6->getType())
2902 GEN_ERROR("select value types should match");
2903 $$ = new SelectInst($2, $4, $6);
2906 | VAARG ResolvedVal ',' Types {
2907 if (!UpRefs.empty())
2908 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2909 $$ = new VAArgInst($2, *$4);
2913 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2914 if (!ExtractElementInst::isValidOperands($2, $4))
2915 GEN_ERROR("Invalid extractelement operands");
2916 $$ = new ExtractElementInst($2, $4);
2919 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2920 if (!InsertElementInst::isValidOperands($2, $4, $6))
2921 GEN_ERROR("Invalid insertelement operands");
2922 $$ = new InsertElementInst($2, $4, $6);
2925 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2926 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2927 GEN_ERROR("Invalid shufflevector operands");
2928 $$ = new ShuffleVectorInst($2, $4, $6);
2932 const Type *Ty = $2->front().first->getType();
2933 if (!Ty->isFirstClassType())
2934 GEN_ERROR("PHI node operands must be of first class type");
2935 $$ = new PHINode(Ty);
2936 ((PHINode*)$$)->reserveOperandSpace($2->size());
2937 while ($2->begin() != $2->end()) {
2938 if ($2->front().first->getType() != Ty)
2939 GEN_ERROR("All elements of a PHI node must be of the same type");
2940 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2943 delete $2; // Free the list...
2946 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
2949 // Handle the short syntax
2950 const PointerType *PFTy = 0;
2951 const FunctionType *Ty = 0;
2952 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2953 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2954 // Pull out the types of all of the arguments...
2955 std::vector<const Type*> ParamTypes;
2956 ParamList::iterator I = $6->begin(), E = $6->end();
2957 for (; I != E; ++I) {
2958 const Type *Ty = I->Val->getType();
2959 if (Ty == Type::VoidTy)
2960 GEN_ERROR("Short call syntax cannot be used with varargs");
2961 ParamTypes.push_back(Ty);
2963 Ty = FunctionType::get($3->get(), ParamTypes, false);
2964 PFTy = PointerType::getUnqual(Ty);
2967 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2970 // Check for call to invalid intrinsic to avoid crashing later.
2971 if (Function *theF = dyn_cast<Function>(V)) {
2972 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2973 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2974 !theF->getIntrinsicID(true))
2975 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
2976 theF->getName() + "'");
2979 // Set up the ParamAttrs for the function
2980 ParamAttrsVector Attrs;
2981 if ($8 != ParamAttr::None) {
2982 ParamAttrsWithIndex PAWI;
2985 Attrs.push_back(PAWI);
2987 // Check the arguments
2989 if ($6->empty()) { // Has no arguments?
2990 // Make sure no arguments is a good thing!
2991 if (Ty->getNumParams() != 0)
2992 GEN_ERROR("No arguments passed to a function that "
2993 "expects arguments");
2994 } else { // Has arguments?
2995 // Loop through FunctionType's arguments and ensure they are specified
2996 // correctly. Also, gather any parameter attributes.
2997 FunctionType::param_iterator I = Ty->param_begin();
2998 FunctionType::param_iterator E = Ty->param_end();
2999 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
3002 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3003 if (ArgI->Val->getType() != *I)
3004 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3005 (*I)->getDescription() + "'");
3006 Args.push_back(ArgI->Val);
3007 if (ArgI->Attrs != ParamAttr::None) {
3008 ParamAttrsWithIndex PAWI;
3010 PAWI.attrs = ArgI->Attrs;
3011 Attrs.push_back(PAWI);
3014 if (Ty->isVarArg()) {
3016 for (; ArgI != ArgE; ++ArgI, ++index) {
3017 Args.push_back(ArgI->Val); // push the remaining varargs
3018 if (ArgI->Attrs != ParamAttr::None) {
3019 ParamAttrsWithIndex PAWI;
3021 PAWI.attrs = ArgI->Attrs;
3022 Attrs.push_back(PAWI);
3025 } else if (I != E || ArgI != ArgE)
3026 GEN_ERROR("Invalid number of parameters detected");
3029 // Finish off the ParamAttrs and check them
3030 const ParamAttrsList *PAL = 0;
3032 PAL = ParamAttrsList::get(Attrs);
3034 // Create the call node
3035 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
3036 CI->setTailCall($1);
3037 CI->setCallingConv($2);
3038 CI->setParamAttrs(PAL);
3049 OptVolatile : VOLATILE {
3060 MemoryInst : MALLOC Types OptCAlign {
3061 if (!UpRefs.empty())
3062 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3063 $$ = new MallocInst(*$2, 0, $3);
3067 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3068 if (!UpRefs.empty())
3069 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3070 Value* tmpVal = getVal($4, $5);
3072 $$ = new MallocInst(*$2, tmpVal, $6);
3075 | ALLOCA Types OptCAlign {
3076 if (!UpRefs.empty())
3077 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3078 $$ = new AllocaInst(*$2, 0, $3);
3082 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3083 if (!UpRefs.empty())
3084 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3085 Value* tmpVal = getVal($4, $5);
3087 $$ = new AllocaInst(*$2, tmpVal, $6);
3090 | FREE ResolvedVal {
3091 if (!isa<PointerType>($2->getType()))
3092 GEN_ERROR("Trying to free nonpointer type " +
3093 $2->getType()->getDescription() + "");
3094 $$ = new FreeInst($2);
3098 | OptVolatile LOAD Types ValueRef OptCAlign {
3099 if (!UpRefs.empty())
3100 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3101 if (!isa<PointerType>($3->get()))
3102 GEN_ERROR("Can't load from nonpointer type: " +
3103 (*$3)->getDescription());
3104 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3105 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3106 (*$3)->getDescription());
3107 Value* tmpVal = getVal(*$3, $4);
3109 $$ = new LoadInst(tmpVal, "", $1, $5);
3112 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3113 if (!UpRefs.empty())
3114 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3115 const PointerType *PT = dyn_cast<PointerType>($5->get());
3117 GEN_ERROR("Can't store to a nonpointer type: " +
3118 (*$5)->getDescription());
3119 const Type *ElTy = PT->getElementType();
3120 if (ElTy != $3->getType())
3121 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3122 "' into space of type '" + ElTy->getDescription() + "'");
3124 Value* tmpVal = getVal(*$5, $6);
3126 $$ = new StoreInst($3, tmpVal, $1, $7);
3129 | GETELEMENTPTR Types ValueRef IndexList {
3130 if (!UpRefs.empty())
3131 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3132 if (!isa<PointerType>($2->get()))
3133 GEN_ERROR("getelementptr insn requires pointer operand");
3135 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
3136 GEN_ERROR("Invalid getelementptr indices for type '" +
3137 (*$2)->getDescription()+ "'");
3138 Value* tmpVal = getVal(*$2, $3);
3140 $$ = new GetElementPtrInst(tmpVal, $4->begin(), $4->end());
3148 // common code from the two 'RunVMAsmParser' functions
3149 static Module* RunParser(Module * M) {
3150 CurModule.CurrentModule = M;
3151 // Check to make sure the parser succeeded
3154 delete ParserResult;
3158 // Emit an error if there are any unresolved types left.
3159 if (!CurModule.LateResolveTypes.empty()) {
3160 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3161 if (DID.Type == ValID::LocalName) {
3162 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3164 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3167 delete ParserResult;
3171 // Emit an error if there are any unresolved values left.
3172 if (!CurModule.LateResolveValues.empty()) {
3173 Value *V = CurModule.LateResolveValues.back();
3174 std::map<Value*, std::pair<ValID, int> >::iterator I =
3175 CurModule.PlaceHolderInfo.find(V);
3177 if (I != CurModule.PlaceHolderInfo.end()) {
3178 ValID &DID = I->second.first;
3179 if (DID.Type == ValID::LocalName) {
3180 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3182 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3185 delete ParserResult;
3190 // Check to make sure that parsing produced a result
3194 // Reset ParserResult variable while saving its value for the result.
3195 Module *Result = ParserResult;
3201 void llvm::GenerateError(const std::string &message, int LineNo) {
3202 if (LineNo == -1) LineNo = LLLgetLineNo();
3203 // TODO: column number in exception
3205 TheParseError->setError(LLLgetFilename(), message, LineNo);
3209 int yyerror(const char *ErrorMsg) {
3210 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3211 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3212 if (yychar != YYEMPTY && yychar != 0) {
3213 errMsg += " while reading token: '";
3214 errMsg += std::string(LLLgetTokenStart(),
3215 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3217 GenerateError(errMsg);