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");
735 const PointerType *PTy = PointerType::get(Ty, AddressSpace);
739 Name = *NameStr; // Copy string
740 delete NameStr; // Free old string
743 // See if this global value was forward referenced. If so, recycle the
747 ID = ValID::createGlobalName(Name);
749 ID = ValID::createGlobalID(CurModule.Values.size());
752 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
753 // Move the global to the end of the list, from whereever it was
754 // previously inserted.
755 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
756 CurModule.CurrentModule->getGlobalList().remove(GV);
757 CurModule.CurrentModule->getGlobalList().push_back(GV);
758 GV->setInitializer(Initializer);
759 GV->setLinkage(Linkage);
760 GV->setVisibility(Visibility);
761 GV->setConstant(isConstantGlobal);
762 GV->setThreadLocal(IsThreadLocal);
763 InsertValue(GV, CurModule.Values);
767 // If this global has a name
769 // if the global we're parsing has an initializer (is a definition) and
770 // has external linkage.
771 if (Initializer && Linkage != GlobalValue::InternalLinkage)
772 // If there is already a global with external linkage with this name
773 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
774 // If we allow this GVar to get created, it will be renamed in the
775 // symbol table because it conflicts with an existing GVar. We can't
776 // allow redefinition of GVars whose linking indicates that their name
777 // must stay the same. Issue the error.
778 GenerateError("Redefinition of global variable named '" + Name +
779 "' of type '" + Ty->getDescription() + "'");
784 // Otherwise there is no existing GV to use, create one now.
786 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
787 CurModule.CurrentModule, IsThreadLocal, AddressSpace);
788 GV->setVisibility(Visibility);
789 InsertValue(GV, CurModule.Values);
793 // setTypeName - Set the specified type to the name given. The name may be
794 // null potentially, in which case this is a noop. The string passed in is
795 // assumed to be a malloc'd string buffer, and is freed by this function.
797 // This function returns true if the type has already been defined, but is
798 // allowed to be redefined in the specified context. If the name is a new name
799 // for the type plane, it is inserted and false is returned.
800 static bool setTypeName(const Type *T, std::string *NameStr) {
801 assert(!inFunctionScope() && "Can't give types function-local names!");
802 if (NameStr == 0) return false;
804 std::string Name(*NameStr); // Copy string
805 delete NameStr; // Free old string
807 // We don't allow assigning names to void type
808 if (T == Type::VoidTy) {
809 GenerateError("Can't assign name '" + Name + "' to the void type");
813 // Set the type name, checking for conflicts as we do so.
814 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
816 if (AlreadyExists) { // Inserting a name that is already defined???
817 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
818 assert(Existing && "Conflict but no matching type?!");
820 // There is only one case where this is allowed: when we are refining an
821 // opaque type. In this case, Existing will be an opaque type.
822 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
823 // We ARE replacing an opaque type!
824 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
828 // Otherwise, this is an attempt to redefine a type. That's okay if
829 // the redefinition is identical to the original. This will be so if
830 // Existing and T point to the same Type object. In this one case we
831 // allow the equivalent redefinition.
832 if (Existing == T) return true; // Yes, it's equal.
834 // Any other kind of (non-equivalent) redefinition is an error.
835 GenerateError("Redefinition of type named '" + Name + "' of type '" +
836 T->getDescription() + "'");
842 //===----------------------------------------------------------------------===//
843 // Code for handling upreferences in type names...
846 // TypeContains - Returns true if Ty directly contains E in it.
848 static bool TypeContains(const Type *Ty, const Type *E) {
849 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
850 E) != Ty->subtype_end();
855 // NestingLevel - The number of nesting levels that need to be popped before
856 // this type is resolved.
857 unsigned NestingLevel;
859 // LastContainedTy - This is the type at the current binding level for the
860 // type. Every time we reduce the nesting level, this gets updated.
861 const Type *LastContainedTy;
863 // UpRefTy - This is the actual opaque type that the upreference is
867 UpRefRecord(unsigned NL, OpaqueType *URTy)
868 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
872 // UpRefs - A list of the outstanding upreferences that need to be resolved.
873 static std::vector<UpRefRecord> UpRefs;
875 /// HandleUpRefs - Every time we finish a new layer of types, this function is
876 /// called. It loops through the UpRefs vector, which is a list of the
877 /// currently active types. For each type, if the up reference is contained in
878 /// the newly completed type, we decrement the level count. When the level
879 /// count reaches zero, the upreferenced type is the type that is passed in:
880 /// thus we can complete the cycle.
882 static PATypeHolder HandleUpRefs(const Type *ty) {
883 // If Ty isn't abstract, or if there are no up-references in it, then there is
884 // nothing to resolve here.
885 if (!ty->isAbstract() || UpRefs.empty()) return ty;
888 UR_OUT("Type '" << Ty->getDescription() <<
889 "' newly formed. Resolving upreferences.\n" <<
890 UpRefs.size() << " upreferences active!\n");
892 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
893 // to zero), we resolve them all together before we resolve them to Ty. At
894 // the end of the loop, if there is anything to resolve to Ty, it will be in
896 OpaqueType *TypeToResolve = 0;
898 for (unsigned i = 0; i != UpRefs.size(); ++i) {
899 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
900 << UpRefs[i].second->getDescription() << ") = "
901 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
902 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
903 // Decrement level of upreference
904 unsigned Level = --UpRefs[i].NestingLevel;
905 UpRefs[i].LastContainedTy = Ty;
906 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
907 if (Level == 0) { // Upreference should be resolved!
908 if (!TypeToResolve) {
909 TypeToResolve = UpRefs[i].UpRefTy;
911 UR_OUT(" * Resolving upreference for "
912 << UpRefs[i].second->getDescription() << "\n";
913 std::string OldName = UpRefs[i].UpRefTy->getDescription());
914 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
915 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
916 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
918 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
919 --i; // Do not skip the next element...
925 UR_OUT(" * Resolving upreference for "
926 << UpRefs[i].second->getDescription() << "\n";
927 std::string OldName = TypeToResolve->getDescription());
928 TypeToResolve->refineAbstractTypeTo(Ty);
934 //===----------------------------------------------------------------------===//
935 // RunVMAsmParser - Define an interface to this parser
936 //===----------------------------------------------------------------------===//
938 static Module* RunParser(Module * M);
940 Module *llvm::RunVMAsmParser(llvm::MemoryBuffer *MB) {
942 Module *M = RunParser(new Module(LLLgetFilename()));
950 llvm::Module *ModuleVal;
951 llvm::Function *FunctionVal;
952 llvm::BasicBlock *BasicBlockVal;
953 llvm::TerminatorInst *TermInstVal;
954 llvm::Instruction *InstVal;
955 llvm::Constant *ConstVal;
957 const llvm::Type *PrimType;
958 std::list<llvm::PATypeHolder> *TypeList;
959 llvm::PATypeHolder *TypeVal;
960 llvm::Value *ValueVal;
961 std::vector<llvm::Value*> *ValueList;
962 llvm::ArgListType *ArgList;
963 llvm::TypeWithAttrs TypeWithAttrs;
964 llvm::TypeWithAttrsList *TypeWithAttrsList;
965 llvm::ParamList *ParamList;
967 // Represent the RHS of PHI node
968 std::list<std::pair<llvm::Value*,
969 llvm::BasicBlock*> > *PHIList;
970 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
971 std::vector<llvm::Constant*> *ConstVector;
973 llvm::GlobalValue::LinkageTypes Linkage;
974 llvm::GlobalValue::VisibilityTypes Visibility;
975 llvm::ParameterAttributes ParamAttrs;
976 llvm::APInt *APIntVal;
981 llvm::APFloat *FPVal;
984 std::string *StrVal; // This memory must be deleted
985 llvm::ValID ValIDVal;
987 llvm::Instruction::BinaryOps BinaryOpVal;
988 llvm::Instruction::TermOps TermOpVal;
989 llvm::Instruction::MemoryOps MemOpVal;
990 llvm::Instruction::CastOps CastOpVal;
991 llvm::Instruction::OtherOps OtherOpVal;
992 llvm::ICmpInst::Predicate IPredicate;
993 llvm::FCmpInst::Predicate FPredicate;
996 %type <ModuleVal> Module
997 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
998 %type <BasicBlockVal> BasicBlock InstructionList
999 %type <TermInstVal> BBTerminatorInst
1000 %type <InstVal> Inst InstVal MemoryInst
1001 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1002 %type <ConstVector> ConstVector
1003 %type <ArgList> ArgList ArgListH
1004 %type <PHIList> PHIList
1005 %type <ParamList> ParamList // For call param lists & GEP indices
1006 %type <ValueList> IndexList // For GEP indices
1007 %type <TypeList> TypeListI
1008 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1009 %type <TypeWithAttrs> ArgType
1010 %type <JumpTable> JumpTable
1011 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1012 %type <BoolVal> ThreadLocal // 'thread_local' or not
1013 %type <BoolVal> OptVolatile // 'volatile' or not
1014 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1015 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1016 %type <Linkage> GVInternalLinkage GVExternalLinkage
1017 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1018 %type <Linkage> AliasLinkage
1019 %type <Visibility> GVVisibilityStyle
1021 // ValueRef - Unresolved reference to a definition or BB
1022 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1023 %type <ValueVal> ResolvedVal // <type> <valref> pair
1024 %type <ValueList> ReturnedVal
1025 // Tokens and types for handling constant integer values
1027 // ESINT64VAL - A negative number within long long range
1028 %token <SInt64Val> ESINT64VAL
1030 // EUINT64VAL - A positive number within uns. long long range
1031 %token <UInt64Val> EUINT64VAL
1033 // ESAPINTVAL - A negative number with arbitrary precision
1034 %token <APIntVal> ESAPINTVAL
1036 // EUAPINTVAL - A positive number with arbitrary precision
1037 %token <APIntVal> EUAPINTVAL
1039 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1040 %token <FPVal> FPVAL // Float or Double constant
1042 // Built in types...
1043 %type <TypeVal> Types ResultTypes
1044 %type <PrimType> IntType FPType PrimType // Classifications
1045 %token <PrimType> VOID INTTYPE
1046 %token <PrimType> FLOAT DOUBLE X86_FP80 FP128 PPC_FP128 LABEL
1050 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR
1051 %token<StrVal> STRINGCONSTANT ATSTRINGCONSTANT PCTSTRINGCONSTANT
1052 %type <StrVal> LocalName OptLocalName OptLocalAssign
1053 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1054 %type <StrVal> OptSection SectionString OptGC
1056 %type <UIntVal> OptAlign OptCAlign OptAddrSpace
1058 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1059 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1060 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1061 %token DLLIMPORT DLLEXPORT EXTERN_WEAK COMMON
1062 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN ADDRSPACE
1063 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1064 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1066 %type <UIntVal> OptCallingConv
1067 %type <ParamAttrs> OptParamAttrs ParamAttr
1068 %type <ParamAttrs> OptFuncAttrs FuncAttr
1070 // Basic Block Terminating Operators
1071 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1074 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1075 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1076 %token <BinaryOpVal> SHL LSHR ASHR
1078 %token <OtherOpVal> ICMP FCMP VICMP VFCMP
1079 %type <IPredicate> IPredicates
1080 %type <FPredicate> FPredicates
1081 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1082 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1084 // Memory Instructions
1085 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1088 %type <CastOpVal> CastOps
1089 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1090 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1093 %token <OtherOpVal> PHI_TOK SELECT VAARG
1094 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1095 %token <OtherOpVal> GETRESULT
1096 %token <OtherOpVal> EXTRACTVALUE INSERTVALUE
1098 // Function Attributes
1099 %token SIGNEXT ZEROEXT NORETURN INREG SRET NOUNWIND NOALIAS BYVAL NEST
1100 %token READNONE READONLY GC
1102 // Visibility Styles
1103 %token DEFAULT HIDDEN PROTECTED
1109 // Operations that are notably excluded from this list include:
1110 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1112 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1113 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1114 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1115 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1118 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1119 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1120 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1121 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1122 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1126 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1127 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1128 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1129 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1130 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1131 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1132 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1133 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1134 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1137 // These are some types that allow classification if we only want a particular
1138 // thing... for example, only a signed, unsigned, or integral type.
1140 FPType : FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80;
1142 LocalName : LOCALVAR | STRINGCONSTANT | PCTSTRINGCONSTANT ;
1143 OptLocalName : LocalName | /*empty*/ { $$ = 0; };
1145 OptAddrSpace : ADDRSPACE '(' EUINT64VAL ')' { $$=$3; }
1146 | /*empty*/ { $$=0; };
1148 /// OptLocalAssign - Value producing statements have an optional assignment
1150 OptLocalAssign : LocalName '=' {
1159 GlobalName : GLOBALVAR | ATSTRINGCONSTANT ;
1161 OptGlobalAssign : GlobalAssign
1167 GlobalAssign : GlobalName '=' {
1173 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1174 | WEAK { $$ = GlobalValue::WeakLinkage; }
1175 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1176 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1177 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1178 | COMMON { $$ = GlobalValue::CommonLinkage; }
1182 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1183 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1184 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1188 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1189 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1190 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1191 | PROTECTED { $$ = GlobalValue::ProtectedVisibility; }
1194 FunctionDeclareLinkage
1195 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1196 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1197 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1200 FunctionDefineLinkage
1201 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1202 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1203 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1204 | WEAK { $$ = GlobalValue::WeakLinkage; }
1205 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1209 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1210 | WEAK { $$ = GlobalValue::WeakLinkage; }
1211 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1214 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1215 CCC_TOK { $$ = CallingConv::C; } |
1216 FASTCC_TOK { $$ = CallingConv::Fast; } |
1217 COLDCC_TOK { $$ = CallingConv::Cold; } |
1218 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1219 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1221 if ((unsigned)$2 != $2)
1222 GEN_ERROR("Calling conv too large");
1227 ParamAttr : ZEROEXT { $$ = ParamAttr::ZExt; }
1228 | ZEXT { $$ = ParamAttr::ZExt; }
1229 | SIGNEXT { $$ = ParamAttr::SExt; }
1230 | SEXT { $$ = ParamAttr::SExt; }
1231 | INREG { $$ = ParamAttr::InReg; }
1232 | SRET { $$ = ParamAttr::StructRet; }
1233 | NOALIAS { $$ = ParamAttr::NoAlias; }
1234 | BYVAL { $$ = ParamAttr::ByVal; }
1235 | NEST { $$ = ParamAttr::Nest; }
1236 | ALIGN EUINT64VAL { $$ =
1237 ParamAttr::constructAlignmentFromInt($2); }
1240 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1241 | OptParamAttrs ParamAttr {
1246 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1247 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1248 | ZEROEXT { $$ = ParamAttr::ZExt; }
1249 | SIGNEXT { $$ = ParamAttr::SExt; }
1250 | READNONE { $$ = ParamAttr::ReadNone; }
1251 | READONLY { $$ = ParamAttr::ReadOnly; }
1254 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1255 | OptFuncAttrs FuncAttr {
1260 OptGC : /* empty */ { $$ = 0; }
1261 | GC STRINGCONSTANT {
1266 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1267 // a comma before it.
1268 OptAlign : /*empty*/ { $$ = 0; } |
1271 if ($$ != 0 && !isPowerOf2_32($$))
1272 GEN_ERROR("Alignment must be a power of two");
1275 OptCAlign : /*empty*/ { $$ = 0; } |
1276 ',' ALIGN EUINT64VAL {
1278 if ($$ != 0 && !isPowerOf2_32($$))
1279 GEN_ERROR("Alignment must be a power of two");
1285 SectionString : SECTION STRINGCONSTANT {
1286 for (unsigned i = 0, e = $2->length(); i != e; ++i)
1287 if ((*$2)[i] == '"' || (*$2)[i] == '\\')
1288 GEN_ERROR("Invalid character in section name");
1293 OptSection : /*empty*/ { $$ = 0; } |
1294 SectionString { $$ = $1; };
1296 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1297 // is set to be the global we are processing.
1299 GlobalVarAttributes : /* empty */ {} |
1300 ',' GlobalVarAttribute GlobalVarAttributes {};
1301 GlobalVarAttribute : SectionString {
1302 CurGV->setSection(*$1);
1306 | ALIGN EUINT64VAL {
1307 if ($2 != 0 && !isPowerOf2_32($2))
1308 GEN_ERROR("Alignment must be a power of two");
1309 CurGV->setAlignment($2);
1313 //===----------------------------------------------------------------------===//
1314 // Types includes all predefined types... except void, because it can only be
1315 // used in specific contexts (function returning void for example).
1317 // Derived types are added later...
1319 PrimType : INTTYPE | FLOAT | DOUBLE | PPC_FP128 | FP128 | X86_FP80 | LABEL ;
1323 $$ = new PATypeHolder(OpaqueType::get());
1327 $$ = new PATypeHolder($1);
1330 | Types OptAddrSpace '*' { // Pointer type?
1331 if (*$1 == Type::LabelTy)
1332 GEN_ERROR("Cannot form a pointer to a basic block");
1333 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1, $2)));
1337 | SymbolicValueRef { // Named types are also simple types...
1338 const Type* tmp = getTypeVal($1);
1340 $$ = new PATypeHolder(tmp);
1342 | '\\' EUINT64VAL { // Type UpReference
1343 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1344 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1345 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1346 $$ = new PATypeHolder(OT);
1347 UR_OUT("New Upreference!\n");
1350 | Types '(' ArgTypeListI ')' OptFuncAttrs {
1351 // Allow but ignore attributes on function types; this permits auto-upgrade.
1352 // FIXME: remove in LLVM 3.0.
1353 const Type *RetTy = *$1;
1354 if (!FunctionType::isValidReturnType(RetTy))
1355 GEN_ERROR("Invalid result type for LLVM function");
1357 std::vector<const Type*> Params;
1358 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1359 for (; I != E; ++I ) {
1360 const Type *Ty = I->Ty->get();
1361 Params.push_back(Ty);
1364 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1365 if (isVarArg) Params.pop_back();
1367 for (unsigned i = 0; i != Params.size(); ++i)
1368 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1369 GEN_ERROR("Function arguments must be value types!");
1373 FunctionType *FT = FunctionType::get(RetTy, Params, isVarArg);
1374 delete $3; // Delete the argument list
1375 delete $1; // Delete the return type handle
1376 $$ = new PATypeHolder(HandleUpRefs(FT));
1379 | VOID '(' ArgTypeListI ')' OptFuncAttrs {
1380 // Allow but ignore attributes on function types; this permits auto-upgrade.
1381 // FIXME: remove in LLVM 3.0.
1382 std::vector<const Type*> Params;
1383 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1384 for ( ; I != E; ++I ) {
1385 const Type* Ty = I->Ty->get();
1386 Params.push_back(Ty);
1389 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1390 if (isVarArg) Params.pop_back();
1392 for (unsigned i = 0; i != Params.size(); ++i)
1393 if (!(Params[i]->isFirstClassType() || isa<OpaqueType>(Params[i])))
1394 GEN_ERROR("Function arguments must be value types!");
1398 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1399 delete $3; // Delete the argument list
1400 $$ = new PATypeHolder(HandleUpRefs(FT));
1404 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1405 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1409 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1410 const llvm::Type* ElemTy = $4->get();
1411 if ((unsigned)$2 != $2)
1412 GEN_ERROR("Unsigned result not equal to signed result");
1413 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1414 GEN_ERROR("Element type of a VectorType must be primitive");
1415 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1419 | '{' TypeListI '}' { // Structure type?
1420 std::vector<const Type*> Elements;
1421 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1422 E = $2->end(); I != E; ++I)
1423 Elements.push_back(*I);
1425 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1429 | '{' '}' { // Empty structure type?
1430 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1433 | '<' '{' TypeListI '}' '>' {
1434 std::vector<const Type*> Elements;
1435 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1436 E = $3->end(); I != E; ++I)
1437 Elements.push_back(*I);
1439 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1443 | '<' '{' '}' '>' { // Empty structure type?
1444 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1450 : Types OptParamAttrs {
1451 // Allow but ignore attributes on function types; this permits auto-upgrade.
1452 // FIXME: remove in LLVM 3.0.
1454 $$.Attrs = ParamAttr::None;
1460 if (!UpRefs.empty())
1461 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1462 if (!(*$1)->isFirstClassType() && !isa<StructType>($1->get()))
1463 GEN_ERROR("LLVM functions cannot return aggregate types");
1467 $$ = new PATypeHolder(Type::VoidTy);
1471 ArgTypeList : ArgType {
1472 $$ = new TypeWithAttrsList();
1476 | ArgTypeList ',' ArgType {
1477 ($$=$1)->push_back($3);
1484 | ArgTypeList ',' DOTDOTDOT {
1486 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1487 TWA.Ty = new PATypeHolder(Type::VoidTy);
1492 $$ = new TypeWithAttrsList;
1493 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1494 TWA.Ty = new PATypeHolder(Type::VoidTy);
1499 $$ = new TypeWithAttrsList();
1503 // TypeList - Used for struct declarations and as a basis for function type
1504 // declaration type lists
1507 $$ = new std::list<PATypeHolder>();
1512 | TypeListI ',' Types {
1513 ($$=$1)->push_back(*$3);
1518 // ConstVal - The various declarations that go into the constant pool. This
1519 // production is used ONLY to represent constants that show up AFTER a 'const',
1520 // 'constant' or 'global' token at global scope. Constants that can be inlined
1521 // into other expressions (such as integers and constexprs) are handled by the
1522 // ResolvedVal, ValueRef and ConstValueRef productions.
1524 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1525 if (!UpRefs.empty())
1526 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1527 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1529 GEN_ERROR("Cannot make array constant with type: '" +
1530 (*$1)->getDescription() + "'");
1531 const Type *ETy = ATy->getElementType();
1532 int NumElements = ATy->getNumElements();
1534 // Verify that we have the correct size...
1535 if (NumElements != -1 && NumElements != (int)$3->size())
1536 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1537 utostr($3->size()) + " arguments, but has size of " +
1538 itostr(NumElements) + "");
1540 // Verify all elements are correct type!
1541 for (unsigned i = 0; i < $3->size(); i++) {
1542 if (ETy != (*$3)[i]->getType())
1543 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1544 ETy->getDescription() +"' as required!\nIt is of type '"+
1545 (*$3)[i]->getType()->getDescription() + "'.");
1548 $$ = ConstantArray::get(ATy, *$3);
1549 delete $1; delete $3;
1553 if (!UpRefs.empty())
1554 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1555 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1557 GEN_ERROR("Cannot make array constant with type: '" +
1558 (*$1)->getDescription() + "'");
1560 int NumElements = ATy->getNumElements();
1561 if (NumElements != -1 && NumElements != 0)
1562 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1563 " arguments, but has size of " + itostr(NumElements) +"");
1564 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1568 | Types 'c' STRINGCONSTANT {
1569 if (!UpRefs.empty())
1570 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1571 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1573 GEN_ERROR("Cannot make array constant with type: '" +
1574 (*$1)->getDescription() + "'");
1576 int NumElements = ATy->getNumElements();
1577 const Type *ETy = ATy->getElementType();
1578 if (NumElements != -1 && NumElements != int($3->length()))
1579 GEN_ERROR("Can't build string constant of size " +
1580 itostr((int)($3->length())) +
1581 " when array has size " + itostr(NumElements) + "");
1582 std::vector<Constant*> Vals;
1583 if (ETy == Type::Int8Ty) {
1584 for (unsigned i = 0; i < $3->length(); ++i)
1585 Vals.push_back(ConstantInt::get(ETy, (*$3)[i]));
1588 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1591 $$ = ConstantArray::get(ATy, Vals);
1595 | Types '<' ConstVector '>' { // Nonempty unsized arr
1596 if (!UpRefs.empty())
1597 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1598 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1600 GEN_ERROR("Cannot make packed constant with type: '" +
1601 (*$1)->getDescription() + "'");
1602 const Type *ETy = PTy->getElementType();
1603 int NumElements = PTy->getNumElements();
1605 // Verify that we have the correct size...
1606 if (NumElements != -1 && NumElements != (int)$3->size())
1607 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1608 utostr($3->size()) + " arguments, but has size of " +
1609 itostr(NumElements) + "");
1611 // Verify all elements are correct type!
1612 for (unsigned i = 0; i < $3->size(); i++) {
1613 if (ETy != (*$3)[i]->getType())
1614 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1615 ETy->getDescription() +"' as required!\nIt is of type '"+
1616 (*$3)[i]->getType()->getDescription() + "'.");
1619 $$ = ConstantVector::get(PTy, *$3);
1620 delete $1; delete $3;
1623 | Types '{' ConstVector '}' {
1624 const StructType *STy = dyn_cast<StructType>($1->get());
1626 GEN_ERROR("Cannot make struct constant with type: '" +
1627 (*$1)->getDescription() + "'");
1629 if ($3->size() != STy->getNumContainedTypes())
1630 GEN_ERROR("Illegal number of initializers for structure type");
1632 // Check to ensure that constants are compatible with the type initializer!
1633 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1634 if ((*$3)[i]->getType() != STy->getElementType(i))
1635 GEN_ERROR("Expected type '" +
1636 STy->getElementType(i)->getDescription() +
1637 "' for element #" + utostr(i) +
1638 " of structure initializer");
1640 // Check to ensure that Type is not packed
1641 if (STy->isPacked())
1642 GEN_ERROR("Unpacked Initializer to vector type '" +
1643 STy->getDescription() + "'");
1645 $$ = ConstantStruct::get(STy, *$3);
1646 delete $1; delete $3;
1650 if (!UpRefs.empty())
1651 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1652 const StructType *STy = dyn_cast<StructType>($1->get());
1654 GEN_ERROR("Cannot make struct constant with type: '" +
1655 (*$1)->getDescription() + "'");
1657 if (STy->getNumContainedTypes() != 0)
1658 GEN_ERROR("Illegal number of initializers for structure type");
1660 // Check to ensure that Type is not packed
1661 if (STy->isPacked())
1662 GEN_ERROR("Unpacked Initializer to vector type '" +
1663 STy->getDescription() + "'");
1665 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1669 | Types '<' '{' ConstVector '}' '>' {
1670 const StructType *STy = dyn_cast<StructType>($1->get());
1672 GEN_ERROR("Cannot make struct constant with type: '" +
1673 (*$1)->getDescription() + "'");
1675 if ($4->size() != STy->getNumContainedTypes())
1676 GEN_ERROR("Illegal number of initializers for structure type");
1678 // Check to ensure that constants are compatible with the type initializer!
1679 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1680 if ((*$4)[i]->getType() != STy->getElementType(i))
1681 GEN_ERROR("Expected type '" +
1682 STy->getElementType(i)->getDescription() +
1683 "' for element #" + utostr(i) +
1684 " of structure initializer");
1686 // Check to ensure that Type is packed
1687 if (!STy->isPacked())
1688 GEN_ERROR("Vector initializer to non-vector type '" +
1689 STy->getDescription() + "'");
1691 $$ = ConstantStruct::get(STy, *$4);
1692 delete $1; delete $4;
1695 | Types '<' '{' '}' '>' {
1696 if (!UpRefs.empty())
1697 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1698 const StructType *STy = dyn_cast<StructType>($1->get());
1700 GEN_ERROR("Cannot make struct constant with type: '" +
1701 (*$1)->getDescription() + "'");
1703 if (STy->getNumContainedTypes() != 0)
1704 GEN_ERROR("Illegal number of initializers for structure type");
1706 // Check to ensure that Type is packed
1707 if (!STy->isPacked())
1708 GEN_ERROR("Vector initializer to non-vector type '" +
1709 STy->getDescription() + "'");
1711 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1716 if (!UpRefs.empty())
1717 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1718 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1720 GEN_ERROR("Cannot make null pointer constant with type: '" +
1721 (*$1)->getDescription() + "'");
1723 $$ = ConstantPointerNull::get(PTy);
1728 if (!UpRefs.empty())
1729 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1730 $$ = UndefValue::get($1->get());
1734 | Types SymbolicValueRef {
1735 if (!UpRefs.empty())
1736 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1737 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1739 GEN_ERROR("Global const reference must be a pointer type " + (*$1)->getDescription());
1741 // ConstExprs can exist in the body of a function, thus creating
1742 // GlobalValues whenever they refer to a variable. Because we are in
1743 // the context of a function, getExistingVal will search the functions
1744 // symbol table instead of the module symbol table for the global symbol,
1745 // which throws things all off. To get around this, we just tell
1746 // getExistingVal that we are at global scope here.
1748 Function *SavedCurFn = CurFun.CurrentFunction;
1749 CurFun.CurrentFunction = 0;
1751 Value *V = getExistingVal(Ty, $2);
1754 CurFun.CurrentFunction = SavedCurFn;
1756 // If this is an initializer for a constant pointer, which is referencing a
1757 // (currently) undefined variable, create a stub now that shall be replaced
1758 // in the future with the right type of variable.
1761 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1762 const PointerType *PT = cast<PointerType>(Ty);
1764 // First check to see if the forward references value is already created!
1765 PerModuleInfo::GlobalRefsType::iterator I =
1766 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1768 if (I != CurModule.GlobalRefs.end()) {
1769 V = I->second; // Placeholder already exists, use it...
1773 if ($2.Type == ValID::GlobalName)
1774 Name = $2.getName();
1775 else if ($2.Type != ValID::GlobalID)
1776 GEN_ERROR("Invalid reference to global");
1778 // Create the forward referenced global.
1780 if (const FunctionType *FTy =
1781 dyn_cast<FunctionType>(PT->getElementType())) {
1782 GV = Function::Create(FTy, GlobalValue::ExternalWeakLinkage, Name,
1783 CurModule.CurrentModule);
1785 GV = new GlobalVariable(PT->getElementType(), false,
1786 GlobalValue::ExternalWeakLinkage, 0,
1787 Name, CurModule.CurrentModule);
1790 // Keep track of the fact that we have a forward ref to recycle it
1791 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1796 $$ = cast<GlobalValue>(V);
1797 delete $1; // Free the type handle
1801 if (!UpRefs.empty())
1802 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1803 if ($1->get() != $2->getType())
1804 GEN_ERROR("Mismatched types for constant expression: " +
1805 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1810 | Types ZEROINITIALIZER {
1811 if (!UpRefs.empty())
1812 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1813 const Type *Ty = $1->get();
1814 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1815 GEN_ERROR("Cannot create a null initialized value of this type");
1816 $$ = Constant::getNullValue(Ty);
1820 | IntType ESINT64VAL { // integral constants
1821 if (!ConstantInt::isValueValidForType($1, $2))
1822 GEN_ERROR("Constant value doesn't fit in type");
1823 $$ = ConstantInt::get($1, $2, true);
1826 | IntType ESAPINTVAL { // arbitrary precision integer constants
1827 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1828 if ($2->getBitWidth() > BitWidth) {
1829 GEN_ERROR("Constant value does not fit in type");
1831 $2->sextOrTrunc(BitWidth);
1832 $$ = ConstantInt::get(*$2);
1836 | IntType EUINT64VAL { // integral constants
1837 if (!ConstantInt::isValueValidForType($1, $2))
1838 GEN_ERROR("Constant value doesn't fit in type");
1839 $$ = ConstantInt::get($1, $2, false);
1842 | IntType EUAPINTVAL { // arbitrary precision integer constants
1843 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1844 if ($2->getBitWidth() > BitWidth) {
1845 GEN_ERROR("Constant value does not fit in type");
1847 $2->zextOrTrunc(BitWidth);
1848 $$ = ConstantInt::get(*$2);
1852 | INTTYPE TRUETOK { // Boolean constants
1853 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1854 $$ = ConstantInt::getTrue();
1857 | INTTYPE FALSETOK { // Boolean constants
1858 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1859 $$ = ConstantInt::getFalse();
1862 | FPType FPVAL { // Floating point constants
1863 if (!ConstantFP::isValueValidForType($1, *$2))
1864 GEN_ERROR("Floating point constant invalid for type");
1865 // Lexer has no type info, so builds all float and double FP constants
1866 // as double. Fix this here. Long double is done right.
1867 if (&$2->getSemantics()==&APFloat::IEEEdouble && $1==Type::FloatTy)
1868 $2->convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven);
1869 $$ = ConstantFP::get(*$2);
1875 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1876 if (!UpRefs.empty())
1877 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1879 const Type *DestTy = $5->get();
1880 if (!CastInst::castIsValid($1, $3, DestTy))
1881 GEN_ERROR("invalid cast opcode for cast from '" +
1882 Val->getType()->getDescription() + "' to '" +
1883 DestTy->getDescription() + "'");
1884 $$ = ConstantExpr::getCast($1, $3, DestTy);
1887 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1888 if (!isa<PointerType>($3->getType()))
1889 GEN_ERROR("GetElementPtr requires a pointer operand");
1892 GetElementPtrInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1894 GEN_ERROR("Index list invalid for constant getelementptr");
1896 SmallVector<Constant*, 8> IdxVec;
1897 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1898 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1899 IdxVec.push_back(C);
1901 GEN_ERROR("Indices to constant getelementptr must be constants");
1905 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1908 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1909 if ($3->getType() != Type::Int1Ty)
1910 GEN_ERROR("Select condition must be of boolean type");
1911 if ($5->getType() != $7->getType())
1912 GEN_ERROR("Select operand types must match");
1913 $$ = ConstantExpr::getSelect($3, $5, $7);
1916 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1917 if ($3->getType() != $5->getType())
1918 GEN_ERROR("Binary operator types must match");
1920 $$ = ConstantExpr::get($1, $3, $5);
1922 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1923 if ($3->getType() != $5->getType())
1924 GEN_ERROR("Logical operator types must match");
1925 if (!$3->getType()->isInteger()) {
1926 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1927 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1928 GEN_ERROR("Logical operator requires integral operands");
1930 $$ = ConstantExpr::get($1, $3, $5);
1933 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1934 if ($4->getType() != $6->getType())
1935 GEN_ERROR("icmp operand types must match");
1936 $$ = ConstantExpr::getICmp($2, $4, $6);
1938 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1939 if ($4->getType() != $6->getType())
1940 GEN_ERROR("fcmp operand types must match");
1941 $$ = ConstantExpr::getFCmp($2, $4, $6);
1943 | VICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1944 if ($4->getType() != $6->getType())
1945 GEN_ERROR("vicmp operand types must match");
1946 $$ = ConstantExpr::getVICmp($2, $4, $6);
1948 | VFCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1949 if ($4->getType() != $6->getType())
1950 GEN_ERROR("vfcmp operand types must match");
1951 $$ = ConstantExpr::getVFCmp($2, $4, $6);
1953 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1954 if (!ExtractElementInst::isValidOperands($3, $5))
1955 GEN_ERROR("Invalid extractelement operands");
1956 $$ = ConstantExpr::getExtractElement($3, $5);
1959 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1960 if (!InsertElementInst::isValidOperands($3, $5, $7))
1961 GEN_ERROR("Invalid insertelement operands");
1962 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1965 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1966 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1967 GEN_ERROR("Invalid shufflevector operands");
1968 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1971 | EXTRACTVALUE '(' ConstVal IndexList ')' {
1972 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
1973 GEN_ERROR("ExtractValue requires an aggregate operand");
1976 ExtractValueInst::getIndexedType($3->getType(), $4->begin(), $4->end());
1978 GEN_ERROR("Index list invalid for constant extractvalue");
1980 SmallVector<Constant*, 8> IdxVec;
1981 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1982 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1983 IdxVec.push_back(C);
1985 GEN_ERROR("Indices to constant extractvalue must be constants");
1989 $$ = ConstantExpr::getExtractValue($3, &IdxVec[0], IdxVec.size());
1992 | INSERTVALUE '(' ConstVal ',' ConstVal IndexList ')' {
1993 if (!isa<StructType>($3->getType()) && !isa<ArrayType>($3->getType()))
1994 GEN_ERROR("InsertValue requires an aggregate operand");
1997 ExtractValueInst::getIndexedType($3->getType(), $6->begin(), $6->end());
1998 if (IdxTy != $5->getType())
1999 GEN_ERROR("Index list invalid for constant insertvalue");
2001 SmallVector<Constant*, 8> IdxVec;
2002 for (unsigned i = 0, e = $6->size(); i != e; ++i)
2003 if (Constant *C = dyn_cast<Constant>((*$6)[i]))
2004 IdxVec.push_back(C);
2006 GEN_ERROR("Indices to constant insertvalue must be constants");
2010 $$ = ConstantExpr::getInsertValue($3, $5, &IdxVec[0], IdxVec.size());
2015 // ConstVector - A list of comma separated constants.
2016 ConstVector : ConstVector ',' ConstVal {
2017 ($$ = $1)->push_back($3);
2021 $$ = new std::vector<Constant*>();
2027 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2028 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
2031 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
2033 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
2034 AliaseeRef : ResultTypes SymbolicValueRef {
2035 const Type* VTy = $1->get();
2036 Value *V = getVal(VTy, $2);
2038 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
2040 GEN_ERROR("Aliases can be created only to global values");
2046 | BITCAST '(' AliaseeRef TO Types ')' {
2048 const Type *DestTy = $5->get();
2049 if (!CastInst::castIsValid($1, $3, DestTy))
2050 GEN_ERROR("invalid cast opcode for cast from '" +
2051 Val->getType()->getDescription() + "' to '" +
2052 DestTy->getDescription() + "'");
2054 $$ = ConstantExpr::getCast($1, $3, DestTy);
2059 //===----------------------------------------------------------------------===//
2060 // Rules to match Modules
2061 //===----------------------------------------------------------------------===//
2063 // Module rule: Capture the result of parsing the whole file into a result
2068 $$ = ParserResult = CurModule.CurrentModule;
2069 CurModule.ModuleDone();
2073 $$ = ParserResult = CurModule.CurrentModule;
2074 CurModule.ModuleDone();
2081 | DefinitionList Definition
2085 : DEFINE { CurFun.isDeclare = false; } Function {
2086 CurFun.FunctionDone();
2089 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
2092 | MODULE ASM_TOK AsmBlock {
2095 | OptLocalAssign TYPE Types {
2096 if (!UpRefs.empty())
2097 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2098 // Eagerly resolve types. This is not an optimization, this is a
2099 // requirement that is due to the fact that we could have this:
2101 // %list = type { %list * }
2102 // %list = type { %list * } ; repeated type decl
2104 // If types are not resolved eagerly, then the two types will not be
2105 // determined to be the same type!
2107 ResolveTypeTo($1, *$3);
2109 if (!setTypeName(*$3, $1) && !$1) {
2111 // If this is a named type that is not a redefinition, add it to the slot
2113 CurModule.Types.push_back(*$3);
2119 | OptLocalAssign TYPE VOID {
2120 ResolveTypeTo($1, $3);
2122 if (!setTypeName($3, $1) && !$1) {
2124 // If this is a named type that is not a redefinition, add it to the slot
2126 CurModule.Types.push_back($3);
2130 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal
2132 /* "Externally Visible" Linkage */
2134 GEN_ERROR("Global value initializer is not a constant");
2135 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2136 $2, $4, $5->getType(), $5, $3, $6);
2138 } GlobalVarAttributes {
2141 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2142 ConstVal OptAddrSpace {
2144 GEN_ERROR("Global value initializer is not a constant");
2145 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4, $7);
2147 } GlobalVarAttributes {
2150 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2151 Types OptAddrSpace {
2152 if (!UpRefs.empty())
2153 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2154 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4, $7);
2157 } GlobalVarAttributes {
2161 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2168 GEN_ERROR("Alias name cannot be empty");
2170 Constant* Aliasee = $5;
2172 GEN_ERROR(std::string("Invalid aliasee for alias: ") + Name);
2174 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2175 CurModule.CurrentModule);
2176 GA->setVisibility($2);
2177 InsertValue(GA, CurModule.Values);
2180 // If there was a forward reference of this alias, resolve it now.
2184 ID = ValID::createGlobalName(Name);
2186 ID = ValID::createGlobalID(CurModule.Values.size()-1);
2188 if (GlobalValue *FWGV =
2189 CurModule.GetForwardRefForGlobal(GA->getType(), ID)) {
2190 // Replace uses of the fwdref with the actual alias.
2191 FWGV->replaceAllUsesWith(GA);
2192 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(FWGV))
2193 GV->eraseFromParent();
2195 cast<Function>(FWGV)->eraseFromParent();
2201 | TARGET TargetDefinition {
2204 | DEPLIBS '=' LibrariesDefinition {
2210 AsmBlock : STRINGCONSTANT {
2211 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2212 if (AsmSoFar.empty())
2213 CurModule.CurrentModule->setModuleInlineAsm(*$1);
2215 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+*$1);
2220 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2221 CurModule.CurrentModule->setTargetTriple(*$3);
2224 | DATALAYOUT '=' STRINGCONSTANT {
2225 CurModule.CurrentModule->setDataLayout(*$3);
2229 LibrariesDefinition : '[' LibList ']';
2231 LibList : LibList ',' STRINGCONSTANT {
2232 CurModule.CurrentModule->addLibrary(*$3);
2237 CurModule.CurrentModule->addLibrary(*$1);
2241 | /* empty: end of list */ {
2246 //===----------------------------------------------------------------------===//
2247 // Rules to match Function Headers
2248 //===----------------------------------------------------------------------===//
2250 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2251 if (!UpRefs.empty())
2252 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2253 if (*$3 == Type::VoidTy)
2254 GEN_ERROR("void typed arguments are invalid");
2255 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2260 | Types OptParamAttrs OptLocalName {
2261 if (!UpRefs.empty())
2262 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2263 if (*$1 == Type::VoidTy)
2264 GEN_ERROR("void typed arguments are invalid");
2265 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2266 $$ = new ArgListType;
2271 ArgList : ArgListH {
2275 | ArgListH ',' DOTDOTDOT {
2277 struct ArgListEntry E;
2278 E.Ty = new PATypeHolder(Type::VoidTy);
2280 E.Attrs = ParamAttr::None;
2285 $$ = new ArgListType;
2286 struct ArgListEntry E;
2287 E.Ty = new PATypeHolder(Type::VoidTy);
2289 E.Attrs = ParamAttr::None;
2298 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2299 OptFuncAttrs OptSection OptAlign OptGC {
2300 std::string FunctionName(*$3);
2301 delete $3; // Free strdup'd memory!
2303 // Check the function result for abstractness if this is a define. We should
2304 // have no abstract types at this point
2305 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2306 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2308 if (!FunctionType::isValidReturnType(*$2))
2309 GEN_ERROR("Invalid result type for LLVM function");
2311 std::vector<const Type*> ParamTypeList;
2312 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2313 if ($7 != ParamAttr::None)
2314 Attrs.push_back(ParamAttrsWithIndex::get(0, $7));
2315 if ($5) { // If there are arguments...
2317 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2318 const Type* Ty = I->Ty->get();
2319 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2320 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2321 ParamTypeList.push_back(Ty);
2322 if (Ty != Type::VoidTy && I->Attrs != ParamAttr::None)
2323 Attrs.push_back(ParamAttrsWithIndex::get(index, I->Attrs));
2327 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2328 if (isVarArg) ParamTypeList.pop_back();
2332 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2334 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2335 const PointerType *PFT = PointerType::getUnqual(FT);
2339 if (!FunctionName.empty()) {
2340 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2342 ID = ValID::createGlobalID(CurModule.Values.size());
2346 // See if this function was forward referenced. If so, recycle the object.
2347 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2348 // Move the function to the end of the list, from whereever it was
2349 // previously inserted.
2350 Fn = cast<Function>(FWRef);
2351 assert(Fn->getParamAttrs().isEmpty() &&
2352 "Forward reference has parameter attributes!");
2353 CurModule.CurrentModule->getFunctionList().remove(Fn);
2354 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2355 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2356 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2357 if (Fn->getFunctionType() != FT ) {
2358 // The existing function doesn't have the same type. This is an overload
2360 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2361 } else if (Fn->getParamAttrs() != PAL) {
2362 // The existing function doesn't have the same parameter attributes.
2363 // This is an overload error.
2364 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2365 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2366 // Neither the existing or the current function is a declaration and they
2367 // have the same name and same type. Clearly this is a redefinition.
2368 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2369 } else if (Fn->isDeclaration()) {
2370 // Make sure to strip off any argument names so we can't get conflicts.
2371 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2375 } else { // Not already defined?
2376 Fn = Function::Create(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2377 CurModule.CurrentModule);
2378 InsertValue(Fn, CurModule.Values);
2381 CurFun.FunctionStart(Fn);
2383 if (CurFun.isDeclare) {
2384 // If we have declaration, always overwrite linkage. This will allow us to
2385 // correctly handle cases, when pointer to function is passed as argument to
2386 // another function.
2387 Fn->setLinkage(CurFun.Linkage);
2388 Fn->setVisibility(CurFun.Visibility);
2390 Fn->setCallingConv($1);
2391 Fn->setParamAttrs(PAL);
2392 Fn->setAlignment($9);
2394 Fn->setSection(*$8);
2398 Fn->setCollector($10->c_str());
2402 // Add all of the arguments we parsed to the function...
2403 if ($5) { // Is null if empty...
2404 if (isVarArg) { // Nuke the last entry
2405 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2406 "Not a varargs marker!");
2407 delete $5->back().Ty;
2408 $5->pop_back(); // Delete the last entry
2410 Function::arg_iterator ArgIt = Fn->arg_begin();
2411 Function::arg_iterator ArgEnd = Fn->arg_end();
2413 for (ArgListType::iterator I = $5->begin();
2414 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2415 delete I->Ty; // Delete the typeholder...
2416 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2422 delete $5; // We're now done with the argument list
2427 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2429 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2430 $$ = CurFun.CurrentFunction;
2432 // Make sure that we keep track of the linkage type even if there was a
2433 // previous "declare".
2435 $$->setVisibility($2);
2438 END : ENDTOK | '}'; // Allow end of '}' to end a function
2440 Function : BasicBlockList END {
2445 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2446 CurFun.CurrentFunction->setLinkage($1);
2447 CurFun.CurrentFunction->setVisibility($2);
2448 $$ = CurFun.CurrentFunction;
2449 CurFun.FunctionDone();
2453 //===----------------------------------------------------------------------===//
2454 // Rules to match Basic Blocks
2455 //===----------------------------------------------------------------------===//
2457 OptSideEffect : /* empty */ {
2466 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2467 $$ = ValID::create($1);
2471 $$ = ValID::create($1);
2474 | FPVAL { // Perhaps it's an FP constant?
2475 $$ = ValID::create($1);
2479 $$ = ValID::create(ConstantInt::getTrue());
2483 $$ = ValID::create(ConstantInt::getFalse());
2487 $$ = ValID::createNull();
2491 $$ = ValID::createUndef();
2494 | ZEROINITIALIZER { // A vector zero constant.
2495 $$ = ValID::createZeroInit();
2498 | '<' ConstVector '>' { // Nonempty unsized packed vector
2499 const Type *ETy = (*$2)[0]->getType();
2500 int NumElements = $2->size();
2502 VectorType* pt = VectorType::get(ETy, NumElements);
2503 PATypeHolder* PTy = new PATypeHolder(
2511 // Verify all elements are correct type!
2512 for (unsigned i = 0; i < $2->size(); i++) {
2513 if (ETy != (*$2)[i]->getType())
2514 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2515 ETy->getDescription() +"' as required!\nIt is of type '" +
2516 (*$2)[i]->getType()->getDescription() + "'.");
2519 $$ = ValID::create(ConstantVector::get(pt, *$2));
2520 delete PTy; delete $2;
2524 $$ = ValID::create($1);
2527 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2528 $$ = ValID::createInlineAsm(*$3, *$5, $2);
2534 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2537 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2538 $$ = ValID::createLocalID($1);
2542 $$ = ValID::createGlobalID($1);
2545 | LocalName { // Is it a named reference...?
2546 $$ = ValID::createLocalName(*$1);
2550 | GlobalName { // Is it a named reference...?
2551 $$ = ValID::createGlobalName(*$1);
2556 // ValueRef - A reference to a definition... either constant or symbolic
2557 ValueRef : SymbolicValueRef | ConstValueRef;
2560 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2561 // type immediately preceeds the value reference, and allows complex constant
2562 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2563 ResolvedVal : Types ValueRef {
2564 if (!UpRefs.empty())
2565 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2566 $$ = getVal(*$1, $2);
2572 ReturnedVal : ResolvedVal {
2573 $$ = new std::vector<Value *>();
2577 | ReturnedVal ',' ResolvedVal {
2578 ($$=$1)->push_back($3);
2582 BasicBlockList : BasicBlockList BasicBlock {
2586 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2592 // Basic blocks are terminated by branching instructions:
2593 // br, br/cc, switch, ret
2595 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2596 setValueName($3, $2);
2599 $1->getInstList().push_back($3);
2604 InstructionList : InstructionList Inst {
2605 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2606 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2607 if (CI2->getParent() == 0)
2608 $1->getInstList().push_back(CI2);
2609 $1->getInstList().push_back($2);
2613 | /* empty */ { // Empty space between instruction lists
2614 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2617 | LABELSTR { // Labelled (named) basic block
2618 $$ = defineBBVal(ValID::createLocalName(*$1));
2625 RET ReturnedVal { // Return with a result...
2626 ValueList &VL = *$2;
2627 assert(!VL.empty() && "Invalid ret operands!");
2628 $$ = ReturnInst::Create(&VL[0], VL.size());
2632 | RET VOID { // Return with no result...
2633 $$ = ReturnInst::Create();
2636 | BR LABEL ValueRef { // Unconditional Branch...
2637 BasicBlock* tmpBB = getBBVal($3);
2639 $$ = BranchInst::Create(tmpBB);
2640 } // Conditional Branch...
2641 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2642 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2643 BasicBlock* tmpBBA = getBBVal($6);
2645 BasicBlock* tmpBBB = getBBVal($9);
2647 Value* tmpVal = getVal(Type::Int1Ty, $3);
2649 $$ = BranchInst::Create(tmpBBA, tmpBBB, tmpVal);
2651 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2652 Value* tmpVal = getVal($2, $3);
2654 BasicBlock* tmpBB = getBBVal($6);
2656 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, $8->size());
2659 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2661 for (; I != E; ++I) {
2662 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2663 S->addCase(CI, I->second);
2665 GEN_ERROR("Switch case is constant, but not a simple integer");
2670 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2671 Value* tmpVal = getVal($2, $3);
2673 BasicBlock* tmpBB = getBBVal($6);
2675 SwitchInst *S = SwitchInst::Create(tmpVal, tmpBB, 0);
2679 | INVOKE OptCallingConv ResultTypes ValueRef '(' ParamList ')' OptFuncAttrs
2680 TO LABEL ValueRef UNWIND LABEL ValueRef {
2682 // Handle the short syntax
2683 const PointerType *PFTy = 0;
2684 const FunctionType *Ty = 0;
2685 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2686 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2687 // Pull out the types of all of the arguments...
2688 std::vector<const Type*> ParamTypes;
2689 ParamList::iterator I = $6->begin(), E = $6->end();
2690 for (; I != E; ++I) {
2691 const Type *Ty = I->Val->getType();
2692 if (Ty == Type::VoidTy)
2693 GEN_ERROR("Short call syntax cannot be used with varargs");
2694 ParamTypes.push_back(Ty);
2697 if (!FunctionType::isValidReturnType(*$3))
2698 GEN_ERROR("Invalid result type for LLVM function");
2700 Ty = FunctionType::get($3->get(), ParamTypes, false);
2701 PFTy = PointerType::getUnqual(Ty);
2706 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2708 BasicBlock *Normal = getBBVal($11);
2710 BasicBlock *Except = getBBVal($14);
2713 SmallVector<ParamAttrsWithIndex, 8> Attrs;
2714 if ($8 != ParamAttr::None)
2715 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
2717 // Check the arguments
2719 if ($6->empty()) { // Has no arguments?
2720 // Make sure no arguments is a good thing!
2721 if (Ty->getNumParams() != 0)
2722 GEN_ERROR("No arguments passed to a function that "
2723 "expects arguments");
2724 } else { // Has arguments?
2725 // Loop through FunctionType's arguments and ensure they are specified
2727 FunctionType::param_iterator I = Ty->param_begin();
2728 FunctionType::param_iterator E = Ty->param_end();
2729 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
2732 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
2733 if (ArgI->Val->getType() != *I)
2734 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2735 (*I)->getDescription() + "'");
2736 Args.push_back(ArgI->Val);
2737 if (ArgI->Attrs != ParamAttr::None)
2738 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2741 if (Ty->isVarArg()) {
2743 for (; ArgI != ArgE; ++ArgI, ++index) {
2744 Args.push_back(ArgI->Val); // push the remaining varargs
2745 if (ArgI->Attrs != ParamAttr::None)
2746 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
2748 } else if (I != E || ArgI != ArgE)
2749 GEN_ERROR("Invalid number of parameters detected");
2754 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
2756 // Create the InvokeInst
2757 InvokeInst *II = InvokeInst::Create(V, Normal, Except,
2758 Args.begin(), Args.end());
2759 II->setCallingConv($2);
2760 II->setParamAttrs(PAL);
2766 $$ = new UnwindInst();
2770 $$ = new UnreachableInst();
2776 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2778 Constant *V = cast<Constant>(getExistingVal($2, $3));
2781 GEN_ERROR("May only switch on a constant pool value");
2783 BasicBlock* tmpBB = getBBVal($6);
2785 $$->push_back(std::make_pair(V, tmpBB));
2787 | IntType ConstValueRef ',' LABEL ValueRef {
2788 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2789 Constant *V = cast<Constant>(getExistingVal($1, $2));
2793 GEN_ERROR("May only switch on a constant pool value");
2795 BasicBlock* tmpBB = getBBVal($5);
2797 $$->push_back(std::make_pair(V, tmpBB));
2800 Inst : OptLocalAssign InstVal {
2801 // Is this definition named?? if so, assign the name...
2802 setValueName($2, $1);
2810 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2811 if (!UpRefs.empty())
2812 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2813 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2814 Value* tmpVal = getVal(*$1, $3);
2816 BasicBlock* tmpBB = getBBVal($5);
2818 $$->push_back(std::make_pair(tmpVal, tmpBB));
2821 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2823 Value* tmpVal = getVal($1->front().first->getType(), $4);
2825 BasicBlock* tmpBB = getBBVal($6);
2827 $1->push_back(std::make_pair(tmpVal, tmpBB));
2831 ParamList : Types OptParamAttrs ValueRef OptParamAttrs {
2832 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2833 if (!UpRefs.empty())
2834 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2835 // Used for call and invoke instructions
2836 $$ = new ParamList();
2837 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getVal($1->get(), $3);
2842 | LABEL OptParamAttrs ValueRef OptParamAttrs {
2843 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2844 // Labels are only valid in ASMs
2845 $$ = new ParamList();
2846 ParamListEntry E; E.Attrs = $2 | $4; E.Val = getBBVal($3);
2850 | ParamList ',' Types OptParamAttrs ValueRef OptParamAttrs {
2851 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2852 if (!UpRefs.empty())
2853 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2855 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getVal($3->get(), $5);
2860 | ParamList ',' LABEL OptParamAttrs ValueRef OptParamAttrs {
2861 // FIXME: Remove trailing OptParamAttrs in LLVM 3.0, it was a mistake in 2.0
2863 ParamListEntry E; E.Attrs = $4 | $6; E.Val = getBBVal($5);
2867 | /*empty*/ { $$ = new ParamList(); };
2869 IndexList // Used for gep instructions and constant expressions
2870 : /*empty*/ { $$ = new std::vector<Value*>(); }
2871 | IndexList ',' ResolvedVal {
2878 OptTailCall : TAIL CALL {
2887 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2888 if (!UpRefs.empty())
2889 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2890 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2891 !isa<VectorType>((*$2).get()))
2893 "Arithmetic operator requires integer, FP, or packed operands");
2894 Value* val1 = getVal(*$2, $3);
2896 Value* val2 = getVal(*$2, $5);
2898 $$ = BinaryOperator::Create($1, val1, val2);
2900 GEN_ERROR("binary operator returned null");
2903 | LogicalOps Types ValueRef ',' ValueRef {
2904 if (!UpRefs.empty())
2905 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2906 if (!(*$2)->isInteger()) {
2907 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2908 !cast<VectorType>($2->get())->getElementType()->isInteger())
2909 GEN_ERROR("Logical operator requires integral operands");
2911 Value* tmpVal1 = getVal(*$2, $3);
2913 Value* tmpVal2 = getVal(*$2, $5);
2915 $$ = BinaryOperator::Create($1, tmpVal1, tmpVal2);
2917 GEN_ERROR("binary operator returned null");
2920 | ICMP IPredicates Types ValueRef ',' ValueRef {
2921 if (!UpRefs.empty())
2922 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2923 if (isa<VectorType>((*$3).get()))
2924 GEN_ERROR("Vector types not supported by icmp instruction");
2925 Value* tmpVal1 = getVal(*$3, $4);
2927 Value* tmpVal2 = getVal(*$3, $6);
2929 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
2931 GEN_ERROR("icmp operator returned null");
2934 | FCMP FPredicates Types ValueRef ',' ValueRef {
2935 if (!UpRefs.empty())
2936 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2937 if (isa<VectorType>((*$3).get()))
2938 GEN_ERROR("Vector types not supported by fcmp instruction");
2939 Value* tmpVal1 = getVal(*$3, $4);
2941 Value* tmpVal2 = getVal(*$3, $6);
2943 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
2945 GEN_ERROR("fcmp operator returned null");
2948 | VICMP IPredicates Types ValueRef ',' ValueRef {
2949 if (!UpRefs.empty())
2950 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2951 if (!isa<VectorType>((*$3).get()))
2952 GEN_ERROR("Scalar types not supported by vicmp instruction");
2953 Value* tmpVal1 = getVal(*$3, $4);
2955 Value* tmpVal2 = getVal(*$3, $6);
2957 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
2959 GEN_ERROR("icmp operator returned null");
2962 | VFCMP FPredicates Types ValueRef ',' ValueRef {
2963 if (!UpRefs.empty())
2964 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2965 if (!isa<VectorType>((*$3).get()))
2966 GEN_ERROR("Scalar types not supported by vfcmp instruction");
2967 Value* tmpVal1 = getVal(*$3, $4);
2969 Value* tmpVal2 = getVal(*$3, $6);
2971 $$ = CmpInst::Create($1, $2, tmpVal1, tmpVal2);
2973 GEN_ERROR("fcmp operator returned null");
2976 | CastOps ResolvedVal TO Types {
2977 if (!UpRefs.empty())
2978 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2980 const Type* DestTy = $4->get();
2981 if (!CastInst::castIsValid($1, Val, DestTy))
2982 GEN_ERROR("invalid cast opcode for cast from '" +
2983 Val->getType()->getDescription() + "' to '" +
2984 DestTy->getDescription() + "'");
2985 $$ = CastInst::Create($1, Val, DestTy);
2988 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2989 if ($2->getType() != Type::Int1Ty)
2990 GEN_ERROR("select condition must be boolean");
2991 if ($4->getType() != $6->getType())
2992 GEN_ERROR("select value types should match");
2993 $$ = SelectInst::Create($2, $4, $6);
2996 | VAARG ResolvedVal ',' Types {
2997 if (!UpRefs.empty())
2998 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2999 $$ = new VAArgInst($2, *$4);
3003 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3004 if (!ExtractElementInst::isValidOperands($2, $4))
3005 GEN_ERROR("Invalid extractelement operands");
3006 $$ = new ExtractElementInst($2, $4);
3009 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3010 if (!InsertElementInst::isValidOperands($2, $4, $6))
3011 GEN_ERROR("Invalid insertelement operands");
3012 $$ = InsertElementInst::Create($2, $4, $6);
3015 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3016 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
3017 GEN_ERROR("Invalid shufflevector operands");
3018 $$ = new ShuffleVectorInst($2, $4, $6);
3022 const Type *Ty = $2->front().first->getType();
3023 if (!Ty->isFirstClassType())
3024 GEN_ERROR("PHI node operands must be of first class type");
3025 $$ = PHINode::Create(Ty);
3026 ((PHINode*)$$)->reserveOperandSpace($2->size());
3027 while ($2->begin() != $2->end()) {
3028 if ($2->front().first->getType() != Ty)
3029 GEN_ERROR("All elements of a PHI node must be of the same type");
3030 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
3033 delete $2; // Free the list...
3036 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ParamList ')'
3039 // Handle the short syntax
3040 const PointerType *PFTy = 0;
3041 const FunctionType *Ty = 0;
3042 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
3043 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3044 // Pull out the types of all of the arguments...
3045 std::vector<const Type*> ParamTypes;
3046 ParamList::iterator I = $6->begin(), E = $6->end();
3047 for (; I != E; ++I) {
3048 const Type *Ty = I->Val->getType();
3049 if (Ty == Type::VoidTy)
3050 GEN_ERROR("Short call syntax cannot be used with varargs");
3051 ParamTypes.push_back(Ty);
3054 if (!FunctionType::isValidReturnType(*$3))
3055 GEN_ERROR("Invalid result type for LLVM function");
3057 Ty = FunctionType::get($3->get(), ParamTypes, false);
3058 PFTy = PointerType::getUnqual(Ty);
3061 Value *V = getVal(PFTy, $4); // Get the function we're calling...
3064 // Check for call to invalid intrinsic to avoid crashing later.
3065 if (Function *theF = dyn_cast<Function>(V)) {
3066 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
3067 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
3068 !theF->getIntrinsicID(true))
3069 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
3070 theF->getName() + "'");
3073 // Set up the ParamAttrs for the function
3074 SmallVector<ParamAttrsWithIndex, 8> Attrs;
3075 if ($8 != ParamAttr::None)
3076 Attrs.push_back(ParamAttrsWithIndex::get(0, $8));
3077 // Check the arguments
3079 if ($6->empty()) { // Has no arguments?
3080 // Make sure no arguments is a good thing!
3081 if (Ty->getNumParams() != 0)
3082 GEN_ERROR("No arguments passed to a function that "
3083 "expects arguments");
3084 } else { // Has arguments?
3085 // Loop through FunctionType's arguments and ensure they are specified
3086 // correctly. Also, gather any parameter attributes.
3087 FunctionType::param_iterator I = Ty->param_begin();
3088 FunctionType::param_iterator E = Ty->param_end();
3089 ParamList::iterator ArgI = $6->begin(), ArgE = $6->end();
3092 for (; ArgI != ArgE && I != E; ++ArgI, ++I, ++index) {
3093 if (ArgI->Val->getType() != *I)
3094 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
3095 (*I)->getDescription() + "'");
3096 Args.push_back(ArgI->Val);
3097 if (ArgI->Attrs != ParamAttr::None)
3098 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3100 if (Ty->isVarArg()) {
3102 for (; ArgI != ArgE; ++ArgI, ++index) {
3103 Args.push_back(ArgI->Val); // push the remaining varargs
3104 if (ArgI->Attrs != ParamAttr::None)
3105 Attrs.push_back(ParamAttrsWithIndex::get(index, ArgI->Attrs));
3107 } else if (I != E || ArgI != ArgE)
3108 GEN_ERROR("Invalid number of parameters detected");
3111 // Finish off the ParamAttrs and check them
3114 PAL = PAListPtr::get(Attrs.begin(), Attrs.end());
3116 // Create the call node
3117 CallInst *CI = CallInst::Create(V, Args.begin(), Args.end());
3118 CI->setTailCall($1);
3119 CI->setCallingConv($2);
3120 CI->setParamAttrs(PAL);
3131 OptVolatile : VOLATILE {
3142 MemoryInst : MALLOC Types OptCAlign {
3143 if (!UpRefs.empty())
3144 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3145 $$ = new MallocInst(*$2, 0, $3);
3149 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
3150 if (!UpRefs.empty())
3151 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3152 Value* tmpVal = getVal($4, $5);
3154 $$ = new MallocInst(*$2, tmpVal, $6);
3157 | ALLOCA Types OptCAlign {
3158 if (!UpRefs.empty())
3159 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3160 $$ = new AllocaInst(*$2, 0, $3);
3164 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
3165 if (!UpRefs.empty())
3166 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3167 Value* tmpVal = getVal($4, $5);
3169 $$ = new AllocaInst(*$2, tmpVal, $6);
3172 | FREE ResolvedVal {
3173 if (!isa<PointerType>($2->getType()))
3174 GEN_ERROR("Trying to free nonpointer type " +
3175 $2->getType()->getDescription() + "");
3176 $$ = new FreeInst($2);
3180 | OptVolatile LOAD Types ValueRef OptCAlign {
3181 if (!UpRefs.empty())
3182 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3183 if (!isa<PointerType>($3->get()))
3184 GEN_ERROR("Can't load from nonpointer type: " +
3185 (*$3)->getDescription());
3186 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3187 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3188 (*$3)->getDescription());
3189 Value* tmpVal = getVal(*$3, $4);
3191 $$ = new LoadInst(tmpVal, "", $1, $5);
3194 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3195 if (!UpRefs.empty())
3196 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3197 const PointerType *PT = dyn_cast<PointerType>($5->get());
3199 GEN_ERROR("Can't store to a nonpointer type: " +
3200 (*$5)->getDescription());
3201 const Type *ElTy = PT->getElementType();
3202 if (ElTy != $3->getType())
3203 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3204 "' into space of type '" + ElTy->getDescription() + "'");
3206 Value* tmpVal = getVal(*$5, $6);
3208 $$ = new StoreInst($3, tmpVal, $1, $7);
3211 | GETRESULT Types ValueRef ',' EUINT64VAL {
3212 Value *TmpVal = getVal($2->get(), $3);
3213 if (!GetResultInst::isValidOperands(TmpVal, $5))
3214 GEN_ERROR("Invalid getresult operands");
3215 $$ = new GetResultInst(TmpVal, $5);
3219 | GETELEMENTPTR Types ValueRef IndexList {
3220 if (!UpRefs.empty())
3221 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3222 if (!isa<PointerType>($2->get()))
3223 GEN_ERROR("getelementptr insn requires pointer operand");
3225 if (!GetElementPtrInst::getIndexedType(*$2, $4->begin(), $4->end()))
3226 GEN_ERROR("Invalid getelementptr indices for type '" +
3227 (*$2)->getDescription()+ "'");
3228 Value* tmpVal = getVal(*$2, $3);
3230 $$ = GetElementPtrInst::Create(tmpVal, $4->begin(), $4->end());
3234 | EXTRACTVALUE Types ValueRef IndexList {
3235 if (!UpRefs.empty())
3236 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3237 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3238 GEN_ERROR("extractvalue insn requires an aggregate operand");
3240 if (!ExtractValueInst::getIndexedType(*$2, $4->begin(), $4->end()))
3241 GEN_ERROR("Invalid extractvalue indices for type '" +
3242 (*$2)->getDescription()+ "'");
3243 Value* tmpVal = getVal(*$2, $3);
3245 $$ = ExtractValueInst::Create(tmpVal, $4->begin(), $4->end());
3249 | INSERTVALUE Types ValueRef ',' Types ValueRef IndexList {
3250 if (!UpRefs.empty())
3251 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3252 if (!isa<StructType>($2->get()) && !isa<ArrayType>($2->get()))
3253 GEN_ERROR("extractvalue insn requires an aggregate operand");
3255 if (ExtractValueInst::getIndexedType(*$2, $7->begin(), $7->end()) != $5->get())
3256 GEN_ERROR("Invalid insertvalue indices for type '" +
3257 (*$2)->getDescription()+ "'");
3258 Value* aggVal = getVal(*$2, $3);
3259 Value* tmpVal = getVal(*$5, $6);
3261 $$ = InsertValueInst::Create(aggVal, tmpVal, $7->begin(), $7->end());
3270 // common code from the two 'RunVMAsmParser' functions
3271 static Module* RunParser(Module * M) {
3272 CurModule.CurrentModule = M;
3273 // Check to make sure the parser succeeded
3276 delete ParserResult;
3280 // Emit an error if there are any unresolved types left.
3281 if (!CurModule.LateResolveTypes.empty()) {
3282 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3283 if (DID.Type == ValID::LocalName) {
3284 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3286 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3289 delete ParserResult;
3293 // Emit an error if there are any unresolved values left.
3294 if (!CurModule.LateResolveValues.empty()) {
3295 Value *V = CurModule.LateResolveValues.back();
3296 std::map<Value*, std::pair<ValID, int> >::iterator I =
3297 CurModule.PlaceHolderInfo.find(V);
3299 if (I != CurModule.PlaceHolderInfo.end()) {
3300 ValID &DID = I->second.first;
3301 if (DID.Type == ValID::LocalName) {
3302 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3304 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3307 delete ParserResult;
3312 // Check to make sure that parsing produced a result
3316 // Reset ParserResult variable while saving its value for the result.
3317 Module *Result = ParserResult;
3323 void llvm::GenerateError(const std::string &message, int LineNo) {
3324 if (LineNo == -1) LineNo = LLLgetLineNo();
3325 // TODO: column number in exception
3327 TheParseError->setError(LLLgetFilename(), message, LineNo);
3331 int yyerror(const char *ErrorMsg) {
3332 std::string where = LLLgetFilename() + ":" + utostr(LLLgetLineNo()) + ": ";
3333 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3334 if (yychar != YYEMPTY && yychar != 0) {
3335 errMsg += " while reading token: '";
3336 errMsg += std::string(LLLgetTokenStart(),
3337 LLLgetTokenStart()+LLLgetTokenLength()) + "'";
3339 GenerateError(errMsg);