1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/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);
498 V = new Argument(Ty);
501 // Remember where this forward reference came from. FIXME, shouldn't we try
502 // to recycle these things??
503 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
506 if (inFunctionScope())
507 InsertValue(V, CurFun.LateResolveValues);
509 InsertValue(V, CurModule.LateResolveValues);
513 /// defineBBVal - This is a definition of a new basic block with the specified
514 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
515 static BasicBlock *defineBBVal(const ValID &ID) {
516 assert(inFunctionScope() && "Can't get basic block at global scope!");
520 // First, see if this was forward referenced
522 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
523 if (BBI != CurFun.BBForwardRefs.end()) {
525 // The forward declaration could have been inserted anywhere in the
526 // function: insert it into the correct place now.
527 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
528 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
530 // We're about to erase the entry, save the key so we can clean it up.
531 ValID Tmp = BBI->first;
533 // Erase the forward ref from the map as its no longer "forward"
534 CurFun.BBForwardRefs.erase(ID);
536 // The key has been removed from the map but so we don't want to leave
537 // strdup'd memory around so destroy it too.
540 // If its a numbered definition, bump the number and set the BB value.
541 if (ID.Type == ValID::LocalID) {
542 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
550 // We haven't seen this BB before and its first mention is a definition.
551 // Just create it and return it.
552 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
553 BB = new BasicBlock(Name, CurFun.CurrentFunction);
554 if (ID.Type == ValID::LocalID) {
555 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
559 ID.destroy(); // Free strdup'd memory
563 /// getBBVal - get an existing BB value or create a forward reference for it.
565 static BasicBlock *getBBVal(const ValID &ID) {
566 assert(inFunctionScope() && "Can't get basic block at global scope!");
570 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
571 if (BBI != CurFun.BBForwardRefs.end()) {
573 } if (ID.Type == ValID::LocalName) {
574 std::string Name = ID.getName();
575 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
577 if (N->getType()->getTypeID() == Type::LabelTyID)
578 BB = cast<BasicBlock>(N);
580 GenerateError("Reference to label '" + Name + "' is actually of type '"+
581 N->getType()->getDescription() + "'");
582 } else if (ID.Type == ValID::LocalID) {
583 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
584 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
585 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
587 GenerateError("Reference to label '%" + utostr(ID.Num) +
588 "' is actually of type '"+
589 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
592 GenerateError("Illegal label reference " + ID.getName());
596 // If its already been defined, return it now.
598 ID.destroy(); // Free strdup'd memory.
602 // Otherwise, this block has not been seen before, create it.
604 if (ID.Type == ValID::LocalName)
606 BB = new BasicBlock(Name, CurFun.CurrentFunction);
608 // Insert it in the forward refs map.
609 CurFun.BBForwardRefs[ID] = BB;
615 //===----------------------------------------------------------------------===//
616 // Code to handle forward references in instructions
617 //===----------------------------------------------------------------------===//
619 // This code handles the late binding needed with statements that reference
620 // values not defined yet... for example, a forward branch, or the PHI node for
623 // This keeps a table (CurFun.LateResolveValues) of all such forward references
624 // and back patchs after we are done.
627 // ResolveDefinitions - If we could not resolve some defs at parsing
628 // time (forward branches, phi functions for loops, etc...) resolve the
632 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
633 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
634 while (!LateResolvers.empty()) {
635 Value *V = LateResolvers.back();
636 LateResolvers.pop_back();
638 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
639 CurModule.PlaceHolderInfo.find(V);
640 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
642 ValID &DID = PHI->second.first;
644 Value *TheRealValue = getExistingVal(V->getType(), DID);
648 V->replaceAllUsesWith(TheRealValue);
650 CurModule.PlaceHolderInfo.erase(PHI);
651 } else if (FutureLateResolvers) {
652 // Functions have their unresolved items forwarded to the module late
654 InsertValue(V, *FutureLateResolvers);
656 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
657 GenerateError("Reference to an invalid definition: '" +DID.getName()+
658 "' of type '" + V->getType()->getDescription() + "'",
662 GenerateError("Reference to an invalid definition: #" +
663 itostr(DID.Num) + " of type '" +
664 V->getType()->getDescription() + "'",
670 LateResolvers.clear();
673 // ResolveTypeTo - A brand new type was just declared. This means that (if
674 // name is not null) things referencing Name can be resolved. Otherwise, things
675 // refering to the number can be resolved. Do this now.
677 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
680 D = ValID::createLocalName(*Name);
682 D = ValID::createLocalID(CurModule.Types.size());
684 std::map<ValID, PATypeHolder>::iterator I =
685 CurModule.LateResolveTypes.find(D);
686 if (I != CurModule.LateResolveTypes.end()) {
687 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
688 CurModule.LateResolveTypes.erase(I);
692 // setValueName - Set the specified value to the name given. The name may be
693 // null potentially, in which case this is a noop. The string passed in is
694 // assumed to be a malloc'd string buffer, and is free'd by this function.
696 static void setValueName(Value *V, std::string *NameStr) {
697 if (!NameStr) return;
698 std::string Name(*NameStr); // Copy string
699 delete NameStr; // Free old string
701 if (V->getType() == Type::VoidTy) {
702 GenerateError("Can't assign name '" + Name+"' to value with void type");
706 assert(inFunctionScope() && "Must be in function scope!");
707 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
708 if (ST.lookup(Name)) {
709 GenerateError("Redefinition of value '" + Name + "' of type '" +
710 V->getType()->getDescription() + "'");
718 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
719 /// this is a declaration, otherwise it is a definition.
720 static GlobalVariable *
721 ParseGlobalVariable(std::string *NameStr,
722 GlobalValue::LinkageTypes Linkage,
723 GlobalValue::VisibilityTypes Visibility,
724 bool isConstantGlobal, const Type *Ty,
725 Constant *Initializer, bool IsThreadLocal) {
726 if (isa<FunctionType>(Ty)) {
727 GenerateError("Cannot declare global vars of function type");
731 const PointerType *PTy = PointerType::get(Ty);
735 Name = *NameStr; // Copy string
736 delete NameStr; // Free old string
739 // See if this global value was forward referenced. If so, recycle the
743 ID = ValID::createGlobalName(Name);
745 ID = ValID::createGlobalID(CurModule.Values.size());
748 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
749 // Move the global to the end of the list, from whereever it was
750 // previously inserted.
751 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
752 CurModule.CurrentModule->getGlobalList().remove(GV);
753 CurModule.CurrentModule->getGlobalList().push_back(GV);
754 GV->setInitializer(Initializer);
755 GV->setLinkage(Linkage);
756 GV->setVisibility(Visibility);
757 GV->setConstant(isConstantGlobal);
758 GV->setThreadLocal(IsThreadLocal);
759 InsertValue(GV, CurModule.Values);
763 // If this global has a name
765 // if the global we're parsing has an initializer (is a definition) and
766 // has external linkage.
767 if (Initializer && Linkage != GlobalValue::InternalLinkage)
768 // If there is already a global with external linkage with this name
769 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
770 // If we allow this GVar to get created, it will be renamed in the
771 // symbol table because it conflicts with an existing GVar. We can't
772 // allow redefinition of GVars whose linking indicates that their name
773 // must stay the same. Issue the error.
774 GenerateError("Redefinition of global variable named '" + Name +
775 "' of type '" + Ty->getDescription() + "'");
780 // Otherwise there is no existing GV to use, create one now.
782 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
783 CurModule.CurrentModule, IsThreadLocal);
784 GV->setVisibility(Visibility);
785 InsertValue(GV, CurModule.Values);
789 // setTypeName - Set the specified type to the name given. The name may be
790 // null potentially, in which case this is a noop. The string passed in is
791 // assumed to be a malloc'd string buffer, and is freed by this function.
793 // This function returns true if the type has already been defined, but is
794 // allowed to be redefined in the specified context. If the name is a new name
795 // for the type plane, it is inserted and false is returned.
796 static bool setTypeName(const Type *T, std::string *NameStr) {
797 assert(!inFunctionScope() && "Can't give types function-local names!");
798 if (NameStr == 0) return false;
800 std::string Name(*NameStr); // Copy string
801 delete NameStr; // Free old string
803 // We don't allow assigning names to void type
804 if (T == Type::VoidTy) {
805 GenerateError("Can't assign name '" + Name + "' to the void type");
809 // Set the type name, checking for conflicts as we do so.
810 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
812 if (AlreadyExists) { // Inserting a name that is already defined???
813 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
814 assert(Existing && "Conflict but no matching type?!");
816 // There is only one case where this is allowed: when we are refining an
817 // opaque type. In this case, Existing will be an opaque type.
818 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
819 // We ARE replacing an opaque type!
820 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
824 // Otherwise, this is an attempt to redefine a type. That's okay if
825 // the redefinition is identical to the original. This will be so if
826 // Existing and T point to the same Type object. In this one case we
827 // allow the equivalent redefinition.
828 if (Existing == T) return true; // Yes, it's equal.
830 // Any other kind of (non-equivalent) redefinition is an error.
831 GenerateError("Redefinition of type named '" + Name + "' of type '" +
832 T->getDescription() + "'");
838 //===----------------------------------------------------------------------===//
839 // Code for handling upreferences in type names...
842 // TypeContains - Returns true if Ty directly contains E in it.
844 static bool TypeContains(const Type *Ty, const Type *E) {
845 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
846 E) != Ty->subtype_end();
851 // NestingLevel - The number of nesting levels that need to be popped before
852 // this type is resolved.
853 unsigned NestingLevel;
855 // LastContainedTy - This is the type at the current binding level for the
856 // type. Every time we reduce the nesting level, this gets updated.
857 const Type *LastContainedTy;
859 // UpRefTy - This is the actual opaque type that the upreference is
863 UpRefRecord(unsigned NL, OpaqueType *URTy)
864 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
868 // UpRefs - A list of the outstanding upreferences that need to be resolved.
869 static std::vector<UpRefRecord> UpRefs;
871 /// HandleUpRefs - Every time we finish a new layer of types, this function is
872 /// called. It loops through the UpRefs vector, which is a list of the
873 /// currently active types. For each type, if the up reference is contained in
874 /// the newly completed type, we decrement the level count. When the level
875 /// count reaches zero, the upreferenced type is the type that is passed in:
876 /// thus we can complete the cycle.
878 static PATypeHolder HandleUpRefs(const Type *ty) {
879 // If Ty isn't abstract, or if there are no up-references in it, then there is
880 // nothing to resolve here.
881 if (!ty->isAbstract() || UpRefs.empty()) return ty;
884 UR_OUT("Type '" << Ty->getDescription() <<
885 "' newly formed. Resolving upreferences.\n" <<
886 UpRefs.size() << " upreferences active!\n");
888 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
889 // to zero), we resolve them all together before we resolve them to Ty. At
890 // the end of the loop, if there is anything to resolve to Ty, it will be in
892 OpaqueType *TypeToResolve = 0;
894 for (unsigned i = 0; i != UpRefs.size(); ++i) {
895 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
896 << UpRefs[i].second->getDescription() << ") = "
897 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
898 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
899 // Decrement level of upreference
900 unsigned Level = --UpRefs[i].NestingLevel;
901 UpRefs[i].LastContainedTy = Ty;
902 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
903 if (Level == 0) { // Upreference should be resolved!
904 if (!TypeToResolve) {
905 TypeToResolve = UpRefs[i].UpRefTy;
907 UR_OUT(" * Resolving upreference for "
908 << UpRefs[i].second->getDescription() << "\n";
909 std::string OldName = UpRefs[i].UpRefTy->getDescription());
910 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
911 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
912 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
914 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
915 --i; // Do not skip the next element...
921 UR_OUT(" * Resolving upreference for "
922 << UpRefs[i].second->getDescription() << "\n";
923 std::string OldName = TypeToResolve->getDescription());
924 TypeToResolve->refineAbstractTypeTo(Ty);
930 //===----------------------------------------------------------------------===//
931 // RunVMAsmParser - Define an interface to this parser
932 //===----------------------------------------------------------------------===//
934 static Module* RunParser(Module * M);
936 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
938 Module *M = RunParser(new Module(LLLgetFilename()));
946 llvm::Module *ModuleVal;
947 llvm::Function *FunctionVal;
948 llvm::BasicBlock *BasicBlockVal;
949 llvm::TerminatorInst *TermInstVal;
950 llvm::Instruction *InstVal;
951 llvm::Constant *ConstVal;
953 const llvm::Type *PrimType;
954 std::list<llvm::PATypeHolder> *TypeList;
955 llvm::PATypeHolder *TypeVal;
956 llvm::Value *ValueVal;
957 std::vector<llvm::Value*> *ValueList;
958 llvm::ArgListType *ArgList;
959 llvm::TypeWithAttrs TypeWithAttrs;
960 llvm::TypeWithAttrsList *TypeWithAttrsList;
961 llvm::ParamList *ParamList;
963 // Represent the RHS of PHI node
964 std::list<std::pair<llvm::Value*,
965 llvm::BasicBlock*> > *PHIList;
966 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
967 std::vector<llvm::Constant*> *ConstVector;
969 llvm::GlobalValue::LinkageTypes Linkage;
970 llvm::GlobalValue::VisibilityTypes Visibility;
972 llvm::APInt *APIntVal;
977 llvm::APFloat *FPVal;
980 std::string *StrVal; // This memory must be deleted
981 llvm::ValID ValIDVal;
983 llvm::Instruction::BinaryOps BinaryOpVal;
984 llvm::Instruction::TermOps TermOpVal;
985 llvm::Instruction::MemoryOps MemOpVal;
986 llvm::Instruction::CastOps CastOpVal;
987 llvm::Instruction::OtherOps OtherOpVal;
988 llvm::ICmpInst::Predicate IPredicate;
989 llvm::FCmpInst::Predicate FPredicate;
992 %type <ModuleVal> Module
993 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
994 %type <BasicBlockVal> BasicBlock InstructionList
995 %type <TermInstVal> BBTerminatorInst
996 %type <InstVal> Inst InstVal MemoryInst
997 %type <ConstVal> ConstVal ConstExpr AliaseeRef
998 %type <ConstVector> ConstVector
999 %type <ArgList> ArgList ArgListH
1000 %type <PHIList> PHIList
1001 %type <ParamList> ParamList // For call param lists & GEP indices
1002 %type <ValueList> IndexList // For GEP indices
1003 %type <TypeList> TypeListI
1004 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1005 %type <TypeWithAttrs> ArgType
1006 %type <JumpTable> JumpTable
1007 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1008 %type <BoolVal> ThreadLocal // 'thread_local' or not
1009 %type <BoolVal> OptVolatile // 'volatile' or not
1010 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1011 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1012 %type <Linkage> GVInternalLinkage GVExternalLinkage
1013 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1014 %type <Linkage> AliasLinkage
1015 %type <Visibility> GVVisibilityStyle
1017 // ValueRef - Unresolved reference to a definition or BB
1018 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1019 %type <ValueVal> ResolvedVal // <type> <valref> pair
1020 // Tokens and types for handling constant integer values
1022 // ESINT64VAL - A negative number within long long range
1023 %token <SInt64Val> ESINT64VAL
1025 // EUINT64VAL - A positive number within uns. long long range
1026 %token <UInt64Val> EUINT64VAL
1028 // ESAPINTVAL - A negative number with arbitrary precision
1029 %token <APIntVal> ESAPINTVAL
1031 // EUAPINTVAL - A positive number with arbitrary precision
1032 %token <APIntVal> EUAPINTVAL
1034 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1035 %token <FPVal> FPVAL // Float or Double constant
1037 // Built in types...
1038 %type <TypeVal> Types ResultTypes
1039 %type <PrimType> IntType FPType PrimType // Classifications
1040 %token <PrimType> VOID INTTYPE
1041 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1045 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1046 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1047 %type <StrVal> LocalName OptLocalName OptLocalAssign
1048 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1049 %type <StrVal> OptSection SectionString
1051 %type <UIntVal> OptAlign OptCAlign
1053 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1054 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1055 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1056 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1057 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
1058 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1059 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1061 %type <UIntVal> OptCallingConv
1062 %type <ParamAttrs> OptParamAttrs ParamAttr
1063 %type <ParamAttrs> OptFuncAttrs FuncAttr
1065 // Basic Block Terminating Operators
1066 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1069 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1070 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1071 %token <BinaryOpVal> SHL LSHR ASHR
1073 %token <OtherOpVal> ICMP FCMP
1074 %type <IPredicate> IPredicates
1075 %type <FPredicate> FPredicates
1076 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1077 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1079 // Memory Instructions
1080 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1083 %type <CastOpVal> CastOps
1084 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1085 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1088 %token <OtherOpVal> PHI_TOK SELECT VAARG
1089 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1091 // Function Attributes
1092 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1093 %token READNONE READONLY
1095 // Visibility Styles
1096 %token DEFAULT HIDDEN PROTECTED
1102 // Operations that are notably excluded from this list include:
1103 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1105 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1106 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1107 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1108 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1111 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1112 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1113 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1114 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1115 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1119 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1120 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1121 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1122 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1123 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1124 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1125 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1126 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1127 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1130 // These are some types that allow classification if we only want a particular
1131 // thing... for example, only a signed, unsigned, or integral type.
1133 FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1135 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1136 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1138 /// OptLocalAssign - Value producing statements have an optional assignment
1140 OptLocalAssign : LocalName '=' {
1149 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1151 OptGlobalAssign : GlobalAssign
1157 GlobalAssign : GlobalName '=' {
1163 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1164 | WEAK { $$ = GlobalValue::WeakLinkage; }
1165 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1166 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1167 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1171 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1172 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1173 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1177 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1178 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1179 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1180 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1183 FunctionDeclareLinkage
1184 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1185 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1186 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1189 FunctionDefineLinkage
1190 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1191 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1192 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1193 | WEAK { $$ = GlobalValue::WeakLinkage; }
1194 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1198 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1199 | WEAK { $$ = GlobalValue::WeakLinkage; }
1200 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1203 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1204 CCC_TOK { $$ = CallingConv::C; } |
1205 FASTCC_TOK { $$ = CallingConv::Fast; } |
1206 COLDCC_TOK { $$ = CallingConv::Cold; } |
1207 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1208 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1210 if ((unsigned)$2 != $2)
1211 GEN_ERROR("Calling conv too large");
1216 ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1217 | ZEXT { $$ = ParamAttr::ZExt; }
1218 | SIGNEXT { $$ = ParamAttr::SExt; }
1219 | SEXT { $$ = ParamAttr::SExt; }
1220 | INREG { $$ = ParamAttr::InReg; }
1221 | SRET { $$ = ParamAttr::StructRet; }
1222 | NOALIAS { $$ = ParamAttr::NoAlias; }
1223 | BYVAL { $$ = ParamAttr::ByVal; }
1224 | NEST { $$ = ParamAttr::Nest; }
1227 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1228 | OptParamAttrs ParamAttr {
1233 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1234 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1235 | ZEROEXT { $$ = ParamAttr::ZExt; }
1236 | SIGNEXT { $$ = ParamAttr::SExt; }
1237 | READNONE { $$ = ParamAttr::ReadNone; }
1238 | READONLY { $$ = ParamAttr::ReadOnly; }
1241 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1242 | OptFuncAttrs FuncAttr {
1247 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1248 // a comma before it.
1249 OptAlign : /*empty*/ { $$ = 0; } |
1252 if ($$ != 0 && !isPowerOf2_32($$))
1253 GEN_ERROR("Alignment must be a power of two");
1256 OptCAlign : /*empty*/ { $$ = 0; } |
1257 ',' ALIGN EUINT64VAL {
1259 if ($$ != 0 && !isPowerOf2_32($$))
1260 GEN_ERROR("Alignment must be a power of two");
1265 SectionString : SECTION STRINGCONSTANT {
1266 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1267 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1268 GEN_ERROR("Invalid character in section name");
1273 OptSection : /*empty*/ { $$ = 0; } |
1274 SectionString { $$ = $1; };
1276 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1277 // is set to be the global we are processing.
1279 GlobalVarAttributes : /* empty */ {} |
1280 ',' GlobalVarAttribute GlobalVarAttributes {};
1281 GlobalVarAttribute : SectionString {
1282 CurGV->setSection(*$1);
1286 | ALIGN EUINT64VAL {
1287 if ($2 != 0 && !isPowerOf2_32($2))
1288 GEN_ERROR("Alignment must be a power of two");
1289 CurGV->setAlignment($2);
1293 //===----------------------------------------------------------------------===//
1294 // Types includes all predefined types... except void, because it can only be
1295 // used in specific contexts (function returning void for example).
1297 // Derived types are added later...
1299 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1303 $$ = new PATypeHolder(OpaqueType::get());
1307 $$ = new PATypeHolder($1);
1310 | Types '*' { // Pointer type?
1311 if (*$1 == Type::LabelTy)
1312 GEN_ERROR("Cannot form a pointer to a basic block");
1313 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1317 | SymbolicValueRef { // Named types are also simple types...
1318 const Type* tmp = getTypeVal($1);
1320 $$ = new PATypeHolder(tmp);
1322 | '\\' EUINT64VAL { // Type UpReference
1323 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1324 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1325 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1326 $$ = new PATypeHolder(OT);
1327 UR_OUT("New Upreference!\n");
1330 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1331 // Allow but ignore attributes on function types; this permits auto-upgrade.
1332 // FIXME: remove in LLVM 3.0.
1333 std::vector<const Type*> Params;
1334 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1335 for (; I != E; ++I ) {
1336 const Type *Ty = I->Ty->get();
1337 Params.push_back(Ty);
1339 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1340 if (isVarArg) Params.pop_back();
1342 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg);
1343 delete $3; // Delete the argument list
1344 delete $1; // Delete the return type handle
1345 $$ = new PATypeHolder(HandleUpRefs(FT));
1348 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1349 // Allow but ignore attributes on function types; this permits auto-upgrade.
1350 // FIXME: remove in LLVM 3.0.
1351 std::vector<const Type*> Params;
1352 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1353 for ( ; I != E; ++I ) {
1354 const Type* Ty = I->Ty->get();
1355 Params.push_back(Ty);
1357 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1358 if (isVarArg) Params.pop_back();
1360 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1361 delete $3; // Delete the argument list
1362 $$ = new PATypeHolder(HandleUpRefs(FT));
1366 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1367 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1371 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1372 const llvm::Type* ElemTy = $4->get();
1373 if ((unsigned)$2 != $2)
1374 GEN_ERROR("Unsigned result not equal to signed result");
1375 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1376 GEN_ERROR("Element type of a VectorType must be primitive");
1377 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1381 | '{' TypeListI '}' { // Structure type?
1382 std::vector<const Type*> Elements;
1383 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1384 E = $2->end(); I != E; ++I)
1385 Elements.push_back(*I);
1387 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1391 | '{' '}' { // Empty structure type?
1392 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1395 | '<' '{' TypeListI '}' '>' {
1396 std::vector<const Type*> Elements;
1397 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1398 E = $3->end(); I != E; ++I)
1399 Elements.push_back(*I);
1401 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1405 | '<' '{' '}' '>' { // Empty structure type?
1406 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1412 : Types OptParamAttrs {
1413 // Allow but ignore attributes on function types; this permits auto-upgrade.
1414 // FIXME: remove in LLVM 3.0.
1416 $$.Attrs = ParamAttr::None;
1422 if (!UpRefs.empty())
1423 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1424 if (!(*$1)->isFirstClassType())
1425 GEN_ERROR("LLVM functions cannot return aggregate types");
1429 $$ = new PATypeHolder(Type::VoidTy);
1433 ArgTypeList : ArgType {
1434 $$ = new TypeWithAttrsList();
1438 | ArgTypeList ',' ArgType {
1439 ($$=$1)->push_back($3);
1446 | ArgTypeList ',' DOTDOTDOT {
1448 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1449 TWA.Ty = new PATypeHolder(Type::VoidTy);
1454 $$ = new TypeWithAttrsList;
1455 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1456 TWA.Ty = new PATypeHolder(Type::VoidTy);
1461 $$ = new TypeWithAttrsList();
1465 // TypeList - Used for struct declarations and as a basis for function type
1466 // declaration type lists
1469 $$ = new std::list<PATypeHolder>();
1474 | TypeListI ',' Types {
1475 ($$=$1)->push_back(*$3);
1480 // ConstVal - The various declarations that go into the constant pool. This
1481 // production is used ONLY to represent constants that show up AFTER a 'const',
1482 // 'constant' or 'global' token at global scope. Constants that can be inlined
1483 // into other expressions (such as integers and constexprs) are handled by the
1484 // ResolvedVal, ValueRef and ConstValueRef productions.
1486 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1487 if (!UpRefs.empty())
1488 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1489 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1491 GEN_ERROR("Cannot make array constant with type: '" +
1492 (*$1)->getDescription() + "'");
1493 const Type *ETy = ATy->getElementType();
1494 int NumElements = ATy->getNumElements();
1496 // Verify that we have the correct size...
1497 if (NumElements != -1 && NumElements != (int)$3->size())
1498 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1499 utostr($3->size()) + " arguments, but has size of " +
1500 itostr(NumElements) + "");
1502 // Verify all elements are correct type!
1503 for (unsigned i = 0; i < $3->size(); i++) {
1504 if (ETy != (*$3)[i]->getType())
1505 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1506 ETy->getDescription() +"' as required!\nIt is of type '"+
1507 (*$3)[i]->getType()->getDescription() + "'.");
1510 $$ = ConstantArray::get(ATy, *$3);
1511 delete $1; delete $3;
1515 if (!UpRefs.empty())
1516 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1517 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1519 GEN_ERROR("Cannot make array constant with type: '" +
1520 (*$1)->getDescription() + "'");
1522 int NumElements = ATy->getNumElements();
1523 if (NumElements != -1 && NumElements != 0)
1524 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1525 " arguments, but has size of " + itostr(NumElements) +"");
1526 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1530 | Types 'c' STRINGCONSTANT {
1531 if (!UpRefs.empty())
1532 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1533 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1535 GEN_ERROR("Cannot make array constant with type: '" +
1536 (*$1)->getDescription() + "'");
1538 int NumElements = ATy->getNumElements();
1539 const Type *ETy = ATy->getElementType();
1540 if (NumElements != -1 && NumElements != int($3->length()))
1541 GEN_ERROR("Can't build string constant of size " +
1542 itostr((int)($3->length())) +
1543 " when array has size " + itostr(NumElements) + "");
1544 std::vector<Constant*> Vals;
1545 if (ETy == Type::Int8Ty) {
1546 for (unsigned i = 0; i < $3->length(); ++i)
1547 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1550 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1553 $$ = ConstantArray::get(ATy, Vals);
1557 | Types '<' ConstVector '>' { // Nonempty unsized arr
1558 if (!UpRefs.empty())
1559 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1560 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1562 GEN_ERROR("Cannot make packed constant with type: '" +
1563 (*$1)->getDescription() + "'");
1564 const Type *ETy = PTy->getElementType();
1565 int NumElements = PTy->getNumElements();
1567 // Verify that we have the correct size...
1568 if (NumElements != -1 && NumElements != (int)$3->size())
1569 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1570 utostr($3->size()) + " arguments, but has size of " +
1571 itostr(NumElements) + "");
1573 // Verify all elements are correct type!
1574 for (unsigned i = 0; i < $3->size(); i++) {
1575 if (ETy != (*$3)[i]->getType())
1576 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1577 ETy->getDescription() +"' as required!\nIt is of type '"+
1578 (*$3)[i]->getType()->getDescription() + "'.");
1581 $$ = ConstantVector::get(PTy, *$3);
1582 delete $1; delete $3;
1585 | Types '{' ConstVector '}' {
1586 const StructType *STy = dyn_cast<StructType>($1->get());
1588 GEN_ERROR("Cannot make struct constant with type: '" +
1589 (*$1)->getDescription() + "'");
1591 if ($3->size() != STy->getNumContainedTypes())
1592 GEN_ERROR("Illegal number of initializers for structure type");
1594 // Check to ensure that constants are compatible with the type initializer!
1595 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1596 if ((*$3)[i]->getType() != STy->getElementType(i))
1597 GEN_ERROR("Expected type '" +
1598 STy->getElementType(i)->getDescription() +
1599 "' for element #" + utostr(i) +
1600 " of structure initializer");
1602 // Check to ensure that Type is not packed
1603 if (STy->isPacked())
1604 GEN_ERROR("Unpacked Initializer to vector type '" +
1605 STy->getDescription() + "'");
1607 $$ = ConstantStruct::get(STy, *$3);
1608 delete $1; delete $3;
1612 if (!UpRefs.empty())
1613 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1614 const StructType *STy = dyn_cast<StructType>($1->get());
1616 GEN_ERROR("Cannot make struct constant with type: '" +
1617 (*$1)->getDescription() + "'");
1619 if (STy->getNumContainedTypes() != 0)
1620 GEN_ERROR("Illegal number of initializers for structure type");
1622 // Check to ensure that Type is not packed
1623 if (STy->isPacked())
1624 GEN_ERROR("Unpacked Initializer to vector type '" +
1625 STy->getDescription() + "'");
1627 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1631 | Types '<' '{' ConstVector '}' '>' {
1632 const StructType *STy = dyn_cast<StructType>($1->get());
1634 GEN_ERROR("Cannot make struct constant with type: '" +
1635 (*$1)->getDescription() + "'");
1637 if ($4->size() != STy->getNumContainedTypes())
1638 GEN_ERROR("Illegal number of initializers for structure type");
1640 // Check to ensure that constants are compatible with the type initializer!
1641 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1642 if ((*$4)[i]->getType() != STy->getElementType(i))
1643 GEN_ERROR("Expected type '" +
1644 STy->getElementType(i)->getDescription() +
1645 "' for element #" + utostr(i) +
1646 " of structure initializer");
1648 // Check to ensure that Type is packed
1649 if (!STy->isPacked())
1650 GEN_ERROR("Vector initializer to non-vector type '" +
1651 STy->getDescription() + "'");
1653 $$ = ConstantStruct::get(STy, *$4);
1654 delete $1; delete $4;
1657 | Types '<' '{' '}' '>' {
1658 if (!UpRefs.empty())
1659 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1660 const StructType *STy = dyn_cast<StructType>($1->get());
1662 GEN_ERROR("Cannot make struct constant with type: '" +
1663 (*$1)->getDescription() + "'");
1665 if (STy->getNumContainedTypes() != 0)
1666 GEN_ERROR("Illegal number of initializers for structure type");
1668 // Check to ensure that Type is packed
1669 if (!STy->isPacked())
1670 GEN_ERROR("Vector initializer to non-vector type '" +
1671 STy->getDescription() + "'");
1673 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1678 if (!UpRefs.empty())
1679 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1680 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1682 GEN_ERROR("Cannot make null pointer constant with type: '" +
1683 (*$1)->getDescription() + "'");
1685 $$ = ConstantPointerNull::get(PTy);
1690 if (!UpRefs.empty())
1691 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1692 $$ = UndefValue::get($1->get());
1696 | Types SymbolicValueRef {
1697 if (!UpRefs.empty())
1698 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1699 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1701 GEN_ERROR("Global const reference must be a pointer type");
1703 // ConstExprs can exist in the body of a function, thus creating
1704 // GlobalValues whenever they refer to a variable. Because we are in
1705 // the context of a function, getExistingVal will search the functions
1706 // symbol table instead of the module symbol table for the global symbol,
1707 // which throws things all off. To get around this, we just tell
1708 // getExistingVal that we are at global scope here.
1710 Function *SavedCurFn = CurFun.CurrentFunction;
1711 CurFun.CurrentFunction = 0;
1713 Value *V = getExistingVal(Ty, $2);
1716 CurFun.CurrentFunction = SavedCurFn;
1718 // If this is an initializer for a constant pointer, which is referencing a
1719 // (currently) undefined variable, create a stub now that shall be replaced
1720 // in the future with the right type of variable.
1723 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1724 const PointerType *PT = cast<PointerType>(Ty);
1726 // First check to see if the forward references value is already created!
1727 PerModuleInfo::GlobalRefsType::iterator I =
1728 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1730 if (I != CurModule.GlobalRefs.end()) {
1731 V = I->second; // Placeholder already exists, use it...
1735 if ($2.Type == ValID::GlobalName)
1736 Name = $2.getName();
1737 else if ($2.Type != ValID::GlobalID)
1738 GEN_ERROR("Invalid reference to global");
1740 // Create the forward referenced global.
1742 if (const FunctionType *FTy =
1743 dyn_cast<FunctionType>(PT->getElementType())) {
1744 GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1745 CurModule.CurrentModule);
1747 GV = new GlobalVariable(PT->getElementType(), false,
1748 GlobalValue::ExternalWeakLinkage, 0,
1749 Name, CurModule.CurrentModule);
1752 // Keep track of the fact that we have a forward ref to recycle it
1753 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1758 $$ = cast<GlobalValue>(V);
1759 delete $1; // Free the type handle
1763 if (!UpRefs.empty())
1764 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1765 if ($1->get() != $2->getType())
1766 GEN_ERROR("Mismatched types for constant expression: " +
1767 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1772 | Types ZEROINITIALIZER {
1773 if (!UpRefs.empty())
1774 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1775 const Type *Ty = $1->get();
1776 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1777 GEN_ERROR("Cannot create a null initialized value of this type");
1778 $$ = Constant::getNullValue(Ty);
1782 | IntType ESINT64VAL { // integral constants
1783 if (!ConstantInt::isValueValidForType($1, $2))
1784 GEN_ERROR("Constant value doesn't fit in type");
1785 $$ = ConstantInt::get($1, $2, true);
1788 | IntType ESAPINTVAL { // arbitrary precision integer constants
1789 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1790 if ($2->getBitWidth() > BitWidth) {
1791 GEN_ERROR("Constant value does not fit in type");
1793 $2->sextOrTrunc(BitWidth);
1794 $$ = ConstantInt::get(*$2);
1798 | IntType EUINT64VAL { // integral constants
1799 if (!ConstantInt::isValueValidForType($1, $2))
1800 GEN_ERROR("Constant value doesn't fit in type");
1801 $$ = ConstantInt::get($1, $2, false);
1804 | IntType EUAPINTVAL { // arbitrary precision integer constants
1805 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1806 if ($2->getBitWidth() > BitWidth) {
1807 GEN_ERROR("Constant value does not fit in type");
1809 $2->zextOrTrunc(BitWidth);
1810 $$ = ConstantInt::get(*$2);
1814 | INTTYPE TRUETOK { // Boolean constants
1815 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1816 $$ = ConstantInt::getTrue();
1819 | INTTYPE FALSETOK { // Boolean constants
1820 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1821 $$ = ConstantInt::getFalse();
1824 | FPType FPVAL { // Floating point constants
1825 if (!ConstantFP::isValueValidForType($1, *$2))
1826 GEN_ERROR("Floating point constant invalid for type");
1827 // Lexer has no type info, so builds all float and double FP constants
1828 // as double. Fix this here. Long double is done right.
1829 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1830 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1831 $$ = ConstantFP::get($1, *$2);
1837 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1838 if (!UpRefs.empty())
1839 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1841 const Type *DestTy = $5->get();
1842 if (!CastInst::castIsValid($1, $3, DestTy))
1843 GEN_ERROR("invalid cast opcode for cast from '" +
1844 Val->getType()->getDescription() + "' to '" +
1845 DestTy->getDescription() + "'");
1846 $$ = ConstantExpr::getCast($1, $3, DestTy);
1849 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1850 if (!isa<PointerType>($3->getType()))
1851 GEN_ERROR("GetElementPtr requires a pointer operand");
1854 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end(),
1857 GEN_ERROR("Index list invalid for constant getelementptr");
1859 SmallVector<Constant*, 8> IdxVec;
1860 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1861 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1862 IdxVec.push_back(C);
1864 GEN_ERROR("Indices to constant getelementptr must be constants");
1868 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1871 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1872 if ($3->getType() != Type::Int1Ty)
1873 GEN_ERROR("Select condition must be of boolean type");
1874 if ($5->getType() != $7->getType())
1875 GEN_ERROR("Select operand types must match");
1876 $$ = ConstantExpr::getSelect($3, $5, $7);
1879 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1880 if ($3->getType() != $5->getType())
1881 GEN_ERROR("Binary operator types must match");
1883 $$ = ConstantExpr::get($1, $3, $5);
1885 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1886 if ($3->getType() != $5->getType())
1887 GEN_ERROR("Logical operator types must match");
1888 if (!$3->getType()->isInteger()) {
1889 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1890 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1891 GEN_ERROR("Logical operator requires integral operands");
1893 $$ = ConstantExpr::get($1, $3, $5);
1896 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1897 if ($4->getType() != $6->getType())
1898 GEN_ERROR("icmp operand types must match");
1899 $$ = ConstantExpr::getICmp($2, $4, $6);
1901 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1902 if ($4->getType() != $6->getType())
1903 GEN_ERROR("fcmp operand types must match");
1904 $$ = ConstantExpr::getFCmp($2, $4, $6);
1906 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1907 if (!ExtractElementInst::isValidOperands($3, $5))
1908 GEN_ERROR("Invalid extractelement operands");
1909 $$ = ConstantExpr::getExtractElement($3, $5);
1912 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1913 if (!InsertElementInst::isValidOperands($3, $5, $7))
1914 GEN_ERROR("Invalid insertelement operands");
1915 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1918 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1919 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1920 GEN_ERROR("Invalid shufflevector operands");
1921 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1926 // ConstVector - A list of comma separated constants.
1927 ConstVector : ConstVector ',' ConstVal {
1928 ($$ = $1)->push_back($3);
1932 $$ = new std::vector<Constant*>();
1938 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1939 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1942 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1944 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1945 AliaseeRef : ResultTypes SymbolicValueRef {
1946 const Type* VTy = $1->get();
1947 Value *V = getVal(VTy, $2);
1949 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1951 GEN_ERROR("Aliases can be created only to global values");
1957 | BITCAST '(' AliaseeRef TO Types ')' {
1959 const Type *DestTy = $5->get();
1960 if (!CastInst::castIsValid($1, $3, DestTy))
1961 GEN_ERROR("invalid cast opcode for cast from '" +
1962 Val->getType()->getDescription() + "' to '" +
1963 DestTy->getDescription() + "'");
1965 $$ = ConstantExpr::getCast($1, $3, DestTy);
1970 //===----------------------------------------------------------------------===//
1971 // Rules to match Modules
1972 //===----------------------------------------------------------------------===//
1974 // Module rule: Capture the result of parsing the whole file into a result
1979 $$ = ParserResult = CurModule.CurrentModule;
1980 CurModule.ModuleDone();
1984 $$ = ParserResult = CurModule.CurrentModule;
1985 CurModule.ModuleDone();
1992 | DefinitionList Definition
1996 : DEFINE { CurFun.isDeclare = false; } Function {
1997 CurFun.FunctionDone();
2000 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2003 | MODULE ASM_TOK AsmBlock {
2006 | OptLocalAssign TYPE Types {
2007 if (!UpRefs.empty())
2008 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2009 // Eagerly resolve types. This is not an optimization, this is a
2010 // requirement that is due to the fact that we could have this:
2012 // %list = type { %list * }
2013 // %list = type { %list * } ; repeated type decl
2015 // If types are not resolved eagerly, then the two types will not be
2016 // determined to be the same type!
2018 ResolveTypeTo($1, *$3);
2020 if (!setTypeName(*$3, $1) && !$1) {
2022 // If this is a named type that is not a redefinition, add it to the slot
2024 CurModule.Types.push_back(*$3);
2030 | OptLocalAssign TYPE VOID {
2031 ResolveTypeTo($1, $3);
2033 if (!setTypeName($3, $1) && !$1) {
2035 // If this is a named type that is not a redefinition, add it to the slot
2037 CurModule.Types.push_back($3);
2041 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal {
2042 /* "Externally Visible" Linkage */
2044 GEN_ERROR("Global value initializer is not a constant");
2045 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2046 $2, $4, $5->getType(), $5, $3);
2048 } GlobalVarAttributes {
2051 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2054 GEN_ERROR("Global value initializer is not a constant");
2055 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4);
2057 } GlobalVarAttributes {
2060 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2062 if (!UpRefs.empty())
2063 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2064 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4);
2067 } GlobalVarAttributes {
2071 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2078 GEN_ERROR("Alias name cannot be empty");
2080 Constant* Aliasee = $5;
2082 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2084 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2085 CurModule.CurrentModule);
2086 GA->setVisibility($2);
2087 InsertValue(GA, CurModule.Values);
2090 // If there was a forward reference of this alias, resolve it now.
2094 ID = ValID::createGlobalName(Name);
2096 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2098 if (GlobalValue *FWGV =
2099 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2100 // Replace uses of the fwdref with the actual alias.
2101 FWGV->replaceAllUsesWith(GA);
2102 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2103 GV->eraseFromParent();
2105 cast<Function>(FWGV)->eraseFromParent();
2111 | TARGET TargetDefinition {
2114 | DEPLIBS '=' LibrariesDefinition {
2120 AsmBlock : STRINGCONSTANT {
2121 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2122 if (AsmSoFar.empty())
2123 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2125 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2130 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2131 CurModule.CurrentModule->setTargetTriple(*$3);
2134 | DATALAYOUT '=' STRINGCONSTANT {
2135 CurModule.CurrentModule->setDataLayout(*$3);
2139 LibrariesDefinition : '[' LibList ']';
2141 LibList : LibList ',' STRINGCONSTANT {
2142 CurModule.CurrentModule->addLibrary(*$3);
2147 CurModule.CurrentModule->addLibrary(*$1);
2151 | /* empty: end of list */ {
2156 //===----------------------------------------------------------------------===//
2157 // Rules to match Function Headers
2158 //===----------------------------------------------------------------------===//
2160 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2161 if (!UpRefs.empty())
2162 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2163 if (*$3 == Type::VoidTy)
2164 GEN_ERROR("void typed arguments are invalid");
2165 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2170 | Types OptParamAttrs OptLocalName {
2171 if (!UpRefs.empty())
2172 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2173 if (*$1 == Type::VoidTy)
2174 GEN_ERROR("void typed arguments are invalid");
2175 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2176 $$ = new ArgListType;
2181 ArgList : ArgListH {
2185 | ArgListH ',' DOTDOTDOT {
2187 struct ArgListEntry E;
2188 E.Ty = new PATypeHolder(Type::VoidTy);
2190 E.Attrs = ParamAttr::None;
2195 $$ = new ArgListType;
2196 struct ArgListEntry E;
2197 E.Ty = new PATypeHolder(Type::VoidTy);
2199 E.Attrs = ParamAttr::None;
2208 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2209 OptFuncAttrs OptSection OptAlign {
2210 std::string FunctionName(*$3);
2211 delete $3; // Free strdup'd memory!
2213 // Check the function result for abstractness if this is a define. We should
2214 // have no abstract types at this point
2215 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2216 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2218 std::vector<const Type*> ParamTypeList;
2219 ParamAttrsVector Attrs;
2220 if ($7 != ParamAttr::None) {
2221 ParamAttrsWithIndex PAWI;
2224 Attrs.push_back(PAWI);
2226 if ($5) { // If there are arguments...
2228 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2229 const Type* Ty = I->Ty->get();
2230 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2231 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2232 ParamTypeList.push_back(Ty);
2233 if (Ty != Type::VoidTy)
2234 if (I->Attrs != ParamAttr::None) {
2235 ParamAttrsWithIndex PAWI;
2237 PAWI.attrs = I->Attrs;
2238 Attrs.push_back(PAWI);
2243 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2244 if (isVarArg) ParamTypeList.pop_back();
2246 ParamAttrsList *PAL = 0;
2248 PAL = ParamAttrsList::get(Attrs);
2250 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2251 const PointerType *PFT = PointerType::get(FT);
2255 if (!FunctionName.empty()) {
2256 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2258 ID = ValID::createGlobalID(CurModule.Values.size());
2262 // See if this function was forward referenced. If so, recycle the object.
2263 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2264 // Move the function to the end of the list, from whereever it was
2265 // previously inserted.
2266 Fn = cast<Function>(FWRef);
2267 assert(!Fn->getParamAttrs() && "Forward reference has parameter attributes!");
2268 CurModule.CurrentModule->getFunctionList().remove(Fn);
2269 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2270 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2271 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2272 if (Fn->getFunctionType() != FT ) {
2273 // The existing function doesn't have the same type. This is an overload
2275 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2276 } else if (Fn->getParamAttrs() != PAL) {
2277 // The existing function doesn't have the same parameter attributes.
2278 // This is an overload error.
2279 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2280 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2281 // Neither the existing or the current function is a declaration and they
2282 // have the same name and same type. Clearly this is a redefinition.
2283 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2284 } else if (Fn->isDeclaration()) {
2285 // Make sure to strip off any argument names so we can't get conflicts.
2286 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2290 } else { // Not already defined?
2291 Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2292 CurModule.CurrentModule);
2293 InsertValue(Fn, CurModule.Values);
2296 CurFun.FunctionStart(Fn);
2298 if (CurFun.isDeclare) {
2299 // If we have declaration, always overwrite linkage. This will allow us to
2300 // correctly handle cases, when pointer to function is passed as argument to
2301 // another function.
2302 Fn->setLinkage(CurFun.Linkage);
2303 Fn->setVisibility(CurFun.Visibility);
2305 Fn->setCallingConv($1);
2306 Fn->setParamAttrs(PAL);
2307 Fn->setAlignment($9);
2309 Fn->setSection(*$8);
2313 // Add all of the arguments we parsed to the function...
2314 if ($5) { // Is null if empty...
2315 if (isVarArg) { // Nuke the last entry
2316 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2317 "Not a varargs marker!");
2318 delete $5->back().Ty;
2319 $5->pop_back(); // Delete the last entry
2321 Function::arg_iterator ArgIt = Fn->arg_begin();
2322 Function::arg_iterator ArgEnd = Fn->arg_end();
2324 for (ArgListType::iterator I = $5->begin();
2325 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2326 delete I->Ty; // Delete the typeholder...
2327 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2333 delete $5; // We're now done with the argument list
2338 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2340 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2341 $$ = CurFun.CurrentFunction;
2343 // Make sure that we keep track of the linkage type even if there was a
2344 // previous "declare".
2346 $$->setVisibility($2);
2349 END : ENDTOK | '}'; // Allow end of '}' to end a function
2351 Function : BasicBlockList END {
2356 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2357 CurFun.CurrentFunction->setLinkage($1);
2358 CurFun.CurrentFunction->setVisibility($2);
2359 $$ = CurFun.CurrentFunction;
2360 CurFun.FunctionDone();
2364 //===----------------------------------------------------------------------===//
2365 // Rules to match Basic Blocks
2366 //===----------------------------------------------------------------------===//
2368 OptSideEffect : /* empty */ {
2377 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2378 $$ = ValID::create($1);
2382 $$ = ValID::create($1);
2385 | FPVAL { // Perhaps it's an FP constant?
2386 $$ = ValID::create($1);
2390 $$ = ValID::create(ConstantInt::getTrue());
2394 $$ = ValID::create(ConstantInt::getFalse());
2398 $$ = ValID::createNull();
2402 $$ = ValID::createUndef();
2405 | ZEROINITIALIZER { // A vector zero constant.
2406 $$ = ValID::createZeroInit();
2409 | '<' ConstVector '>' { // Nonempty unsized packed vector
2410 const Type *ETy = (*$2)[0]->getType();
2411 int NumElements = $2->size();
2413 VectorType* pt = VectorType::get(ETy, NumElements);
2414 PATypeHolder* PTy = new PATypeHolder(
2422 // Verify all elements are correct type!
2423 for (unsigned i = 0; i < $2->size(); i++) {
2424 if (ETy != (*$2)[i]->getType())
2425 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2426 ETy->getDescription() +"' as required!\nIt is of type '" +
2427 (*$2)[i]->getType()->getDescription() + "'.");
2430 $$ = ValID::create(ConstantVector::get(pt, *$2));
2431 delete PTy; delete $2;
2435 $$ = ValID::create($1);
2438 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2439 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2445 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2448 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2449 $$ = ValID::createLocalID($1);
2453 $$ = ValID::createGlobalID($1);
2456 | LocalName { // Is it a named reference...?
2457 $$ = ValID::createLocalName(*$1);
2461 | GlobalName { // Is it a named reference...?
2462 $$ = ValID::createGlobalName(*$1);
2467 // ValueRef - A reference to a definition... either constant or symbolic
2468 ValueRef : SymbolicValueRef | ConstValueRef;
2471 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2472 // type immediately preceeds the value reference, and allows complex constant
2473 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2474 ResolvedVal : Types ValueRef {
2475 if (!UpRefs.empty())
2476 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2477 $$ = getVal(*$1, $2);
2483 BasicBlockList : BasicBlockList BasicBlock {
2487 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2493 // Basic blocks are terminated by branching instructions:
2494 // br, br/cc, switch, ret
2496 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2497 setValueName($3, $2);
2500 $1->getInstList().push_back($3);
2505 InstructionList : InstructionList Inst {
2506 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2507 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2508 if (CI2->getParent() == 0)
2509 $1->getInstList().push_back(CI2);
2510 $1->getInstList().push_back($2);
2514 | /* empty */ { // Empty space between instruction lists
2515 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2518 | LABELSTR { // Labelled (named) basic block
2519 $$ = defineBBVal(ValID::createLocalName(*$1));
2525 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2526 $$ = new ReturnInst($2);
2529 | RET VOID { // Return with no result...
2530 $$ = new ReturnInst();
2533 | BR LABEL ValueRef { // Unconditional Branch...
2534 BasicBlock* tmpBB = getBBVal($3);
2536 $$ = new BranchInst(tmpBB);
2537 } // Conditional Branch...
2538 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2539 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2540 BasicBlock* tmpBBA = getBBVal($6);
2542 BasicBlock* tmpBBB = getBBVal($9);
2544 Value* tmpVal = getVal(Type::Int1Ty, $3);
2546 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2548 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2549 Value* tmpVal = getVal($2, $3);
2551 BasicBlock* tmpBB = getBBVal($6);
2553 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2556 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2558 for (; I != E; ++I) {
2559 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2560 S->addCase(CI, I->second);
2562 GEN_ERROR("Switch case is constant, but not a simple integer");
2567 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2568 Value* tmpVal = getVal($2, $3);
2570 BasicBlock* tmpBB = getBBVal($6);
2572 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2576 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2577 TO LABEL ValueRef UNWIND LABEL ValueRef {
2579 // Handle the short syntax
2580 const PointerType *PFTy = 0;
2581 const FunctionType *Ty = 0;
2582 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2583 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2584 // Pull out the types of all of the arguments...
2585 std::vector<const Type*> ParamTypes;
2586 ParamList::iterator I = $6->begin(), E = $6->end();
2587 for (; I != E; ++I) {
2588 const Type *Ty = I->Val->getType();
2589 if (Ty == Type::VoidTy)
2590 GEN_ERROR("Short call syntax cannot be used with varargs");
2591 ParamTypes.push_back(Ty);
2593 Ty = FunctionType::get($3->get(), ParamTypes, false);
2594 PFTy = PointerType::get(Ty);
2599 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2601 BasicBlock *Normal = getBBVal($11);
2603 BasicBlock *Except = getBBVal($14);
2606 ParamAttrsVector Attrs;
2607 if ($8 != ParamAttr::None) {
2608 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2609 Attrs.push_back(PAWI);
2612 // Check the arguments
2614 if ($6->empty()) { // Has no arguments?
2615 // Make sure no arguments is a good thing!
2616 if (Ty->getNumParams() != 0)
2617 GEN_ERROR("No arguments passed to a function that "
2618 "expects arguments");
2619 } else { // Has arguments?
2620 // Loop through FunctionType's arguments and ensure they are specified
2622 FunctionType::param_iterator I = Ty->param_begin();
2623 FunctionType::param_iterator E = Ty->param_end();
2624 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2627 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2628 if (ArgI->Val->getType() != *I)
2629 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2630 (*I)->getDescription() + "'");
2631 Args.push_back(ArgI->Val);
2632 if (ArgI->Attrs != ParamAttr::None) {
2633 ParamAttrsWithIndex PAWI;
2635 PAWI.attrs = ArgI->Attrs;
2636 Attrs.push_back(PAWI);
2640 if (Ty->isVarArg()) {
2642 for (; ArgI != ArgE; ++ArgI)
2643 Args.push_back(ArgI->Val); // push the remaining varargs
2644 } else if (I != E || ArgI != ArgE)
2645 GEN_ERROR("Invalid number of parameters detected");
2648 ParamAttrsList *PAL = 0;
2650 PAL = ParamAttrsList::get(Attrs);
2652 // Create the InvokeInst
2653 InvokeInst *II = new InvokeInst(V, Normal, Except, Args.begin(), Args.end());
2654 II->setCallingConv($2);
2655 II->setParamAttrs(PAL);
2661 $$ = new UnwindInst();
2665 $$ = new UnreachableInst();
2671 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2673 Constant *V = cast<Constant>(getExistingVal($2, $3));
2676 GEN_ERROR("May only switch on a constant pool value");
2678 BasicBlock* tmpBB = getBBVal($6);
2680 $$->push_back(std::make_pair(V, tmpBB));
2682 | IntType ConstValueRef ',' LABEL ValueRef {
2683 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2684 Constant *V = cast<Constant>(getExistingVal($1, $2));
2688 GEN_ERROR("May only switch on a constant pool value");
2690 BasicBlock* tmpBB = getBBVal($5);
2692 $$->push_back(std::make_pair(V, tmpBB));
2695 Inst : OptLocalAssign InstVal {
2696 // Is this definition named?? if so, assign the name...
2697 setValueName($2, $1);
2705 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2706 if (!UpRefs.empty())
2707 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2708 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2709 Value* tmpVal = getVal(*$1, $3);
2711 BasicBlock* tmpBB = getBBVal($5);
2713 $$->push_back(std::make_pair(tmpVal, tmpBB));
2716 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2718 Value* tmpVal = getVal($1->front().first->getType(), $4);
2720 BasicBlock* tmpBB = getBBVal($6);
2722 $1->push_back(std::make_pair(tmpVal, tmpBB));
2726 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2727 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2728 if (!UpRefs.empty())
2729 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2730 // Used for call and invoke instructions
2731 $$ = new ParamList();
2732 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
2737 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2738 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2739 // Labels are only valid in ASMs
2740 $$ = new ParamList();
2741 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
2745 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2746 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2747 if (!UpRefs.empty())
2748 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2750 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
2755 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2756 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2758 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
2762 | /*empty*/ { $$ = new ParamList(); };
2764 IndexList // Used for gep instructions and constant expressions
2765 : /*empty*/ { $$ = new std::vector<Value*>(); }
2766 | IndexList ',' ResolvedVal {
2773 OptTailCall : TAIL CALL {
2782 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2783 if (!UpRefs.empty())
2784 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2785 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2786 !isa<VectorType>((*$2).get()))
2788 "Arithmetic operator requires integer, FP, or packed operands");
2789 Value* val1 = getVal(*$2, $3);
2791 Value* val2 = getVal(*$2, $5);
2793 $$ = BinaryOperator::create($1, val1, val2);
2795 GEN_ERROR("binary operator returned null");
2798 | LogicalOps Types ValueRef ',' ValueRef {
2799 if (!UpRefs.empty())
2800 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2801 if (!(*$2)->isInteger()) {
2802 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2803 !cast<VectorType>($2->get())->getElementType()->isInteger())
2804 GEN_ERROR("Logical operator requires integral operands");
2806 Value* tmpVal1 = getVal(*$2, $3);
2808 Value* tmpVal2 = getVal(*$2, $5);
2810 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2812 GEN_ERROR("binary operator returned null");
2815 | ICMP IPredicates Types ValueRef ',' ValueRef {
2816 if (!UpRefs.empty())
2817 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2818 if (isa<VectorType>((*$3).get()))
2819 GEN_ERROR("Vector types not supported by icmp instruction");
2820 Value* tmpVal1 = getVal(*$3, $4);
2822 Value* tmpVal2 = getVal(*$3, $6);
2824 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2826 GEN_ERROR("icmp operator returned null");
2829 | FCMP FPredicates Types ValueRef ',' ValueRef {
2830 if (!UpRefs.empty())
2831 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2832 if (isa<VectorType>((*$3).get()))
2833 GEN_ERROR("Vector types not supported by fcmp instruction");
2834 Value* tmpVal1 = getVal(*$3, $4);
2836 Value* tmpVal2 = getVal(*$3, $6);
2838 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2840 GEN_ERROR("fcmp operator returned null");
2843 | CastOps ResolvedVal TO Types {
2844 if (!UpRefs.empty())
2845 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2847 const Type* DestTy = $4->get();
2848 if (!CastInst::castIsValid($1, Val, DestTy))
2849 GEN_ERROR("invalid cast opcode for cast from '" +
2850 Val->getType()->getDescription() + "' to '" +
2851 DestTy->getDescription() + "'");
2852 $$ = CastInst::create($1, Val, DestTy);
2855 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2856 if ($2->getType() != Type::Int1Ty)
2857 GEN_ERROR("select condition must be boolean");
2858 if ($4->getType() != $6->getType())
2859 GEN_ERROR("select value types should match");
2860 $$ = new SelectInst($2, $4, $6);
2863 | VAARG ResolvedVal ',' Types {
2864 if (!UpRefs.empty())
2865 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2866 $$ = new VAArgInst($2, *$4);
2870 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2871 if (!ExtractElementInst::isValidOperands($2, $4))
2872 GEN_ERROR("Invalid extractelement operands");
2873 $$ = new ExtractElementInst($2, $4);
2876 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2877 if (!InsertElementInst::isValidOperands($2, $4, $6))
2878 GEN_ERROR("Invalid insertelement operands");
2879 $$ = new InsertElementInst($2, $4, $6);
2882 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2883 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2884 GEN_ERROR("Invalid shufflevector operands");
2885 $$ = new ShuffleVectorInst($2, $4, $6);
2889 const Type *Ty = $2->front().first->getType();
2890 if (!Ty->isFirstClassType())
2891 GEN_ERROR("PHI node operands must be of first class type");
2892 $$ = new PHINode(Ty);
2893 ((PHINode*)$$)->reserveOperandSpace($2->size());
2894 while ($2->begin() != $2->end()) {
2895 if ($2->front().first->getType() != Ty)
2896 GEN_ERROR("All elements of a PHI node must be of the same type");
2897 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2900 delete $2; // Free the list...
2903 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
2906 // Handle the short syntax
2907 const PointerType *PFTy = 0;
2908 const FunctionType *Ty = 0;
2909 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2910 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2911 // Pull out the types of all of the arguments...
2912 std::vector<const Type*> ParamTypes;
2913 ParamList::iterator I = $6->begin(), E = $6->end();
2914 for (; I != E; ++I) {
2915 const Type *Ty = I->Val->getType();
2916 if (Ty == Type::VoidTy)
2917 GEN_ERROR("Short call syntax cannot be used with varargs");
2918 ParamTypes.push_back(Ty);
2920 Ty = FunctionType::get($3->get(), ParamTypes, false);
2921 PFTy = PointerType::get(Ty);
2924 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2927 // Check for call to invalid intrinsic to avoid crashing later.
2928 if (Function *theF = dyn_cast<Function>(V)) {
2929 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2930 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2931 !theF->getIntrinsicID(true))
2932 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
2933 theF->getName() + "'");
2936 // Set up the ParamAttrs for the function
2937 ParamAttrsVector Attrs;
2938 if ($8 != ParamAttr::None) {
2939 ParamAttrsWithIndex PAWI;
2942 Attrs.push_back(PAWI);
2944 // Check the arguments
2946 if ($6->empty()) { // Has no arguments?
2947 // Make sure no arguments is a good thing!
2948 if (Ty->getNumParams() != 0)
2949 GEN_ERROR("No arguments passed to a function that "
2950 "expects arguments");
2951 } else { // Has arguments?
2952 // Loop through FunctionType's arguments and ensure they are specified
2953 // correctly. Also, gather any parameter attributes.
2954 FunctionType::param_iterator I = Ty->param_begin();
2955 FunctionType::param_iterator E = Ty->param_end();
2956 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2959 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2960 if (ArgI->Val->getType() != *I)
2961 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2962 (*I)->getDescription() + "'");
2963 Args.push_back(ArgI->Val);
2964 if (ArgI->Attrs != ParamAttr::None) {
2965 ParamAttrsWithIndex PAWI;
2967 PAWI.attrs = ArgI->Attrs;
2968 Attrs.push_back(PAWI);
2971 if (Ty->isVarArg()) {
2973 for (; ArgI != ArgE; ++ArgI)
2974 Args.push_back(ArgI->Val); // push the remaining varargs
2975 } else if (I != E || ArgI != ArgE)
2976 GEN_ERROR("Invalid number of parameters detected");
2979 // Finish off the ParamAttrs and check them
2980 ParamAttrsList *PAL = 0;
2982 PAL = ParamAttrsList::get(Attrs);
2984 // Create the call node
2985 CallInst *CI = new CallInst(V, Args.begin(), Args.end());
2986 CI->setTailCall($1);
2987 CI->setCallingConv($2);
2988 CI->setParamAttrs(PAL);
2999 OptVolatile : VOLATILE {
3010 MemoryInst : MALLOC Types OptCAlign {
3011 if (!UpRefs.empty())
3012 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3013 $$ = new MallocInst(*$2, 0, $3);
3017 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3018 if (!UpRefs.empty())
3019 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3020 Value* tmpVal = getVal($4, $5);
3022 $$ = new MallocInst(*$2, tmpVal, $6);
3025 | ALLOCA Types OptCAlign {
3026 if (!UpRefs.empty())
3027 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3028 $$ = new AllocaInst(*$2, 0, $3);
3032 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3033 if (!UpRefs.empty())
3034 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3035 Value* tmpVal = getVal($4, $5);
3037 $$ = new AllocaInst(*$2, tmpVal, $6);
3040 | FREE ResolvedVal {
3041 if (!isa<PointerType>($2->getType()))
3042 GEN_ERROR("Trying to free nonpointer type " +
3043 $2->getType()->getDescription() + "");
3044 $$ = new FreeInst($2);
3048 | OptVolatile LOAD Types ValueRef OptCAlign {
3049 if (!UpRefs.empty())
3050 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3051 if (!isa<PointerType>($3->get()))
3052 GEN_ERROR("Can't load from nonpointer type: " +
3053 (*$3)->getDescription());
3054 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3055 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3056 (*$3)->getDescription());
3057 Value* tmpVal = getVal(*$3, $4);
3059 $$ = new LoadInst(tmpVal, "", $1, $5);
3062 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3063 if (!UpRefs.empty())
3064 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3065 const PointerType *PT = dyn_cast<PointerType>($5->get());
3067 GEN_ERROR("Can't store to a nonpointer type: " +
3068 (*$5)->getDescription());
3069 const Type *ElTy = PT->getElementType();
3070 if (ElTy != $3->getType())
3071 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3072 "' into space of type '" + ElTy->getDescription() + "'");
3074 Value* tmpVal = getVal(*$5, $6);
3076 $$ = new StoreInst($3, tmpVal, $1, $7);
3079 | GETELEMENTPTR Types ValueRef IndexList {
3080 if (!UpRefs.empty())
3081 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3082 if (!isa<PointerType>($2->get()))
3083 GEN_ERROR("getelementptr insn requires pointer operand");
3085 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end(), true))
3086 GEN_ERROR("Invalid getelementptr indices for type '" +
3087 (*$2)->getDescription()+ "'");
3088 Value* tmpVal = getVal(*$2, $3);
3090 $$ = new GetElementPtrInst(tmpVal, $4->begin(), $4->end());
3098 // common code from the two 'RunVMAsmParser' functions
3099 static Module* RunParser(Module * M) {
3100 CurModule.CurrentModule = M;
3101 // Check to make sure the parser succeeded
3104 delete ParserResult;
3108 // Emit an error if there are any unresolved types left.
3109 if (!CurModule.LateResolveTypes.empty()) {
3110 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3111 if (DID.Type == ValID::LocalName) {
3112 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3114 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3117 delete ParserResult;
3121 // Emit an error if there are any unresolved values left.
3122 if (!CurModule.LateResolveValues.empty()) {
3123 Value *V = CurModule.LateResolveValues.back();
3124 std::map<Value*, std::pair<ValID, int> >::iterator I =
3125 CurModule.PlaceHolderInfo.find(V);
3127 if (I != CurModule.PlaceHolderInfo.end()) {
3128 ValID &DID = I->second.first;
3129 if (DID.Type == ValID::LocalName) {
3130 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3132 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3135 delete ParserResult;
3140 // Check to make sure that parsing produced a result
3144 // Reset ParserResult variable while saving its value for the result.
3145 Module *Result = ParserResult;
3151 void llvm::GenerateError(const std::string &message, int LineNo) {
3152 if (LineNo == -1) LineNo = LLLgetLineNo();
3153 // TODO: column number in exception
3155 TheParseError->setError(LLLgetFilename(), message, LineNo);
3159 int yyerror(const char *ErrorMsg) {
3160 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3161 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3162 if (yychar != YYEMPTY && yychar != 0) {
3163 errMsg += " while reading token: '";
3164 errMsg += std::string(LLLgetTokenStart(),
3165 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3167 GenerateError(errMsg);