1 //===-- llvmAsmParser.y - Parser for llvm assembly files --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the bison parser for LLVM assembly languages files.
12 //===----------------------------------------------------------------------===//
15 #include "ParserInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Streams.h"
35 // The following is a gross hack. In order to rid the libAsmParser library of
36 // exceptions, we have to have a way of getting the yyparse function to go into
37 // an error situation. So, whenever we want an error to occur, the GenerateError
38 // function (see bottom of file) sets TriggerError. Then, at the end of each
39 // production in the grammer we use CHECK_FOR_ERROR which will invoke YYERROR
40 // (a goto) to put YACC in error state. Furthermore, several calls to
41 // GenerateError are made from inside productions and they must simulate the
42 // previous exception behavior by exiting the production immediately. We have
43 // replaced these with the GEN_ERROR macro which calls GeneratError and then
44 // immediately invokes YYERROR. This would be so much cleaner if it was a
45 // recursive descent parser.
46 static bool TriggerError = false;
47 #define CHECK_FOR_ERROR { if (TriggerError) { TriggerError = false; YYABORT; } }
48 #define GEN_ERROR(msg) { GenerateError(msg); YYERROR; }
50 int yyerror(const char *ErrorMsg); // Forward declarations to prevent "implicit
51 int yylex(); // declaration" of xxx warnings.
55 std::string CurFilename;
58 Debug("debug-yacc", cl::desc("Print yacc debug state changes"),
59 cl::Hidden, cl::init(false));
64 static Module *ParserResult;
66 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
67 // relating to upreferences in the input stream.
69 //#define DEBUG_UPREFS 1
71 #define UR_OUT(X) cerr << X
76 #define YYERROR_VERBOSE 1
78 static GlobalVariable *CurGV;
81 // This contains info used when building the body of a function. It is
82 // destroyed when the function is completed.
84 typedef std::vector<Value *> ValueList; // Numbered defs
87 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers=0);
89 static struct PerModuleInfo {
90 Module *CurrentModule;
91 ValueList Values; // Module level numbered definitions
92 ValueList LateResolveValues;
93 std::vector<PATypeHolder> Types;
94 std::map<ValID, PATypeHolder> LateResolveTypes;
96 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
97 /// how they were referenced and on which line of the input they came from so
98 /// that we can resolve them later and print error messages as appropriate.
99 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
101 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
102 // references to global values. Global values may be referenced before they
103 // are defined, and if so, the temporary object that they represent is held
104 // here. This is used for forward references of GlobalValues.
106 typedef std::map<std::pair<const PointerType *,
107 ValID>, GlobalValue*> GlobalRefsType;
108 GlobalRefsType GlobalRefs;
111 // If we could not resolve some functions at function compilation time
112 // (calls to functions before they are defined), resolve them now... Types
113 // are resolved when the constant pool has been completely parsed.
115 ResolveDefinitions(LateResolveValues);
119 // Check to make sure that all global value forward references have been
122 if (!GlobalRefs.empty()) {
123 std::string UndefinedReferences = "Unresolved global references exist:\n";
125 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
127 UndefinedReferences += " " + I->first.first->getDescription() + " " +
128 I->first.second.getName() + "\n";
130 GenerateError(UndefinedReferences);
134 Values.clear(); // Clear out function local definitions
139 // GetForwardRefForGlobal - Check to see if there is a forward reference
140 // for this global. If so, remove it from the GlobalRefs map and return it.
141 // If not, just return null.
142 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ParamAttrsList *PAL,
144 // Check to see if there is a forward reference to this global variable...
145 // if there is, eliminate it and patch the reference to use the new def'n.
146 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(PTy, ID));
147 GlobalValue *Ret = 0;
148 if (I != GlobalRefs.end()) {
150 if (PAL && isa<Function>(Ret))
151 Ret = cast<Function>(Ret)->getParamAttrs() == PAL ? Ret : 0;
158 bool TypeIsUnresolved(PATypeHolder* PATy) {
159 // If it isn't abstract, its resolved
160 const Type* Ty = PATy->get();
161 if (!Ty->isAbstract())
163 // Traverse the type looking for abstract types. If it isn't abstract then
164 // we don't need to traverse that leg of the type.
165 std::vector<const Type*> WorkList, SeenList;
166 WorkList.push_back(Ty);
167 while (!WorkList.empty()) {
168 const Type* Ty = WorkList.back();
169 SeenList.push_back(Ty);
171 if (const OpaqueType* OpTy = dyn_cast<OpaqueType>(Ty)) {
172 // Check to see if this is an unresolved type
173 std::map<ValID, PATypeHolder>::iterator I = LateResolveTypes.begin();
174 std::map<ValID, PATypeHolder>::iterator E = LateResolveTypes.end();
175 for ( ; I != E; ++I) {
176 if (I->second.get() == OpTy)
179 } else if (const SequentialType* SeqTy = dyn_cast<SequentialType>(Ty)) {
180 const Type* TheTy = SeqTy->getElementType();
181 if (TheTy->isAbstract() && TheTy != Ty) {
182 std::vector<const Type*>::iterator I = SeenList.begin(),
188 WorkList.push_back(TheTy);
190 } else if (const StructType* StrTy = dyn_cast<StructType>(Ty)) {
191 for (unsigned i = 0; i < StrTy->getNumElements(); ++i) {
192 const Type* TheTy = StrTy->getElementType(i);
193 if (TheTy->isAbstract() && TheTy != Ty) {
194 std::vector<const Type*>::iterator I = SeenList.begin(),
200 WorkList.push_back(TheTy);
209 static struct PerFunctionInfo {
210 Function *CurrentFunction; // Pointer to current function being created
212 ValueList Values; // Keep track of #'d definitions
214 ValueList LateResolveValues;
215 bool isDeclare; // Is this function a forward declararation?
216 GlobalValue::LinkageTypes Linkage; // Linkage for forward declaration.
217 GlobalValue::VisibilityTypes Visibility;
219 /// BBForwardRefs - When we see forward references to basic blocks, keep
220 /// track of them here.
221 std::map<ValID, BasicBlock*> BBForwardRefs;
223 inline PerFunctionInfo() {
226 Linkage = GlobalValue::ExternalLinkage;
227 Visibility = GlobalValue::DefaultVisibility;
230 inline void FunctionStart(Function *M) {
235 void FunctionDone() {
236 // Any forward referenced blocks left?
237 if (!BBForwardRefs.empty()) {
238 GenerateError("Undefined reference to label " +
239 BBForwardRefs.begin()->second->getName());
243 // Resolve all forward references now.
244 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
246 Values.clear(); // Clear out function local definitions
247 BBForwardRefs.clear();
250 Linkage = GlobalValue::ExternalLinkage;
251 Visibility = GlobalValue::DefaultVisibility;
253 } CurFun; // Info for the current function...
255 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
258 //===----------------------------------------------------------------------===//
259 // Code to handle definitions of all the types
260 //===----------------------------------------------------------------------===//
262 static void InsertValue(Value *V, ValueList &ValueTab = CurFun.Values) {
263 // Things that have names or are void typed don't get slot numbers
264 if (V->hasName() || (V->getType() == Type::VoidTy))
267 // In the case of function values, we have to allow for the forward reference
268 // of basic blocks, which are included in the numbering. Consequently, we keep
269 // track of the next insertion location with NextValNum. When a BB gets
270 // inserted, it could change the size of the CurFun.Values vector.
271 if (&ValueTab == &CurFun.Values) {
272 if (ValueTab.size() <= CurFun.NextValNum)
273 ValueTab.resize(CurFun.NextValNum+1);
274 ValueTab[CurFun.NextValNum++] = V;
277 // For all other lists, its okay to just tack it on the back of the vector.
278 ValueTab.push_back(V);
281 static const Type *getTypeVal(const ValID &D, bool DoNotImprovise = false) {
283 case ValID::LocalID: // Is it a numbered definition?
284 // Module constants occupy the lowest numbered slots...
285 if (D.Num < CurModule.Types.size())
286 return CurModule.Types[D.Num];
288 case ValID::LocalName: // Is it a named definition?
289 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
290 D.destroy(); // Free old strdup'd memory...
295 GenerateError("Internal parser error: Invalid symbol type reference");
299 // If we reached here, we referenced either a symbol that we don't know about
300 // or an id number that hasn't been read yet. We may be referencing something
301 // forward, so just create an entry to be resolved later and get to it...
303 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
306 if (inFunctionScope()) {
307 if (D.Type == ValID::LocalName) {
308 GenerateError("Reference to an undefined type: '" + D.getName() + "'");
311 GenerateError("Reference to an undefined type: #" + utostr(D.Num));
316 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
317 if (I != CurModule.LateResolveTypes.end())
320 Type *Typ = OpaqueType::get();
321 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
325 // getExistingVal - Look up the value specified by the provided type and
326 // the provided ValID. If the value exists and has already been defined, return
327 // it. Otherwise return null.
329 static Value *getExistingVal(const Type *Ty, const ValID &D) {
330 if (isa<FunctionType>(Ty)) {
331 GenerateError("Functions are not values and "
332 "must be referenced as pointers");
337 case ValID::LocalID: { // Is it a numbered definition?
338 // Check that the number is within bounds.
339 if (D.Num >= CurFun.Values.size())
341 Value *Result = CurFun.Values[D.Num];
342 if (Ty != Result->getType()) {
343 GenerateError("Numbered value (%" + utostr(D.Num) + ") of type '" +
344 Result->getType()->getDescription() + "' does not match "
345 "expected type, '" + Ty->getDescription() + "'");
350 case ValID::GlobalID: { // Is it a numbered definition?
351 if (D.Num >= CurModule.Values.size())
353 Value *Result = CurModule.Values[D.Num];
354 if (Ty != Result->getType()) {
355 GenerateError("Numbered value (@" + utostr(D.Num) + ") of type '" +
356 Result->getType()->getDescription() + "' does not match "
357 "expected type, '" + Ty->getDescription() + "'");
363 case ValID::LocalName: { // Is it a named definition?
364 if (!inFunctionScope())
366 ValueSymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
367 Value *N = SymTab.lookup(D.Name);
370 if (N->getType() != Ty)
373 D.destroy(); // Free old strdup'd memory...
376 case ValID::GlobalName: { // Is it a named definition?
377 ValueSymbolTable &SymTab = CurModule.CurrentModule->getValueSymbolTable();
378 Value *N = SymTab.lookup(D.Name);
381 if (N->getType() != Ty)
384 D.destroy(); // Free old strdup'd memory...
388 // Check to make sure that "Ty" is an integral type, and that our
389 // value will fit into the specified type...
390 case ValID::ConstSIntVal: // Is it a constant pool reference??
391 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
392 GenerateError("Signed integral constant '" +
393 itostr(D.ConstPool64) + "' is invalid for type '" +
394 Ty->getDescription() + "'");
397 return ConstantInt::get(Ty, D.ConstPool64, true);
399 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
400 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
401 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
402 GenerateError("Integral constant '" + utostr(D.UConstPool64) +
403 "' is invalid or out of range");
405 } else { // This is really a signed reference. Transmogrify.
406 return ConstantInt::get(Ty, D.ConstPool64, true);
409 return ConstantInt::get(Ty, D.UConstPool64);
412 case ValID::ConstFPVal: // Is it a floating point const pool reference?
413 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP)) {
414 GenerateError("FP constant invalid for type");
417 return ConstantFP::get(Ty, D.ConstPoolFP);
419 case ValID::ConstNullVal: // Is it a null value?
420 if (!isa<PointerType>(Ty)) {
421 GenerateError("Cannot create a a non pointer null");
424 return ConstantPointerNull::get(cast<PointerType>(Ty));
426 case ValID::ConstUndefVal: // Is it an undef value?
427 return UndefValue::get(Ty);
429 case ValID::ConstZeroVal: // Is it a zero value?
430 return Constant::getNullValue(Ty);
432 case ValID::ConstantVal: // Fully resolved constant?
433 if (D.ConstantValue->getType() != Ty) {
434 GenerateError("Constant expression type different from required type");
437 return D.ConstantValue;
439 case ValID::InlineAsmVal: { // Inline asm expression
440 const PointerType *PTy = dyn_cast<PointerType>(Ty);
441 const FunctionType *FTy =
442 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
443 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints)) {
444 GenerateError("Invalid type for asm constraint string");
447 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
448 D.IAD->HasSideEffects);
449 D.destroy(); // Free InlineAsmDescriptor.
453 assert(0 && "Unhandled case!");
457 assert(0 && "Unhandled case!");
461 // getVal - This function is identical to getExistingVal, except that if a
462 // value is not already defined, it "improvises" by creating a placeholder var
463 // that looks and acts just like the requested variable. When the value is
464 // defined later, all uses of the placeholder variable are replaced with the
467 static Value *getVal(const Type *Ty, const ValID &ID) {
468 if (Ty == Type::LabelTy) {
469 GenerateError("Cannot use a basic block here");
473 // See if the value has already been defined.
474 Value *V = getExistingVal(Ty, ID);
476 if (TriggerError) return 0;
478 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty)) {
479 GenerateError("Invalid use of a composite type");
483 // If we reached here, we referenced either a symbol that we don't know about
484 // or an id number that hasn't been read yet. We may be referencing something
485 // forward, so just create an entry to be resolved later and get to it...
488 case ValID::GlobalName:
489 case ValID::GlobalID: {
490 const PointerType *PTy = dyn_cast<PointerType>(Ty);
492 GenerateError("Invalid type for reference to global" );
495 const Type* ElTy = PTy->getElementType();
496 if (const FunctionType *FTy = dyn_cast<FunctionType>(ElTy))
497 V = new Function(FTy, GlobalValue::ExternalLinkage);
499 V = new GlobalVariable(ElTy, false, GlobalValue::ExternalLinkage);
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");
555 // We haven't seen this BB before and its first mention is a definition.
556 // Just create it and return it.
557 std::string Name (ID.Type == ValID::LocalName ? ID.Name : "");
558 BB = new BasicBlock(Name, CurFun.CurrentFunction);
559 if (ID.Type == ValID::LocalID) {
560 assert(ID.Num == CurFun.NextValNum && "Invalid new block number");
564 ID.destroy(); // Free strdup'd memory
568 /// getBBVal - get an existing BB value or create a forward reference for it.
570 static BasicBlock *getBBVal(const ValID &ID) {
571 assert(inFunctionScope() && "Can't get basic block at global scope!");
575 std::map<ValID, BasicBlock*>::iterator BBI = CurFun.BBForwardRefs.find(ID);
576 if (BBI != CurFun.BBForwardRefs.end()) {
578 } if (ID.Type == ValID::LocalName) {
579 std::string Name = ID.Name;
580 Value *N = CurFun.CurrentFunction->getValueSymbolTable().lookup(Name);
582 if (N->getType()->getTypeID() == Type::LabelTyID)
583 BB = cast<BasicBlock>(N);
585 GenerateError("Reference to label '" + Name + "' is actually of type '"+
586 N->getType()->getDescription() + "'");
587 } else if (ID.Type == ValID::LocalID) {
588 if (ID.Num < CurFun.NextValNum && ID.Num < CurFun.Values.size()) {
589 if (CurFun.Values[ID.Num]->getType()->getTypeID() == Type::LabelTyID)
590 BB = cast<BasicBlock>(CurFun.Values[ID.Num]);
592 GenerateError("Reference to label '%" + utostr(ID.Num) +
593 "' is actually of type '"+
594 CurFun.Values[ID.Num]->getType()->getDescription() + "'");
597 GenerateError("Illegal label reference " + ID.getName());
601 // If its already been defined, return it now.
603 ID.destroy(); // Free strdup'd memory.
607 // Otherwise, this block has not been seen before, create it.
609 if (ID.Type == ValID::LocalName)
611 BB = new BasicBlock(Name, CurFun.CurrentFunction);
613 // Insert it in the forward refs map.
614 CurFun.BBForwardRefs[ID] = BB;
620 //===----------------------------------------------------------------------===//
621 // Code to handle forward references in instructions
622 //===----------------------------------------------------------------------===//
624 // This code handles the late binding needed with statements that reference
625 // values not defined yet... for example, a forward branch, or the PHI node for
628 // This keeps a table (CurFun.LateResolveValues) of all such forward references
629 // and back patchs after we are done.
632 // ResolveDefinitions - If we could not resolve some defs at parsing
633 // time (forward branches, phi functions for loops, etc...) resolve the
637 ResolveDefinitions(ValueList &LateResolvers, ValueList *FutureLateResolvers) {
638 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
639 while (!LateResolvers.empty()) {
640 Value *V = LateResolvers.back();
641 LateResolvers.pop_back();
643 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
644 CurModule.PlaceHolderInfo.find(V);
645 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error!");
647 ValID &DID = PHI->second.first;
649 Value *TheRealValue = getExistingVal(V->getType(), DID);
653 V->replaceAllUsesWith(TheRealValue);
655 CurModule.PlaceHolderInfo.erase(PHI);
656 } else if (FutureLateResolvers) {
657 // Functions have their unresolved items forwarded to the module late
659 InsertValue(V, *FutureLateResolvers);
661 if (DID.Type == ValID::LocalName || DID.Type == ValID::GlobalName) {
662 GenerateError("Reference to an invalid definition: '" +DID.getName()+
663 "' of type '" + V->getType()->getDescription() + "'",
667 GenerateError("Reference to an invalid definition: #" +
668 itostr(DID.Num) + " of type '" +
669 V->getType()->getDescription() + "'",
675 LateResolvers.clear();
678 // ResolveTypeTo - A brand new type was just declared. This means that (if
679 // name is not null) things referencing Name can be resolved. Otherwise, things
680 // refering to the number can be resolved. Do this now.
682 static void ResolveTypeTo(char *Name, const Type *ToTy) {
684 if (Name) D = ValID::createLocalName(Name);
685 else 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, char *NameStr) {
700 if (!NameStr) return;
701 std::string Name(NameStr); // Copy string
702 free(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(char *NameStr,
725 GlobalValue::LinkageTypes Linkage,
726 GlobalValue::VisibilityTypes Visibility,
727 bool isConstantGlobal, const Type *Ty,
728 Constant *Initializer, bool IsThreadLocal) {
729 if (isa<FunctionType>(Ty)) {
730 GenerateError("Cannot declare global vars of function type");
734 const PointerType *PTy = PointerType::get(Ty);
738 Name = NameStr; // Copy string
739 free(NameStr); // Free old string
742 // See if this global value was forward referenced. If so, recycle the
746 ID = ValID::createGlobalName((char*)Name.c_str());
748 ID = ValID::createGlobalID(CurModule.Values.size());
751 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, 0, ID)) {
752 // Move the global to the end of the list, from whereever it was
753 // previously inserted.
754 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
755 CurModule.CurrentModule->getGlobalList().remove(GV);
756 CurModule.CurrentModule->getGlobalList().push_back(GV);
757 GV->setInitializer(Initializer);
758 GV->setLinkage(Linkage);
759 GV->setVisibility(Visibility);
760 GV->setConstant(isConstantGlobal);
761 GV->setThreadLocal(IsThreadLocal);
762 InsertValue(GV, CurModule.Values);
766 // If this global has a name
768 // if the global we're parsing has an initializer (is a definition) and
769 // has external linkage.
770 if (Initializer && Linkage != GlobalValue::InternalLinkage)
771 // If there is already a global with external linkage with this name
772 if (CurModule.CurrentModule->getGlobalVariable(Name, false)) {
773 // If we allow this GVar to get created, it will be renamed in the
774 // symbol table because it conflicts with an existing GVar. We can't
775 // allow redefinition of GVars whose linking indicates that their name
776 // must stay the same. Issue the error.
777 GenerateError("Redefinition of global variable named '" + Name +
778 "' of type '" + Ty->getDescription() + "'");
783 // Otherwise there is no existing GV to use, create one now.
785 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
786 CurModule.CurrentModule, IsThreadLocal);
787 GV->setVisibility(Visibility);
788 InsertValue(GV, CurModule.Values);
792 // setTypeName - Set the specified type to the name given. The name may be
793 // null potentially, in which case this is a noop. The string passed in is
794 // assumed to be a malloc'd string buffer, and is freed by this function.
796 // This function returns true if the type has already been defined, but is
797 // allowed to be redefined in the specified context. If the name is a new name
798 // for the type plane, it is inserted and false is returned.
799 static bool setTypeName(const Type *T, char *NameStr) {
800 assert(!inFunctionScope() && "Can't give types function-local names!");
801 if (NameStr == 0) return false;
803 std::string Name(NameStr); // Copy string
804 free(NameStr); // Free old string
806 // We don't allow assigning names to void type
807 if (T == Type::VoidTy) {
808 GenerateError("Can't assign name '" + Name + "' to the void type");
812 // Set the type name, checking for conflicts as we do so.
813 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
815 if (AlreadyExists) { // Inserting a name that is already defined???
816 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
817 assert(Existing && "Conflict but no matching type?!");
819 // There is only one case where this is allowed: when we are refining an
820 // opaque type. In this case, Existing will be an opaque type.
821 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
822 // We ARE replacing an opaque type!
823 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
827 // Otherwise, this is an attempt to redefine a type. That's okay if
828 // the redefinition is identical to the original. This will be so if
829 // Existing and T point to the same Type object. In this one case we
830 // allow the equivalent redefinition.
831 if (Existing == T) return true; // Yes, it's equal.
833 // Any other kind of (non-equivalent) redefinition is an error.
834 GenerateError("Redefinition of type named '" + Name + "' of type '" +
835 T->getDescription() + "'");
841 //===----------------------------------------------------------------------===//
842 // Code for handling upreferences in type names...
845 // TypeContains - Returns true if Ty directly contains E in it.
847 static bool TypeContains(const Type *Ty, const Type *E) {
848 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
849 E) != Ty->subtype_end();
854 // NestingLevel - The number of nesting levels that need to be popped before
855 // this type is resolved.
856 unsigned NestingLevel;
858 // LastContainedTy - This is the type at the current binding level for the
859 // type. Every time we reduce the nesting level, this gets updated.
860 const Type *LastContainedTy;
862 // UpRefTy - This is the actual opaque type that the upreference is
866 UpRefRecord(unsigned NL, OpaqueType *URTy)
867 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
871 // UpRefs - A list of the outstanding upreferences that need to be resolved.
872 static std::vector<UpRefRecord> UpRefs;
874 /// HandleUpRefs - Every time we finish a new layer of types, this function is
875 /// called. It loops through the UpRefs vector, which is a list of the
876 /// currently active types. For each type, if the up reference is contained in
877 /// the newly completed type, we decrement the level count. When the level
878 /// count reaches zero, the upreferenced type is the type that is passed in:
879 /// thus we can complete the cycle.
881 static PATypeHolder HandleUpRefs(const Type *ty) {
882 // If Ty isn't abstract, or if there are no up-references in it, then there is
883 // nothing to resolve here.
884 if (!ty->isAbstract() || UpRefs.empty()) return ty;
887 UR_OUT("Type '" << Ty->getDescription() <<
888 "' newly formed. Resolving upreferences.\n" <<
889 UpRefs.size() << " upreferences active!\n");
891 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
892 // to zero), we resolve them all together before we resolve them to Ty. At
893 // the end of the loop, if there is anything to resolve to Ty, it will be in
895 OpaqueType *TypeToResolve = 0;
897 for (unsigned i = 0; i != UpRefs.size(); ++i) {
898 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
899 << UpRefs[i].second->getDescription() << ") = "
900 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
901 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
902 // Decrement level of upreference
903 unsigned Level = --UpRefs[i].NestingLevel;
904 UpRefs[i].LastContainedTy = Ty;
905 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
906 if (Level == 0) { // Upreference should be resolved!
907 if (!TypeToResolve) {
908 TypeToResolve = UpRefs[i].UpRefTy;
910 UR_OUT(" * Resolving upreference for "
911 << UpRefs[i].second->getDescription() << "\n";
912 std::string OldName = UpRefs[i].UpRefTy->getDescription());
913 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
914 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
915 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
917 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
918 --i; // Do not skip the next element...
924 UR_OUT(" * Resolving upreference for "
925 << UpRefs[i].second->getDescription() << "\n";
926 std::string OldName = TypeToResolve->getDescription());
927 TypeToResolve->refineAbstractTypeTo(Ty);
933 //===----------------------------------------------------------------------===//
934 // RunVMAsmParser - Define an interface to this parser
935 //===----------------------------------------------------------------------===//
937 static Module* RunParser(Module * M);
939 Module *llvm::RunVMAsmParser(const std::string &Filename, FILE *F) {
942 CurFilename = Filename;
943 return RunParser(new Module(CurFilename));
946 Module *llvm::RunVMAsmParser(const char * AsmString, Module * M) {
947 set_scan_string(AsmString);
949 CurFilename = "from_memory";
951 return RunParser(new Module (CurFilename));
960 llvm::Module *ModuleVal;
961 llvm::Function *FunctionVal;
962 llvm::BasicBlock *BasicBlockVal;
963 llvm::TerminatorInst *TermInstVal;
964 llvm::Instruction *InstVal;
965 llvm::Constant *ConstVal;
967 const llvm::Type *PrimType;
968 std::list<llvm::PATypeHolder> *TypeList;
969 llvm::PATypeHolder *TypeVal;
970 llvm::Value *ValueVal;
971 std::vector<llvm::Value*> *ValueList;
972 llvm::ArgListType *ArgList;
973 llvm::TypeWithAttrs TypeWithAttrs;
974 llvm::TypeWithAttrsList *TypeWithAttrsList;
975 llvm::ValueRefList *ValueRefList;
977 // Represent the RHS of PHI node
978 std::list<std::pair<llvm::Value*,
979 llvm::BasicBlock*> > *PHIList;
980 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
981 std::vector<llvm::Constant*> *ConstVector;
983 llvm::GlobalValue::LinkageTypes Linkage;
984 llvm::GlobalValue::VisibilityTypes Visibility;
986 llvm::APInt *APIntVal;
994 char *StrVal; // This memory is strdup'd!
995 llvm::ValID ValIDVal; // strdup'd memory maybe!
997 llvm::Instruction::BinaryOps BinaryOpVal;
998 llvm::Instruction::TermOps TermOpVal;
999 llvm::Instruction::MemoryOps MemOpVal;
1000 llvm::Instruction::CastOps CastOpVal;
1001 llvm::Instruction::OtherOps OtherOpVal;
1002 llvm::ICmpInst::Predicate IPredicate;
1003 llvm::FCmpInst::Predicate FPredicate;
1006 %type <ModuleVal> Module
1007 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1008 %type <BasicBlockVal> BasicBlock InstructionList
1009 %type <TermInstVal> BBTerminatorInst
1010 %type <InstVal> Inst InstVal MemoryInst
1011 %type <ConstVal> ConstVal ConstExpr AliaseeRef
1012 %type <ConstVector> ConstVector
1013 %type <ArgList> ArgList ArgListH
1014 %type <PHIList> PHIList
1015 %type <ValueRefList> ValueRefList // For call param lists & GEP indices
1016 %type <ValueList> IndexList // For GEP indices
1017 %type <TypeList> TypeListI
1018 %type <TypeWithAttrsList> ArgTypeList ArgTypeListI
1019 %type <TypeWithAttrs> ArgType
1020 %type <JumpTable> JumpTable
1021 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1022 %type <BoolVal> ThreadLocal // 'thread_local' or not
1023 %type <BoolVal> OptVolatile // 'volatile' or not
1024 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1025 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1026 %type <Linkage> GVInternalLinkage GVExternalLinkage
1027 %type <Linkage> FunctionDefineLinkage FunctionDeclareLinkage
1028 %type <Linkage> AliasLinkage
1029 %type <Visibility> GVVisibilityStyle
1031 // ValueRef - Unresolved reference to a definition or BB
1032 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1033 %type <ValueVal> ResolvedVal // <type> <valref> pair
1034 // Tokens and types for handling constant integer values
1036 // ESINT64VAL - A negative number within long long range
1037 %token <SInt64Val> ESINT64VAL
1039 // EUINT64VAL - A positive number within uns. long long range
1040 %token <UInt64Val> EUINT64VAL
1042 // ESAPINTVAL - A negative number with arbitrary precision
1043 %token <APIntVal> ESAPINTVAL
1045 // EUAPINTVAL - A positive number with arbitrary precision
1046 %token <APIntVal> EUAPINTVAL
1048 %token <UIntVal> LOCALVAL_ID GLOBALVAL_ID // %123 @123
1049 %token <FPVal> FPVAL // Float or Double constant
1051 // Built in types...
1052 %type <TypeVal> Types ResultTypes
1053 %type <PrimType> IntType FPType PrimType // Classifications
1054 %token <PrimType> VOID INTTYPE
1055 %token <PrimType> FLOAT DOUBLE LABEL
1058 %token<StrVal> LOCALVAR GLOBALVAR LABELSTR STRINGCONSTANT ATSTRINGCONSTANT
1059 %type <StrVal> LocalName OptLocalName OptLocalAssign
1060 %type <StrVal> GlobalName OptGlobalAssign GlobalAssign
1061 %type <UIntVal> OptAlign OptCAlign
1062 %type <StrVal> OptSection SectionString
1064 %token ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1065 %token DECLARE DEFINE GLOBAL CONSTANT SECTION ALIAS VOLATILE THREAD_LOCAL
1066 %token TO DOTDOTDOT NULL_TOK UNDEF INTERNAL LINKONCE WEAK APPENDING
1067 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1068 %token OPAQUE EXTERNAL TARGET TRIPLE ALIGN
1069 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1070 %token CC_TOK CCC_TOK FASTCC_TOK COLDCC_TOK X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1072 %type <UIntVal> OptCallingConv
1073 %type <ParamAttrs> OptParamAttrs ParamAttr
1074 %type <ParamAttrs> OptFuncAttrs FuncAttr
1076 // Basic Block Terminating Operators
1077 %token <TermOpVal> RET BR SWITCH INVOKE UNWIND UNREACHABLE
1080 %type <BinaryOpVal> ArithmeticOps LogicalOps // Binops Subcatagories
1081 %token <BinaryOpVal> ADD SUB MUL UDIV SDIV FDIV UREM SREM FREM AND OR XOR
1082 %token <BinaryOpVal> SHL LSHR ASHR
1084 %token <OtherOpVal> ICMP FCMP
1085 %type <IPredicate> IPredicates
1086 %type <FPredicate> FPredicates
1087 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1088 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1090 // Memory Instructions
1091 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1094 %type <CastOpVal> CastOps
1095 %token <CastOpVal> TRUNC ZEXT SEXT FPTRUNC FPEXT BITCAST
1096 %token <CastOpVal> UITOFP SITOFP FPTOUI FPTOSI INTTOPTR PTRTOINT
1099 %token <OtherOpVal> PHI_TOK SELECT VAARG
1100 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1102 // Function Attributes
1103 %token NORETURN INREG SRET NOUNWIND
1105 // Visibility Styles
1106 %token DEFAULT HIDDEN
1112 // Operations that are notably excluded from this list include:
1113 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1115 ArithmeticOps: ADD | SUB | MUL | UDIV | SDIV | FDIV | UREM | SREM | FREM;
1116 LogicalOps : SHL | LSHR | ASHR | AND | OR | XOR;
1117 CastOps : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | BITCAST |
1118 UITOFP | SITOFP | FPTOUI | FPTOSI | INTTOPTR | PTRTOINT;
1121 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1122 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1123 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1124 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1125 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1129 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1130 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1131 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1132 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1133 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1134 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1135 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1136 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1137 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1140 // These are some types that allow classification if we only want a particular
1141 // thing... for example, only a signed, unsigned, or integral type.
1143 FPType : FLOAT | DOUBLE;
1145 LocalName : LOCALVAR | STRINGCONSTANT;
1146 OptLocalName : LocalName | /*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; }
1181 : DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1182 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1183 | EXTERNAL { $$ = GlobalValue::ExternalLinkage; }
1187 : /*empty*/ { $$ = GlobalValue::DefaultVisibility; }
1188 | DEFAULT { $$ = GlobalValue::DefaultVisibility; }
1189 | HIDDEN { $$ = GlobalValue::HiddenVisibility; }
1192 FunctionDeclareLinkage
1193 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1194 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1195 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1198 FunctionDefineLinkage
1199 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1200 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1201 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1202 | WEAK { $$ = GlobalValue::WeakLinkage; }
1203 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1207 : /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1208 | WEAK { $$ = GlobalValue::WeakLinkage; }
1209 | INTERNAL { $$ = GlobalValue::InternalLinkage; }
1212 OptCallingConv : /*empty*/ { $$ = CallingConv::C; } |
1213 CCC_TOK { $$ = CallingConv::C; } |
1214 FASTCC_TOK { $$ = CallingConv::Fast; } |
1215 COLDCC_TOK { $$ = CallingConv::Cold; } |
1216 X86_STDCALLCC_TOK { $$ = CallingConv::X86_StdCall; } |
1217 X86_FASTCALLCC_TOK { $$ = CallingConv::X86_FastCall; } |
1219 if ((unsigned)$2 != $2)
1220 GEN_ERROR("Calling conv too large");
1225 ParamAttr : ZEXT { $$ = ParamAttr::ZExt; }
1226 | SEXT { $$ = ParamAttr::SExt; }
1227 | INREG { $$ = ParamAttr::InReg; }
1228 | SRET { $$ = ParamAttr::StructRet; }
1231 OptParamAttrs : /* empty */ { $$ = ParamAttr::None; }
1232 | OptParamAttrs ParamAttr {
1237 FuncAttr : NORETURN { $$ = ParamAttr::NoReturn; }
1238 | NOUNWIND { $$ = ParamAttr::NoUnwind; }
1242 OptFuncAttrs : /* empty */ { $$ = ParamAttr::None; }
1243 | OptFuncAttrs FuncAttr {
1248 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1249 // a comma before it.
1250 OptAlign : /*empty*/ { $$ = 0; } |
1253 if ($$ != 0 && !isPowerOf2_32($$))
1254 GEN_ERROR("Alignment must be a power of two");
1257 OptCAlign : /*empty*/ { $$ = 0; } |
1258 ',' ALIGN EUINT64VAL {
1260 if ($$ != 0 && !isPowerOf2_32($$))
1261 GEN_ERROR("Alignment must be a power of two");
1266 SectionString : SECTION STRINGCONSTANT {
1267 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1268 if ($2[i] == '"' || $2[i] == '\\')
1269 GEN_ERROR("Invalid character in section name");
1274 OptSection : /*empty*/ { $$ = 0; } |
1275 SectionString { $$ = $1; };
1277 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1278 // is set to be the global we are processing.
1280 GlobalVarAttributes : /* empty */ {} |
1281 ',' GlobalVarAttribute GlobalVarAttributes {};
1282 GlobalVarAttribute : SectionString {
1283 CurGV->setSection($1);
1287 | ALIGN EUINT64VAL {
1288 if ($2 != 0 && !isPowerOf2_32($2))
1289 GEN_ERROR("Alignment must be a power of two");
1290 CurGV->setAlignment($2);
1294 //===----------------------------------------------------------------------===//
1295 // Types includes all predefined types... except void, because it can only be
1296 // used in specific contexts (function returning void for example).
1298 // Derived types are added later...
1300 PrimType : INTTYPE | FLOAT | DOUBLE | LABEL ;
1304 $$ = new PATypeHolder(OpaqueType::get());
1308 $$ = new PATypeHolder($1);
1311 | Types '*' { // Pointer type?
1312 if (*$1 == Type::LabelTy)
1313 GEN_ERROR("Cannot form a pointer to a basic block");
1314 $$ = new PATypeHolder(HandleUpRefs(PointerType::get(*$1)));
1318 | SymbolicValueRef { // Named types are also simple types...
1319 const Type* tmp = getTypeVal($1);
1321 $$ = new PATypeHolder(tmp);
1323 | '\\' EUINT64VAL { // Type UpReference
1324 if ($2 > (uint64_t)~0U) GEN_ERROR("Value out of range");
1325 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1326 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1327 $$ = new PATypeHolder(OT);
1328 UR_OUT("New Upreference!\n");
1331 | Types '(' ArgTypeListI ')' {
1332 std::vector<const Type*> Params;
1334 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1335 for (; I != E; ++I, ++index) {
1336 const Type *Ty = I->Ty->get();
1337 Params.push_back(Ty);
1339 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1340 if (isVarArg) Params.pop_back();
1342 FunctionType *FT = FunctionType::get(*$1, Params, isVarArg);
1343 delete $3; // Delete the argument list
1344 delete $1; // Delete the return type handle
1345 $$ = new PATypeHolder(HandleUpRefs(FT));
1348 | VOID '(' ArgTypeListI ')' {
1349 std::vector<const Type*> Params;
1350 TypeWithAttrsList::iterator I = $3->begin(), E = $3->end();
1352 for ( ; I != E; ++I, ++index) {
1353 const Type* Ty = I->Ty->get();
1354 Params.push_back(Ty);
1356 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1357 if (isVarArg) Params.pop_back();
1359 FunctionType *FT = FunctionType::get($1, Params, isVarArg);
1360 delete $3; // Delete the argument list
1361 $$ = new PATypeHolder(HandleUpRefs(FT));
1365 | '[' EUINT64VAL 'x' Types ']' { // Sized array type?
1366 $$ = new PATypeHolder(HandleUpRefs(ArrayType::get(*$4, (unsigned)$2)));
1370 | '<' EUINT64VAL 'x' Types '>' { // Vector type?
1371 const llvm::Type* ElemTy = $4->get();
1372 if ((unsigned)$2 != $2)
1373 GEN_ERROR("Unsigned result not equal to signed result");
1374 if (!ElemTy->isFloatingPoint() && !ElemTy->isInteger())
1375 GEN_ERROR("Element type of a VectorType must be primitive");
1376 if (!isPowerOf2_32($2))
1377 GEN_ERROR("Vector length should be a power of 2");
1378 $$ = new PATypeHolder(HandleUpRefs(VectorType::get(*$4, (unsigned)$2)));
1382 | '{' TypeListI '}' { // Structure type?
1383 std::vector<const Type*> Elements;
1384 for (std::list<llvm::PATypeHolder>::iterator I = $2->begin(),
1385 E = $2->end(); I != E; ++I)
1386 Elements.push_back(*I);
1388 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1392 | '{' '}' { // Empty structure type?
1393 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1396 | '<' '{' TypeListI '}' '>' {
1397 std::vector<const Type*> Elements;
1398 for (std::list<llvm::PATypeHolder>::iterator I = $3->begin(),
1399 E = $3->end(); I != E; ++I)
1400 Elements.push_back(*I);
1402 $$ = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1406 | '<' '{' '}' '>' { // Empty structure type?
1407 $$ = new PATypeHolder(StructType::get(std::vector<const Type*>(), true));
1415 $$.Attrs = ParamAttr::None;
1421 if (!UpRefs.empty())
1422 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1423 if (!(*$1)->isFirstClassType())
1424 GEN_ERROR("LLVM functions cannot return aggregate types");
1428 $$ = new PATypeHolder(Type::VoidTy);
1432 ArgTypeList : ArgType {
1433 $$ = new TypeWithAttrsList();
1437 | ArgTypeList ',' ArgType {
1438 ($$=$1)->push_back($3);
1445 | ArgTypeList ',' DOTDOTDOT {
1447 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1448 TWA.Ty = new PATypeHolder(Type::VoidTy);
1453 $$ = new TypeWithAttrsList;
1454 TypeWithAttrs TWA; TWA.Attrs = ParamAttr::None;
1455 TWA.Ty = new PATypeHolder(Type::VoidTy);
1460 $$ = new TypeWithAttrsList();
1464 // TypeList - Used for struct declarations and as a basis for function type
1465 // declaration type lists
1468 $$ = new std::list<PATypeHolder>();
1473 | TypeListI ',' Types {
1474 ($$=$1)->push_back(*$3);
1479 // ConstVal - The various declarations that go into the constant pool. This
1480 // production is used ONLY to represent constants that show up AFTER a 'const',
1481 // 'constant' or 'global' token at global scope. Constants that can be inlined
1482 // into other expressions (such as integers and constexprs) are handled by the
1483 // ResolvedVal, ValueRef and ConstValueRef productions.
1485 ConstVal: Types '[' ConstVector ']' { // Nonempty unsized arr
1486 if (!UpRefs.empty())
1487 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1488 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1490 GEN_ERROR("Cannot make array constant with type: '" +
1491 (*$1)->getDescription() + "'");
1492 const Type *ETy = ATy->getElementType();
1493 int NumElements = ATy->getNumElements();
1495 // Verify that we have the correct size...
1496 if (NumElements != -1 && NumElements != (int)$3->size())
1497 GEN_ERROR("Type mismatch: constant sized array initialized with " +
1498 utostr($3->size()) + " arguments, but has size of " +
1499 itostr(NumElements) + "");
1501 // Verify all elements are correct type!
1502 for (unsigned i = 0; i < $3->size(); i++) {
1503 if (ETy != (*$3)[i]->getType())
1504 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1505 ETy->getDescription() +"' as required!\nIt is of type '"+
1506 (*$3)[i]->getType()->getDescription() + "'.");
1509 $$ = ConstantArray::get(ATy, *$3);
1510 delete $1; delete $3;
1514 if (!UpRefs.empty())
1515 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1516 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1518 GEN_ERROR("Cannot make array constant with type: '" +
1519 (*$1)->getDescription() + "'");
1521 int NumElements = ATy->getNumElements();
1522 if (NumElements != -1 && NumElements != 0)
1523 GEN_ERROR("Type mismatch: constant sized array initialized with 0"
1524 " arguments, but has size of " + itostr(NumElements) +"");
1525 $$ = ConstantArray::get(ATy, std::vector<Constant*>());
1529 | Types 'c' STRINGCONSTANT {
1530 if (!UpRefs.empty())
1531 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1532 const ArrayType *ATy = dyn_cast<ArrayType>($1->get());
1534 GEN_ERROR("Cannot make array constant with type: '" +
1535 (*$1)->getDescription() + "'");
1537 int NumElements = ATy->getNumElements();
1538 const Type *ETy = ATy->getElementType();
1539 char *EndStr = UnEscapeLexed($3, true);
1540 if (NumElements != -1 && NumElements != (EndStr-$3))
1541 GEN_ERROR("Can't build string constant of size " +
1542 itostr((int)(EndStr-$3)) +
1543 " when array has size " + itostr(NumElements) + "");
1544 std::vector<Constant*> Vals;
1545 if (ETy == Type::Int8Ty) {
1546 for (unsigned char *C = (unsigned char *)$3;
1547 C != (unsigned char*)EndStr; ++C)
1548 Vals.push_back(ConstantInt::get(ETy, *C));
1551 GEN_ERROR("Cannot build string arrays of non byte sized elements");
1554 $$ = ConstantArray::get(ATy, Vals);
1558 | Types '<' ConstVector '>' { // Nonempty unsized arr
1559 if (!UpRefs.empty())
1560 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1561 const VectorType *PTy = dyn_cast<VectorType>($1->get());
1563 GEN_ERROR("Cannot make packed constant with type: '" +
1564 (*$1)->getDescription() + "'");
1565 const Type *ETy = PTy->getElementType();
1566 int NumElements = PTy->getNumElements();
1568 // Verify that we have the correct size...
1569 if (NumElements != -1 && NumElements != (int)$3->size())
1570 GEN_ERROR("Type mismatch: constant sized packed initialized with " +
1571 utostr($3->size()) + " arguments, but has size of " +
1572 itostr(NumElements) + "");
1574 // Verify all elements are correct type!
1575 for (unsigned i = 0; i < $3->size(); i++) {
1576 if (ETy != (*$3)[i]->getType())
1577 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
1578 ETy->getDescription() +"' as required!\nIt is of type '"+
1579 (*$3)[i]->getType()->getDescription() + "'.");
1582 $$ = ConstantVector::get(PTy, *$3);
1583 delete $1; delete $3;
1586 | Types '{' ConstVector '}' {
1587 const StructType *STy = dyn_cast<StructType>($1->get());
1589 GEN_ERROR("Cannot make struct constant with type: '" +
1590 (*$1)->getDescription() + "'");
1592 if ($3->size() != STy->getNumContainedTypes())
1593 GEN_ERROR("Illegal number of initializers for structure type");
1595 // Check to ensure that constants are compatible with the type initializer!
1596 for (unsigned i = 0, e = $3->size(); i != e; ++i)
1597 if ((*$3)[i]->getType() != STy->getElementType(i))
1598 GEN_ERROR("Expected type '" +
1599 STy->getElementType(i)->getDescription() +
1600 "' for element #" + utostr(i) +
1601 " of structure initializer");
1603 // Check to ensure that Type is not packed
1604 if (STy->isPacked())
1605 GEN_ERROR("Unpacked Initializer to vector type '" +
1606 STy->getDescription() + "'");
1608 $$ = ConstantStruct::get(STy, *$3);
1609 delete $1; delete $3;
1613 if (!UpRefs.empty())
1614 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1615 const StructType *STy = dyn_cast<StructType>($1->get());
1617 GEN_ERROR("Cannot make struct constant with type: '" +
1618 (*$1)->getDescription() + "'");
1620 if (STy->getNumContainedTypes() != 0)
1621 GEN_ERROR("Illegal number of initializers for structure type");
1623 // Check to ensure that Type is not packed
1624 if (STy->isPacked())
1625 GEN_ERROR("Unpacked Initializer to vector type '" +
1626 STy->getDescription() + "'");
1628 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1632 | Types '<' '{' ConstVector '}' '>' {
1633 const StructType *STy = dyn_cast<StructType>($1->get());
1635 GEN_ERROR("Cannot make struct constant with type: '" +
1636 (*$1)->getDescription() + "'");
1638 if ($4->size() != STy->getNumContainedTypes())
1639 GEN_ERROR("Illegal number of initializers for structure type");
1641 // Check to ensure that constants are compatible with the type initializer!
1642 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1643 if ((*$4)[i]->getType() != STy->getElementType(i))
1644 GEN_ERROR("Expected type '" +
1645 STy->getElementType(i)->getDescription() +
1646 "' for element #" + utostr(i) +
1647 " of structure initializer");
1649 // Check to ensure that Type is packed
1650 if (!STy->isPacked())
1651 GEN_ERROR("Vector initializer to non-vector type '" +
1652 STy->getDescription() + "'");
1654 $$ = ConstantStruct::get(STy, *$4);
1655 delete $1; delete $4;
1658 | Types '<' '{' '}' '>' {
1659 if (!UpRefs.empty())
1660 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1661 const StructType *STy = dyn_cast<StructType>($1->get());
1663 GEN_ERROR("Cannot make struct constant with type: '" +
1664 (*$1)->getDescription() + "'");
1666 if (STy->getNumContainedTypes() != 0)
1667 GEN_ERROR("Illegal number of initializers for structure type");
1669 // Check to ensure that Type is packed
1670 if (!STy->isPacked())
1671 GEN_ERROR("Vector initializer to non-vector type '" +
1672 STy->getDescription() + "'");
1674 $$ = ConstantStruct::get(STy, std::vector<Constant*>());
1679 if (!UpRefs.empty())
1680 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1681 const PointerType *PTy = dyn_cast<PointerType>($1->get());
1683 GEN_ERROR("Cannot make null pointer constant with type: '" +
1684 (*$1)->getDescription() + "'");
1686 $$ = ConstantPointerNull::get(PTy);
1691 if (!UpRefs.empty())
1692 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1693 $$ = UndefValue::get($1->get());
1697 | Types SymbolicValueRef {
1698 if (!UpRefs.empty())
1699 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1700 const PointerType *Ty = dyn_cast<PointerType>($1->get());
1702 GEN_ERROR("Global const reference must be a pointer type");
1704 // ConstExprs can exist in the body of a function, thus creating
1705 // GlobalValues whenever they refer to a variable. Because we are in
1706 // the context of a function, getExistingVal will search the functions
1707 // symbol table instead of the module symbol table for the global symbol,
1708 // which throws things all off. To get around this, we just tell
1709 // getExistingVal that we are at global scope here.
1711 Function *SavedCurFn = CurFun.CurrentFunction;
1712 CurFun.CurrentFunction = 0;
1714 Value *V = getExistingVal(Ty, $2);
1717 CurFun.CurrentFunction = SavedCurFn;
1719 // If this is an initializer for a constant pointer, which is referencing a
1720 // (currently) undefined variable, create a stub now that shall be replaced
1721 // in the future with the right type of variable.
1724 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers!");
1725 const PointerType *PT = cast<PointerType>(Ty);
1727 // First check to see if the forward references value is already created!
1728 PerModuleInfo::GlobalRefsType::iterator I =
1729 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
1731 if (I != CurModule.GlobalRefs.end()) {
1732 V = I->second; // Placeholder already exists, use it...
1736 if ($2.Type == ValID::GlobalName)
1738 else if ($2.Type != ValID::GlobalID)
1739 GEN_ERROR("Invalid reference to global");
1741 // Create the forward referenced global.
1743 if (const FunctionType *FTy =
1744 dyn_cast<FunctionType>(PT->getElementType())) {
1745 GV = new Function(FTy, GlobalValue::ExternalWeakLinkage, Name,
1746 CurModule.CurrentModule);
1748 GV = new GlobalVariable(PT->getElementType(), false,
1749 GlobalValue::ExternalWeakLinkage, 0,
1750 Name, CurModule.CurrentModule);
1753 // Keep track of the fact that we have a forward ref to recycle it
1754 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
1759 $$ = cast<GlobalValue>(V);
1760 delete $1; // Free the type handle
1764 if (!UpRefs.empty())
1765 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1766 if ($1->get() != $2->getType())
1767 GEN_ERROR("Mismatched types for constant expression: " +
1768 (*$1)->getDescription() + " and " + $2->getType()->getDescription());
1773 | Types ZEROINITIALIZER {
1774 if (!UpRefs.empty())
1775 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
1776 const Type *Ty = $1->get();
1777 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
1778 GEN_ERROR("Cannot create a null initialized value of this type");
1779 $$ = Constant::getNullValue(Ty);
1783 | IntType ESINT64VAL { // integral constants
1784 if (!ConstantInt::isValueValidForType($1, $2))
1785 GEN_ERROR("Constant value doesn't fit in type");
1786 $$ = ConstantInt::get($1, $2, true);
1789 | IntType ESAPINTVAL { // arbitrary precision integer constants
1790 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1791 if ($2->getBitWidth() > BitWidth) {
1792 GEN_ERROR("Constant value does not fit in type");
1794 $2->sextOrTrunc(BitWidth);
1795 $$ = ConstantInt::get(*$2);
1799 | IntType EUINT64VAL { // integral constants
1800 if (!ConstantInt::isValueValidForType($1, $2))
1801 GEN_ERROR("Constant value doesn't fit in type");
1802 $$ = ConstantInt::get($1, $2, false);
1805 | IntType EUAPINTVAL { // arbitrary precision integer constants
1806 uint32_t BitWidth = cast<IntegerType>($1)->getBitWidth();
1807 if ($2->getBitWidth() > BitWidth) {
1808 GEN_ERROR("Constant value does not fit in type");
1810 $2->zextOrTrunc(BitWidth);
1811 $$ = ConstantInt::get(*$2);
1815 | INTTYPE TRUETOK { // Boolean constants
1816 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1817 $$ = ConstantInt::getTrue();
1820 | INTTYPE FALSETOK { // Boolean constants
1821 assert(cast<IntegerType>($1)->getBitWidth() == 1 && "Not Bool?");
1822 $$ = ConstantInt::getFalse();
1825 | FPType FPVAL { // Float & Double constants
1826 if (!ConstantFP::isValueValidForType($1, $2))
1827 GEN_ERROR("Floating point constant invalid for type");
1828 $$ = ConstantFP::get($1, $2);
1833 ConstExpr: CastOps '(' ConstVal TO Types ')' {
1834 if (!UpRefs.empty())
1835 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
1837 const Type *DestTy = $5->get();
1838 if (!CastInst::castIsValid($1, $3, DestTy))
1839 GEN_ERROR("invalid cast opcode for cast from '" +
1840 Val->getType()->getDescription() + "' to '" +
1841 DestTy->getDescription() + "'");
1842 $$ = ConstantExpr::getCast($1, $3, DestTy);
1845 | GETELEMENTPTR '(' ConstVal IndexList ')' {
1846 if (!isa<PointerType>($3->getType()))
1847 GEN_ERROR("GetElementPtr requires a pointer operand");
1850 GetElementPtrInst::getIndexedType($3->getType(), &(*$4)[0], $4->size(),
1853 GEN_ERROR("Index list invalid for constant getelementptr");
1855 SmallVector<Constant*, 8> IdxVec;
1856 for (unsigned i = 0, e = $4->size(); i != e; ++i)
1857 if (Constant *C = dyn_cast<Constant>((*$4)[i]))
1858 IdxVec.push_back(C);
1860 GEN_ERROR("Indices to constant getelementptr must be constants");
1864 $$ = ConstantExpr::getGetElementPtr($3, &IdxVec[0], IdxVec.size());
1867 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1868 if ($3->getType() != Type::Int1Ty)
1869 GEN_ERROR("Select condition must be of boolean type");
1870 if ($5->getType() != $7->getType())
1871 GEN_ERROR("Select operand types must match");
1872 $$ = ConstantExpr::getSelect($3, $5, $7);
1875 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
1876 if ($3->getType() != $5->getType())
1877 GEN_ERROR("Binary operator types must match");
1879 $$ = ConstantExpr::get($1, $3, $5);
1881 | LogicalOps '(' ConstVal ',' ConstVal ')' {
1882 if ($3->getType() != $5->getType())
1883 GEN_ERROR("Logical operator types must match");
1884 if (!$3->getType()->isInteger()) {
1885 if (Instruction::isShift($1) || !isa<VectorType>($3->getType()) ||
1886 !cast<VectorType>($3->getType())->getElementType()->isInteger())
1887 GEN_ERROR("Logical operator requires integral operands");
1889 $$ = ConstantExpr::get($1, $3, $5);
1892 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
1893 if ($4->getType() != $6->getType())
1894 GEN_ERROR("icmp operand types must match");
1895 $$ = ConstantExpr::getICmp($2, $4, $6);
1897 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
1898 if ($4->getType() != $6->getType())
1899 GEN_ERROR("fcmp operand types must match");
1900 $$ = ConstantExpr::getFCmp($2, $4, $6);
1902 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
1903 if (!ExtractElementInst::isValidOperands($3, $5))
1904 GEN_ERROR("Invalid extractelement operands");
1905 $$ = ConstantExpr::getExtractElement($3, $5);
1908 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1909 if (!InsertElementInst::isValidOperands($3, $5, $7))
1910 GEN_ERROR("Invalid insertelement operands");
1911 $$ = ConstantExpr::getInsertElement($3, $5, $7);
1914 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
1915 if (!ShuffleVectorInst::isValidOperands($3, $5, $7))
1916 GEN_ERROR("Invalid shufflevector operands");
1917 $$ = ConstantExpr::getShuffleVector($3, $5, $7);
1922 // ConstVector - A list of comma separated constants.
1923 ConstVector : ConstVector ',' ConstVal {
1924 ($$ = $1)->push_back($3);
1928 $$ = new std::vector<Constant*>();
1934 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
1935 GlobalType : GLOBAL { $$ = false; } | CONSTANT { $$ = true; };
1938 ThreadLocal : THREAD_LOCAL { $$ = true; } | { $$ = false; };
1940 // AliaseeRef - Match either GlobalValue or bitcast to GlobalValue.
1941 AliaseeRef : ResultTypes SymbolicValueRef {
1942 const Type* VTy = $1->get();
1943 Value *V = getVal(VTy, $2);
1944 GlobalValue* Aliasee = dyn_cast<GlobalValue>(V);
1946 GEN_ERROR("Aliases can be created only to global values");
1952 | BITCAST '(' AliaseeRef TO Types ')' {
1954 const Type *DestTy = $5->get();
1955 if (!CastInst::castIsValid($1, $3, DestTy))
1956 GEN_ERROR("invalid cast opcode for cast from '" +
1957 Val->getType()->getDescription() + "' to '" +
1958 DestTy->getDescription() + "'");
1960 $$ = ConstantExpr::getCast($1, $3, DestTy);
1965 //===----------------------------------------------------------------------===//
1966 // Rules to match Modules
1967 //===----------------------------------------------------------------------===//
1969 // Module rule: Capture the result of parsing the whole file into a result
1974 $$ = ParserResult = CurModule.CurrentModule;
1975 CurModule.ModuleDone();
1979 $$ = ParserResult = CurModule.CurrentModule;
1980 CurModule.ModuleDone();
1987 | DefinitionList Definition
1991 : DEFINE { CurFun.isDeclare = false; } Function {
1992 CurFun.FunctionDone();
1995 | DECLARE { CurFun.isDeclare = true; } FunctionProto {
1998 | MODULE ASM_TOK AsmBlock {
2001 | OptLocalAssign TYPE Types {
2002 if (!UpRefs.empty())
2003 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2004 // Eagerly resolve types. This is not an optimization, this is a
2005 // requirement that is due to the fact that we could have this:
2007 // %list = type { %list * }
2008 // %list = type { %list * } ; repeated type decl
2010 // If types are not resolved eagerly, then the two types will not be
2011 // determined to be the same type!
2013 ResolveTypeTo($1, *$3);
2015 if (!setTypeName(*$3, $1) && !$1) {
2017 // If this is a named type that is not a redefinition, add it to the slot
2019 CurModule.Types.push_back(*$3);
2025 | OptLocalAssign TYPE VOID {
2026 ResolveTypeTo($1, $3);
2028 if (!setTypeName($3, $1) && !$1) {
2030 // If this is a named type that is not a redefinition, add it to the slot
2032 CurModule.Types.push_back($3);
2036 | OptGlobalAssign GVVisibilityStyle ThreadLocal GlobalType ConstVal {
2037 /* "Externally Visible" Linkage */
2039 GEN_ERROR("Global value initializer is not a constant");
2040 CurGV = ParseGlobalVariable($1, GlobalValue::ExternalLinkage,
2041 $2, $4, $5->getType(), $5, $3);
2043 } GlobalVarAttributes {
2046 | OptGlobalAssign GVInternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2049 GEN_ERROR("Global value initializer is not a constant");
2050 CurGV = ParseGlobalVariable($1, $2, $3, $5, $6->getType(), $6, $4);
2052 } GlobalVarAttributes {
2055 | OptGlobalAssign GVExternalLinkage GVVisibilityStyle ThreadLocal GlobalType
2057 if (!UpRefs.empty())
2058 GEN_ERROR("Invalid upreference in type: " + (*$6)->getDescription());
2059 CurGV = ParseGlobalVariable($1, $2, $3, $5, *$6, 0, $4);
2062 } GlobalVarAttributes {
2066 | OptGlobalAssign GVVisibilityStyle ALIAS AliasLinkage AliaseeRef {
2067 std::string Name($1);
2069 GEN_ERROR("Alias name cannot be empty");
2071 Constant* Aliasee = $5;
2073 GEN_ERROR(std::string("Invalid aliasee for alias: ") + $1);
2075 GlobalAlias* GA = new GlobalAlias(Aliasee->getType(), $4, Name, Aliasee,
2076 CurModule.CurrentModule);
2077 GA->setVisibility($2);
2078 InsertValue(GA, CurModule.Values);
2081 | TARGET TargetDefinition {
2084 | DEPLIBS '=' LibrariesDefinition {
2090 AsmBlock : STRINGCONSTANT {
2091 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2092 char *EndStr = UnEscapeLexed($1, true);
2093 std::string NewAsm($1, EndStr);
2096 if (AsmSoFar.empty())
2097 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2099 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2103 TargetDefinition : TRIPLE '=' STRINGCONSTANT {
2104 CurModule.CurrentModule->setTargetTriple($3);
2107 | DATALAYOUT '=' STRINGCONSTANT {
2108 CurModule.CurrentModule->setDataLayout($3);
2112 LibrariesDefinition : '[' LibList ']';
2114 LibList : LibList ',' STRINGCONSTANT {
2115 CurModule.CurrentModule->addLibrary($3);
2120 CurModule.CurrentModule->addLibrary($1);
2124 | /* empty: end of list */ {
2129 //===----------------------------------------------------------------------===//
2130 // Rules to match Function Headers
2131 //===----------------------------------------------------------------------===//
2133 ArgListH : ArgListH ',' Types OptParamAttrs OptLocalName {
2134 if (!UpRefs.empty())
2135 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2136 if (*$3 == Type::VoidTy)
2137 GEN_ERROR("void typed arguments are invalid");
2138 ArgListEntry E; E.Attrs = $4; E.Ty = $3; E.Name = $5;
2143 | Types OptParamAttrs OptLocalName {
2144 if (!UpRefs.empty())
2145 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2146 if (*$1 == Type::VoidTy)
2147 GEN_ERROR("void typed arguments are invalid");
2148 ArgListEntry E; E.Attrs = $2; E.Ty = $1; E.Name = $3;
2149 $$ = new ArgListType;
2154 ArgList : ArgListH {
2158 | ArgListH ',' DOTDOTDOT {
2160 struct ArgListEntry E;
2161 E.Ty = new PATypeHolder(Type::VoidTy);
2163 E.Attrs = ParamAttr::None;
2168 $$ = new ArgListType;
2169 struct ArgListEntry E;
2170 E.Ty = new PATypeHolder(Type::VoidTy);
2172 E.Attrs = ParamAttr::None;
2181 FunctionHeaderH : OptCallingConv ResultTypes GlobalName '(' ArgList ')'
2182 OptFuncAttrs OptSection OptAlign {
2184 std::string FunctionName($3);
2185 free($3); // Free strdup'd memory!
2187 // Check the function result for abstractness if this is a define. We should
2188 // have no abstract types at this point
2189 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved($2))
2190 GEN_ERROR("Reference to abstract result: "+ $2->get()->getDescription());
2192 std::vector<const Type*> ParamTypeList;
2193 ParamAttrsVector Attrs;
2194 if ($7 != ParamAttr::None) {
2195 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $7;
2196 Attrs.push_back(PAWI);
2198 if ($5) { // If there are arguments...
2200 for (ArgListType::iterator I = $5->begin(); I != $5->end(); ++I, ++index) {
2201 const Type* Ty = I->Ty->get();
2202 if (!CurFun.isDeclare && CurModule.TypeIsUnresolved(I->Ty))
2203 GEN_ERROR("Reference to abstract argument: " + Ty->getDescription());
2204 ParamTypeList.push_back(Ty);
2205 if (Ty != Type::VoidTy)
2206 if (I->Attrs != ParamAttr::None) {
2207 ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = I->Attrs;
2208 Attrs.push_back(PAWI);
2213 bool isVarArg = ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2214 if (isVarArg) ParamTypeList.pop_back();
2216 ParamAttrsList *PAL = 0;
2218 PAL = ParamAttrsList::get(Attrs);
2220 FunctionType *FT = FunctionType::get(*$2, ParamTypeList, isVarArg);
2221 const PointerType *PFT = PointerType::get(FT);
2225 if (!FunctionName.empty()) {
2226 ID = ValID::createGlobalName((char*)FunctionName.c_str());
2228 ID = ValID::createGlobalID(CurModule.Values.size());
2232 // See if this function was forward referenced. If so, recycle the object.
2233 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, PAL, ID)) {
2234 // Move the function to the end of the list, from whereever it was
2235 // previously inserted.
2236 Fn = cast<Function>(FWRef);
2237 CurModule.CurrentModule->getFunctionList().remove(Fn);
2238 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2239 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2240 (Fn = CurModule.CurrentModule->getFunction(FunctionName))) {
2241 if (Fn->getFunctionType() != FT || PAL != Fn->getParamAttrs()) {
2242 // The existing function doesn't have the same type. This is an overload
2244 GEN_ERROR("Overload of function '" + FunctionName + "' not permitted.");
2245 } else if (!CurFun.isDeclare && !Fn->isDeclaration()) {
2246 // Neither the existing or the current function is a declaration and they
2247 // have the same name and same type. Clearly this is a redefinition.
2248 GEN_ERROR("Redefinition of function '" + FunctionName + "'");
2249 } if (Fn->isDeclaration()) {
2250 // Make sure to strip off any argument names so we can't get conflicts.
2251 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2255 } else { // Not already defined?
2256 Fn = new Function(FT, GlobalValue::ExternalWeakLinkage, FunctionName,
2257 CurModule.CurrentModule);
2258 Fn->setParamAttrs(PAL);
2260 InsertValue(Fn, CurModule.Values);
2263 CurFun.FunctionStart(Fn);
2265 if (CurFun.isDeclare) {
2266 // If we have declaration, always overwrite linkage. This will allow us to
2267 // correctly handle cases, when pointer to function is passed as argument to
2268 // another function.
2269 Fn->setLinkage(CurFun.Linkage);
2270 Fn->setVisibility(CurFun.Visibility);
2272 Fn->setCallingConv($1);
2273 Fn->setAlignment($9);
2279 // Add all of the arguments we parsed to the function...
2280 if ($5) { // Is null if empty...
2281 if (isVarArg) { // Nuke the last entry
2282 assert($5->back().Ty->get() == Type::VoidTy && $5->back().Name == 0 &&
2283 "Not a varargs marker!");
2284 delete $5->back().Ty;
2285 $5->pop_back(); // Delete the last entry
2287 Function::arg_iterator ArgIt = Fn->arg_begin();
2288 Function::arg_iterator ArgEnd = Fn->arg_end();
2290 for (ArgListType::iterator I = $5->begin();
2291 I != $5->end() && ArgIt != ArgEnd; ++I, ++ArgIt) {
2292 delete I->Ty; // Delete the typeholder...
2293 setValueName(ArgIt, I->Name); // Insert arg into symtab...
2299 delete $5; // We're now done with the argument list
2304 BEGIN : BEGINTOK | '{'; // Allow BEGIN or '{' to start a function
2306 FunctionHeader : FunctionDefineLinkage GVVisibilityStyle FunctionHeaderH BEGIN {
2307 $$ = CurFun.CurrentFunction;
2309 // Make sure that we keep track of the linkage type even if there was a
2310 // previous "declare".
2312 $$->setVisibility($2);
2315 END : ENDTOK | '}'; // Allow end of '}' to end a function
2317 Function : BasicBlockList END {
2322 FunctionProto : FunctionDeclareLinkage GVVisibilityStyle FunctionHeaderH {
2323 CurFun.CurrentFunction->setLinkage($1);
2324 CurFun.CurrentFunction->setVisibility($2);
2325 $$ = CurFun.CurrentFunction;
2326 CurFun.FunctionDone();
2330 //===----------------------------------------------------------------------===//
2331 // Rules to match Basic Blocks
2332 //===----------------------------------------------------------------------===//
2334 OptSideEffect : /* empty */ {
2343 ConstValueRef : ESINT64VAL { // A reference to a direct constant
2344 $$ = ValID::create($1);
2348 $$ = ValID::create($1);
2351 | FPVAL { // Perhaps it's an FP constant?
2352 $$ = ValID::create($1);
2356 $$ = ValID::create(ConstantInt::getTrue());
2360 $$ = ValID::create(ConstantInt::getFalse());
2364 $$ = ValID::createNull();
2368 $$ = ValID::createUndef();
2371 | ZEROINITIALIZER { // A vector zero constant.
2372 $$ = ValID::createZeroInit();
2375 | '<' ConstVector '>' { // Nonempty unsized packed vector
2376 const Type *ETy = (*$2)[0]->getType();
2377 int NumElements = $2->size();
2379 VectorType* pt = VectorType::get(ETy, NumElements);
2380 PATypeHolder* PTy = new PATypeHolder(
2388 // Verify all elements are correct type!
2389 for (unsigned i = 0; i < $2->size(); i++) {
2390 if (ETy != (*$2)[i]->getType())
2391 GEN_ERROR("Element #" + utostr(i) + " is not of type '" +
2392 ETy->getDescription() +"' as required!\nIt is of type '" +
2393 (*$2)[i]->getType()->getDescription() + "'.");
2396 $$ = ValID::create(ConstantVector::get(pt, *$2));
2397 delete PTy; delete $2;
2401 $$ = ValID::create($1);
2404 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2405 char *End = UnEscapeLexed($3, true);
2406 std::string AsmStr = std::string($3, End);
2407 End = UnEscapeLexed($5, true);
2408 std::string Constraints = std::string($5, End);
2409 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2415 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2418 SymbolicValueRef : LOCALVAL_ID { // Is it an integer reference...?
2419 $$ = ValID::createLocalID($1);
2423 $$ = ValID::createGlobalID($1);
2426 | LocalName { // Is it a named reference...?
2427 $$ = ValID::createLocalName($1);
2430 | GlobalName { // Is it a named reference...?
2431 $$ = ValID::createGlobalName($1);
2435 // ValueRef - A reference to a definition... either constant or symbolic
2436 ValueRef : SymbolicValueRef | ConstValueRef;
2439 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2440 // type immediately preceeds the value reference, and allows complex constant
2441 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2442 ResolvedVal : Types ValueRef {
2443 if (!UpRefs.empty())
2444 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2445 $$ = getVal(*$1, $2);
2451 BasicBlockList : BasicBlockList BasicBlock {
2455 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2461 // Basic blocks are terminated by branching instructions:
2462 // br, br/cc, switch, ret
2464 BasicBlock : InstructionList OptLocalAssign BBTerminatorInst {
2465 setValueName($3, $2);
2468 $1->getInstList().push_back($3);
2473 InstructionList : InstructionList Inst {
2474 if (CastInst *CI1 = dyn_cast<CastInst>($2))
2475 if (CastInst *CI2 = dyn_cast<CastInst>(CI1->getOperand(0)))
2476 if (CI2->getParent() == 0)
2477 $1->getInstList().push_back(CI2);
2478 $1->getInstList().push_back($2);
2482 | /* empty */ { // Empty space between instruction lists
2483 $$ = defineBBVal(ValID::createLocalID(CurFun.NextValNum));
2486 | LABELSTR { // Labelled (named) basic block
2487 $$ = defineBBVal(ValID::createLocalName($1));
2491 BBTerminatorInst : RET ResolvedVal { // Return with a result...
2492 $$ = new ReturnInst($2);
2495 | RET VOID { // Return with no result...
2496 $$ = new ReturnInst();
2499 | BR LABEL ValueRef { // Unconditional Branch...
2500 BasicBlock* tmpBB = getBBVal($3);
2502 $$ = new BranchInst(tmpBB);
2503 } // Conditional Branch...
2504 | BR INTTYPE ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2505 assert(cast<IntegerType>($2)->getBitWidth() == 1 && "Not Bool?");
2506 BasicBlock* tmpBBA = getBBVal($6);
2508 BasicBlock* tmpBBB = getBBVal($9);
2510 Value* tmpVal = getVal(Type::Int1Ty, $3);
2512 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2514 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2515 Value* tmpVal = getVal($2, $3);
2517 BasicBlock* tmpBB = getBBVal($6);
2519 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2522 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2524 for (; I != E; ++I) {
2525 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2526 S->addCase(CI, I->second);
2528 GEN_ERROR("Switch case is constant, but not a simple integer");
2533 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2534 Value* tmpVal = getVal($2, $3);
2536 BasicBlock* tmpBB = getBBVal($6);
2538 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2542 | INVOKE OptCallingConv ResultTypes ValueRef '(' ValueRefList ')' OptFuncAttrs
2543 TO LABEL ValueRef UNWIND LABEL ValueRef {
2545 // Handle the short syntax
2546 const PointerType *PFTy = 0;
2547 const FunctionType *Ty = 0;
2548 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2549 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2550 // Pull out the types of all of the arguments...
2551 std::vector<const Type*> ParamTypes;
2552 ValueRefList::iterator I = $6->begin(), E = $6->end();
2553 for (; I != E; ++I) {
2554 const Type *Ty = I->Val->getType();
2555 if (Ty == Type::VoidTy)
2556 GEN_ERROR("Short call syntax cannot be used with varargs");
2557 ParamTypes.push_back(Ty);
2559 Ty = FunctionType::get($3->get(), ParamTypes, false);
2560 PFTy = PointerType::get(Ty);
2565 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2567 BasicBlock *Normal = getBBVal($11);
2569 BasicBlock *Except = getBBVal($14);
2572 ParamAttrsVector Attrs;
2573 if ($8 != ParamAttr::None) {
2574 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = 8;
2575 Attrs.push_back(PAWI);
2578 // Check the arguments
2580 if ($6->empty()) { // Has no arguments?
2581 // Make sure no arguments is a good thing!
2582 if (Ty->getNumParams() != 0)
2583 GEN_ERROR("No arguments passed to a function that "
2584 "expects arguments");
2585 } else { // Has arguments?
2586 // Loop through FunctionType's arguments and ensure they are specified
2588 FunctionType::param_iterator I = Ty->param_begin();
2589 FunctionType::param_iterator E = Ty->param_end();
2590 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2592 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2593 if (ArgI->Val->getType() != *I)
2594 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2595 (*I)->getDescription() + "'");
2596 Args.push_back(ArgI->Val);
2597 if (ArgI->Attrs != ParamAttr::None) {
2598 ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = ArgI->Attrs;
2599 Attrs.push_back(PAWI);
2603 if (Ty->isVarArg()) {
2605 for (; ArgI != ArgE; ++ArgI)
2606 Args.push_back(ArgI->Val); // push the remaining varargs
2607 } else if (I != E || ArgI != ArgE)
2608 GEN_ERROR("Invalid number of parameters detected");
2611 ParamAttrsList *PAL = 0;
2613 PAL = ParamAttrsList::get(Attrs);
2614 if (isa<Function>(V))
2615 if (PAL != cast<Function>(V)->getParamAttrs())
2616 GEN_ERROR("Invalid parameter attributes for function invoked");
2618 // Create the InvokeInst
2619 InvokeInst *II = new InvokeInst(V, Normal, Except, &Args[0], Args.size());
2620 II->setCallingConv($2);
2621 II->setParamAttrs(PAL);
2627 $$ = new UnwindInst();
2631 $$ = new UnreachableInst();
2637 JumpTable : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2639 Constant *V = cast<Constant>(getExistingVal($2, $3));
2642 GEN_ERROR("May only switch on a constant pool value");
2644 BasicBlock* tmpBB = getBBVal($6);
2646 $$->push_back(std::make_pair(V, tmpBB));
2648 | IntType ConstValueRef ',' LABEL ValueRef {
2649 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2650 Constant *V = cast<Constant>(getExistingVal($1, $2));
2654 GEN_ERROR("May only switch on a constant pool value");
2656 BasicBlock* tmpBB = getBBVal($5);
2658 $$->push_back(std::make_pair(V, tmpBB));
2661 Inst : OptLocalAssign InstVal {
2662 // Is this definition named?? if so, assign the name...
2663 setValueName($2, $1);
2671 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2672 if (!UpRefs.empty())
2673 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2674 $$ = new std::list<std::pair<Value*, BasicBlock*> >();
2675 Value* tmpVal = getVal(*$1, $3);
2677 BasicBlock* tmpBB = getBBVal($5);
2679 $$->push_back(std::make_pair(tmpVal, tmpBB));
2682 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2684 Value* tmpVal = getVal($1->front().first->getType(), $4);
2686 BasicBlock* tmpBB = getBBVal($6);
2688 $1->push_back(std::make_pair(tmpVal, tmpBB));
2692 ValueRefList : Types ValueRef OptParamAttrs {
2693 if (!UpRefs.empty())
2694 GEN_ERROR("Invalid upreference in type: " + (*$1)->getDescription());
2695 // Used for call and invoke instructions
2696 $$ = new ValueRefList();
2697 ValueRefListEntry E; E.Attrs = $3; E.Val = getVal($1->get(), $2);
2701 | ValueRefList ',' Types ValueRef OptParamAttrs {
2702 if (!UpRefs.empty())
2703 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2705 ValueRefListEntry E; E.Attrs = $5; E.Val = getVal($3->get(), $4);
2710 | /*empty*/ { $$ = new ValueRefList(); };
2712 IndexList // Used for gep instructions and constant expressions
2713 : /*empty*/ { $$ = new std::vector<Value*>(); }
2714 | IndexList ',' ResolvedVal {
2721 OptTailCall : TAIL CALL {
2730 InstVal : ArithmeticOps Types ValueRef ',' ValueRef {
2731 if (!UpRefs.empty())
2732 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2733 if (!(*$2)->isInteger() && !(*$2)->isFloatingPoint() &&
2734 !isa<VectorType>((*$2).get()))
2736 "Arithmetic operator requires integer, FP, or packed operands");
2737 if (isa<VectorType>((*$2).get()) &&
2738 ($1 == Instruction::URem ||
2739 $1 == Instruction::SRem ||
2740 $1 == Instruction::FRem))
2741 GEN_ERROR("Remainder not supported on vector types");
2742 Value* val1 = getVal(*$2, $3);
2744 Value* val2 = getVal(*$2, $5);
2746 $$ = BinaryOperator::create($1, val1, val2);
2748 GEN_ERROR("binary operator returned null");
2751 | LogicalOps Types ValueRef ',' ValueRef {
2752 if (!UpRefs.empty())
2753 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2754 if (!(*$2)->isInteger()) {
2755 if (Instruction::isShift($1) || !isa<VectorType>($2->get()) ||
2756 !cast<VectorType>($2->get())->getElementType()->isInteger())
2757 GEN_ERROR("Logical operator requires integral operands");
2759 Value* tmpVal1 = getVal(*$2, $3);
2761 Value* tmpVal2 = getVal(*$2, $5);
2763 $$ = BinaryOperator::create($1, tmpVal1, tmpVal2);
2765 GEN_ERROR("binary operator returned null");
2768 | ICMP IPredicates Types ValueRef ',' ValueRef {
2769 if (!UpRefs.empty())
2770 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2771 if (isa<VectorType>((*$3).get()))
2772 GEN_ERROR("Vector types not supported by icmp instruction");
2773 Value* tmpVal1 = getVal(*$3, $4);
2775 Value* tmpVal2 = getVal(*$3, $6);
2777 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2779 GEN_ERROR("icmp operator returned null");
2782 | FCMP FPredicates Types ValueRef ',' ValueRef {
2783 if (!UpRefs.empty())
2784 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
2785 if (isa<VectorType>((*$3).get()))
2786 GEN_ERROR("Vector types not supported by fcmp instruction");
2787 Value* tmpVal1 = getVal(*$3, $4);
2789 Value* tmpVal2 = getVal(*$3, $6);
2791 $$ = CmpInst::create($1, $2, tmpVal1, tmpVal2);
2793 GEN_ERROR("fcmp operator returned null");
2796 | CastOps ResolvedVal TO Types {
2797 if (!UpRefs.empty())
2798 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2800 const Type* DestTy = $4->get();
2801 if (!CastInst::castIsValid($1, Val, DestTy))
2802 GEN_ERROR("invalid cast opcode for cast from '" +
2803 Val->getType()->getDescription() + "' to '" +
2804 DestTy->getDescription() + "'");
2805 $$ = CastInst::create($1, Val, DestTy);
2808 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2809 if ($2->getType() != Type::Int1Ty)
2810 GEN_ERROR("select condition must be boolean");
2811 if ($4->getType() != $6->getType())
2812 GEN_ERROR("select value types should match");
2813 $$ = new SelectInst($2, $4, $6);
2816 | VAARG ResolvedVal ',' Types {
2817 if (!UpRefs.empty())
2818 GEN_ERROR("Invalid upreference in type: " + (*$4)->getDescription());
2819 $$ = new VAArgInst($2, *$4);
2823 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
2824 if (!ExtractElementInst::isValidOperands($2, $4))
2825 GEN_ERROR("Invalid extractelement operands");
2826 $$ = new ExtractElementInst($2, $4);
2829 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2830 if (!InsertElementInst::isValidOperands($2, $4, $6))
2831 GEN_ERROR("Invalid insertelement operands");
2832 $$ = new InsertElementInst($2, $4, $6);
2835 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
2836 if (!ShuffleVectorInst::isValidOperands($2, $4, $6))
2837 GEN_ERROR("Invalid shufflevector operands");
2838 $$ = new ShuffleVectorInst($2, $4, $6);
2842 const Type *Ty = $2->front().first->getType();
2843 if (!Ty->isFirstClassType())
2844 GEN_ERROR("PHI node operands must be of first class type");
2845 $$ = new PHINode(Ty);
2846 ((PHINode*)$$)->reserveOperandSpace($2->size());
2847 while ($2->begin() != $2->end()) {
2848 if ($2->front().first->getType() != Ty)
2849 GEN_ERROR("All elements of a PHI node must be of the same type");
2850 cast<PHINode>($$)->addIncoming($2->front().first, $2->front().second);
2853 delete $2; // Free the list...
2856 | OptTailCall OptCallingConv ResultTypes ValueRef '(' ValueRefList ')'
2859 // Handle the short syntax
2860 const PointerType *PFTy = 0;
2861 const FunctionType *Ty = 0;
2862 if (!(PFTy = dyn_cast<PointerType>($3->get())) ||
2863 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2864 // Pull out the types of all of the arguments...
2865 std::vector<const Type*> ParamTypes;
2866 ValueRefList::iterator I = $6->begin(), E = $6->end();
2867 for (; I != E; ++I) {
2868 const Type *Ty = I->Val->getType();
2869 if (Ty == Type::VoidTy)
2870 GEN_ERROR("Short call syntax cannot be used with varargs");
2871 ParamTypes.push_back(Ty);
2873 Ty = FunctionType::get($3->get(), ParamTypes, false);
2874 PFTy = PointerType::get(Ty);
2877 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2880 // Check for call to invalid intrinsic to avoid crashing later.
2881 if (Function *theF = dyn_cast<Function>(V)) {
2882 if (theF->hasName() && (theF->getValueName()->getKeyLength() >= 5) &&
2883 (0 == strncmp(theF->getValueName()->getKeyData(), "llvm.", 5)) &&
2884 !theF->getIntrinsicID(true))
2885 GEN_ERROR("Call to invalid LLVM intrinsic function '" +
2886 theF->getName() + "'");
2889 // Set up the ParamAttrs for the function
2890 ParamAttrsVector Attrs;
2891 if ($8 != ParamAttr::None) {
2892 ParamAttrsWithIndex PAWI; PAWI.index = 0; PAWI.attrs = $8;
2893 Attrs.push_back(PAWI);
2895 // Check the arguments
2897 if ($6->empty()) { // Has no arguments?
2898 // Make sure no arguments is a good thing!
2899 if (Ty->getNumParams() != 0)
2900 GEN_ERROR("No arguments passed to a function that "
2901 "expects arguments");
2902 } else { // Has arguments?
2903 // Loop through FunctionType's arguments and ensure they are specified
2904 // correctly. Also, gather any parameter attributes.
2905 FunctionType::param_iterator I = Ty->param_begin();
2906 FunctionType::param_iterator E = Ty->param_end();
2907 ValueRefList::iterator ArgI = $6->begin(), ArgE = $6->end();
2909 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2910 if (ArgI->Val->getType() != *I)
2911 GEN_ERROR("Parameter " + ArgI->Val->getName()+ " is not of type '" +
2912 (*I)->getDescription() + "'");
2913 Args.push_back(ArgI->Val);
2914 if (ArgI->Attrs != ParamAttr::None) {
2915 ParamAttrsWithIndex PAWI; PAWI.index = index; PAWI.attrs = ArgI->Attrs;
2916 Attrs.push_back(PAWI);
2919 if (Ty->isVarArg()) {
2921 for (; ArgI != ArgE; ++ArgI)
2922 Args.push_back(ArgI->Val); // push the remaining varargs
2923 } else if (I != E || ArgI != ArgE)
2924 GEN_ERROR("Invalid number of parameters detected");
2927 // Finish off the ParamAttrs and check them
2928 ParamAttrsList *PAL = 0;
2930 PAL = ParamAttrsList::get(Attrs);
2931 if (isa<Function>(V))
2932 if (PAL != cast<Function>(V)->getParamAttrs())
2933 GEN_ERROR("Invalid parameter attributes for function called");
2935 // Create the call node
2936 CallInst *CI = new CallInst(V, &Args[0], Args.size());
2937 CI->setTailCall($1);
2938 CI->setCallingConv($2);
2939 CI->setParamAttrs(PAL);
2950 OptVolatile : VOLATILE {
2961 MemoryInst : MALLOC Types OptCAlign {
2962 if (!UpRefs.empty())
2963 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2964 $$ = new MallocInst(*$2, 0, $3);
2968 | MALLOC Types ',' INTTYPE ValueRef OptCAlign {
2969 if (!UpRefs.empty())
2970 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2971 Value* tmpVal = getVal($4, $5);
2973 $$ = new MallocInst(*$2, tmpVal, $6);
2976 | ALLOCA Types OptCAlign {
2977 if (!UpRefs.empty())
2978 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2979 $$ = new AllocaInst(*$2, 0, $3);
2983 | ALLOCA Types ',' INTTYPE ValueRef OptCAlign {
2984 if (!UpRefs.empty())
2985 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
2986 Value* tmpVal = getVal($4, $5);
2988 $$ = new AllocaInst(*$2, tmpVal, $6);
2991 | FREE ResolvedVal {
2992 if (!isa<PointerType>($2->getType()))
2993 GEN_ERROR("Trying to free nonpointer type " +
2994 $2->getType()->getDescription() + "");
2995 $$ = new FreeInst($2);
2999 | OptVolatile LOAD Types ValueRef OptCAlign {
3000 if (!UpRefs.empty())
3001 GEN_ERROR("Invalid upreference in type: " + (*$3)->getDescription());
3002 if (!isa<PointerType>($3->get()))
3003 GEN_ERROR("Can't load from nonpointer type: " +
3004 (*$3)->getDescription());
3005 if (!cast<PointerType>($3->get())->getElementType()->isFirstClassType())
3006 GEN_ERROR("Can't load from pointer of non-first-class type: " +
3007 (*$3)->getDescription());
3008 Value* tmpVal = getVal(*$3, $4);
3010 $$ = new LoadInst(tmpVal, "", $1, $5);
3013 | OptVolatile STORE ResolvedVal ',' Types ValueRef OptCAlign {
3014 if (!UpRefs.empty())
3015 GEN_ERROR("Invalid upreference in type: " + (*$5)->getDescription());
3016 const PointerType *PT = dyn_cast<PointerType>($5->get());
3018 GEN_ERROR("Can't store to a nonpointer type: " +
3019 (*$5)->getDescription());
3020 const Type *ElTy = PT->getElementType();
3021 if (ElTy != $3->getType())
3022 GEN_ERROR("Can't store '" + $3->getType()->getDescription() +
3023 "' into space of type '" + ElTy->getDescription() + "'");
3025 Value* tmpVal = getVal(*$5, $6);
3027 $$ = new StoreInst($3, tmpVal, $1, $7);
3030 | GETELEMENTPTR Types ValueRef IndexList {
3031 if (!UpRefs.empty())
3032 GEN_ERROR("Invalid upreference in type: " + (*$2)->getDescription());
3033 if (!isa<PointerType>($2->get()))
3034 GEN_ERROR("getelementptr insn requires pointer operand");
3036 if (!GetElementPtrInst::getIndexedType(*$2, &(*$4)[0], $4->size(), true))
3037 GEN_ERROR("Invalid getelementptr indices for type '" +
3038 (*$2)->getDescription()+ "'");
3039 Value* tmpVal = getVal(*$2, $3);
3041 $$ = new GetElementPtrInst(tmpVal, &(*$4)[0], $4->size());
3049 // common code from the two 'RunVMAsmParser' functions
3050 static Module* RunParser(Module * M) {
3052 llvmAsmlineno = 1; // Reset the current line number...
3053 CurModule.CurrentModule = M;
3058 // Check to make sure the parser succeeded
3061 delete ParserResult;
3065 // Emit an error if there are any unresolved types left.
3066 if (!CurModule.LateResolveTypes.empty()) {
3067 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
3068 if (DID.Type == ValID::LocalName) {
3069 GenerateError("Undefined type remains at eof: '"+DID.getName() + "'");
3071 GenerateError("Undefined type remains at eof: #" + itostr(DID.Num));
3074 delete ParserResult;
3078 // Emit an error if there are any unresolved values left.
3079 if (!CurModule.LateResolveValues.empty()) {
3080 Value *V = CurModule.LateResolveValues.back();
3081 std::map<Value*, std::pair<ValID, int> >::iterator I =
3082 CurModule.PlaceHolderInfo.find(V);
3084 if (I != CurModule.PlaceHolderInfo.end()) {
3085 ValID &DID = I->second.first;
3086 if (DID.Type == ValID::LocalName) {
3087 GenerateError("Undefined value remains at eof: "+DID.getName() + "'");
3089 GenerateError("Undefined value remains at eof: #" + itostr(DID.Num));
3092 delete ParserResult;
3097 // Check to make sure that parsing produced a result
3101 // Reset ParserResult variable while saving its value for the result.
3102 Module *Result = ParserResult;
3108 void llvm::GenerateError(const std::string &message, int LineNo) {
3109 if (LineNo == -1) LineNo = llvmAsmlineno;
3110 // TODO: column number in exception
3112 TheParseError->setError(CurFilename, message, LineNo);
3116 int yyerror(const char *ErrorMsg) {
3118 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3119 + ":" + utostr((unsigned) llvmAsmlineno) + ": ";
3120 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3121 if (yychar != YYEMPTY && yychar != 0)
3122 errMsg += " while reading token: '" + std::string(llvmAsmtext, llvmAsmleng)+
3124 GenerateError(errMsg);