1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/AutoUpgrade.h"
22 #include "llvm/Support/GetElementPtrTypeIterator.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/Streams.h"
33 // The following is a gross hack. In order to rid the libAsmParser library of
34 // exceptions, we have to have a way of getting the yyparse function to go into
35 // an error situation. So, whenever we want an error to occur, the GenerateError
36 // function (see bottom of file) sets TriggerError. Then, at the end of each
37 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
38 // (a goto) to put YACC in error state. Furthermore, several calls to
39 // GenerateError are made from inside productions and they must simulate the
40 // previous exception behavior by exiting the production immediately. We have
41 // replaced these with the GEN_ERROR macro which calls GeneratError and then
42 // immediately invokes YYERROR. This would be so much cleaner if it was a
43 // recursive descent parser.
44 static bool TriggerError = false;
45 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
46 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
48 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
49 int yylex(); // declaration" of xxx warnings.
53 static Module *ParserResult;
55 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
56 // relating to upreferences in the input stream.
58 //#define DEBUG_UPREFS 1
60 #define UR_OUT(X) cerr << X
65 #define YYERROR_VERBOSE 1
67 static GlobalVariable *CurGV;
70 // This contains info used when building the body of a function. It is
71 // destroyed when the function is completed.
73 typedef std::vector<Value *> ValueList; // Numbered defs
76 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
78 static struct PerModuleInfo {
79 Module *CurrentModule;
80 ValueList Values; // Module level numbered definitions
81 ValueList LateResolveValues;
82 std::vector<PATypeHolder> Types;
83 std::map<ValID, PATypeHolder> LateResolveTypes;
85 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
86 /// how they were referenced and on which line of the input they came from so
87 /// that we can resolve them later and print error messages as appropriate.
88 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
90 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
91 // references to global values. Global values may be referenced before they
92 // are defined, and if so, the temporary object that they represent is held
93 // here. This is used for forward references of GlobalValues.
95 typedef std::map<std::pair<const PointerType *,
96 ValID>, GlobalValue*> GlobalRefsType;
97 GlobalRefsType GlobalRefs;
100 // If we could not resolve some functions at function compilation time
101 // (calls to functions before they are defined), resolve them now... Types
102 // are resolved when the constant pool has been completely parsed.
104 ResolveDefinitions(LateResolveValues);
108 // Check to make sure that all global value forward references have been
111 if (!GlobalRefs.empty()) {
112 std::string UndefinedReferences = "Unresolved global references exist:\n";
114 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
116 UndefinedReferences += " " + I->first.first->getDescription() + " " +
117 I->first.second.getName() + "\n";
119 GenerateError(UndefinedReferences);
123 // Look for intrinsic functions and CallInst that need to be upgraded
124 for (Module::iterator FI = CurrentModule->begin(),
125 FE = CurrentModule->end(); FI != FE; )
126 UpgradeCallsToIntrinsic(FI++); // must be post-increment, as we remove
128 Values.clear(); // Clear out function local definitions
133 // GetForwardRefForGlobal - Check to see if there is a forward reference
134 // for this global. If so, remove it from the GlobalRefs map and return it.
135 // If not, just return null.
136 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
137 // Check to see if there is a forward reference to this global variable...
138 // if there is, eliminate it and patch the reference to use the new def'n.
139 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
140 GlobalValue *Ret = 0;
141 if (I != GlobalRefs.end()) {
148 bool TypeIsUnresolved(PATypeHolder* PATy) {
149 // If it isn't abstract, its resolved
150 const Type* Ty = PATy->get();
151 if (!Ty->isAbstract())
153 // Traverse the type looking for abstract types. If it isn't abstract then
154 // we don't need to traverse that leg of the type.
155 std::vector<const Type*> WorkList, SeenList;
156 WorkList.push_back(Ty);
157 while (!WorkList.empty()) {
158 const Type* Ty = WorkList.back();
159 SeenList.push_back(Ty);
161 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
162 // Check to see if this is an unresolved type
163 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
164 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
165 for ( ; I != E; ++I) {
166 if (I->second.get() == OpTy)
169 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
170 const Type* TheTy = SeqTy->getElementType();
171 if (TheTy->isAbstract() && TheTy != Ty) {
172 std::vector<const Type*>::iterator I = SeenList.begin(),
178 WorkList.push_back(TheTy);
180 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
181 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
182 const Type* TheTy = StrTy->getElementType(i);
183 if (TheTy->isAbstract() && TheTy != Ty) {
184 std::vector<const Type*>::iterator I = SeenList.begin(),
190 WorkList.push_back(TheTy);
199 static struct PerFunctionInfo {
200 Function *CurrentFunction; // Pointer to current function being created
202 ValueList Values; // Keep track of #'d definitions
204 ValueList LateResolveValues;
205 bool isDeclare; // Is this function a forward declararation?
206 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
207 GlobalValue::VisibilityTypes Visibility;
209 /// BBForwardRefs - When we see forward references to basic blocks, keep
210 /// track of them here.
211 std::map<ValID, BasicBlock*> BBForwardRefs;
213 inline PerFunctionInfo() {
216 Linkage = GlobalValue::ExternalLinkage;
217 Visibility = GlobalValue::DefaultVisibility;
220 inline void FunctionStart(Function *M) {
225 void FunctionDone() {
226 // Any forward referenced blocks left?
227 if (!BBForwardRefs.empty()) {
228 GenerateError("Undefined reference to label " +
229 BBForwardRefs.begin()->second->getName());
233 // Resolve all forward references now.
234 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
236 Values.clear(); // Clear out function local definitions
237 BBForwardRefs.clear();
240 Linkage = GlobalValue::ExternalLinkage;
241 Visibility = GlobalValue::DefaultVisibility;
243 } CurFun; // Info for the current function...
245 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
248 //===----------------------------------------------------------------------===//
249 // Code to handle definitions of all the types
250 //===----------------------------------------------------------------------===//
252 static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
253 // Things that have names or are void typed don't get slot numbers
254 if (V->hasName() || (V->getType() == Type::VoidTy))
257 // In the case of function values, we have to allow for the forward reference
258 // of basic blocks, which are included in the numbering. Consequently, we keep
259 // track of the next insertion location with NextValNum. When a BB gets
260 // inserted, it could change the size of the CurFun.Values vector.
261 if (&ValueTab == &CurFun.Values) {
262 if (ValueTab.size() <= CurFun.NextValNum)
263 ValueTab.resize(CurFun.NextValNum+1);
264 ValueTab[CurFun.NextValNum++] = V;
267 // For all other lists, its okay to just tack it on the back of the vector.
268 ValueTab.push_back(V);
271 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
273 case ValID::LocalID: // Is it a numbered definition?
274 // Module constants occupy the lowest numbered slots...
275 if (D.Num < CurModule.Types.size())
276 return CurModule.Types[D.Num];
278 case ValID::LocalName: // Is it a named definition?
279 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.getName())) {
280 D.destroy(); // Free old strdup'd memory...
285 GenerateError("Internal parser error: Invalid symbol type reference");
289 // If we reached here, we referenced either a symbol that we don't know about
290 // or an id number that hasn't been read yet. We may be referencing something
291 // forward, so just create an entry to be resolved later and get to it...
293 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
296 if (inFunctionScope()) {
297 if (D.Type == ValID::LocalName) {
298 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
301 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
306 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
307 if (I != CurModule.LateResolveTypes.end())
310 Type *Typ = OpaqueType::get();
311 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
315 // getExistingVal - Look up the value specified by the provided type and
316 // the provided ValID. If the value exists and has already been defined, return
317 // it. Otherwise return null.
319 static Value *getExistingVal(const Type *Ty, const ValID &D) {
320 if (isa<FunctionType>(Ty)) {
321 GenerateError("Functions are not values and "
322 "must be referenced as pointers");
327 case ValID::LocalID: { // Is it a numbered definition?
328 // Check that the number is within bounds.
329 if (D.Num >= CurFun.Values.size())
331 Value *Result = CurFun.Values[D.Num];
332 if (Ty != Result->getType()) {
333 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
334 Result->getType()->getDescription() + "' does not match "
335 "expected type, '" + Ty->getDescription() + "'");
340 case ValID::GlobalID: { // Is it a numbered definition?
341 if (D.Num >= CurModule.Values.size())
343 Value *Result = CurModule.Values[D.Num];
344 if (Ty != Result->getType()) {
345 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
346 Result->getType()->getDescription() + "' does not match "
347 "expected type, '" + Ty->getDescription() + "'");
353 case ValID::LocalName: { // Is it a named definition?
354 if (!inFunctionScope())
356 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
357 Value *N = SymTab.lookup(D.getName());
360 if (N->getType() != Ty)
363 D.destroy(); // Free old strdup'd memory...
366 case ValID::GlobalName: { // Is it a named definition?
367 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
368 Value *N = SymTab.lookup(D.getName());
371 if (N->getType() != Ty)
374 D.destroy(); // Free old strdup'd memory...
378 // Check to make sure that "Ty" is an integral type, and that our
379 // value will fit into the specified type...
380 case ValID::ConstSIntVal: // Is it a constant pool reference??
381 if (!isa<IntegerType>(Ty) ||
382 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
383 GenerateError("Signed integral constant '" +
384 itostr(D.ConstPool64) + "' is invalid for type '" +
385 Ty->getDescription() + "'");
388 return ConstantInt::get(Ty, D.ConstPool64, true);
390 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
391 if (isa<IntegerType>(Ty) &&
392 ConstantInt::isValueValidForType(Ty, D.UConstPool64))
393 return ConstantInt::get(Ty, D.UConstPool64);
395 if (!isa<IntegerType>(Ty) ||
396 !ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
397 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
398 "' is invalid or out of range for type '" +
399 Ty->getDescription() + "'");
402 // This is really a signed reference. Transmogrify.
403 return ConstantInt::get(Ty, D.ConstPool64, true);
405 case ValID::ConstFPVal: // Is it a floating point const pool reference?
406 if (!Ty->isFloatingPoint() ||
407 !ConstantFP::isValueValidForType(Ty, *D.ConstPoolFP)) {
408 GenerateError("FP constant invalid for type");
411 // Lexer has no type info, so builds all float and double FP constants
412 // as double. Fix this here. Long double does not need this.
413 if (&D.ConstPoolFP->getSemantics() == &APFloat::IEEEdouble &&
415 D.ConstPoolFP->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
416 return ConstantFP::get(*D.ConstPoolFP);
418 case ValID::ConstNullVal: // Is it a null value?
419 if (!isa<PointerType>(Ty)) {
420 GenerateError("Cannot create a a non pointer null");
423 return ConstantPointerNull::get(cast<PointerType>(Ty));
425 case ValID::ConstUndefVal: // Is it an undef value?
426 return UndefValue::get(Ty);
428 case ValID::ConstZeroVal: // Is it a zero value?
429 return Constant::getNullValue(Ty);
431 case ValID::ConstantVal: // Fully resolved constant?
432 if (D.ConstantValue->getType() != Ty) {
433 GenerateError("Constant expression type different from required type");
436 return D.ConstantValue;
438 case ValID::InlineAsmVal: { // Inline asm expression
439 const PointerType *PTy = dyn_cast<PointerType>(Ty);
440 const FunctionType *FTy =
441 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
442 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
443 GenerateError("Invalid type for asm constraint string");
446 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
447 D.IAD->HasSideEffects);
448 D.destroy(); // Free InlineAsmDescriptor.
452 assert(0 && "Unhandled case!");
456 assert(0 && "Unhandled case!");
460 // getVal - This function is identical to getExistingVal, except that if a
461 // value is not already defined, it "improvises" by creating a placeholder var
462 // that looks and acts just like the requested variable. When the value is
463 // defined later, all uses of the placeholder variable are replaced with the
466 static Value *getVal(const Type *Ty, const ValID &ID) {
467 if (Ty == Type::LabelTy) {
468 GenerateError("Cannot use a basic block here");
472 // See if the value has already been defined.
473 Value *V = getExistingVal(Ty, ID);
475 if (TriggerError) return 0;
477 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
478 GenerateError("Invalid use of a non-first-class type");
482 // If we reached here, we referenced either a symbol that we don't know about
483 // or an id number that hasn't been read yet. We may be referencing something
484 // forward, so just create an entry to be resolved later and get to it...
487 case ValID::GlobalName:
488 case ValID::GlobalID: {
489 const PointerType *PTy = dyn_cast<PointerType>(Ty);
491 GenerateError("Invalid type for reference to global" );
494 const Type* ElTy = PTy->getElementType();
495 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
496 V = Function::Create(FTy, GlobalValue::ExternalLinkage);
498 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage, 0, "",
499 (Module*)0, false, PTy->getAddressSpace());
503 V = new Argument(Ty);
506 // Remember where this forward reference came from. FIXME, shouldn't we try
507 // to recycle these things??
508 CurModule.PlaceHolderInfo.insert(std::make_pair(V, std::make_pair(ID,
511 if (inFunctionScope())
512 InsertValue(V, CurFun.LateResolveValues);
514 InsertValue(V, CurModule.LateResolveValues);
518 /// defineBBVal - This is a definition of a new basic block with the specified
519 /// identifier which must be the same as CurFun.NextValNum, if its numeric.
520 static BasicBlock *defineBBVal(const ValID &ID) {
521 assert(inFunctionScope() && "Can't get basic block at global scope!");
525 // First, see if this was forward referenced
527 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
528 if (BBI != CurFun.BBForwardRefs.end()) {
530 // The forward declaration could have been inserted anywhere in the
531 // function: insert it into the correct place now.
532 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
533 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
535 // We're about to erase the entry, save the key so we can clean it up.
536 ValID Tmp = BBI->first;
538 // Erase the forward ref from the map as its no longer "forward"
539 CurFun.BBForwardRefs.erase(ID);
541 // The key has been removed from the map but so we don't want to leave
542 // strdup'd memory around so destroy it too.
545 // If its a numbered definition, bump the number and set the BB value.
546 if (ID.Type == ValID::LocalID) {
547 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
551 // We haven't seen this BB before and its first mention is a definition.
552 // Just create it and return it.
553 std::string Name (ID.Type == ValID::LocalName ? ID.getName() : "");
554 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
555 if (ID.Type == ValID::LocalID) {
556 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
565 /// getBBVal - get an existing BB value or create a forward reference for it.
567 static BasicBlock *getBBVal(const ValID &ID) {
568 assert(inFunctionScope() && "Can't get basic block at global scope!");
572 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
573 if (BBI != CurFun.BBForwardRefs.end()) {
575 } if (ID.Type == ValID::LocalName) {
576 std::string Name = ID.getName();
577 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
579 if (N->getType()->getTypeID() == Type::LabelTyID)
580 BB = cast<BasicBlock>(N);
582 GenerateError("Reference to label '" + Name + "' is actually of type '"+
583 N->getType()->getDescription() + "'");
585 } else if (ID.Type == ValID::LocalID) {
586 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
587 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
588 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
590 GenerateError("Reference to label '%" + utostr(ID.Num) +
591 "' is actually of type '"+
592 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
595 GenerateError("Illegal label reference " + ID.getName());
599 // If its already been defined, return it now.
601 ID.destroy(); // Free strdup'd memory.
605 // Otherwise, this block has not been seen before, create it.
607 if (ID.Type == ValID::LocalName)
609 BB = BasicBlock::Create(Name, CurFun.CurrentFunction);
611 // Insert it in the forward refs map.
612 CurFun.BBForwardRefs[ID] = BB;
618 //===----------------------------------------------------------------------===//
619 // Code to handle forward references in instructions
620 //===----------------------------------------------------------------------===//
622 // This code handles the late binding needed with statements that reference
623 // values not defined yet... for example, a forward branch, or the PHI node for
626 // This keeps a table (CurFun.LateResolveValues) of all such forward references
627 // and back patchs after we are done.
630 // ResolveDefinitions - If we could not resolve some defs at parsing
631 // time (forward branches, phi functions for loops, etc...) resolve the
635 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
636 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
637 while (!LateResolvers.empty()) {
638 Value *V = LateResolvers.back();
639 LateResolvers.pop_back();
641 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
642 CurModule.PlaceHolderInfo.find(V);
643 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
645 ValID &DID = PHI->second.first;
647 Value *TheRealValue = getExistingVal(V->getType(), DID);
651 V->replaceAllUsesWith(TheRealValue);
653 CurModule.PlaceHolderInfo.erase(PHI);
654 } else if (FutureLateResolvers) {
655 // Functions have their unresolved items forwarded to the module late
657 InsertValue(V, *FutureLateResolvers);
659 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
660 GenerateError("Reference to an invalid definition: '" +DID.getName()+
661 "' of type '" + V->getType()->getDescription() + "'",
665 GenerateError("Reference to an invalid definition: #" +
666 itostr(DID.Num) + " of type '" +
667 V->getType()->getDescription() + "'",
673 LateResolvers.clear();
676 // ResolveTypeTo - A brand new type was just declared. This means that (if
677 // name is not null) things referencing Name can be resolved. Otherwise, things
678 // refering to the number can be resolved. Do this now.
680 static void ResolveTypeTo(std::string *Name, const Type *ToTy) {
683 D = ValID::createLocalName(*Name);
685 D = ValID::createLocalID(CurModule.Types.size());
687 std::map<ValID, PATypeHolder>::iterator I =
688 CurModule.LateResolveTypes.find(D);
689 if (I != CurModule.LateResolveTypes.end()) {
690 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
691 CurModule.LateResolveTypes.erase(I);
695 // setValueName - Set the specified value to the name given. The name may be
696 // null potentially, in which case this is a noop. The string passed in is
697 // assumed to be a malloc'd string buffer, and is free'd by this function.
699 static void setValueName(Value *V, std::string *NameStr) {
700 if (!NameStr) return;
701 std::string Name(*NameStr); // Copy string
702 delete NameStr; // Free old string
704 if (V->getType() == Type::VoidTy) {
705 GenerateError("Can't assign name '" + Name+"' to value with void type");
709 assert(inFunctionScope() && "Must be in function scope!");
710 ValueSymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
711 if (ST.lookup(Name)) {
712 GenerateError("Redefinition of value '" + Name + "' of type '" +
713 V->getType()->getDescription() + "'");
721 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
722 /// this is a declaration, otherwise it is a definition.
723 static GlobalVariable *
724 ParseGlobalVariable(std::string *NameStr,
725 GlobalValue::LinkageTypes Linkage,
726 GlobalValue::VisibilityTypes Visibility,
727 bool isConstantGlobal, const Type *Ty,
728 Constant *Initializer, bool IsThreadLocal,
729 unsigned AddressSpace = 0) {
730 if (isa<FunctionType>(Ty)) {
731 GenerateError("Cannot declare global vars of function type");
734 if (Ty == Type::LabelTy) {
735 GenerateError("Cannot declare global vars of label type");
739 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
743 Name = *NameStr; // Copy string
744 delete NameStr; // Free old string
747 // See if this global value was forward referenced. If so, recycle the
751 ID = ValID::createGlobalName(Name);
753 ID = ValID::createGlobalID(CurModule.Values.size());
756 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
757 // Move the global to the end of the list, from whereever it was
758 // previously inserted.
759 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
760 CurModule.CurrentModule->getGlobalList().remove(GV);
761 CurModule.CurrentModule->getGlobalList().push_back(GV);
762 GV->setInitializer(Initializer);
763 GV->setLinkage(Linkage);
764 GV->setVisibility(Visibility);
765 GV->setConstant(isConstantGlobal);
766 GV->setThreadLocal(IsThreadLocal);
767 InsertValue(GV, CurModule.Values);
771 // If this global has a name
773 // if the global we're parsing has an initializer (is a definition) and
774 // has external linkage.
775 if (Initializer && Linkage != GlobalValue::InternalLinkage)
776 // If there is already a global with external linkage with this name
777 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
778 // If we allow this GVar to get created, it will be renamed in the
779 // symbol table because it conflicts with an existing GVar. We can't
780 // allow redefinition of GVars whose linking indicates that their name
781 // must stay the same. Issue the error.
782 GenerateError("Redefinition of global variable named '" + Name +
783 "' of type '" + Ty->getDescription() + "'");
788 // Otherwise there is no existing GV to use, create one now.
790 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
791 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
792 GV->setVisibility(Visibility);
793 InsertValue(GV, CurModule.Values);
797 // setTypeName - Set the specified type to the name given. The name may be
798 // null potentially, in which case this is a noop. The string passed in is
799 // assumed to be a malloc'd string buffer, and is freed by this function.
801 // This function returns true if the type has already been defined, but is
802 // allowed to be redefined in the specified context. If the name is a new name
803 // for the type plane, it is inserted and false is returned.
804 static bool setTypeName(const Type *T, std::string *NameStr) {
805 assert(!inFunctionScope() && "Can't give types function-local names!");
806 if (NameStr == 0) return false;
808 std::string Name(*NameStr); // Copy string
809 delete NameStr; // Free old string
811 // We don't allow assigning names to void type
812 if (T == Type::VoidTy) {
813 GenerateError("Can't assign name '" + Name + "' to the void type");
817 // Set the type name, checking for conflicts as we do so.
818 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
820 if (AlreadyExists) { // Inserting a name that is already defined???
821 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
822 assert(Existing && "Conflict but no matching type?!");
824 // There is only one case where this is allowed: when we are refining an
825 // opaque type. In this case, Existing will be an opaque type.
826 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
827 // We ARE replacing an opaque type!
828 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
832 // Otherwise, this is an attempt to redefine a type. That's okay if
833 // the redefinition is identical to the original. This will be so if
834 // Existing and T point to the same Type object. In this one case we
835 // allow the equivalent redefinition.
836 if (Existing == T) return true; // Yes, it's equal.
838 // Any other kind of (non-equivalent) redefinition is an error.
839 GenerateError("Redefinition of type named '" + Name + "' of type '" +
840 T->getDescription() + "'");
846 //===----------------------------------------------------------------------===//
847 // Code for handling upreferences in type names...
850 // TypeContains - Returns true if Ty directly contains E in it.
852 static bool TypeContains(const Type *Ty, const Type *E) {
853 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
854 E) != Ty->subtype_end();
859 // NestingLevel - The number of nesting levels that need to be popped before
860 // this type is resolved.
861 unsigned NestingLevel;
863 // LastContainedTy - This is the type at the current binding level for the
864 // type. Every time we reduce the nesting level, this gets updated.
865 const Type *LastContainedTy;
867 // UpRefTy - This is the actual opaque type that the upreference is
871 UpRefRecord(unsigned NL, OpaqueType *URTy)
872 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
876 // UpRefs - A list of the outstanding upreferences that need to be resolved.
877 static std::vector<UpRefRecord> UpRefs;
879 /// HandleUpRefs - Every time we finish a new layer of types, this function is
880 /// called. It loops through the UpRefs vector, which is a list of the
881 /// currently active types. For each type, if the up reference is contained in
882 /// the newly completed type, we decrement the level count. When the level
883 /// count reaches zero, the upreferenced type is the type that is passed in:
884 /// thus we can complete the cycle.
886 static PATypeHolder HandleUpRefs(const Type *ty) {
887 // If Ty isn't abstract, or if there are no up-references in it, then there is
888 // nothing to resolve here.
889 if (!ty->isAbstract() || UpRefs.empty()) return ty;
892 UR_OUT("Type '" << Ty->getDescription() <<
893 "' newly formed. Resolving upreferences.\n" <<
894 UpRefs.size() << " upreferences active!\n");
896 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
897 // to zero), we resolve them all together before we resolve them to Ty. At
898 // the end of the loop, if there is anything to resolve to Ty, it will be in
900 OpaqueType *TypeToResolve = 0;
902 for (unsigned i = 0; i != UpRefs.size(); ++i) {
903 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
904 << UpRefs[i].second->getDescription() << ") = "
905 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
906 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
907 // Decrement level of upreference
908 unsigned Level = --UpRefs[i].NestingLevel;
909 UpRefs[i].LastContainedTy = Ty;
910 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
911 if (Level == 0) { // Upreference should be resolved!
912 if (!TypeToResolve) {
913 TypeToResolve = UpRefs[i].UpRefTy;
915 UR_OUT(" * Resolving upreference for "
916 << UpRefs[i].second->getDescription() << "\n";
917 std::string OldName = UpRefs[i].UpRefTy->getDescription());
918 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
919 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
920 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
922 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
923 --i; // Do not skip the next element...
929 UR_OUT(" * Resolving upreference for "
930 << UpRefs[i].second->getDescription() << "\n";
931 std::string OldName = TypeToResolve->getDescription());
932 TypeToResolve->refineAbstractTypeTo(Ty);
938 //===----------------------------------------------------------------------===//
939 // RunVMAsmParser - Define an interface to this parser
940 //===----------------------------------------------------------------------===//
942 static Module* RunParser(Module * M);
944 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
946 Module *M = RunParser(new Module(LLLgetFilename()));
954 llvm::Module *ModuleVal;
955 llvm::Function *FunctionVal;
956 llvm::BasicBlock *BasicBlockVal;
957 llvm::TerminatorInst *TermInstVal;
958 llvm::Instruction *InstVal;
959 llvm::Constant *ConstVal;
961 const llvm::Type *PrimType;
962 std::list<llvm::PATypeHolder> *TypeList;
963 llvm::PATypeHolder *TypeVal;
964 llvm::Value *ValueVal;
965 std::vector<llvm::Value*> *ValueList;
966 std::vector<unsigned> *ConstantList;
967 llvm::ArgListType *ArgList;
968 llvm::TypeWithAttrs TypeWithAttrs;
969 llvm::TypeWithAttrsList *TypeWithAttrsList;
970 llvm::ParamList *ParamList;
972 // Represent the RHS of PHI node
973 std::list<std::pair<llvm::Value*,
974 llvm::BasicBlock*> > *PHIList;
975 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
976 std::vector<llvm::Constant*> *ConstVector;
978 llvm::GlobalValue::LinkageTypes Linkage;
979 llvm::GlobalValue::VisibilityTypes Visibility;
980 llvm::ParameterAttributes ParamAttrs;
981 llvm::APInt *APIntVal;
986 llvm::APFloat *FPVal;
989 std::string *StrVal; // This memory must be deleted
990 llvm::ValID ValIDVal;
992 llvm::Instruction::BinaryOps BinaryOpVal;
993 llvm::Instruction::TermOps TermOpVal;
994 llvm::Instruction::MemoryOps MemOpVal;
995 llvm::Instruction::CastOps CastOpVal;
996 llvm::Instruction::OtherOps OtherOpVal;
997 llvm::ICmpInst::Predicate IPredicate;
998 llvm::FCmpInst::Predicate FPredicate;
1001 %type <ModuleVal> Module
1002 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1003 %type <BasicBlockVal> BasicBlock InstructionList
1004 %type <TermInstVal> BBTerminatorInst
1005 %type <InstVal> Inst InstVal MemoryInst
1006 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1007 %type <ConstVector> ConstVector
1008 %type <ArgList> ArgList ArgListH
1009 %type <PHIList> PHIList
1010 %type <ParamList> ParamList // For call param lists & GEP indices
1011 %type <ValueList> IndexList // For GEP indices
1012 %type <ConstantList> ConstantIndexList // For insertvalue/extractvalue indices
1013 %type <TypeList> TypeListI
1014 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1015 %type <TypeWithAttrs> ArgType
1016 %type <JumpTable> JumpTable
1017 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1018 %type <BoolVal> ThreadLocal // 'thread_local' or not
1019 %type <BoolVal> OptVolatile // 'volatile' or not
1020 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1021 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1022 %type <Linkage> GVInternalLinkage GVExternalLinkage
1023 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1024 %type <Linkage> AliasLinkage
1025 %type <Visibility> GVVisibilityStyle
1027 // ValueRef - Unresolved reference to a definition or BB
1028 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1029 %type <ValueVal> ResolvedVal // <type> <valref> pair
1030 %type <ValueList> ReturnedVal
1031 // Tokens and types for handling constant integer values
1033 // ESINT64VAL - A negative number within long long range
1034 %token <SInt64Val> ESINT64VAL
1036 // EUINT64VAL - A positive number within uns. long long range
1037 %token <UInt64Val> EUINT64VAL
1039 // ESAPINTVAL - A negative number with arbitrary precision
1040 %token <APIntVal> ESAPINTVAL
1042 // EUAPINTVAL - A positive number with arbitrary precision
1043 %token <APIntVal> EUAPINTVAL
1045 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1046 %token <FPVal> FPVAL // Float or Double constant
1048 // Built in types...
1049 %type <TypeVal> Types ResultTypes
1050 %type <PrimType> IntType FPType PrimType // Classifications
1051 %token <PrimType> VOID INTTYPE
1052 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1056 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1057 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1058 %type <StrVal> LocalName OptLocalName OptLocalAssign
1059 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1060 %type <StrVal> OptSection SectionString OptGC
1062 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1064 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1065 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1066 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1067 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1068 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1069 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1070 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1072 %type <UIntVal> OptCallingConv
1073 %type <ParamAttrs> OptParamAttrs ParamAttr
1074 %type <ParamAttrs> OptFuncAttrs FuncAttr
1076 // Basic Block Terminating Operators
1077 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1080 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1081 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1082 %token <BinaryOpVal> SHL LSHR ASHR
1084 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1085 %type <IPredicate> IPredicates
1086 %type <FPredicate> FPredicates
1087 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1088 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1090 // Memory Instructions
1091 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1094 %type <CastOpVal> CastOps
1095 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1096 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1099 %token <OtherOpVal> PHI_TOK SELECT VAARG
1100 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1101 %token <OtherOpVal> GETRESULT
1102 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1104 // Function Attributes
1105 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1106 %token READNONE READONLY GC
1108 // Visibility Styles
1109 %token DEFAULT HIDDEN PROTECTED
1115 // Operations that are notably excluded from this list include:
1116 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1118 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1119 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1120 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1121 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1124 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1125 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1126 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1127 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1128 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1132 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1133 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1134 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1135 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1136 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1137 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1138 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1139 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1140 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1143 // These are some types that allow classification if we only want a particular
1144 // thing... for example, only a signed, unsigned, or integral type.
1146 FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1148 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1149 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1151 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1152 | /*empty*/ { $$=0; };
1154 /// OptLocalAssign - Value producing statements have an optional assignment
1156 OptLocalAssign : LocalName '=' {
1165 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1167 OptGlobalAssign : GlobalAssign
1173 GlobalAssign : GlobalName '=' {
1179 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1180 | WEAK { $$ = GlobalValue::WeakLinkage; }
1181 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1182 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1183 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1184 | COMMON { $$ = GlobalValue::CommonLinkage; }
1188 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1189 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1190 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1194 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1195 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1196 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1197 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1200 FunctionDeclareLinkage
1201 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1202 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1203 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1206 FunctionDefineLinkage
1207 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1208 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1209 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1210 | WEAK { $$ = GlobalValue::WeakLinkage; }
1211 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1215 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1216 | WEAK { $$ = GlobalValue::WeakLinkage; }
1217 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1220 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1221 CCC_TOK { $$ = CallingConv::C; } |
1222 FASTCC_TOK { $$ = CallingConv::Fast; } |
1223 COLDCC_TOK { $$ = CallingConv::Cold; } |
1224 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1225 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1227 if ((unsigned)$2 != $2)
1228 GEN_ERROR("Calling conv too large");
1233 ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1234 | ZEXT { $$ = ParamAttr::ZExt; }
1235 | SIGNEXT { $$ = ParamAttr::SExt; }
1236 | SEXT { $$ = ParamAttr::SExt; }
1237 | INREG { $$ = ParamAttr::InReg; }
1238 | SRET { $$ = ParamAttr::StructRet; }
1239 | NOALIAS { $$ = ParamAttr::NoAlias; }
1240 | BYVAL { $$ = ParamAttr::ByVal; }
1241 | NEST { $$ = ParamAttr::Nest; }
1242 | ALIGN EUINT64VAL { $$ =
1243 ParamAttr::constructAlignmentFromInt($2); }
1246 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1247 | OptParamAttrs ParamAttr {
1252 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1253 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1254 | ZEROEXT { $$ = ParamAttr::ZExt; }
1255 | SIGNEXT { $$ = ParamAttr::SExt; }
1256 | READNONE { $$ = ParamAttr::ReadNone; }
1257 | READONLY { $$ = ParamAttr::ReadOnly; }
1260 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1261 | OptFuncAttrs FuncAttr {
1266 OptGC : /* empty */ { $$ = 0; }
1267 | GC STRINGCONSTANT {
1272 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1273 // a comma before it.
1274 OptAlign : /*empty*/ { $$ = 0; } |
1277 if ($$ != 0 && !isPowerOf2_32($$))
1278 GEN_ERROR("Alignment must be a power of two");
1281 OptCAlign : /*empty*/ { $$ = 0; } |
1282 ',' ALIGN EUINT64VAL {
1284 if ($$ != 0 && !isPowerOf2_32($$))
1285 GEN_ERROR("Alignment must be a power of two");
1291 SectionString : SECTION STRINGCONSTANT {
1292 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1293 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1294 GEN_ERROR("Invalid character in section name");
1299 OptSection : /*empty*/ { $$ = 0; } |
1300 SectionString { $$ = $1; };
1302 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1303 // is set to be the global we are processing.
1305 GlobalVarAttributes : /* empty */ {} |
1306 ',' GlobalVarAttribute GlobalVarAttributes {};
1307 GlobalVarAttribute : SectionString {
1308 CurGV->setSection(*$1);
1312 | ALIGN EUINT64VAL {
1313 if ($2 != 0 && !isPowerOf2_32($2))
1314 GEN_ERROR("Alignment must be a power of two");
1315 CurGV->setAlignment($2);
1319 //===----------------------------------------------------------------------===//
1320 // Types includes all predefined types... except void, because it can only be
1321 // used in specific contexts (function returning void for example).
1323 // Derived types are added later...
1325 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1329 $$ = new PATypeHolder(OpaqueType::get());
1333 $$ = new PATypeHolder($1);
1336 | Types OptAddrSpace '*' { // Pointer type?
1337 if (*$1 == Type::LabelTy)
1338 GEN_ERROR("Cannot form a pointer to a basic block");
1339 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1343 | SymbolicValueRef { // Named types are also simple types...
1344 const Type* tmp = getTypeVal($1);
1346 $$ = new PATypeHolder(tmp);
1348 | '\\' EUINT64VAL { // Type UpReference
1349 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1350 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1351 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1352 $$ = new PATypeHolder(OT);
1353 UR_OUT("New Upreference!\n");
1356 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1357 // Allow but ignore attributes on function types; this permits auto-upgrade.
1358 // FIXME: remove in LLVM 3.0.
1359 const Type *RetTy = *$1;
1360 if (!FunctionType::isValidReturnType(RetTy))
1361 GEN_ERROR("Invalid result type for LLVM function");
1363 std::vector<const Type*> Params;
1364 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1365 for (; I != E; ++I ) {
1366 const Type *Ty = I->Ty->get();
1367 Params.push_back(Ty);
1370 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1371 if (isVarArg) Params.pop_back();
1373 for (unsigned i = 0; i != Params.size(); ++i)
1374 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1375 GEN_ERROR("Function arguments must be value types!");
1379 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1380 delete $3; // Delete the argument list
1381 delete $1; // Delete the return type handle
1382 $$ = new PATypeHolder(HandleUpRefs(FT));
1385 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1386 // Allow but ignore attributes on function types; this permits auto-upgrade.
1387 // FIXME: remove in LLVM 3.0.
1388 std::vector<const Type*> Params;
1389 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1390 for ( ; I != E; ++I ) {
1391 const Type* Ty = I->Ty->get();
1392 Params.push_back(Ty);
1395 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1396 if (isVarArg) Params.pop_back();
1398 for (unsigned i = 0; i != Params.size(); ++i)
1399 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1400 GEN_ERROR("Function arguments must be value types!");
1404 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1405 delete $3; // Delete the argument list
1406 $$ = new PATypeHolder(HandleUpRefs(FT));
1410 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1411 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, $2)));
1415 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1416 const llvm::Type* ElemTy = $4->get();
1417 if ((unsigned)$2 != $2)
1418 GEN_ERROR("Unsigned result not equal to signed result");
1419 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1420 GEN_ERROR("Element type of a VectorType must be primitive");
1421 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1425 | '{' TypeListI '}' { // Structure type?
1426 std::vector<const Type*> Elements;
1427 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1428 E = $2->end(); I != E; ++I)
1429 Elements.push_back(*I);
1431 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1435 | '{' '}' { // Empty structure type?
1436 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1439 | '<' '{' TypeListI '}' '>' {
1440 std::vector<const Type*> Elements;
1441 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1442 E = $3->end(); I != E; ++I)
1443 Elements.push_back(*I);
1445 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1449 | '<' '{' '}' '>' { // Empty structure type?
1450 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1456 : Types OptParamAttrs {
1457 // Allow but ignore attributes on function types; this permits auto-upgrade.
1458 // FIXME: remove in LLVM 3.0.
1460 $$.Attrs = ParamAttr::None;
1466 if (!UpRefs.empty())
1467 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1468 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1469 GEN_ERROR("LLVM functions cannot return aggregate types");
1473 $$ = new PATypeHolder(Type::VoidTy);
1477 ArgTypeList : ArgType {
1478 $$ = new TypeWithAttrsList();
1482 | ArgTypeList ',' ArgType {
1483 ($$=$1)->push_back($3);
1490 | ArgTypeList ',' DOTDOTDOT {
1492 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1493 TWA.Ty = new PATypeHolder(Type::VoidTy);
1498 $$ = new TypeWithAttrsList;
1499 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1500 TWA.Ty = new PATypeHolder(Type::VoidTy);
1505 $$ = new TypeWithAttrsList();
1509 // TypeList - Used for struct declarations and as a basis for function type
1510 // declaration type lists
1513 $$ = new std::list<PATypeHolder>();
1518 | TypeListI ',' Types {
1519 ($$=$1)->push_back(*$3);
1524 // ConstVal - The various declarations that go into the constant pool. This
1525 // production is used ONLY to represent constants that show up AFTER a 'const',
1526 // 'constant' or 'global' token at global scope. Constants that can be inlined
1527 // into other expressions (such as integers and constexprs) are handled by the
1528 // ResolvedVal, ValueRef and ConstValueRef productions.
1530 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
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() + "'");
1537 const Type *ETy = ATy->getElementType();
1538 uint64_t NumElements = ATy->getNumElements();
1540 // Verify that we have the correct size...
1541 if (NumElements != -1 && NumElements != (int)$3->size())
1542 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1543 utostr($3->size()) + " arguments, but has size of " +
1544 itostr(NumElements) + "");
1546 // Verify all elements are correct type!
1547 for (unsigned i = 0; i < $3->size(); i++) {
1548 if (ETy != (*$3)[i]->getType())
1549 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1550 ETy->getDescription() +"' as required!\nIt is of type '"+
1551 (*$3)[i]->getType()->getDescription() + "'.");
1554 $$ = ConstantArray::get(ATy, *$3);
1555 delete $1; delete $3;
1559 if (!UpRefs.empty())
1560 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1561 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1563 GEN_ERROR("Cannot make array constant with type: '" +
1564 (*$1)->getDescription() + "'");
1566 uint64_t NumElements = ATy->getNumElements();
1567 if (NumElements != -1 && NumElements != 0)
1568 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1569 " arguments, but has size of " + itostr(NumElements) +"");
1570 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1574 | Types 'c' STRINGCONSTANT {
1575 if (!UpRefs.empty())
1576 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1577 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1579 GEN_ERROR("Cannot make array constant with type: '" +
1580 (*$1)->getDescription() + "'");
1582 uint64_t NumElements = ATy->getNumElements();
1583 const Type *ETy = ATy->getElementType();
1584 if (NumElements != -1 && NumElements != int($3->length()))
1585 GEN_ERROR("Can't build string constant of size " +
1586 itostr((int)($3->length())) +
1587 " when array has size " + itostr(NumElements) + "");
1588 std::vector<Constant*> Vals;
1589 if (ETy == Type::Int8Ty) {
1590 for (unsigned i = 0; i < $3->length(); ++i)
1591 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1594 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1597 $$ = ConstantArray::get(ATy, Vals);
1601 | Types '<' ConstVector '>' { // Nonempty unsized arr
1602 if (!UpRefs.empty())
1603 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1604 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1606 GEN_ERROR("Cannot make packed constant with type: '" +
1607 (*$1)->getDescription() + "'");
1608 const Type *ETy = PTy->getElementType();
1609 unsigned NumElements = PTy->getNumElements();
1611 // Verify that we have the correct size...
1612 if (NumElements != -1 && NumElements != (int)$3->size())
1613 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1614 utostr($3->size()) + " arguments, but has size of " +
1615 itostr(NumElements) + "");
1617 // Verify all elements are correct type!
1618 for (unsigned i = 0; i < $3->size(); i++) {
1619 if (ETy != (*$3)[i]->getType())
1620 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1621 ETy->getDescription() +"' as required!\nIt is of type '"+
1622 (*$3)[i]->getType()->getDescription() + "'.");
1625 $$ = ConstantVector::get(PTy, *$3);
1626 delete $1; delete $3;
1629 | Types '{' ConstVector '}' {
1630 const StructType *STy = dyn_cast<StructType>($1->get());
1632 GEN_ERROR("Cannot make struct constant with type: '" +
1633 (*$1)->getDescription() + "'");
1635 if ($3->size() != STy->getNumContainedTypes())
1636 GEN_ERROR("Illegal number of initializers for structure type");
1638 // Check to ensure that constants are compatible with the type initializer!
1639 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1640 if ((*$3)[i]->getType() != STy->getElementType(i))
1641 GEN_ERROR("Expected type '" +
1642 STy->getElementType(i)->getDescription() +
1643 "' for element #" + utostr(i) +
1644 " of structure initializer");
1646 // Check to ensure that Type is not packed
1647 if (STy->isPacked())
1648 GEN_ERROR("Unpacked Initializer to vector type '" +
1649 STy->getDescription() + "'");
1651 $$ = ConstantStruct::get(STy, *$3);
1652 delete $1; delete $3;
1656 if (!UpRefs.empty())
1657 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1658 const StructType *STy = dyn_cast<StructType>($1->get());
1660 GEN_ERROR("Cannot make struct constant with type: '" +
1661 (*$1)->getDescription() + "'");
1663 if (STy->getNumContainedTypes() != 0)
1664 GEN_ERROR("Illegal number of initializers for structure type");
1666 // Check to ensure that Type is not packed
1667 if (STy->isPacked())
1668 GEN_ERROR("Unpacked Initializer to vector type '" +
1669 STy->getDescription() + "'");
1671 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1675 | Types '<' '{' ConstVector '}' '>' {
1676 const StructType *STy = dyn_cast<StructType>($1->get());
1678 GEN_ERROR("Cannot make struct constant with type: '" +
1679 (*$1)->getDescription() + "'");
1681 if ($4->size() != STy->getNumContainedTypes())
1682 GEN_ERROR("Illegal number of initializers for structure type");
1684 // Check to ensure that constants are compatible with the type initializer!
1685 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1686 if ((*$4)[i]->getType() != STy->getElementType(i))
1687 GEN_ERROR("Expected type '" +
1688 STy->getElementType(i)->getDescription() +
1689 "' for element #" + utostr(i) +
1690 " of structure initializer");
1692 // Check to ensure that Type is packed
1693 if (!STy->isPacked())
1694 GEN_ERROR("Vector initializer to non-vector type '" +
1695 STy->getDescription() + "'");
1697 $$ = ConstantStruct::get(STy, *$4);
1698 delete $1; delete $4;
1701 | Types '<' '{' '}' '>' {
1702 if (!UpRefs.empty())
1703 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1704 const StructType *STy = dyn_cast<StructType>($1->get());
1706 GEN_ERROR("Cannot make struct constant with type: '" +
1707 (*$1)->getDescription() + "'");
1709 if (STy->getNumContainedTypes() != 0)
1710 GEN_ERROR("Illegal number of initializers for structure type");
1712 // Check to ensure that Type is packed
1713 if (!STy->isPacked())
1714 GEN_ERROR("Vector initializer to non-vector type '" +
1715 STy->getDescription() + "'");
1717 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1722 if (!UpRefs.empty())
1723 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1724 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1726 GEN_ERROR("Cannot make null pointer constant with type: '" +
1727 (*$1)->getDescription() + "'");
1729 $$ = ConstantPointerNull::get(PTy);
1734 if (!UpRefs.empty())
1735 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1736 $$ = UndefValue::get($1->get());
1740 | Types SymbolicValueRef {
1741 if (!UpRefs.empty())
1742 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1743 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1745 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1747 // ConstExprs can exist in the body of a function, thus creating
1748 // GlobalValues whenever they refer to a variable. Because we are in
1749 // the context of a function, getExistingVal will search the functions
1750 // symbol table instead of the module symbol table for the global symbol,
1751 // which throws things all off. To get around this, we just tell
1752 // getExistingVal that we are at global scope here.
1754 Function *SavedCurFn = CurFun.CurrentFunction;
1755 CurFun.CurrentFunction = 0;
1757 Value *V = getExistingVal(Ty, $2);
1760 CurFun.CurrentFunction = SavedCurFn;
1762 // If this is an initializer for a constant pointer, which is referencing a
1763 // (currently) undefined variable, create a stub now that shall be replaced
1764 // in the future with the right type of variable.
1767 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1768 const PointerType *PT = cast<PointerType>(Ty);
1770 // First check to see if the forward references value is already created!
1771 PerModuleInfo::GlobalRefsType::iterator I =
1772 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1774 if (I != CurModule.GlobalRefs.end()) {
1775 V = I->second; // Placeholder already exists, use it...
1779 if ($2.Type == ValID::GlobalName)
1780 Name = $2.getName();
1781 else if ($2.Type != ValID::GlobalID)
1782 GEN_ERROR("Invalid reference to global");
1784 // Create the forward referenced global.
1786 if (const FunctionType *FTy =
1787 dyn_cast<FunctionType>(PT->getElementType())) {
1788 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1789 CurModule.CurrentModule);
1791 GV = new GlobalVariable(PT->getElementType(), false,
1792 GlobalValue::ExternalWeakLinkage, 0,
1793 Name, CurModule.CurrentModule);
1796 // Keep track of the fact that we have a forward ref to recycle it
1797 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1802 $$ = cast<GlobalValue>(V);
1803 delete $1; // Free the type handle
1807 if (!UpRefs.empty())
1808 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1809 if ($1->get() != $2->getType())
1810 GEN_ERROR("Mismatched types for constant expression: " +
1811 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1816 | Types ZEROINITIALIZER {
1817 if (!UpRefs.empty())
1818 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1819 const Type *Ty = $1->get();
1820 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1821 GEN_ERROR("Cannot create a null initialized value of this type");
1822 $$ = Constant::getNullValue(Ty);
1826 | IntType ESINT64VAL { // integral constants
1827 if (!ConstantInt::isValueValidForType($1, $2))
1828 GEN_ERROR("Constant value doesn't fit in type");
1829 $$ = ConstantInt::get($1, $2, true);
1832 | IntType ESAPINTVAL { // arbitrary precision integer constants
1833 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1834 if ($2->getBitWidth() > BitWidth) {
1835 GEN_ERROR("Constant value does not fit in type");
1837 $2->sextOrTrunc(BitWidth);
1838 $$ = ConstantInt::get(*$2);
1842 | IntType EUINT64VAL { // integral constants
1843 if (!ConstantInt::isValueValidForType($1, $2))
1844 GEN_ERROR("Constant value doesn't fit in type");
1845 $$ = ConstantInt::get($1, $2, false);
1848 | IntType EUAPINTVAL { // arbitrary precision integer constants
1849 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1850 if ($2->getBitWidth() > BitWidth) {
1851 GEN_ERROR("Constant value does not fit in type");
1853 $2->zextOrTrunc(BitWidth);
1854 $$ = ConstantInt::get(*$2);
1858 | INTTYPE TRUETOK { // Boolean constants
1859 if (cast<IntegerType>($1)->getBitWidth() != 1)
1860 GEN_ERROR("Constant true must have type i1");
1861 $$ = ConstantInt::getTrue();
1864 | INTTYPE FALSETOK { // Boolean constants
1865 if (cast<IntegerType>($1)->getBitWidth() != 1)
1866 GEN_ERROR("Constant false must have type i1");
1867 $$ = ConstantInt::getFalse();
1870 | FPType FPVAL { // Floating point constants
1871 if (!ConstantFP::isValueValidForType($1, *$2))
1872 GEN_ERROR("Floating point constant invalid for type");
1873 // Lexer has no type info, so builds all float and double FP constants
1874 // as double. Fix this here. Long double is done right.
1875 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1876 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1877 $$ = ConstantFP::get(*$2);
1883 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1884 if (!UpRefs.empty())
1885 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1887 const Type *DestTy = $5->get();
1888 if (!CastInst::castIsValid($1, $3, DestTy))
1889 GEN_ERROR("invalid cast opcode for cast from '" +
1890 Val->getType()->getDescription() + "' to '" +
1891 DestTy->getDescription() + "'");
1892 $$ = ConstantExpr::getCast($1, $3, DestTy);
1895 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1896 if (!isa<PointerType>($3->getType()))
1897 GEN_ERROR("GetElementPtr requires a pointer operand");
1900 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1902 GEN_ERROR("Index list invalid for constant getelementptr");
1904 SmallVector<Constant*, 8> IdxVec;
1905 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1906 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1907 IdxVec.push_back(C);
1909 GEN_ERROR("Indices to constant getelementptr must be constants");
1913 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1916 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1917 if ($3->getType() != Type::Int1Ty)
1918 GEN_ERROR("Select condition must be of boolean type");
1919 if ($5->getType() != $7->getType())
1920 GEN_ERROR("Select operand types must match");
1921 $$ = ConstantExpr::getSelect($3, $5, $7);
1924 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1925 if ($3->getType() != $5->getType())
1926 GEN_ERROR("Binary operator types must match");
1928 $$ = ConstantExpr::get($1, $3, $5);
1930 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1931 if ($3->getType() != $5->getType())
1932 GEN_ERROR("Logical operator types must match");
1933 if (!$3->getType()->isInteger()) {
1934 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1935 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1936 GEN_ERROR("Logical operator requires integral operands");
1938 $$ = ConstantExpr::get($1, $3, $5);
1941 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1942 if ($4->getType() != $6->getType())
1943 GEN_ERROR("icmp operand types must match");
1944 $$ = ConstantExpr::getICmp($2, $4, $6);
1946 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1947 if ($4->getType() != $6->getType())
1948 GEN_ERROR("fcmp operand types must match");
1949 $$ = ConstantExpr::getFCmp($2, $4, $6);
1951 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1952 if ($4->getType() != $6->getType())
1953 GEN_ERROR("vicmp operand types must match");
1954 $$ = ConstantExpr::getVICmp($2, $4, $6);
1956 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1957 if ($4->getType() != $6->getType())
1958 GEN_ERROR("vfcmp operand types must match");
1959 $$ = ConstantExpr::getVFCmp($2, $4, $6);
1961 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1962 if (!ExtractElementInst::isValidOperands($3, $5))
1963 GEN_ERROR("Invalid extractelement operands");
1964 $$ = ConstantExpr::getExtractElement($3, $5);
1967 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1968 if (!InsertElementInst::isValidOperands($3, $5, $7))
1969 GEN_ERROR("Invalid insertelement operands");
1970 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1973 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1974 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1975 GEN_ERROR("Invalid shufflevector operands");
1976 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1979 | EXTRACTVALUE '(' ConstVal ConstantIndexList ')' {
1980 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
1981 GEN_ERROR("ExtractValue requires an aggregate operand");
1983 $$ = ConstantExpr::getExtractValue($3, &(*$4)[0], $4->size());
1987 | INSERTVALUE '(' ConstVal ',' ConstVal ConstantIndexList ')' {
1988 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
1989 GEN_ERROR("InsertValue requires an aggregate operand");
1991 $$ = ConstantExpr::getInsertValue($3, $5, &(*$6)[0], $6->size());
1997 // ConstVector - A list of comma separated constants.
1998 ConstVector : ConstVector ',' ConstVal {
1999 ($$ = $1)->push_back($3);
2003 $$ = new std::vector<Constant*>();
2009 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2010 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2013 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2015 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2016 AliaseeRef : ResultTypes SymbolicValueRef {
2017 const Type* VTy = $1->get();
2018 Value *V = getVal(VTy, $2);
2020 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2022 GEN_ERROR("Aliases can be created only to global values");
2028 | BITCAST '(' AliaseeRef TO Types ')' {
2030 const Type *DestTy = $5->get();
2031 if (!CastInst::castIsValid($1, $3, DestTy))
2032 GEN_ERROR("invalid cast opcode for cast from '" +
2033 Val->getType()->getDescription() + "' to '" +
2034 DestTy->getDescription() + "'");
2036 $$ = ConstantExpr::getCast($1, $3, DestTy);
2041 //===----------------------------------------------------------------------===//
2042 // Rules to match Modules
2043 //===----------------------------------------------------------------------===//
2045 // Module rule: Capture the result of parsing the whole file into a result
2050 $$ = ParserResult = CurModule.CurrentModule;
2051 CurModule.ModuleDone();
2055 $$ = ParserResult = CurModule.CurrentModule;
2056 CurModule.ModuleDone();
2063 | DefinitionList Definition
2067 : DEFINE { CurFun.isDeclare = false; } Function {
2068 CurFun.FunctionDone();
2071 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2074 | MODULE ASM_TOK AsmBlock {
2077 | OptLocalAssign TYPE Types {
2078 if (!UpRefs.empty())
2079 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2080 // Eagerly resolve types. This is not an optimization, this is a
2081 // requirement that is due to the fact that we could have this:
2083 // %list = type { %list * }
2084 // %list = type { %list * } ; repeated type decl
2086 // If types are not resolved eagerly, then the two types will not be
2087 // determined to be the same type!
2089 ResolveTypeTo($1, *$3);
2091 if (!setTypeName(*$3, $1) && !$1) {
2093 // If this is a named type that is not a redefinition, add it to the slot
2095 CurModule.Types.push_back(*$3);
2101 | OptLocalAssign TYPE VOID {
2102 ResolveTypeTo($1, $3);
2104 if (!setTypeName($3, $1) && !$1) {
2106 // If this is a named type that is not a redefinition, add it to the slot
2108 CurModule.Types.push_back($3);
2112 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2114 /* "Externally Visible" Linkage */
2116 GEN_ERROR("Global value initializer is not a constant");
2117 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2118 $2, $4, $5->getType(), $5, $3, $6);
2120 } GlobalVarAttributes {
2123 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2124 ConstVal OptAddrSpace {
2126 GEN_ERROR("Global value initializer is not a constant");
2127 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2129 } GlobalVarAttributes {
2132 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2133 Types OptAddrSpace {
2134 if (!UpRefs.empty())
2135 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2136 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2139 } GlobalVarAttributes {
2143 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2150 GEN_ERROR("Alias name cannot be empty");
2152 Constant* Aliasee = $5;
2154 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2156 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2157 CurModule.CurrentModule);
2158 GA->setVisibility($2);
2159 InsertValue(GA, CurModule.Values);
2162 // If there was a forward reference of this alias, resolve it now.
2166 ID = ValID::createGlobalName(Name);
2168 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2170 if (GlobalValue *FWGV =
2171 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2172 // Replace uses of the fwdref with the actual alias.
2173 FWGV->replaceAllUsesWith(GA);
2174 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2175 GV->eraseFromParent();
2177 cast<Function>(FWGV)->eraseFromParent();
2183 | TARGET TargetDefinition {
2186 | DEPLIBS '=' LibrariesDefinition {
2192 AsmBlock : STRINGCONSTANT {
2193 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2194 if (AsmSoFar.empty())
2195 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2197 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2202 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2203 CurModule.CurrentModule->setTargetTriple(*$3);
2206 | DATALAYOUT '=' STRINGCONSTANT {
2207 CurModule.CurrentModule->setDataLayout(*$3);
2211 LibrariesDefinition : '[' LibList ']';
2213 LibList : LibList ',' STRINGCONSTANT {
2214 CurModule.CurrentModule->addLibrary(*$3);
2219 CurModule.CurrentModule->addLibrary(*$1);
2223 | /* empty: end of list */ {
2228 //===----------------------------------------------------------------------===//
2229 // Rules to match Function Headers
2230 //===----------------------------------------------------------------------===//
2232 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2233 if (!UpRefs.empty())
2234 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2235 if (!(*$3)->isFirstClassType())
2236 GEN_ERROR("Argument types must be first-class");
2237 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2242 | Types OptParamAttrs OptLocalName {
2243 if (!UpRefs.empty())
2244 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2245 if (!(*$1)->isFirstClassType())
2246 GEN_ERROR("Argument types must be first-class");
2247 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2248 $$ = new ArgListType;
2253 ArgList : ArgListH {
2257 | ArgListH ',' DOTDOTDOT {
2259 struct ArgListEntry E;
2260 E.Ty = new PATypeHolder(Type::VoidTy);
2262 E.Attrs = ParamAttr::None;
2267 $$ = new ArgListType;
2268 struct ArgListEntry E;
2269 E.Ty = new PATypeHolder(Type::VoidTy);
2271 E.Attrs = ParamAttr::None;
2280 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2281 OptFuncAttrs OptSection OptAlign OptGC {
2282 std::string FunctionName(*$3);
2283 delete $3; // Free strdup'd memory!
2285 // Check the function result for abstractness if this is a define. We should
2286 // have no abstract types at this point
2287 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2288 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2290 if (!FunctionType::isValidReturnType(*$2))
2291 GEN_ERROR("Invalid result type for LLVM function");
2293 std::vector<const Type*> ParamTypeList;
2294 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2295 if ($7 != ParamAttr::None)
2296 Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
2297 if ($5) { // If there are arguments...
2299 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2300 const Type* Ty = I->Ty->get();
2301 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2302 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2303 ParamTypeList.push_back(Ty);
2304 if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2305 Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
2309 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2310 if (isVarArg) ParamTypeList.pop_back();
2314 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2316 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2317 const PointerType *PFT = PointerType::getUnqual(FT);
2321 if (!FunctionName.empty()) {
2322 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2324 ID = ValID::createGlobalID(CurModule.Values.size());
2328 // See if this function was forward referenced. If so, recycle the object.
2329 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2330 // Move the function to the end of the list, from whereever it was
2331 // previously inserted.
2332 Fn = cast<Function>(FWRef);
2333 assert(Fn->getParamAttrs().isEmpty() &&
2334 "Forward reference has parameter attributes!");
2335 CurModule.CurrentModule->getFunctionList().remove(Fn);
2336 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2337 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2338 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2339 if (Fn->getFunctionType() != FT ) {
2340 // The existing function doesn't have the same type. This is an overload
2342 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2343 } else if (Fn->getParamAttrs() != PAL) {
2344 // The existing function doesn't have the same parameter attributes.
2345 // This is an overload error.
2346 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2347 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2348 // Neither the existing or the current function is a declaration and they
2349 // have the same name and same type. Clearly this is a redefinition.
2350 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2351 } else if (Fn->isDeclaration()) {
2352 // Make sure to strip off any argument names so we can't get conflicts.
2353 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2357 } else { // Not already defined?
2358 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2359 CurModule.CurrentModule);
2360 InsertValue(Fn, CurModule.Values);
2363 CurFun.FunctionStart(Fn);
2365 if (CurFun.isDeclare) {
2366 // If we have declaration, always overwrite linkage. This will allow us to
2367 // correctly handle cases, when pointer to function is passed as argument to
2368 // another function.
2369 Fn->setLinkage(CurFun.Linkage);
2370 Fn->setVisibility(CurFun.Visibility);
2372 Fn->setCallingConv($1);
2373 Fn->setParamAttrs(PAL);
2374 Fn->setAlignment($9);
2376 Fn->setSection(*$8);
2380 Fn->setCollector($10->c_str());
2384 // Add all of the arguments we parsed to the function...
2385 if ($5) { // Is null if empty...
2386 if (isVarArg) { // Nuke the last entry
2387 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2388 "Not a varargs marker!");
2389 delete $5->back().Ty;
2390 $5->pop_back(); // Delete the last entry
2392 Function::arg_iterator ArgIt = Fn->arg_begin();
2393 Function::arg_iterator ArgEnd = Fn->arg_end();
2395 for (ArgListType::iterator I = $5->begin();
2396 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2397 delete I->Ty; // Delete the typeholder...
2398 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2404 delete $5; // We're now done with the argument list
2409 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2411 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2412 $$ = CurFun.CurrentFunction;
2414 // Make sure that we keep track of the linkage type even if there was a
2415 // previous "declare".
2417 $$->setVisibility($2);
2420 END : ENDTOK | '}'; // Allow end of '}' to end a function
2422 Function : BasicBlockList END {
2427 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2428 CurFun.CurrentFunction->setLinkage($1);
2429 CurFun.CurrentFunction->setVisibility($2);
2430 $$ = CurFun.CurrentFunction;
2431 CurFun.FunctionDone();
2435 //===----------------------------------------------------------------------===//
2436 // Rules to match Basic Blocks
2437 //===----------------------------------------------------------------------===//
2439 OptSideEffect : /* empty */ {
2448 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2449 $$ = ValID::create($1);
2453 $$ = ValID::create($1);
2456 | FPVAL { // Perhaps it's an FP constant?
2457 $$ = ValID::create($1);
2461 $$ = ValID::create(ConstantInt::getTrue());
2465 $$ = ValID::create(ConstantInt::getFalse());
2469 $$ = ValID::createNull();
2473 $$ = ValID::createUndef();
2476 | ZEROINITIALIZER { // A vector zero constant.
2477 $$ = ValID::createZeroInit();
2480 | '<' ConstVector '>' { // Nonempty unsized packed vector
2481 const Type *ETy = (*$2)[0]->getType();
2482 unsigned NumElements = $2->size();
2484 if (!ETy->isInteger() && !ETy->isFloatingPoint())
2485 GEN_ERROR("Invalid vector element type: " + ETy->getDescription());
2487 VectorType* pt = VectorType::get(ETy, NumElements);
2488 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(pt));
2490 // Verify all elements are correct type!
2491 for (unsigned i = 0; i < $2->size(); i++) {
2492 if (ETy != (*$2)[i]->getType())
2493 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2494 ETy->getDescription() +"' as required!\nIt is of type '" +
2495 (*$2)[i]->getType()->getDescription() + "'.");
2498 $$ = ValID::create(ConstantVector::get(pt, *$2));
2499 delete PTy; delete $2;
2502 | '[' ConstVector ']' { // Nonempty unsized arr
2503 const Type *ETy = (*$2)[0]->getType();
2504 uint64_t NumElements = $2->size();
2506 if (!ETy->isFirstClassType())
2507 GEN_ERROR("Invalid array element type: " + ETy->getDescription());
2509 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2510 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(ATy));
2512 // Verify all elements are correct type!
2513 for (unsigned i = 0; i < $2->size(); i++) {
2514 if (ETy != (*$2)[i]->getType())
2515 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2516 ETy->getDescription() +"' as required!\nIt is of type '"+
2517 (*$2)[i]->getType()->getDescription() + "'.");
2520 $$ = ValID::create(ConstantArray::get(ATy, *$2));
2521 delete PTy; delete $2;
2525 // Use undef instead of an array because it's inconvenient to determine
2526 // the element type at this point, there being no elements to examine.
2527 $$ = ValID::createUndef();
2530 | 'c' STRINGCONSTANT {
2531 uint64_t NumElements = $2->length();
2532 const Type *ETy = Type::Int8Ty;
2534 ArrayType *ATy = ArrayType::get(ETy, NumElements);
2536 std::vector<Constant*> Vals;
2537 for (unsigned i = 0; i < $2->length(); ++i)
2538 Vals.push_back(ConstantInt::get(ETy, (*$2)[i]));
2540 $$ = ValID::create(ConstantArray::get(ATy, Vals));
2543 | '{' ConstVector '}' {
2544 std::vector<const Type*> Elements($2->size());
2545 for (unsigned i = 0, e = $2->size(); i != e; ++i)
2546 Elements[i] = (*$2)[i]->getType();
2548 const StructType *STy = StructType::get(Elements);
2549 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2551 $$ = ValID::create(ConstantStruct::get(STy, *$2));
2552 delete PTy; delete $2;
2556 const StructType *STy = StructType::get(std::vector<const Type*>());
2557 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2560 | '<' '{' ConstVector '}' '>' {
2561 std::vector<const Type*> Elements($3->size());
2562 for (unsigned i = 0, e = $3->size(); i != e; ++i)
2563 Elements[i] = (*$3)[i]->getType();
2565 const StructType *STy = StructType::get(Elements, /*isPacked=*/true);
2566 PATypeHolder* PTy = new PATypeHolder(HandleUpRefs(STy));
2568 $$ = ValID::create(ConstantStruct::get(STy, *$3));
2569 delete PTy; delete $3;
2573 const StructType *STy = StructType::get(std::vector<const Type*>(),
2575 $$ = ValID::create(ConstantStruct::get(STy, std::vector<Constant*>()));
2579 $$ = ValID::create($1);
2582 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2583 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2589 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2592 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2593 $$ = ValID::createLocalID($1);
2597 $$ = ValID::createGlobalID($1);
2600 | LocalName { // Is it a named reference...?
2601 $$ = ValID::createLocalName(*$1);
2605 | GlobalName { // Is it a named reference...?
2606 $$ = ValID::createGlobalName(*$1);
2611 // ValueRef - A reference to a definition... either constant or symbolic
2612 ValueRef : SymbolicValueRef | ConstValueRef;
2615 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2616 // type immediately preceeds the value reference, and allows complex constant
2617 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2618 ResolvedVal : Types ValueRef {
2619 if (!UpRefs.empty())
2620 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2621 $$ = getVal(*$1, $2);
2627 ReturnedVal : ResolvedVal {
2628 $$ = new std::vector<Value *>();
2632 | ReturnedVal ',' ResolvedVal {
2633 ($$=$1)->push_back($3);
2637 BasicBlockList : BasicBlockList BasicBlock {
2641 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2647 // Basic blocks are terminated by branching instructions:
2648 // br, br/cc, switch, ret
2650 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2651 setValueName($3, $2);
2654 $1->getInstList().push_back($3);
2659 InstructionList : InstructionList Inst {
2660 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2661 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2662 if (CI2->getParent() == 0)
2663 $1->getInstList().push_back(CI2);
2664 $1->getInstList().push_back($2);
2668 | /* empty */ { // Empty space between instruction lists
2669 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2672 | LABELSTR { // Labelled (named) basic block
2673 $$ = defineBBVal(ValID::createLocalName(*$1));
2680 RET ReturnedVal { // Return with a result...
2681 ValueList &VL = *$2;
2682 assert(!VL.empty() && "Invalid ret operands!");
2683 $$ = ReturnInst::Create(&VL[0], VL.size());
2687 | RET VOID { // Return with no result...
2688 $$ = ReturnInst::Create();
2691 | BR LABEL ValueRef { // Unconditional Branch...
2692 BasicBlock* tmpBB = getBBVal($3);
2694 $$ = BranchInst::Create(tmpBB);
2695 } // Conditional Branch...
2696 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2697 if (cast<IntegerType>($2)->getBitWidth() != 1)
2698 GEN_ERROR("Branch condition must have type i1");
2699 BasicBlock* tmpBBA = getBBVal($6);
2701 BasicBlock* tmpBBB = getBBVal($9);
2703 Value* tmpVal = getVal(Type::Int1Ty, $3);
2705 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2707 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2708 Value* tmpVal = getVal($2, $3);
2710 BasicBlock* tmpBB = getBBVal($6);
2712 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2715 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2717 for (; I != E; ++I) {
2718 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2719 S->addCase(CI, I->second);
2721 GEN_ERROR("Switch case is constant, but not a simple integer");
2726 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2727 Value* tmpVal = getVal($2, $3);
2729 BasicBlock* tmpBB = getBBVal($6);
2731 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2735 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2736 TO LABEL ValueRef UNWIND LABEL ValueRef {
2738 // Handle the short syntax
2739 const PointerType *PFTy = 0;
2740 const FunctionType *Ty = 0;
2741 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2742 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2743 // Pull out the types of all of the arguments...
2744 std::vector<const Type*> ParamTypes;
2745 ParamList::iterator I = $6->begin(), E = $6->end();
2746 for (; I != E; ++I) {
2747 const Type *Ty = I->Val->getType();
2748 if (Ty == Type::VoidTy)
2749 GEN_ERROR("Short call syntax cannot be used with varargs");
2750 ParamTypes.push_back(Ty);
2753 if (!FunctionType::isValidReturnType(*$3))
2754 GEN_ERROR("Invalid result type for LLVM function");
2756 Ty = FunctionType::get($3->get(), ParamTypes, false);
2757 PFTy = PointerType::getUnqual(Ty);
2762 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2764 BasicBlock *Normal = getBBVal($11);
2766 BasicBlock *Except = getBBVal($14);
2769 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2770 if ($8 != ParamAttr::None)
2771 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
2773 // Check the arguments
2775 if ($6->empty()) { // Has no arguments?
2776 // Make sure no arguments is a good thing!
2777 if (Ty->getNumParams() != 0)
2778 GEN_ERROR("No arguments passed to a function that "
2779 "expects arguments");
2780 } else { // Has arguments?
2781 // Loop through FunctionType's arguments and ensure they are specified
2783 FunctionType::param_iterator I = Ty->param_begin();
2784 FunctionType::param_iterator E = Ty->param_end();
2785 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2788 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2789 if (ArgI->Val->getType() != *I)
2790 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2791 (*I)->getDescription() + "'");
2792 Args.push_back(ArgI->Val);
2793 if (ArgI->Attrs != ParamAttr::None)
2794 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2797 if (Ty->isVarArg()) {
2799 for (; ArgI != ArgE; ++ArgI, ++index) {
2800 Args.push_back(ArgI->Val); // push the remaining varargs
2801 if (ArgI->Attrs != ParamAttr::None)
2802 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2804 } else if (I != E || ArgI != ArgE)
2805 GEN_ERROR("Invalid number of parameters detected");
2810 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2812 // Create the InvokeInst
2813 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2814 Args.begin(), Args.end());
2815 II->setCallingConv($2);
2816 II->setParamAttrs(PAL);
2822 $$ = new UnwindInst();
2826 $$ = new UnreachableInst();
2832 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2834 Constant *V = cast<Constant>(getExistingVal($2, $3));
2837 GEN_ERROR("May only switch on a constant pool value");
2839 BasicBlock* tmpBB = getBBVal($6);
2841 $$->push_back(std::make_pair(V, tmpBB));
2843 | IntType ConstValueRef ',' LABEL ValueRef {
2844 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2845 Constant *V = cast<Constant>(getExistingVal($1, $2));
2849 GEN_ERROR("May only switch on a constant pool value");
2851 BasicBlock* tmpBB = getBBVal($5);
2853 $$->push_back(std::make_pair(V, tmpBB));
2856 Inst : OptLocalAssign InstVal {
2857 // Is this definition named?? if so, assign the name...
2858 setValueName($2, $1);
2866 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2867 if (!UpRefs.empty())
2868 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2869 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2870 Value* tmpVal = getVal(*$1, $3);
2872 BasicBlock* tmpBB = getBBVal($5);
2874 $$->push_back(std::make_pair(tmpVal, tmpBB));
2877 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2879 Value* tmpVal = getVal($1->front().first->getType(), $4);
2881 BasicBlock* tmpBB = getBBVal($6);
2883 $1->push_back(std::make_pair(tmpVal, tmpBB));
2887 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2888 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2889 if (!UpRefs.empty())
2890 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2891 // Used for call and invoke instructions
2892 $$ = new ParamList();
2893 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
2898 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2899 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2900 // Labels are only valid in ASMs
2901 $$ = new ParamList();
2902 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
2906 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2907 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2908 if (!UpRefs.empty())
2909 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2911 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
2916 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2917 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2919 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
2923 | /*empty*/ { $$ = new ParamList(); };
2925 IndexList // Used for gep instructions and constant expressions
2926 : /*empty*/ { $$ = new std::vector<Value*>(); }
2927 | IndexList ',' ResolvedVal {
2934 ConstantIndexList // Used for insertvalue and extractvalue instructions
2936 $$ = new std::vector<unsigned>();
2937 if ((unsigned)$2 != $2)
2938 GEN_ERROR("Index " + utostr($2) + " is not valid for insertvalue or extractvalue.");
2941 | ConstantIndexList ',' EUINT64VAL {
2943 if ((unsigned)$3 != $3)
2944 GEN_ERROR("Index " + utostr($3) + " is not valid for insertvalue or extractvalue.");
2950 OptTailCall : TAIL CALL {
2959 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2960 if (!UpRefs.empty())
2961 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2962 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2963 !isa<VectorType>((*$2).get()))
2965 "Arithmetic operator requires integer, FP, or packed operands");
2966 Value* val1 = getVal(*$2, $3);
2968 Value* val2 = getVal(*$2, $5);
2970 $$ = BinaryOperator::Create($1, val1, val2);
2972 GEN_ERROR("binary operator returned null");
2975 | LogicalOps Types ValueRef ',' ValueRef {
2976 if (!UpRefs.empty())
2977 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2978 if (!(*$2)->isInteger()) {
2979 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2980 !cast<VectorType>($2->get())->getElementType()->isInteger())
2981 GEN_ERROR("Logical operator requires integral operands");
2983 Value* tmpVal1 = getVal(*$2, $3);
2985 Value* tmpVal2 = getVal(*$2, $5);
2987 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
2989 GEN_ERROR("binary operator returned null");
2992 | ICMP IPredicates Types ValueRef ',' ValueRef {
2993 if (!UpRefs.empty())
2994 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2995 if (isa<VectorType>((*$3).get()))
2996 GEN_ERROR("Vector types not supported by icmp instruction");
2997 Value* tmpVal1 = getVal(*$3, $4);
2999 Value* tmpVal2 = getVal(*$3, $6);
3001 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3003 GEN_ERROR("icmp operator returned null");
3006 | FCMP FPredicates Types ValueRef ',' ValueRef {
3007 if (!UpRefs.empty())
3008 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3009 if (isa<VectorType>((*$3).get()))
3010 GEN_ERROR("Vector types not supported by fcmp instruction");
3011 Value* tmpVal1 = getVal(*$3, $4);
3013 Value* tmpVal2 = getVal(*$3, $6);
3015 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3017 GEN_ERROR("fcmp operator returned null");
3020 | VICMP IPredicates Types ValueRef ',' ValueRef {
3021 if (!UpRefs.empty())
3022 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3023 if (!isa<VectorType>((*$3).get()))
3024 GEN_ERROR("Scalar types not supported by vicmp instruction");
3025 Value* tmpVal1 = getVal(*$3, $4);
3027 Value* tmpVal2 = getVal(*$3, $6);
3029 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3031 GEN_ERROR("icmp operator returned null");
3034 | VFCMP FPredicates Types ValueRef ',' ValueRef {
3035 if (!UpRefs.empty())
3036 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3037 if (!isa<VectorType>((*$3).get()))
3038 GEN_ERROR("Scalar types not supported by vfcmp instruction");
3039 Value* tmpVal1 = getVal(*$3, $4);
3041 Value* tmpVal2 = getVal(*$3, $6);
3043 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
3045 GEN_ERROR("fcmp operator returned null");
3048 | CastOps ResolvedVal TO Types {
3049 if (!UpRefs.empty())
3050 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3052 const Type* DestTy = $4->get();
3053 if (!CastInst::castIsValid($1, Val, DestTy))
3054 GEN_ERROR("invalid cast opcode for cast from '" +
3055 Val->getType()->getDescription() + "' to '" +
3056 DestTy->getDescription() + "'");
3057 $$ = CastInst::Create($1, Val, DestTy);
3060 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3061 if ($2->getType() != Type::Int1Ty)
3062 GEN_ERROR("select condition must be boolean");
3063 if ($4->getType() != $6->getType())
3064 GEN_ERROR("select value types should match");
3065 $$ = SelectInst::Create($2, $4, $6);
3068 | VAARG ResolvedVal ',' Types {
3069 if (!UpRefs.empty())
3070 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
3071 $$ = new VAArgInst($2, *$4);
3075 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3076 if (!ExtractElementInst::isValidOperands($2, $4))
3077 GEN_ERROR("Invalid extractelement operands");
3078 $$ = new ExtractElementInst($2, $4);
3081 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3082 if (!InsertElementInst::isValidOperands($2, $4, $6))
3083 GEN_ERROR("Invalid insertelement operands");
3084 $$ = InsertElementInst::Create($2, $4, $6);
3087 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3088 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3089 GEN_ERROR("Invalid shufflevector operands");
3090 $$ = new ShuffleVectorInst($2, $4, $6);
3094 const Type *Ty = $2->front().first->getType();
3095 if (!Ty->isFirstClassType())
3096 GEN_ERROR("PHI node operands must be of first class type");
3097 $$ = PHINode::Create(Ty);
3098 ((PHINode*)$$)->reserveOperandSpace($2->size());
3099 while ($2->begin() != $2->end()) {
3100 if ($2->front().first->getType() != Ty)
3101 GEN_ERROR("All elements of a PHI node must be of the same type");
3102 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3105 delete $2; // Free the list...
3108 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
3111 // Handle the short syntax
3112 const PointerType *PFTy = 0;
3113 const FunctionType *Ty = 0;
3114 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3115 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3116 // Pull out the types of all of the arguments...
3117 std::vector<const Type*> ParamTypes;
3118 ParamList::iterator I = $6->begin(), E = $6->end();
3119 for (; I != E; ++I) {
3120 const Type *Ty = I->Val->getType();
3121 if (Ty == Type::VoidTy)
3122 GEN_ERROR("Short call syntax cannot be used with varargs");
3123 ParamTypes.push_back(Ty);
3126 if (!FunctionType::isValidReturnType(*$3))
3127 GEN_ERROR("Invalid result type for LLVM function");
3129 Ty = FunctionType::get($3->get(), ParamTypes, false);
3130 PFTy = PointerType::getUnqual(Ty);
3133 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3136 // Check for call to invalid intrinsic to avoid crashing later.
3137 if (Function *theF = dyn_cast<Function>(V)) {
3138 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3139 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3140 !theF->getIntrinsicID(true))
3141 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3142 theF->getName() + "'");
3145 // Set up the ParamAttrs for the function
3146 SmallVector<ParamAttrsWithIndex, 8> Attrs;
3147 if ($8 != ParamAttr::None)
3148 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
3149 // Check the arguments
3151 if ($6->empty()) { // Has no arguments?
3152 // Make sure no arguments is a good thing!
3153 if (Ty->getNumParams() != 0)
3154 GEN_ERROR("No arguments passed to a function that "
3155 "expects arguments");
3156 } else { // Has arguments?
3157 // Loop through FunctionType's arguments and ensure they are specified
3158 // correctly. Also, gather any parameter attributes.
3159 FunctionType::param_iterator I = Ty->param_begin();
3160 FunctionType::param_iterator E = Ty->param_end();
3161 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
3164 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3165 if (ArgI->Val->getType() != *I)
3166 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3167 (*I)->getDescription() + "'");
3168 Args.push_back(ArgI->Val);
3169 if (ArgI->Attrs != ParamAttr::None)
3170 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3172 if (Ty->isVarArg()) {
3174 for (; ArgI != ArgE; ++ArgI, ++index) {
3175 Args.push_back(ArgI->Val); // push the remaining varargs
3176 if (ArgI->Attrs != ParamAttr::None)
3177 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3179 } else if (I != E || ArgI != ArgE)
3180 GEN_ERROR("Invalid number of parameters detected");
3183 // Finish off the ParamAttrs and check them
3186 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
3188 // Create the call node
3189 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3190 CI->setTailCall($1);
3191 CI->setCallingConv($2);
3192 CI->setParamAttrs(PAL);
3203 OptVolatile : VOLATILE {
3214 MemoryInst : MALLOC Types OptCAlign {
3215 if (!UpRefs.empty())
3216 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3217 $$ = new MallocInst(*$2, 0, $3);
3221 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3222 if (!UpRefs.empty())
3223 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3224 if ($4 != Type::Int32Ty)
3225 GEN_ERROR("Malloc array size is not a 32-bit integer!");
3226 Value* tmpVal = getVal($4, $5);
3228 $$ = new MallocInst(*$2, tmpVal, $6);
3231 | ALLOCA Types OptCAlign {
3232 if (!UpRefs.empty())
3233 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3234 $$ = new AllocaInst(*$2, 0, $3);
3238 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3239 if (!UpRefs.empty())
3240 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3241 if ($4 != Type::Int32Ty)
3242 GEN_ERROR("Alloca array size is not a 32-bit integer!");
3243 Value* tmpVal = getVal($4, $5);
3245 $$ = new AllocaInst(*$2, tmpVal, $6);
3248 | FREE ResolvedVal {
3249 if (!isa<PointerType>($2->getType()))
3250 GEN_ERROR("Trying to free nonpointer type " +
3251 $2->getType()->getDescription() + "");
3252 $$ = new FreeInst($2);
3256 | OptVolatile LOAD Types ValueRef OptCAlign {
3257 if (!UpRefs.empty())
3258 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3259 if (!isa<PointerType>($3->get()))
3260 GEN_ERROR("Can't load from nonpointer type: " +
3261 (*$3)->getDescription());
3262 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3263 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3264 (*$3)->getDescription());
3265 Value* tmpVal = getVal(*$3, $4);
3267 $$ = new LoadInst(tmpVal, "", $1, $5);
3270 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3271 if (!UpRefs.empty())
3272 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3273 const PointerType *PT = dyn_cast<PointerType>($5->get());
3275 GEN_ERROR("Can't store to a nonpointer type: " +
3276 (*$5)->getDescription());
3277 const Type *ElTy = PT->getElementType();
3278 if (ElTy != $3->getType())
3279 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3280 "' into space of type '" + ElTy->getDescription() + "'");
3282 Value* tmpVal = getVal(*$5, $6);
3284 $$ = new StoreInst($3, tmpVal, $1, $7);
3287 | GETRESULT Types ValueRef ',' EUINT64VAL {
3288 Value *TmpVal = getVal($2->get(), $3);
3289 if (!GetResultInst::isValidOperands(TmpVal, $5))
3290 GEN_ERROR("Invalid getresult operands");
3291 $$ = new GetResultInst(TmpVal, $5);
3295 | GETELEMENTPTR Types ValueRef IndexList {
3296 if (!UpRefs.empty())
3297 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3298 if (!isa<PointerType>($2->get()))
3299 GEN_ERROR("getelementptr insn requires pointer operand");
3301 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3302 GEN_ERROR("Invalid getelementptr indices for type '" +
3303 (*$2)->getDescription()+ "'");
3304 Value* tmpVal = getVal(*$2, $3);
3306 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3310 | EXTRACTVALUE Types ValueRef ConstantIndexList {
3311 if (!UpRefs.empty())
3312 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3313 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3314 GEN_ERROR("extractvalue insn requires an aggregate operand");
3316 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3317 GEN_ERROR("Invalid extractvalue indices for type '" +
3318 (*$2)->getDescription()+ "'");
3319 Value* tmpVal = getVal(*$2, $3);
3321 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3325 | INSERTVALUE Types ValueRef ',' Types ValueRef ConstantIndexList {
3326 if (!UpRefs.empty())
3327 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3328 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3329 GEN_ERROR("extractvalue insn requires an aggregate operand");
3331 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3332 GEN_ERROR("Invalid insertvalue indices for type '" +
3333 (*$2)->getDescription()+ "'");
3334 Value* aggVal = getVal(*$2, $3);
3335 Value* tmpVal = getVal(*$5, $6);
3337 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3346 // common code from the two 'RunVMAsmParser' functions
3347 static Module* RunParser(Module * M) {
3348 CurModule.CurrentModule = M;
3349 // Check to make sure the parser succeeded
3352 delete ParserResult;
3356 // Emit an error if there are any unresolved types left.
3357 if (!CurModule.LateResolveTypes.empty()) {
3358 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3359 if (DID.Type == ValID::LocalName) {
3360 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3362 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3365 delete ParserResult;
3369 // Emit an error if there are any unresolved values left.
3370 if (!CurModule.LateResolveValues.empty()) {
3371 Value *V = CurModule.LateResolveValues.back();
3372 std::map<Value*, std::pair<ValID, int> >::iterator I =
3373 CurModule.PlaceHolderInfo.find(V);
3375 if (I != CurModule.PlaceHolderInfo.end()) {
3376 ValID &DID = I->second.first;
3377 if (DID.Type == ValID::LocalName) {
3378 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3380 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3383 delete ParserResult;
3388 // Check to make sure that parsing produced a result
3392 // Reset ParserResult variable while saving its value for the result.
3393 Module *Result = ParserResult;
3399 void llvm::GenerateError(const std::string &message, int LineNo) {
3400 if (LineNo == -1) LineNo = LLLgetLineNo();
3401 // TODO: column number in exception
3403 TheParseError->setError(LLLgetFilename(), message, LineNo);
3407 int yyerror(const char *ErrorMsg) {
3408 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3409 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3410 if (yychar != YYEMPTY && yychar != 0) {
3411 errMsg += " while reading token: '";
3412 errMsg += std::string(LLLgetTokenStart(),
3413 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3415 GenerateError(errMsg);