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 "UpgradeInternals.h"
16 #include "llvm/CallingConv.h"
17 #include "llvm/InlineAsm.h"
18 #include "llvm/Instructions.h"
19 #include "llvm/Module.h"
20 #include "llvm/SymbolTable.h"
21 #include "llvm/Support/GetElementPtrTypeIterator.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/Support/MathExtras.h"
29 // DEBUG_UPREFS - Define this symbol if you want to enable debugging output
30 // relating to upreferences in the input stream.
32 //#define DEBUG_UPREFS 1
34 #define UR_OUT(X) std::cerr << X
39 #define YYERROR_VERBOSE 1
40 #define YYINCLUDED_STDLIB_H
46 int yyerror(const char*);
47 static void warning(const std::string& WarningMsg);
51 std::istream* LexInput;
52 static std::string CurFilename;
54 // This bool controls whether attributes are ever added to function declarations
55 // definitions and calls.
56 static bool AddAttributes = false;
58 static Module *ParserResult;
59 static bool ObsoleteVarArgs;
60 static bool NewVarArgs;
61 static BasicBlock *CurBB;
62 static GlobalVariable *CurGV;
64 // This contains info used when building the body of a function. It is
65 // destroyed when the function is completed.
67 typedef std::vector<Value *> ValueList; // Numbered defs
69 typedef std::pair<std::string,const Type*> RenameMapKey;
70 typedef std::map<RenameMapKey,std::string> RenameMapType;
73 ResolveDefinitions(std::map<const Type *,ValueList> &LateResolvers,
74 std::map<const Type *,ValueList> *FutureLateResolvers = 0);
76 static struct PerModuleInfo {
77 Module *CurrentModule;
78 std::map<const Type *, ValueList> Values; // Module level numbered definitions
79 std::map<const Type *,ValueList> LateResolveValues;
80 std::vector<PATypeHolder> Types;
81 std::map<ValID, PATypeHolder> LateResolveTypes;
82 static Module::Endianness Endian;
83 static Module::PointerSize PointerSize;
84 RenameMapType RenameMap;
86 /// PlaceHolderInfo - When temporary placeholder objects are created, remember
87 /// how they were referenced and on which line of the input they came from so
88 /// that we can resolve them later and print error messages as appropriate.
89 std::map<Value*, std::pair<ValID, int> > PlaceHolderInfo;
91 // GlobalRefs - This maintains a mapping between <Type, ValID>'s and forward
92 // references to global values. Global values may be referenced before they
93 // are defined, and if so, the temporary object that they represent is held
94 // here. This is used for forward references of GlobalValues.
96 typedef std::map<std::pair<const PointerType *, ValID>, GlobalValue*>
98 GlobalRefsType GlobalRefs;
101 // If we could not resolve some functions at function compilation time
102 // (calls to functions before they are defined), resolve them now... Types
103 // are resolved when the constant pool has been completely parsed.
105 ResolveDefinitions(LateResolveValues);
107 // Check to make sure that all global value forward references have been
110 if (!GlobalRefs.empty()) {
111 std::string UndefinedReferences = "Unresolved global references exist:\n";
113 for (GlobalRefsType::iterator I = GlobalRefs.begin(), E =GlobalRefs.end();
115 UndefinedReferences += " " + I->first.first->getDescription() + " " +
116 I->first.second.getName() + "\n";
118 error(UndefinedReferences);
122 if (CurrentModule->getDataLayout().empty()) {
123 std::string dataLayout;
124 if (Endian != Module::AnyEndianness)
125 dataLayout.append(Endian == Module::BigEndian ? "E" : "e");
126 if (PointerSize != Module::AnyPointerSize) {
127 if (!dataLayout.empty())
129 dataLayout.append(PointerSize == Module::Pointer64 ?
130 "p:64:64" : "p:32:32");
132 CurrentModule->setDataLayout(dataLayout);
135 Values.clear(); // Clear out function local definitions
140 // GetForwardRefForGlobal - Check to see if there is a forward reference
141 // for this global. If so, remove it from the GlobalRefs map and return it.
142 // If not, just return null.
143 GlobalValue *GetForwardRefForGlobal(const PointerType *PTy, ValID ID) {
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()) {
154 void setEndianness(Module::Endianness E) { Endian = E; }
155 void setPointerSize(Module::PointerSize sz) { PointerSize = sz; }
158 Module::Endianness PerModuleInfo::Endian = Module::AnyEndianness;
159 Module::PointerSize PerModuleInfo::PointerSize = Module::AnyPointerSize;
161 static struct PerFunctionInfo {
162 Function *CurrentFunction; // Pointer to current function being created
164 std::map<const Type*, ValueList> Values; // Keep track of #'d definitions
165 std::map<const Type*, ValueList> LateResolveValues;
166 bool isDeclare; // Is this function a forward declararation?
167 GlobalValue::LinkageTypes Linkage;// Linkage for forward declaration.
169 /// BBForwardRefs - When we see forward references to basic blocks, keep
170 /// track of them here.
171 std::map<BasicBlock*, std::pair<ValID, int> > BBForwardRefs;
172 std::vector<BasicBlock*> NumberedBlocks;
173 RenameMapType RenameMap;
177 inline PerFunctionInfo() {
180 Linkage = GlobalValue::ExternalLinkage;
183 inline void FunctionStart(Function *M) {
188 void FunctionDone() {
189 NumberedBlocks.clear();
191 // Any forward referenced blocks left?
192 if (!BBForwardRefs.empty()) {
193 error("Undefined reference to label " +
194 BBForwardRefs.begin()->first->getName());
198 // Resolve all forward references now.
199 ResolveDefinitions(LateResolveValues, &CurModule.LateResolveValues);
201 Values.clear(); // Clear out function local definitions
205 Linkage = GlobalValue::ExternalLinkage;
207 } CurFun; // Info for the current function...
209 static bool inFunctionScope() { return CurFun.CurrentFunction != 0; }
212 //===----------------------------------------------------------------------===//
213 // Code to handle definitions of all the types
214 //===----------------------------------------------------------------------===//
216 static int InsertValue(Value *V,
217 std::map<const Type*,ValueList> &ValueTab = CurFun.Values) {
218 if (V->hasName()) return -1; // Is this a numbered definition?
220 // Yes, insert the value into the value table...
221 ValueList &List = ValueTab[V->getType()];
223 return List.size()-1;
226 static const Type *getType(const ValID &D, bool DoNotImprovise = false) {
228 case ValID::NumberVal: // Is it a numbered definition?
229 // Module constants occupy the lowest numbered slots...
230 if ((unsigned)D.Num < CurModule.Types.size()) {
231 return CurModule.Types[(unsigned)D.Num];
234 case ValID::NameVal: // Is it a named definition?
235 if (const Type *N = CurModule.CurrentModule->getTypeByName(D.Name)) {
236 D.destroy(); // Free old strdup'd memory...
241 error("Internal parser error: Invalid symbol type reference");
245 // If we reached here, we referenced either a symbol that we don't know about
246 // or an id number that hasn't been read yet. We may be referencing something
247 // forward, so just create an entry to be resolved later and get to it...
249 if (DoNotImprovise) return 0; // Do we just want a null to be returned?
252 if (inFunctionScope()) {
253 if (D.Type == ValID::NameVal) {
254 error("Reference to an undefined type: '" + D.getName() + "'");
257 error("Reference to an undefined type: #" + itostr(D.Num));
262 std::map<ValID, PATypeHolder>::iterator I =CurModule.LateResolveTypes.find(D);
263 if (I != CurModule.LateResolveTypes.end())
266 Type *Typ = OpaqueType::get();
267 CurModule.LateResolveTypes.insert(std::make_pair(D, Typ));
271 // getExistingValue - Look up the value specified by the provided type and
272 // the provided ValID. If the value exists and has already been defined, return
273 // it. Otherwise return null.
275 static Value *getExistingValue(const Type *Ty, const ValID &D) {
276 if (isa<FunctionType>(Ty)) {
277 error("Functions are not values and must be referenced as pointers");
281 case ValID::NumberVal: { // Is it a numbered definition?
282 unsigned Num = (unsigned)D.Num;
284 // Module constants occupy the lowest numbered slots...
285 std::map<const Type*,ValueList>::iterator VI = CurModule.Values.find(Ty);
286 if (VI != CurModule.Values.end()) {
287 if (Num < VI->second.size())
288 return VI->second[Num];
289 Num -= VI->second.size();
292 // Make sure that our type is within bounds
293 VI = CurFun.Values.find(Ty);
294 if (VI == CurFun.Values.end()) return 0;
296 // Check that the number is within bounds...
297 if (VI->second.size() <= Num) return 0;
299 return VI->second[Num];
302 case ValID::NameVal: { // Is it a named definition?
303 // Get the name out of the ID
304 std::string Name(D.Name);
306 RenameMapKey Key = std::make_pair(Name, Ty);
307 if (inFunctionScope()) {
308 // See if the name was renamed
309 RenameMapType::const_iterator I = CurFun.RenameMap.find(Key);
310 std::string LookupName;
311 if (I != CurFun.RenameMap.end())
312 LookupName = I->second;
315 SymbolTable &SymTab = CurFun.CurrentFunction->getValueSymbolTable();
316 V = SymTab.lookup(Ty, LookupName);
319 RenameMapType::const_iterator I = CurModule.RenameMap.find(Key);
320 std::string LookupName;
321 if (I != CurModule.RenameMap.end())
322 LookupName = I->second;
325 V = CurModule.CurrentModule->getValueSymbolTable().lookup(Ty, LookupName);
330 D.destroy(); // Free old strdup'd memory...
334 // Check to make sure that "Ty" is an integral type, and that our
335 // value will fit into the specified type...
336 case ValID::ConstSIntVal: // Is it a constant pool reference??
337 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64)) {
338 error("Signed integral constant '" + itostr(D.ConstPool64) +
339 "' is invalid for type '" + Ty->getDescription() + "'");
341 return ConstantInt::get(Ty, D.ConstPool64);
343 case ValID::ConstUIntVal: // Is it an unsigned const pool reference?
344 if (!ConstantInt::isValueValidForType(Ty, D.UConstPool64)) {
345 if (!ConstantInt::isValueValidForType(Ty, D.ConstPool64))
346 error("Integral constant '" + utostr(D.UConstPool64) +
347 "' is invalid or out of range");
348 else // This is really a signed reference. Transmogrify.
349 return ConstantInt::get(Ty, D.ConstPool64);
351 return ConstantInt::get(Ty, D.UConstPool64);
353 case ValID::ConstFPVal: // Is it a floating point const pool reference?
354 if (!ConstantFP::isValueValidForType(Ty, D.ConstPoolFP))
355 error("FP constant invalid for type");
356 return ConstantFP::get(Ty, D.ConstPoolFP);
358 case ValID::ConstNullVal: // Is it a null value?
359 if (!isa<PointerType>(Ty))
360 error("Cannot create a a non pointer null");
361 return ConstantPointerNull::get(cast<PointerType>(Ty));
363 case ValID::ConstUndefVal: // Is it an undef value?
364 return UndefValue::get(Ty);
366 case ValID::ConstZeroVal: // Is it a zero value?
367 return Constant::getNullValue(Ty);
369 case ValID::ConstantVal: // Fully resolved constant?
370 if (D.ConstantValue->getType() != Ty)
371 error("Constant expression type different from required type");
372 return D.ConstantValue;
374 case ValID::InlineAsmVal: { // Inline asm expression
375 const PointerType *PTy = dyn_cast<PointerType>(Ty);
376 const FunctionType *FTy =
377 PTy ? dyn_cast<FunctionType>(PTy->getElementType()) : 0;
378 if (!FTy || !InlineAsm::Verify(FTy, D.IAD->Constraints))
379 error("Invalid type for asm constraint string");
380 InlineAsm *IA = InlineAsm::get(FTy, D.IAD->AsmString, D.IAD->Constraints,
381 D.IAD->HasSideEffects);
382 D.destroy(); // Free InlineAsmDescriptor.
386 assert(0 && "Unhandled case");
390 assert(0 && "Unhandled case");
394 // getVal - This function is identical to getExistingValue, except that if a
395 // value is not already defined, it "improvises" by creating a placeholder var
396 // that looks and acts just like the requested variable. When the value is
397 // defined later, all uses of the placeholder variable are replaced with the
400 static Value *getVal(const Type *Ty, const ValID &ID) {
401 if (Ty == Type::LabelTy)
402 error("Cannot use a basic block here");
404 // See if the value has already been defined.
405 Value *V = getExistingValue(Ty, ID);
408 if (!Ty->isFirstClassType() && !isa<OpaqueType>(Ty))
409 error("Invalid use of a composite type");
411 // If we reached here, we referenced either a symbol that we don't know about
412 // or an id number that hasn't been read yet. We may be referencing something
413 // forward, so just create an entry to be resolved later and get to it...
414 V = new Argument(Ty);
416 // Remember where this forward reference came from. FIXME, shouldn't we try
417 // to recycle these things??
418 CurModule.PlaceHolderInfo.insert(
419 std::make_pair(V, std::make_pair(ID, Upgradelineno-1)));
421 if (inFunctionScope())
422 InsertValue(V, CurFun.LateResolveValues);
424 InsertValue(V, CurModule.LateResolveValues);
428 /// getBBVal - This is used for two purposes:
429 /// * If isDefinition is true, a new basic block with the specified ID is being
431 /// * If isDefinition is true, this is a reference to a basic block, which may
432 /// or may not be a forward reference.
434 static BasicBlock *getBBVal(const ValID &ID, bool isDefinition = false) {
435 assert(inFunctionScope() && "Can't get basic block at global scope");
441 error("Illegal label reference " + ID.getName());
443 case ValID::NumberVal: // Is it a numbered definition?
444 if (unsigned(ID.Num) >= CurFun.NumberedBlocks.size())
445 CurFun.NumberedBlocks.resize(ID.Num+1);
446 BB = CurFun.NumberedBlocks[ID.Num];
448 case ValID::NameVal: // Is it a named definition?
450 if (Value *N = CurFun.CurrentFunction->
451 getValueSymbolTable().lookup(Type::LabelTy, Name)) {
452 if (N->getType() != Type::LabelTy)
453 error("Name '" + Name + "' does not refer to a BasicBlock");
454 BB = cast<BasicBlock>(N);
459 // See if the block has already been defined.
461 // If this is the definition of the block, make sure the existing value was
462 // just a forward reference. If it was a forward reference, there will be
463 // an entry for it in the PlaceHolderInfo map.
464 if (isDefinition && !CurFun.BBForwardRefs.erase(BB))
465 // The existing value was a definition, not a forward reference.
466 error("Redefinition of label " + ID.getName());
468 ID.destroy(); // Free strdup'd memory.
472 // Otherwise this block has not been seen before.
473 BB = new BasicBlock("", CurFun.CurrentFunction);
474 if (ID.Type == ValID::NameVal) {
475 BB->setName(ID.Name);
477 CurFun.NumberedBlocks[ID.Num] = BB;
480 // If this is not a definition, keep track of it so we can use it as a forward
483 // Remember where this forward reference came from.
484 CurFun.BBForwardRefs[BB] = std::make_pair(ID, Upgradelineno);
486 // The forward declaration could have been inserted anywhere in the
487 // function: insert it into the correct place now.
488 CurFun.CurrentFunction->getBasicBlockList().remove(BB);
489 CurFun.CurrentFunction->getBasicBlockList().push_back(BB);
496 //===----------------------------------------------------------------------===//
497 // Code to handle forward references in instructions
498 //===----------------------------------------------------------------------===//
500 // This code handles the late binding needed with statements that reference
501 // values not defined yet... for example, a forward branch, or the PHI node for
504 // This keeps a table (CurFun.LateResolveValues) of all such forward references
505 // and back patchs after we are done.
508 // ResolveDefinitions - If we could not resolve some defs at parsing
509 // time (forward branches, phi functions for loops, etc...) resolve the
513 ResolveDefinitions(std::map<const Type*,ValueList> &LateResolvers,
514 std::map<const Type*,ValueList> *FutureLateResolvers) {
515 // Loop over LateResolveDefs fixing up stuff that couldn't be resolved
516 for (std::map<const Type*,ValueList>::iterator LRI = LateResolvers.begin(),
517 E = LateResolvers.end(); LRI != E; ++LRI) {
518 ValueList &List = LRI->second;
519 while (!List.empty()) {
520 Value *V = List.back();
523 std::map<Value*, std::pair<ValID, int> >::iterator PHI =
524 CurModule.PlaceHolderInfo.find(V);
525 assert(PHI != CurModule.PlaceHolderInfo.end() && "Placeholder error");
527 ValID &DID = PHI->second.first;
529 Value *TheRealValue = getExistingValue(LRI->first, DID);
531 V->replaceAllUsesWith(TheRealValue);
533 CurModule.PlaceHolderInfo.erase(PHI);
534 } else if (FutureLateResolvers) {
535 // Functions have their unresolved items forwarded to the module late
537 InsertValue(V, *FutureLateResolvers);
539 if (DID.Type == ValID::NameVal) {
540 error("Reference to an invalid definition: '" +DID.getName()+
541 "' of type '" + V->getType()->getDescription() + "'",
545 error("Reference to an invalid definition: #" +
546 itostr(DID.Num) + " of type '" +
547 V->getType()->getDescription() + "'", PHI->second.second);
554 LateResolvers.clear();
557 // ResolveTypeTo - A brand new type was just declared. This means that (if
558 // name is not null) things referencing Name can be resolved. Otherwise, things
559 // refering to the number can be resolved. Do this now.
561 static void ResolveTypeTo(char *Name, const Type *ToTy) {
563 if (Name) D = ValID::create(Name);
564 else D = ValID::create((int)CurModule.Types.size());
566 std::map<ValID, PATypeHolder>::iterator I =
567 CurModule.LateResolveTypes.find(D);
568 if (I != CurModule.LateResolveTypes.end()) {
569 ((DerivedType*)I->second.get())->refineAbstractTypeTo(ToTy);
570 CurModule.LateResolveTypes.erase(I);
574 /// @brief This just makes any name given to it unique, up to MAX_UINT times.
575 static std::string makeNameUnique(const std::string& Name) {
576 static unsigned UniqueNameCounter = 1;
577 std::string Result(Name);
578 Result += ".upgrd." + llvm::utostr(UniqueNameCounter++);
582 /// This is the implementation portion of TypeHasInteger. It traverses the
583 /// type given, avoiding recursive types, and returns true as soon as it finds
584 /// an integer type. If no integer type is found, it returns false.
585 static bool TypeHasIntegerI(const Type *Ty, std::vector<const Type*> Stack) {
586 // Handle some easy cases
587 if (Ty->isPrimitiveType() || (Ty->getTypeID() == Type::OpaqueTyID))
591 if (const SequentialType *STy = dyn_cast<SequentialType>(Ty))
592 return STy->getElementType()->isInteger();
594 // Avoid type structure recursion
595 for (std::vector<const Type*>::iterator I = Stack.begin(), E = Stack.end();
600 // Push us on the type stack
603 if (const FunctionType *FTy = dyn_cast<FunctionType>(Ty)) {
604 if (TypeHasIntegerI(FTy->getReturnType(), Stack))
606 FunctionType::param_iterator I = FTy->param_begin();
607 FunctionType::param_iterator E = FTy->param_end();
609 if (TypeHasIntegerI(*I, Stack))
612 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
613 StructType::element_iterator I = STy->element_begin();
614 StructType::element_iterator E = STy->element_end();
615 for (; I != E; ++I) {
616 if (TypeHasIntegerI(*I, Stack))
621 // There shouldn't be anything else, but its definitely not integer
622 assert(0 && "What type is this?");
626 /// This is the interface to TypeHasIntegerI. It just provides the type stack,
627 /// to avoid recursion, and then calls TypeHasIntegerI.
628 static inline bool TypeHasInteger(const Type *Ty) {
629 std::vector<const Type*> TyStack;
630 return TypeHasIntegerI(Ty, TyStack);
633 // setValueName - Set the specified value to the name given. The name may be
634 // null potentially, in which case this is a noop. The string passed in is
635 // assumed to be a malloc'd string buffer, and is free'd by this function.
637 static void setValueName(Value *V, char *NameStr) {
639 std::string Name(NameStr); // Copy string
640 free(NameStr); // Free old string
642 if (V->getType() == Type::VoidTy) {
643 error("Can't assign name '" + Name + "' to value with void type");
647 assert(inFunctionScope() && "Must be in function scope");
649 // Search the function's symbol table for an existing value of this name
651 SymbolTable &ST = CurFun.CurrentFunction->getValueSymbolTable();
652 SymbolTable::plane_const_iterator PI = ST.plane_begin(), PE =ST.plane_end();
653 for ( ; PI != PE; ++PI) {
654 SymbolTable::value_const_iterator VI = PI->second.find(Name);
655 if (VI != PI->second.end()) {
656 Existing = VI->second;
661 // An existing value of the same name was found. This might have happened
662 // because of the integer type planes collapsing in LLVM 2.0.
663 if (Existing->getType() == V->getType() &&
664 !TypeHasInteger(Existing->getType())) {
665 // If the type does not contain any integers in them then this can't be
666 // a type plane collapsing issue. It truly is a redefinition and we
667 // should error out as the assembly is invalid.
668 error("Redefinition of value named '" + Name + "' of type '" +
669 V->getType()->getDescription() + "'");
672 // In LLVM 2.0 we don't allow names to be re-used for any values in a
673 // function, regardless of Type. Previously re-use of names was okay as
674 // long as they were distinct types. With type planes collapsing because
675 // of the signedness change and because of PR411, this can no longer be
676 // supported. We must search the entire symbol table for a conflicting
677 // name and make the name unique. No warning is needed as this can't
679 std::string NewName = makeNameUnique(Name);
680 // We're changing the name but it will probably be used by other
681 // instructions as operands later on. Consequently we have to retain
682 // a mapping of the renaming that we're doing.
683 RenameMapKey Key = std::make_pair(Name,V->getType());
684 CurFun.RenameMap[Key] = NewName;
693 /// ParseGlobalVariable - Handle parsing of a global. If Initializer is null,
694 /// this is a declaration, otherwise it is a definition.
695 static GlobalVariable *
696 ParseGlobalVariable(char *NameStr,GlobalValue::LinkageTypes Linkage,
697 bool isConstantGlobal, const Type *Ty,
698 Constant *Initializer) {
699 if (isa<FunctionType>(Ty))
700 error("Cannot declare global vars of function type");
702 const PointerType *PTy = PointerType::get(Ty);
706 Name = NameStr; // Copy string
707 free(NameStr); // Free old string
710 // See if this global value was forward referenced. If so, recycle the
714 ID = ValID::create((char*)Name.c_str());
716 ID = ValID::create((int)CurModule.Values[PTy].size());
719 if (GlobalValue *FWGV = CurModule.GetForwardRefForGlobal(PTy, ID)) {
720 // Move the global to the end of the list, from whereever it was
721 // previously inserted.
722 GlobalVariable *GV = cast<GlobalVariable>(FWGV);
723 CurModule.CurrentModule->getGlobalList().remove(GV);
724 CurModule.CurrentModule->getGlobalList().push_back(GV);
725 GV->setInitializer(Initializer);
726 GV->setLinkage(Linkage);
727 GV->setConstant(isConstantGlobal);
728 InsertValue(GV, CurModule.Values);
732 // If this global has a name, check to see if there is already a definition
733 // of this global in the module and emit warnings if there are conflicts.
735 // The global has a name. See if there's an existing one of the same name.
736 if (CurModule.CurrentModule->getNamedGlobal(Name)) {
737 // We found an existing global ov the same name. This isn't allowed
738 // in LLVM 2.0. Consequently, we must alter the name of the global so it
739 // can at least compile. This can happen because of type planes
740 // There is alread a global of the same name which means there is a
741 // conflict. Let's see what we can do about it.
742 std::string NewName(makeNameUnique(Name));
743 if (Linkage == GlobalValue::InternalLinkage) {
744 // The linkage type is internal so just warn about the rename without
745 // invoking "scarey language" about linkage failures. GVars with
746 // InternalLinkage can be renamed at will.
747 warning("Global variable '" + Name + "' was renamed to '"+
750 // The linkage of this gval is external so we can't reliably rename
751 // it because it could potentially create a linking problem.
752 // However, we can't leave the name conflict in the output either or
753 // it won't assemble with LLVM 2.0. So, all we can do is rename
754 // this one to something unique and emit a warning about the problem.
755 warning("Renaming global variable '" + Name + "' to '" + NewName +
756 "' may cause linkage errors");
759 // Put the renaming in the global rename map
760 RenameMapKey Key = std::make_pair(Name,PointerType::get(Ty));
761 CurModule.RenameMap[Key] = NewName;
768 // Otherwise there is no existing GV to use, create one now.
770 new GlobalVariable(Ty, isConstantGlobal, Linkage, Initializer, Name,
771 CurModule.CurrentModule);
772 InsertValue(GV, CurModule.Values);
776 // setTypeName - Set the specified type to the name given. The name may be
777 // null potentially, in which case this is a noop. The string passed in is
778 // assumed to be a malloc'd string buffer, and is freed by this function.
780 // This function returns true if the type has already been defined, but is
781 // allowed to be redefined in the specified context. If the name is a new name
782 // for the type plane, it is inserted and false is returned.
783 static bool setTypeName(const Type *T, char *NameStr) {
784 assert(!inFunctionScope() && "Can't give types function-local names");
785 if (NameStr == 0) return false;
787 std::string Name(NameStr); // Copy string
788 free(NameStr); // Free old string
790 // We don't allow assigning names to void type
791 if (T == Type::VoidTy) {
792 error("Can't assign name '" + Name + "' to the void type");
796 // Set the type name, checking for conflicts as we do so.
797 bool AlreadyExists = CurModule.CurrentModule->addTypeName(Name, T);
799 if (AlreadyExists) { // Inserting a name that is already defined???
800 const Type *Existing = CurModule.CurrentModule->getTypeByName(Name);
801 assert(Existing && "Conflict but no matching type?");
803 // There is only one case where this is allowed: when we are refining an
804 // opaque type. In this case, Existing will be an opaque type.
805 if (const OpaqueType *OpTy = dyn_cast<OpaqueType>(Existing)) {
806 // We ARE replacing an opaque type!
807 const_cast<OpaqueType*>(OpTy)->refineAbstractTypeTo(T);
811 // Otherwise, this is an attempt to redefine a type. That's okay if
812 // the redefinition is identical to the original. This will be so if
813 // Existing and T point to the same Type object. In this one case we
814 // allow the equivalent redefinition.
815 if (Existing == T) return true; // Yes, it's equal.
817 // Any other kind of (non-equivalent) redefinition is an error.
818 error("Redefinition of type named '" + Name + "' in the '" +
819 T->getDescription() + "' type plane");
825 //===----------------------------------------------------------------------===//
826 // Code for handling upreferences in type names...
829 // TypeContains - Returns true if Ty directly contains E in it.
831 static bool TypeContains(const Type *Ty, const Type *E) {
832 return std::find(Ty->subtype_begin(), Ty->subtype_end(),
833 E) != Ty->subtype_end();
838 // NestingLevel - The number of nesting levels that need to be popped before
839 // this type is resolved.
840 unsigned NestingLevel;
842 // LastContainedTy - This is the type at the current binding level for the
843 // type. Every time we reduce the nesting level, this gets updated.
844 const Type *LastContainedTy;
846 // UpRefTy - This is the actual opaque type that the upreference is
850 UpRefRecord(unsigned NL, OpaqueType *URTy)
851 : NestingLevel(NL), LastContainedTy(URTy), UpRefTy(URTy) {}
855 // UpRefs - A list of the outstanding upreferences that need to be resolved.
856 static std::vector<UpRefRecord> UpRefs;
858 /// HandleUpRefs - Every time we finish a new layer of types, this function is
859 /// called. It loops through the UpRefs vector, which is a list of the
860 /// currently active types. For each type, if the up reference is contained in
861 /// the newly completed type, we decrement the level count. When the level
862 /// count reaches zero, the upreferenced type is the type that is passed in:
863 /// thus we can complete the cycle.
865 static PATypeHolder HandleUpRefs(const Type *ty) {
866 // If Ty isn't abstract, or if there are no up-references in it, then there is
867 // nothing to resolve here.
868 if (!ty->isAbstract() || UpRefs.empty()) return ty;
871 UR_OUT("Type '" << Ty->getDescription() <<
872 "' newly formed. Resolving upreferences.\n" <<
873 UpRefs.size() << " upreferences active!\n");
875 // If we find any resolvable upreferences (i.e., those whose NestingLevel goes
876 // to zero), we resolve them all together before we resolve them to Ty. At
877 // the end of the loop, if there is anything to resolve to Ty, it will be in
879 OpaqueType *TypeToResolve = 0;
881 for (unsigned i = 0; i != UpRefs.size(); ++i) {
882 UR_OUT(" UR#" << i << " - TypeContains(" << Ty->getDescription() << ", "
883 << UpRefs[i].second->getDescription() << ") = "
884 << (TypeContains(Ty, UpRefs[i].second) ? "true" : "false") << "\n");
885 if (TypeContains(Ty, UpRefs[i].LastContainedTy)) {
886 // Decrement level of upreference
887 unsigned Level = --UpRefs[i].NestingLevel;
888 UpRefs[i].LastContainedTy = Ty;
889 UR_OUT(" Uplevel Ref Level = " << Level << "\n");
890 if (Level == 0) { // Upreference should be resolved!
891 if (!TypeToResolve) {
892 TypeToResolve = UpRefs[i].UpRefTy;
894 UR_OUT(" * Resolving upreference for "
895 << UpRefs[i].second->getDescription() << "\n";
896 std::string OldName = UpRefs[i].UpRefTy->getDescription());
897 UpRefs[i].UpRefTy->refineAbstractTypeTo(TypeToResolve);
898 UR_OUT(" * Type '" << OldName << "' refined upreference to: "
899 << (const void*)Ty << ", " << Ty->getDescription() << "\n");
901 UpRefs.erase(UpRefs.begin()+i); // Remove from upreference list...
902 --i; // Do not skip the next element...
908 UR_OUT(" * Resolving upreference for "
909 << UpRefs[i].second->getDescription() << "\n";
910 std::string OldName = TypeToResolve->getDescription());
911 TypeToResolve->refineAbstractTypeTo(Ty);
917 static inline Instruction::TermOps
918 getTermOp(TermOps op) {
920 default : assert(0 && "Invalid OldTermOp");
921 case RetOp : return Instruction::Ret;
922 case BrOp : return Instruction::Br;
923 case SwitchOp : return Instruction::Switch;
924 case InvokeOp : return Instruction::Invoke;
925 case UnwindOp : return Instruction::Unwind;
926 case UnreachableOp: return Instruction::Unreachable;
930 static inline Instruction::BinaryOps
931 getBinaryOp(BinaryOps op, const Type *Ty, Signedness Sign) {
933 default : assert(0 && "Invalid OldBinaryOps");
939 case SetGT : assert(0 && "Should use getCompareOp");
940 case AddOp : return Instruction::Add;
941 case SubOp : return Instruction::Sub;
942 case MulOp : return Instruction::Mul;
944 // This is an obsolete instruction so we must upgrade it based on the
945 // types of its operands.
946 bool isFP = Ty->isFloatingPoint();
947 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
948 // If its a packed type we want to use the element type
949 isFP = PTy->getElementType()->isFloatingPoint();
951 return Instruction::FDiv;
952 else if (Sign == Signed)
953 return Instruction::SDiv;
954 return Instruction::UDiv;
956 case UDivOp : return Instruction::UDiv;
957 case SDivOp : return Instruction::SDiv;
958 case FDivOp : return Instruction::FDiv;
960 // This is an obsolete instruction so we must upgrade it based on the
961 // types of its operands.
962 bool isFP = Ty->isFloatingPoint();
963 if (const PackedType* PTy = dyn_cast<PackedType>(Ty))
964 // If its a packed type we want to use the element type
965 isFP = PTy->getElementType()->isFloatingPoint();
966 // Select correct opcode
968 return Instruction::FRem;
969 else if (Sign == Signed)
970 return Instruction::SRem;
971 return Instruction::URem;
973 case URemOp : return Instruction::URem;
974 case SRemOp : return Instruction::SRem;
975 case FRemOp : return Instruction::FRem;
976 case AndOp : return Instruction::And;
977 case OrOp : return Instruction::Or;
978 case XorOp : return Instruction::Xor;
982 static inline Instruction::OtherOps
983 getCompareOp(BinaryOps op, unsigned short &predicate, const Type* &Ty,
985 bool isSigned = Sign == Signed;
986 bool isFP = Ty->isFloatingPoint();
988 default : assert(0 && "Invalid OldSetCC");
991 predicate = FCmpInst::FCMP_OEQ;
992 return Instruction::FCmp;
994 predicate = ICmpInst::ICMP_EQ;
995 return Instruction::ICmp;
999 predicate = FCmpInst::FCMP_UNE;
1000 return Instruction::FCmp;
1002 predicate = ICmpInst::ICMP_NE;
1003 return Instruction::ICmp;
1007 predicate = FCmpInst::FCMP_OLE;
1008 return Instruction::FCmp;
1011 predicate = ICmpInst::ICMP_SLE;
1013 predicate = ICmpInst::ICMP_ULE;
1014 return Instruction::ICmp;
1018 predicate = FCmpInst::FCMP_OGE;
1019 return Instruction::FCmp;
1022 predicate = ICmpInst::ICMP_SGE;
1024 predicate = ICmpInst::ICMP_UGE;
1025 return Instruction::ICmp;
1029 predicate = FCmpInst::FCMP_OLT;
1030 return Instruction::FCmp;
1033 predicate = ICmpInst::ICMP_SLT;
1035 predicate = ICmpInst::ICMP_ULT;
1036 return Instruction::ICmp;
1040 predicate = FCmpInst::FCMP_OGT;
1041 return Instruction::FCmp;
1044 predicate = ICmpInst::ICMP_SGT;
1046 predicate = ICmpInst::ICMP_UGT;
1047 return Instruction::ICmp;
1052 static inline Instruction::MemoryOps getMemoryOp(MemoryOps op) {
1054 default : assert(0 && "Invalid OldMemoryOps");
1055 case MallocOp : return Instruction::Malloc;
1056 case FreeOp : return Instruction::Free;
1057 case AllocaOp : return Instruction::Alloca;
1058 case LoadOp : return Instruction::Load;
1059 case StoreOp : return Instruction::Store;
1060 case GetElementPtrOp : return Instruction::GetElementPtr;
1064 static inline Instruction::OtherOps
1065 getOtherOp(OtherOps op, Signedness Sign) {
1067 default : assert(0 && "Invalid OldOtherOps");
1068 case PHIOp : return Instruction::PHI;
1069 case CallOp : return Instruction::Call;
1070 case ShlOp : return Instruction::Shl;
1073 return Instruction::AShr;
1074 return Instruction::LShr;
1075 case SelectOp : return Instruction::Select;
1076 case UserOp1 : return Instruction::UserOp1;
1077 case UserOp2 : return Instruction::UserOp2;
1078 case VAArg : return Instruction::VAArg;
1079 case ExtractElementOp : return Instruction::ExtractElement;
1080 case InsertElementOp : return Instruction::InsertElement;
1081 case ShuffleVectorOp : return Instruction::ShuffleVector;
1082 case ICmpOp : return Instruction::ICmp;
1083 case FCmpOp : return Instruction::FCmp;
1084 case LShrOp : return Instruction::LShr;
1085 case AShrOp : return Instruction::AShr;
1089 static inline Value*
1090 getCast(CastOps op, Value *Src, Signedness SrcSign, const Type *DstTy,
1091 Signedness DstSign, bool ForceInstruction = false) {
1092 Instruction::CastOps Opcode;
1093 const Type* SrcTy = Src->getType();
1095 if (SrcTy->isFloatingPoint() && isa<PointerType>(DstTy)) {
1096 // fp -> ptr cast is no longer supported but we must upgrade this
1097 // by doing a double cast: fp -> int -> ptr
1098 SrcTy = Type::Int64Ty;
1099 Opcode = Instruction::IntToPtr;
1100 if (isa<Constant>(Src)) {
1101 Src = ConstantExpr::getCast(Instruction::FPToUI,
1102 cast<Constant>(Src), SrcTy);
1104 std::string NewName(makeNameUnique(Src->getName()));
1105 Src = new FPToUIInst(Src, SrcTy, NewName, CurBB);
1107 } else if (isa<IntegerType>(DstTy) &&
1108 cast<IntegerType>(DstTy)->getBitWidth() == 1) {
1109 // cast type %x to bool was previously defined as setne type %x, null
1110 // The cast semantic is now to truncate, not compare so we must retain
1111 // the original intent by replacing the cast with a setne
1112 Constant* Null = Constant::getNullValue(SrcTy);
1113 Instruction::OtherOps Opcode = Instruction::ICmp;
1114 unsigned short predicate = ICmpInst::ICMP_NE;
1115 if (SrcTy->isFloatingPoint()) {
1116 Opcode = Instruction::FCmp;
1117 predicate = FCmpInst::FCMP_ONE;
1118 } else if (!SrcTy->isInteger() && !isa<PointerType>(SrcTy)) {
1119 error("Invalid cast to bool");
1121 if (isa<Constant>(Src) && !ForceInstruction)
1122 return ConstantExpr::getCompare(predicate, cast<Constant>(Src), Null);
1124 return CmpInst::create(Opcode, predicate, Src, Null);
1126 // Determine the opcode to use by calling CastInst::getCastOpcode
1128 CastInst::getCastOpcode(Src, SrcSign == Signed, DstTy, DstSign == Signed);
1130 } else switch (op) {
1131 default: assert(0 && "Invalid cast token");
1132 case TruncOp: Opcode = Instruction::Trunc; break;
1133 case ZExtOp: Opcode = Instruction::ZExt; break;
1134 case SExtOp: Opcode = Instruction::SExt; break;
1135 case FPTruncOp: Opcode = Instruction::FPTrunc; break;
1136 case FPExtOp: Opcode = Instruction::FPExt; break;
1137 case FPToUIOp: Opcode = Instruction::FPToUI; break;
1138 case FPToSIOp: Opcode = Instruction::FPToSI; break;
1139 case UIToFPOp: Opcode = Instruction::UIToFP; break;
1140 case SIToFPOp: Opcode = Instruction::SIToFP; break;
1141 case PtrToIntOp: Opcode = Instruction::PtrToInt; break;
1142 case IntToPtrOp: Opcode = Instruction::IntToPtr; break;
1143 case BitCastOp: Opcode = Instruction::BitCast; break;
1146 if (isa<Constant>(Src) && !ForceInstruction)
1147 return ConstantExpr::getCast(Opcode, cast<Constant>(Src), DstTy);
1148 return CastInst::create(Opcode, Src, DstTy);
1151 static Instruction *
1152 upgradeIntrinsicCall(const Type* RetTy, const ValID &ID,
1153 std::vector<Value*>& Args) {
1155 std::string Name = ID.Type == ValID::NameVal ? ID.Name : "";
1156 if (Name == "llvm.isunordered.f32" || Name == "llvm.isunordered.f64") {
1157 if (Args.size() != 2)
1158 error("Invalid prototype for " + Name + " prototype");
1159 return new FCmpInst(FCmpInst::FCMP_UNO, Args[0], Args[1]);
1161 static unsigned upgradeCount = 1;
1162 const Type* PtrTy = PointerType::get(Type::Int8Ty);
1163 std::vector<const Type*> Params;
1164 if (Name == "llvm.va_start" || Name == "llvm.va_end") {
1165 if (Args.size() != 1)
1166 error("Invalid prototype for " + Name + " prototype");
1167 Params.push_back(PtrTy);
1168 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1169 const PointerType *PFTy = PointerType::get(FTy);
1170 Value* Func = getVal(PFTy, ID);
1171 std::string InstName("va_upgrade");
1172 InstName += llvm::utostr(upgradeCount++);
1173 Args[0] = new BitCastInst(Args[0], PtrTy, InstName, CurBB);
1174 return new CallInst(Func, Args);
1175 } else if (Name == "llvm.va_copy") {
1176 if (Args.size() != 2)
1177 error("Invalid prototype for " + Name + " prototype");
1178 Params.push_back(PtrTy);
1179 Params.push_back(PtrTy);
1180 const FunctionType *FTy = FunctionType::get(Type::VoidTy, Params, false);
1181 const PointerType *PFTy = PointerType::get(FTy);
1182 Value* Func = getVal(PFTy, ID);
1183 std::string InstName0("va_upgrade");
1184 InstName0 += llvm::utostr(upgradeCount++);
1185 std::string InstName1("va_upgrade");
1186 InstName1 += llvm::utostr(upgradeCount++);
1187 Args[0] = new BitCastInst(Args[0], PtrTy, InstName0, CurBB);
1188 Args[1] = new BitCastInst(Args[1], PtrTy, InstName1, CurBB);
1189 return new CallInst(Func, Args);
1195 const Type* upgradeGEPIndices(const Type* PTy,
1196 std::vector<ValueInfo> *Indices,
1197 std::vector<Value*> &VIndices,
1198 std::vector<Constant*> *CIndices = 0) {
1199 // Traverse the indices with a gep_type_iterator so we can build the list
1200 // of constant and value indices for use later. Also perform upgrades
1202 if (CIndices) CIndices->clear();
1203 for (unsigned i = 0, e = Indices->size(); i != e; ++i)
1204 VIndices.push_back((*Indices)[i].V);
1205 generic_gep_type_iterator<std::vector<Value*>::iterator>
1206 GTI = gep_type_begin(PTy, VIndices.begin(), VIndices.end()),
1207 GTE = gep_type_end(PTy, VIndices.begin(), VIndices.end());
1208 for (unsigned i = 0, e = Indices->size(); i != e && GTI != GTE; ++i, ++GTI) {
1209 Value *Index = VIndices[i];
1210 if (CIndices && !isa<Constant>(Index))
1211 error("Indices to constant getelementptr must be constants");
1212 // LLVM 1.2 and earlier used ubyte struct indices. Convert any ubyte
1213 // struct indices to i32 struct indices with ZExt for compatibility.
1214 else if (isa<StructType>(*GTI)) { // Only change struct indices
1215 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Index))
1216 if (CUI->getType()->getBitWidth() == 8)
1218 ConstantExpr::getCast(Instruction::ZExt, CUI, Type::Int32Ty);
1220 // Make sure that unsigned SequentialType indices are zext'd to
1221 // 64-bits if they were smaller than that because LLVM 2.0 will sext
1222 // all indices for SequentialType elements. We must retain the same
1223 // semantic (zext) for unsigned types.
1224 if (const IntegerType *Ity = dyn_cast<IntegerType>(Index->getType()))
1225 if (Ity->getBitWidth() < 64 && (*Indices)[i].S == Unsigned) {
1227 Index = ConstantExpr::getCast(Instruction::ZExt,
1228 cast<Constant>(Index), Type::Int64Ty);
1230 Index = CastInst::create(Instruction::ZExt, Index, Type::Int64Ty,
1231 makeNameUnique("gep_upgrade"), CurBB);
1232 VIndices[i] = Index;
1235 // Add to the CIndices list, if requested.
1237 CIndices->push_back(cast<Constant>(Index));
1241 GetElementPtrInst::getIndexedType(PTy, VIndices, true);
1243 error("Index list invalid for constant getelementptr");
1247 unsigned upgradeCallingConv(unsigned CC) {
1249 case OldCallingConv::C : return CallingConv::C;
1250 case OldCallingConv::CSRet : return CallingConv::C;
1251 case OldCallingConv::Fast : return CallingConv::Fast;
1252 case OldCallingConv::Cold : return CallingConv::Cold;
1253 case OldCallingConv::X86_StdCall : return CallingConv::X86_StdCall;
1254 case OldCallingConv::X86_FastCall: return CallingConv::X86_FastCall;
1260 Module* UpgradeAssembly(const std::string &infile, std::istream& in,
1261 bool debug, bool addAttrs)
1264 CurFilename = infile;
1267 AddAttributes = addAttrs;
1268 ObsoleteVarArgs = false;
1271 CurModule.CurrentModule = new Module(CurFilename);
1273 // Check to make sure the parser succeeded
1276 delete ParserResult;
1277 std::cerr << "llvm-upgrade: parse failed.\n";
1281 // Check to make sure that parsing produced a result
1282 if (!ParserResult) {
1283 std::cerr << "llvm-upgrade: no parse result.\n";
1287 // Reset ParserResult variable while saving its value for the result.
1288 Module *Result = ParserResult;
1291 //Not all functions use vaarg, so make a second check for ObsoleteVarArgs
1294 if ((F = Result->getNamedFunction("llvm.va_start"))
1295 && F->getFunctionType()->getNumParams() == 0)
1296 ObsoleteVarArgs = true;
1297 if((F = Result->getNamedFunction("llvm.va_copy"))
1298 && F->getFunctionType()->getNumParams() == 1)
1299 ObsoleteVarArgs = true;
1302 if (ObsoleteVarArgs && NewVarArgs) {
1303 error("This file is corrupt: it uses both new and old style varargs");
1307 if(ObsoleteVarArgs) {
1308 if(Function* F = Result->getNamedFunction("llvm.va_start")) {
1309 if (F->arg_size() != 0) {
1310 error("Obsolete va_start takes 0 argument");
1316 //bar = alloca typeof(foo)
1320 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1321 const Type* ArgTy = F->getFunctionType()->getReturnType();
1322 const Type* ArgTyPtr = PointerType::get(ArgTy);
1323 Function* NF = cast<Function>(Result->getOrInsertFunction(
1324 "llvm.va_start", RetTy, ArgTyPtr, (Type *)0));
1326 while (!F->use_empty()) {
1327 CallInst* CI = cast<CallInst>(F->use_back());
1328 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vastart.fix.1", CI);
1329 new CallInst(NF, bar, "", CI);
1330 Value* foo = new LoadInst(bar, "vastart.fix.2", CI);
1331 CI->replaceAllUsesWith(foo);
1332 CI->getParent()->getInstList().erase(CI);
1334 Result->getFunctionList().erase(F);
1337 if(Function* F = Result->getNamedFunction("llvm.va_end")) {
1338 if(F->arg_size() != 1) {
1339 error("Obsolete va_end takes 1 argument");
1345 //bar = alloca 1 of typeof(foo)
1347 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1348 const Type* ArgTy = F->getFunctionType()->getParamType(0);
1349 const Type* ArgTyPtr = PointerType::get(ArgTy);
1350 Function* NF = cast<Function>(Result->getOrInsertFunction(
1351 "llvm.va_end", RetTy, ArgTyPtr, (Type *)0));
1353 while (!F->use_empty()) {
1354 CallInst* CI = cast<CallInst>(F->use_back());
1355 AllocaInst* bar = new AllocaInst(ArgTy, 0, "vaend.fix.1", CI);
1356 new StoreInst(CI->getOperand(1), bar, CI);
1357 new CallInst(NF, bar, "", CI);
1358 CI->getParent()->getInstList().erase(CI);
1360 Result->getFunctionList().erase(F);
1363 if(Function* F = Result->getNamedFunction("llvm.va_copy")) {
1364 if(F->arg_size() != 1) {
1365 error("Obsolete va_copy takes 1 argument");
1370 //a = alloca 1 of typeof(foo)
1371 //b = alloca 1 of typeof(foo)
1376 const Type* RetTy = Type::getPrimitiveType(Type::VoidTyID);
1377 const Type* ArgTy = F->getFunctionType()->getReturnType();
1378 const Type* ArgTyPtr = PointerType::get(ArgTy);
1379 Function* NF = cast<Function>(Result->getOrInsertFunction(
1380 "llvm.va_copy", RetTy, ArgTyPtr, ArgTyPtr, (Type *)0));
1382 while (!F->use_empty()) {
1383 CallInst* CI = cast<CallInst>(F->use_back());
1384 AllocaInst* a = new AllocaInst(ArgTy, 0, "vacopy.fix.1", CI);
1385 AllocaInst* b = new AllocaInst(ArgTy, 0, "vacopy.fix.2", CI);
1386 new StoreInst(CI->getOperand(1), b, CI);
1387 new CallInst(NF, a, b, "", CI);
1388 Value* foo = new LoadInst(a, "vacopy.fix.3", CI);
1389 CI->replaceAllUsesWith(foo);
1390 CI->getParent()->getInstList().erase(CI);
1392 Result->getFunctionList().erase(F);
1399 } // end llvm namespace
1401 using namespace llvm;
1406 llvm::Module *ModuleVal;
1407 llvm::Function *FunctionVal;
1408 std::pair<llvm::PATypeInfo, char*> *ArgVal;
1409 llvm::BasicBlock *BasicBlockVal;
1410 llvm::TerminatorInst *TermInstVal;
1411 llvm::InstrInfo InstVal;
1412 llvm::ConstInfo ConstVal;
1413 llvm::ValueInfo ValueVal;
1414 llvm::PATypeInfo TypeVal;
1415 llvm::TypeInfo PrimType;
1416 llvm::PHIListInfo PHIList;
1417 std::list<llvm::PATypeInfo> *TypeList;
1418 std::vector<llvm::ValueInfo> *ValueList;
1419 std::vector<llvm::ConstInfo> *ConstVector;
1422 std::vector<std::pair<llvm::PATypeInfo,char*> > *ArgList;
1423 // Represent the RHS of PHI node
1424 std::vector<std::pair<llvm::Constant*, llvm::BasicBlock*> > *JumpTable;
1426 llvm::GlobalValue::LinkageTypes Linkage;
1434 char *StrVal; // This memory is strdup'd!
1435 llvm::ValID ValIDVal; // strdup'd memory maybe!
1437 llvm::BinaryOps BinaryOpVal;
1438 llvm::TermOps TermOpVal;
1439 llvm::MemoryOps MemOpVal;
1440 llvm::OtherOps OtherOpVal;
1441 llvm::CastOps CastOpVal;
1442 llvm::ICmpInst::Predicate IPred;
1443 llvm::FCmpInst::Predicate FPred;
1444 llvm::Module::Endianness Endianness;
1447 %type <ModuleVal> Module FunctionList
1448 %type <FunctionVal> Function FunctionProto FunctionHeader BasicBlockList
1449 %type <BasicBlockVal> BasicBlock InstructionList
1450 %type <TermInstVal> BBTerminatorInst
1451 %type <InstVal> Inst InstVal MemoryInst
1452 %type <ConstVal> ConstVal ConstExpr
1453 %type <ConstVector> ConstVector
1454 %type <ArgList> ArgList ArgListH
1455 %type <ArgVal> ArgVal
1456 %type <PHIList> PHIList
1457 %type <ValueList> ValueRefList ValueRefListE // For call param lists
1458 %type <ValueList> IndexList // For GEP derived indices
1459 %type <TypeList> TypeListI ArgTypeListI
1460 %type <JumpTable> JumpTable
1461 %type <BoolVal> GlobalType // GLOBAL or CONSTANT?
1462 %type <BoolVal> OptVolatile // 'volatile' or not
1463 %type <BoolVal> OptTailCall // TAIL CALL or plain CALL.
1464 %type <BoolVal> OptSideEffect // 'sideeffect' or not.
1465 %type <Linkage> OptLinkage
1466 %type <Endianness> BigOrLittle
1468 // ValueRef - Unresolved reference to a definition or BB
1469 %type <ValIDVal> ValueRef ConstValueRef SymbolicValueRef
1470 %type <ValueVal> ResolvedVal // <type> <valref> pair
1472 // Tokens and types for handling constant integer values
1474 // ESINT64VAL - A negative number within long long range
1475 %token <SInt64Val> ESINT64VAL
1477 // EUINT64VAL - A positive number within uns. long long range
1478 %token <UInt64Val> EUINT64VAL
1479 %type <SInt64Val> EINT64VAL
1481 %token <SIntVal> SINTVAL // Signed 32 bit ints...
1482 %token <UIntVal> UINTVAL // Unsigned 32 bit ints...
1483 %type <SIntVal> INTVAL
1484 %token <FPVal> FPVAL // Float or Double constant
1486 // Built in types...
1487 %type <TypeVal> Types TypesV UpRTypes UpRTypesV
1488 %type <PrimType> SIntType UIntType IntType FPType PrimType // Classifications
1489 %token <PrimType> VOID BOOL SBYTE UBYTE SHORT USHORT INT UINT LONG ULONG
1490 %token <PrimType> FLOAT DOUBLE TYPE LABEL
1492 %token <StrVal> VAR_ID LABELSTR STRINGCONSTANT
1493 %type <StrVal> Name OptName OptAssign
1494 %type <UIntVal> OptAlign OptCAlign
1495 %type <StrVal> OptSection SectionString
1497 %token IMPLEMENTATION ZEROINITIALIZER TRUETOK FALSETOK BEGINTOK ENDTOK
1498 %token DECLARE GLOBAL CONSTANT SECTION VOLATILE
1499 %token TO DOTDOTDOT NULL_TOK UNDEF CONST INTERNAL LINKONCE WEAK APPENDING
1500 %token DLLIMPORT DLLEXPORT EXTERN_WEAK
1501 %token OPAQUE NOT EXTERNAL TARGET TRIPLE ENDIAN POINTERSIZE LITTLE BIG ALIGN
1502 %token DEPLIBS CALL TAIL ASM_TOK MODULE SIDEEFFECT
1503 %token CC_TOK CCC_TOK CSRETCC_TOK FASTCC_TOK COLDCC_TOK
1504 %token X86_STDCALLCC_TOK X86_FASTCALLCC_TOK
1506 %type <UIntVal> OptCallingConv
1508 // Basic Block Terminating Operators
1509 %token <TermOpVal> RET BR SWITCH INVOKE UNREACHABLE
1510 %token UNWIND EXCEPT
1513 %type <BinaryOpVal> ArithmeticOps LogicalOps SetCondOps // Binops Subcatagories
1514 %token <BinaryOpVal> ADD SUB MUL DIV UDIV SDIV FDIV REM UREM SREM FREM
1515 %token <BinaryOpVal> AND OR XOR
1516 %token <BinaryOpVal> SETLE SETGE SETLT SETGT SETEQ SETNE // Binary Comparators
1517 %token <OtherOpVal> ICMP FCMP
1519 // Memory Instructions
1520 %token <MemOpVal> MALLOC ALLOCA FREE LOAD STORE GETELEMENTPTR
1523 %type <OtherOpVal> ShiftOps
1524 %token <OtherOpVal> PHI_TOK SELECT SHL SHR ASHR LSHR VAARG
1525 %token <OtherOpVal> EXTRACTELEMENT INSERTELEMENT SHUFFLEVECTOR
1526 %token VAARG_old VANEXT_old //OBSOLETE
1528 // Support for ICmp/FCmp Predicates, which is 1.9++ but not 2.0
1529 %type <IPred> IPredicates
1530 %type <FPred> FPredicates
1531 %token EQ NE SLT SGT SLE SGE ULT UGT ULE UGE
1532 %token OEQ ONE OLT OGT OLE OGE ORD UNO UEQ UNE
1534 %token <CastOpVal> CAST TRUNC ZEXT SEXT FPTRUNC FPEXT FPTOUI FPTOSI
1535 %token <CastOpVal> UITOFP SITOFP PTRTOINT INTTOPTR BITCAST
1536 %type <CastOpVal> CastOps
1542 // Handle constant integer size restriction and conversion...
1547 if ($1 > (uint32_t)INT32_MAX) // Outside of my range!
1548 error("Value too large for type");
1554 : ESINT64VAL // These have same type and can't cause problems...
1556 if ($1 > (uint64_t)INT64_MAX) // Outside of my range!
1557 error("Value too large for type");
1561 // Operations that are notably excluded from this list include:
1562 // RET, BR, & SWITCH because they end basic blocks and are treated specially.
1565 : ADD | SUB | MUL | DIV | UDIV | SDIV | FDIV | REM | UREM | SREM | FREM
1573 : SETLE | SETGE | SETLT | SETGT | SETEQ | SETNE
1577 : EQ { $$ = ICmpInst::ICMP_EQ; } | NE { $$ = ICmpInst::ICMP_NE; }
1578 | SLT { $$ = ICmpInst::ICMP_SLT; } | SGT { $$ = ICmpInst::ICMP_SGT; }
1579 | SLE { $$ = ICmpInst::ICMP_SLE; } | SGE { $$ = ICmpInst::ICMP_SGE; }
1580 | ULT { $$ = ICmpInst::ICMP_ULT; } | UGT { $$ = ICmpInst::ICMP_UGT; }
1581 | ULE { $$ = ICmpInst::ICMP_ULE; } | UGE { $$ = ICmpInst::ICMP_UGE; }
1585 : OEQ { $$ = FCmpInst::FCMP_OEQ; } | ONE { $$ = FCmpInst::FCMP_ONE; }
1586 | OLT { $$ = FCmpInst::FCMP_OLT; } | OGT { $$ = FCmpInst::FCMP_OGT; }
1587 | OLE { $$ = FCmpInst::FCMP_OLE; } | OGE { $$ = FCmpInst::FCMP_OGE; }
1588 | ORD { $$ = FCmpInst::FCMP_ORD; } | UNO { $$ = FCmpInst::FCMP_UNO; }
1589 | UEQ { $$ = FCmpInst::FCMP_UEQ; } | UNE { $$ = FCmpInst::FCMP_UNE; }
1590 | ULT { $$ = FCmpInst::FCMP_ULT; } | UGT { $$ = FCmpInst::FCMP_UGT; }
1591 | ULE { $$ = FCmpInst::FCMP_ULE; } | UGE { $$ = FCmpInst::FCMP_UGE; }
1592 | TRUETOK { $$ = FCmpInst::FCMP_TRUE; }
1593 | FALSETOK { $$ = FCmpInst::FCMP_FALSE; }
1596 : SHL | SHR | ASHR | LSHR
1600 : TRUNC | ZEXT | SEXT | FPTRUNC | FPEXT | FPTOUI | FPTOSI
1601 | UITOFP | SITOFP | PTRTOINT | INTTOPTR | BITCAST | CAST
1604 // These are some types that allow classification if we only want a particular
1605 // thing... for example, only a signed, unsigned, or integral type.
1607 : LONG | INT | SHORT | SBYTE
1611 : ULONG | UINT | USHORT | UBYTE
1615 : SIntType | UIntType
1622 // OptAssign - Value producing statements have an optional assignment component
1632 : INTERNAL { $$ = GlobalValue::InternalLinkage; }
1633 | LINKONCE { $$ = GlobalValue::LinkOnceLinkage; }
1634 | WEAK { $$ = GlobalValue::WeakLinkage; }
1635 | APPENDING { $$ = GlobalValue::AppendingLinkage; }
1636 | DLLIMPORT { $$ = GlobalValue::DLLImportLinkage; }
1637 | DLLEXPORT { $$ = GlobalValue::DLLExportLinkage; }
1638 | EXTERN_WEAK { $$ = GlobalValue::ExternalWeakLinkage; }
1639 | /*empty*/ { $$ = GlobalValue::ExternalLinkage; }
1643 : /*empty*/ { CurFun.LastCC = $$ = OldCallingConv::C; }
1644 | CCC_TOK { CurFun.LastCC = $$ = OldCallingConv::C; }
1645 | CSRETCC_TOK { CurFun.LastCC = $$ = OldCallingConv::CSRet; }
1646 | FASTCC_TOK { CurFun.LastCC = $$ = OldCallingConv::Fast; }
1647 | COLDCC_TOK { CurFun.LastCC = $$ = OldCallingConv::Cold; }
1648 | X86_STDCALLCC_TOK { CurFun.LastCC = $$ = OldCallingConv::X86_StdCall; }
1649 | X86_FASTCALLCC_TOK { CurFun.LastCC = $$ = OldCallingConv::X86_FastCall; }
1650 | CC_TOK EUINT64VAL {
1651 if ((unsigned)$2 != $2)
1652 error("Calling conv too large");
1657 // OptAlign/OptCAlign - An optional alignment, and an optional alignment with
1658 // a comma before it.
1660 : /*empty*/ { $$ = 0; }
1661 | ALIGN EUINT64VAL {
1663 if ($$ != 0 && !isPowerOf2_32($$))
1664 error("Alignment must be a power of two");
1669 : /*empty*/ { $$ = 0; }
1670 | ',' ALIGN EUINT64VAL {
1672 if ($$ != 0 && !isPowerOf2_32($$))
1673 error("Alignment must be a power of two");
1678 : SECTION STRINGCONSTANT {
1679 for (unsigned i = 0, e = strlen($2); i != e; ++i)
1680 if ($2[i] == '"' || $2[i] == '\\')
1681 error("Invalid character in section name");
1687 : /*empty*/ { $$ = 0; }
1688 | SectionString { $$ = $1; }
1691 // GlobalVarAttributes - Used to pass the attributes string on a global. CurGV
1692 // is set to be the global we are processing.
1696 | ',' GlobalVarAttribute GlobalVarAttributes {}
1701 CurGV->setSection($1);
1704 | ALIGN EUINT64VAL {
1705 if ($2 != 0 && !isPowerOf2_32($2))
1706 error("Alignment must be a power of two");
1707 CurGV->setAlignment($2);
1712 //===----------------------------------------------------------------------===//
1713 // Types includes all predefined types... except void, because it can only be
1714 // used in specific contexts (function returning void for example). To have
1715 // access to it, a user must explicitly use TypesV.
1718 // TypesV includes all of 'Types', but it also includes the void type.
1722 $$.T = new PATypeHolder($1.T);
1730 $$.T = new PATypeHolder($1.T);
1737 if (!UpRefs.empty())
1738 error("Invalid upreference in type: " + (*$1.T)->getDescription());
1744 : BOOL | SBYTE | UBYTE | SHORT | USHORT | INT | UINT
1745 | LONG | ULONG | FLOAT | DOUBLE | LABEL
1748 // Derived types are added later...
1751 $$.T = new PATypeHolder($1.T);
1755 $$.T = new PATypeHolder(OpaqueType::get());
1758 | SymbolicValueRef { // Named types are also simple types...
1759 const Type* tmp = getType($1);
1760 $$.T = new PATypeHolder(tmp);
1761 $$.S = Signless; // FIXME: what if its signed?
1763 | '\\' EUINT64VAL { // Type UpReference
1764 if ($2 > (uint64_t)~0U)
1765 error("Value out of range");
1766 OpaqueType *OT = OpaqueType::get(); // Use temporary placeholder
1767 UpRefs.push_back(UpRefRecord((unsigned)$2, OT)); // Add to vector...
1768 $$.T = new PATypeHolder(OT);
1770 UR_OUT("New Upreference!\n");
1772 | UpRTypesV '(' ArgTypeListI ')' { // Function derived type?
1773 std::vector<const Type*> Params;
1774 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1775 E = $3->end(); I != E; ++I) {
1776 Params.push_back(I->T->get());
1779 FunctionType::ParamAttrsList ParamAttrs;
1780 if (CurFun.LastCC == OldCallingConv::CSRet) {
1781 ParamAttrs.push_back(FunctionType::NoAttributeSet);
1782 ParamAttrs.push_back(FunctionType::StructRetAttribute);
1784 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
1785 if (isVarArg) Params.pop_back();
1787 $$.T = new PATypeHolder(
1788 HandleUpRefs(FunctionType::get($1.T->get(),Params,isVarArg, ParamAttrs)));
1790 delete $1.T; // Delete the return type handle
1791 delete $3; // Delete the argument list
1793 | '[' EUINT64VAL 'x' UpRTypes ']' { // Sized array type?
1794 $$.T = new PATypeHolder(HandleUpRefs(ArrayType::get($4.T->get(),
1799 | '<' EUINT64VAL 'x' UpRTypes '>' { // Packed array type?
1800 const llvm::Type* ElemTy = $4.T->get();
1801 if ((unsigned)$2 != $2)
1802 error("Unsigned result not equal to signed result");
1803 if (!(ElemTy->isInteger() || ElemTy->isFloatingPoint()))
1804 error("Elements of a PackedType must be integer or floating point");
1805 if (!isPowerOf2_32($2))
1806 error("PackedType length should be a power of 2");
1807 $$.T = new PATypeHolder(HandleUpRefs(PackedType::get(ElemTy,
1812 | '{' TypeListI '}' { // Structure type?
1813 std::vector<const Type*> Elements;
1814 for (std::list<llvm::PATypeInfo>::iterator I = $2->begin(),
1815 E = $2->end(); I != E; ++I)
1816 Elements.push_back(I->T->get());
1817 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements)));
1821 | '{' '}' { // Empty structure type?
1822 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>()));
1825 | '<' '{' TypeListI '}' '>' { // Packed Structure type?
1826 std::vector<const Type*> Elements;
1827 for (std::list<llvm::PATypeInfo>::iterator I = $3->begin(),
1828 E = $3->end(); I != E; ++I) {
1829 Elements.push_back(I->T->get());
1832 $$.T = new PATypeHolder(HandleUpRefs(StructType::get(Elements, true)));
1836 | '<' '{' '}' '>' { // Empty packed structure type?
1837 $$.T = new PATypeHolder(StructType::get(std::vector<const Type*>(),true));
1840 | UpRTypes '*' { // Pointer type?
1841 if ($1.T->get() == Type::LabelTy)
1842 error("Cannot form a pointer to a basic block");
1843 $$.T = new PATypeHolder(HandleUpRefs(PointerType::get($1.T->get())));
1849 // TypeList - Used for struct declarations and as a basis for function type
1850 // declaration type lists
1854 $$ = new std::list<PATypeInfo>();
1857 | TypeListI ',' UpRTypes {
1858 ($$=$1)->push_back($3);
1862 // ArgTypeList - List of types for a function type declaration...
1865 | TypeListI ',' DOTDOTDOT {
1867 VoidTI.T = new PATypeHolder(Type::VoidTy);
1868 VoidTI.S = Signless;
1869 ($$=$1)->push_back(VoidTI);
1872 $$ = new std::list<PATypeInfo>();
1874 VoidTI.T = new PATypeHolder(Type::VoidTy);
1875 VoidTI.S = Signless;
1876 $$->push_back(VoidTI);
1879 $$ = new std::list<PATypeInfo>();
1883 // ConstVal - The various declarations that go into the constant pool. This
1884 // production is used ONLY to represent constants that show up AFTER a 'const',
1885 // 'constant' or 'global' token at global scope. Constants that can be inlined
1886 // into other expressions (such as integers and constexprs) are handled by the
1887 // ResolvedVal, ValueRef and ConstValueRef productions.
1890 : Types '[' ConstVector ']' { // Nonempty unsized arr
1891 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1893 error("Cannot make array constant with type: '" +
1894 $1.T->get()->getDescription() + "'");
1895 const Type *ETy = ATy->getElementType();
1896 int NumElements = ATy->getNumElements();
1898 // Verify that we have the correct size...
1899 if (NumElements != -1 && NumElements != (int)$3->size())
1900 error("Type mismatch: constant sized array initialized with " +
1901 utostr($3->size()) + " arguments, but has size of " +
1902 itostr(NumElements) + "");
1904 // Verify all elements are correct type!
1905 std::vector<Constant*> Elems;
1906 for (unsigned i = 0; i < $3->size(); i++) {
1907 Constant *C = (*$3)[i].C;
1908 const Type* ValTy = C->getType();
1910 error("Element #" + utostr(i) + " is not of type '" +
1911 ETy->getDescription() +"' as required!\nIt is of type '"+
1912 ValTy->getDescription() + "'");
1915 $$.C = ConstantArray::get(ATy, Elems);
1921 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1923 error("Cannot make array constant with type: '" +
1924 $1.T->get()->getDescription() + "'");
1925 int NumElements = ATy->getNumElements();
1926 if (NumElements != -1 && NumElements != 0)
1927 error("Type mismatch: constant sized array initialized with 0"
1928 " arguments, but has size of " + itostr(NumElements) +"");
1929 $$.C = ConstantArray::get(ATy, std::vector<Constant*>());
1933 | Types 'c' STRINGCONSTANT {
1934 const ArrayType *ATy = dyn_cast<ArrayType>($1.T->get());
1936 error("Cannot make array constant with type: '" +
1937 $1.T->get()->getDescription() + "'");
1938 int NumElements = ATy->getNumElements();
1939 const Type *ETy = dyn_cast<IntegerType>(ATy->getElementType());
1940 if (!ETy || cast<IntegerType>(ETy)->getBitWidth() != 8)
1941 error("String arrays require type i8, not '" + ETy->getDescription() +
1943 char *EndStr = UnEscapeLexed($3, true);
1944 if (NumElements != -1 && NumElements != (EndStr-$3))
1945 error("Can't build string constant of size " +
1946 itostr((int)(EndStr-$3)) + " when array has size " +
1947 itostr(NumElements) + "");
1948 std::vector<Constant*> Vals;
1949 for (char *C = (char *)$3; C != (char *)EndStr; ++C)
1950 Vals.push_back(ConstantInt::get(ETy, *C));
1952 $$.C = ConstantArray::get(ATy, Vals);
1956 | Types '<' ConstVector '>' { // Nonempty unsized arr
1957 const PackedType *PTy = dyn_cast<PackedType>($1.T->get());
1959 error("Cannot make packed constant with type: '" +
1960 $1.T->get()->getDescription() + "'");
1961 const Type *ETy = PTy->getElementType();
1962 int NumElements = PTy->getNumElements();
1963 // Verify that we have the correct size...
1964 if (NumElements != -1 && NumElements != (int)$3->size())
1965 error("Type mismatch: constant sized packed initialized with " +
1966 utostr($3->size()) + " arguments, but has size of " +
1967 itostr(NumElements) + "");
1968 // Verify all elements are correct type!
1969 std::vector<Constant*> Elems;
1970 for (unsigned i = 0; i < $3->size(); i++) {
1971 Constant *C = (*$3)[i].C;
1972 const Type* ValTy = C->getType();
1974 error("Element #" + utostr(i) + " is not of type '" +
1975 ETy->getDescription() +"' as required!\nIt is of type '"+
1976 ValTy->getDescription() + "'");
1979 $$.C = ConstantPacked::get(PTy, Elems);
1984 | Types '{' ConstVector '}' {
1985 const StructType *STy = dyn_cast<StructType>($1.T->get());
1987 error("Cannot make struct constant with type: '" +
1988 $1.T->get()->getDescription() + "'");
1989 if ($3->size() != STy->getNumContainedTypes())
1990 error("Illegal number of initializers for structure type");
1992 // Check to ensure that constants are compatible with the type initializer!
1993 std::vector<Constant*> Fields;
1994 for (unsigned i = 0, e = $3->size(); i != e; ++i) {
1995 Constant *C = (*$3)[i].C;
1996 if (C->getType() != STy->getElementType(i))
1997 error("Expected type '" + STy->getElementType(i)->getDescription() +
1998 "' for element #" + utostr(i) + " of structure initializer");
1999 Fields.push_back(C);
2001 $$.C = ConstantStruct::get(STy, Fields);
2007 const StructType *STy = dyn_cast<StructType>($1.T->get());
2009 error("Cannot make struct constant with type: '" +
2010 $1.T->get()->getDescription() + "'");
2011 if (STy->getNumContainedTypes() != 0)
2012 error("Illegal number of initializers for structure type");
2013 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2017 | Types '<' '{' ConstVector '}' '>' {
2018 const StructType *STy = dyn_cast<StructType>($1.T->get());
2020 error("Cannot make packed struct constant with type: '" +
2021 $1.T->get()->getDescription() + "'");
2022 if ($4->size() != STy->getNumContainedTypes())
2023 error("Illegal number of initializers for packed structure type");
2025 // Check to ensure that constants are compatible with the type initializer!
2026 std::vector<Constant*> Fields;
2027 for (unsigned i = 0, e = $4->size(); i != e; ++i) {
2028 Constant *C = (*$4)[i].C;
2029 if (C->getType() != STy->getElementType(i))
2030 error("Expected type '" + STy->getElementType(i)->getDescription() +
2031 "' for element #" + utostr(i) + " of packed struct initializer");
2032 Fields.push_back(C);
2034 $$.C = ConstantStruct::get(STy, Fields);
2039 | Types '<' '{' '}' '>' {
2040 const StructType *STy = dyn_cast<StructType>($1.T->get());
2042 error("Cannot make packed struct constant with type: '" +
2043 $1.T->get()->getDescription() + "'");
2044 if (STy->getNumContainedTypes() != 0)
2045 error("Illegal number of initializers for packed structure type");
2046 $$.C = ConstantStruct::get(STy, std::vector<Constant*>());
2051 const PointerType *PTy = dyn_cast<PointerType>($1.T->get());
2053 error("Cannot make null pointer constant with type: '" +
2054 $1.T->get()->getDescription() + "'");
2055 $$.C = ConstantPointerNull::get(PTy);
2060 $$.C = UndefValue::get($1.T->get());
2064 | Types SymbolicValueRef {
2065 const PointerType *Ty = dyn_cast<PointerType>($1.T->get());
2067 error("Global const reference must be a pointer type, not" +
2068 $1.T->get()->getDescription());
2070 // ConstExprs can exist in the body of a function, thus creating
2071 // GlobalValues whenever they refer to a variable. Because we are in
2072 // the context of a function, getExistingValue will search the functions
2073 // symbol table instead of the module symbol table for the global symbol,
2074 // which throws things all off. To get around this, we just tell
2075 // getExistingValue that we are at global scope here.
2077 Function *SavedCurFn = CurFun.CurrentFunction;
2078 CurFun.CurrentFunction = 0;
2079 Value *V = getExistingValue(Ty, $2);
2080 CurFun.CurrentFunction = SavedCurFn;
2082 // If this is an initializer for a constant pointer, which is referencing a
2083 // (currently) undefined variable, create a stub now that shall be replaced
2084 // in the future with the right type of variable.
2087 assert(isa<PointerType>(Ty) && "Globals may only be used as pointers");
2088 const PointerType *PT = cast<PointerType>(Ty);
2090 // First check to see if the forward references value is already created!
2091 PerModuleInfo::GlobalRefsType::iterator I =
2092 CurModule.GlobalRefs.find(std::make_pair(PT, $2));
2094 if (I != CurModule.GlobalRefs.end()) {
2095 V = I->second; // Placeholder already exists, use it...
2099 if ($2.Type == ValID::NameVal) Name = $2.Name;
2101 // Create the forward referenced global.
2103 if (const FunctionType *FTy =
2104 dyn_cast<FunctionType>(PT->getElementType())) {
2105 GV = new Function(FTy, GlobalValue::ExternalLinkage, Name,
2106 CurModule.CurrentModule);
2108 GV = new GlobalVariable(PT->getElementType(), false,
2109 GlobalValue::ExternalLinkage, 0,
2110 Name, CurModule.CurrentModule);
2113 // Keep track of the fact that we have a forward ref to recycle it
2114 CurModule.GlobalRefs.insert(std::make_pair(std::make_pair(PT, $2), GV));
2118 $$.C = cast<GlobalValue>(V);
2120 delete $1.T; // Free the type handle
2123 if ($1.T->get() != $2.C->getType())
2124 error("Mismatched types for constant expression");
2129 | Types ZEROINITIALIZER {
2130 const Type *Ty = $1.T->get();
2131 if (isa<FunctionType>(Ty) || Ty == Type::LabelTy || isa<OpaqueType>(Ty))
2132 error("Cannot create a null initialized value of this type");
2133 $$.C = Constant::getNullValue(Ty);
2137 | SIntType EINT64VAL { // integral constants
2138 const Type *Ty = $1.T;
2139 if (!ConstantInt::isValueValidForType(Ty, $2))
2140 error("Constant value doesn't fit in type");
2141 $$.C = ConstantInt::get(Ty, $2);
2144 | UIntType EUINT64VAL { // integral constants
2145 const Type *Ty = $1.T;
2146 if (!ConstantInt::isValueValidForType(Ty, $2))
2147 error("Constant value doesn't fit in type");
2148 $$.C = ConstantInt::get(Ty, $2);
2151 | BOOL TRUETOK { // Boolean constants
2152 $$.C = ConstantInt::get(Type::Int1Ty, true);
2155 | BOOL FALSETOK { // Boolean constants
2156 $$.C = ConstantInt::get(Type::Int1Ty, false);
2159 | FPType FPVAL { // Float & Double constants
2160 if (!ConstantFP::isValueValidForType($1.T, $2))
2161 error("Floating point constant invalid for type");
2162 $$.C = ConstantFP::get($1.T, $2);
2168 : CastOps '(' ConstVal TO Types ')' {
2169 const Type* SrcTy = $3.C->getType();
2170 const Type* DstTy = $5.T->get();
2171 Signedness SrcSign = $3.S;
2172 Signedness DstSign = $5.S;
2173 if (!SrcTy->isFirstClassType())
2174 error("cast constant expression from a non-primitive type: '" +
2175 SrcTy->getDescription() + "'");
2176 if (!DstTy->isFirstClassType())
2177 error("cast constant expression to a non-primitive type: '" +
2178 DstTy->getDescription() + "'");
2179 $$.C = cast<Constant>(getCast($1, $3.C, SrcSign, DstTy, DstSign));
2183 | GETELEMENTPTR '(' ConstVal IndexList ')' {
2184 const Type *Ty = $3.C->getType();
2185 if (!isa<PointerType>(Ty))
2186 error("GetElementPtr requires a pointer operand");
2188 std::vector<Value*> VIndices;
2189 std::vector<Constant*> CIndices;
2190 upgradeGEPIndices($3.C->getType(), $4, VIndices, &CIndices);
2193 $$.C = ConstantExpr::getGetElementPtr($3.C, CIndices);
2196 | SELECT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2197 if (!$3.C->getType()->isInteger() ||
2198 cast<IntegerType>($3.C->getType())->getBitWidth() != 1)
2199 error("Select condition must be bool type");
2200 if ($5.C->getType() != $7.C->getType())
2201 error("Select operand types must match");
2202 $$.C = ConstantExpr::getSelect($3.C, $5.C, $7.C);
2205 | ArithmeticOps '(' ConstVal ',' ConstVal ')' {
2206 const Type *Ty = $3.C->getType();
2207 if (Ty != $5.C->getType())
2208 error("Binary operator types must match");
2209 // First, make sure we're dealing with the right opcode by upgrading from
2210 // obsolete versions.
2211 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2213 // HACK: llvm 1.3 and earlier used to emit invalid pointer constant exprs.
2214 // To retain backward compatibility with these early compilers, we emit a
2215 // cast to the appropriate integer type automatically if we are in the
2216 // broken case. See PR424 for more information.
2217 if (!isa<PointerType>(Ty)) {
2218 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2220 const Type *IntPtrTy = 0;
2221 switch (CurModule.CurrentModule->getPointerSize()) {
2222 case Module::Pointer32: IntPtrTy = Type::Int32Ty; break;
2223 case Module::Pointer64: IntPtrTy = Type::Int64Ty; break;
2224 default: error("invalid pointer binary constant expr");
2226 $$.C = ConstantExpr::get(Opcode,
2227 ConstantExpr::getCast(Instruction::PtrToInt, $3.C, IntPtrTy),
2228 ConstantExpr::getCast(Instruction::PtrToInt, $5.C, IntPtrTy));
2229 $$.C = ConstantExpr::getCast(Instruction::IntToPtr, $$.C, Ty);
2233 | LogicalOps '(' ConstVal ',' ConstVal ')' {
2234 const Type* Ty = $3.C->getType();
2235 if (Ty != $5.C->getType())
2236 error("Logical operator types must match");
2237 if (!Ty->isInteger()) {
2238 if (!isa<PackedType>(Ty) ||
2239 !cast<PackedType>(Ty)->getElementType()->isInteger())
2240 error("Logical operator requires integer operands");
2242 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $3.S);
2243 $$.C = ConstantExpr::get(Opcode, $3.C, $5.C);
2246 | SetCondOps '(' ConstVal ',' ConstVal ')' {
2247 const Type* Ty = $3.C->getType();
2248 if (Ty != $5.C->getType())
2249 error("setcc operand types must match");
2250 unsigned short pred;
2251 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $3.S);
2252 $$.C = ConstantExpr::getCompare(Opcode, $3.C, $5.C);
2255 | ICMP IPredicates '(' ConstVal ',' ConstVal ')' {
2256 if ($4.C->getType() != $6.C->getType())
2257 error("icmp operand types must match");
2258 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2261 | FCMP FPredicates '(' ConstVal ',' ConstVal ')' {
2262 if ($4.C->getType() != $6.C->getType())
2263 error("fcmp operand types must match");
2264 $$.C = ConstantExpr::getCompare($2, $4.C, $6.C);
2267 | ShiftOps '(' ConstVal ',' ConstVal ')' {
2268 if (!$5.C->getType()->isInteger() ||
2269 cast<IntegerType>($5.C->getType())->getBitWidth() != 8)
2270 error("Shift count for shift constant must be unsigned byte");
2271 if (!$3.C->getType()->isInteger())
2272 error("Shift constant expression requires integer operand");
2273 $$.C = ConstantExpr::get(getOtherOp($1, $3.S), $3.C, $5.C);
2276 | EXTRACTELEMENT '(' ConstVal ',' ConstVal ')' {
2277 if (!ExtractElementInst::isValidOperands($3.C, $5.C))
2278 error("Invalid extractelement operands");
2279 $$.C = ConstantExpr::getExtractElement($3.C, $5.C);
2282 | INSERTELEMENT '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2283 if (!InsertElementInst::isValidOperands($3.C, $5.C, $7.C))
2284 error("Invalid insertelement operands");
2285 $$.C = ConstantExpr::getInsertElement($3.C, $5.C, $7.C);
2288 | SHUFFLEVECTOR '(' ConstVal ',' ConstVal ',' ConstVal ')' {
2289 if (!ShuffleVectorInst::isValidOperands($3.C, $5.C, $7.C))
2290 error("Invalid shufflevector operands");
2291 $$.C = ConstantExpr::getShuffleVector($3.C, $5.C, $7.C);
2297 // ConstVector - A list of comma separated constants.
2299 : ConstVector ',' ConstVal { ($$ = $1)->push_back($3); }
2301 $$ = new std::vector<ConstInfo>();
2307 // GlobalType - Match either GLOBAL or CONSTANT for global declarations...
2309 : GLOBAL { $$ = false; }
2310 | CONSTANT { $$ = true; }
2314 //===----------------------------------------------------------------------===//
2315 // Rules to match Modules
2316 //===----------------------------------------------------------------------===//
2318 // Module rule: Capture the result of parsing the whole file into a result
2323 $$ = ParserResult = $1;
2324 CurModule.ModuleDone();
2328 // FunctionList - A list of functions, preceeded by a constant pool.
2331 : FunctionList Function { $$ = $1; CurFun.FunctionDone(); }
2332 | FunctionList FunctionProto { $$ = $1; }
2333 | FunctionList MODULE ASM_TOK AsmBlock { $$ = $1; }
2334 | FunctionList IMPLEMENTATION { $$ = $1; }
2336 $$ = CurModule.CurrentModule;
2337 // Emit an error if there are any unresolved types left.
2338 if (!CurModule.LateResolveTypes.empty()) {
2339 const ValID &DID = CurModule.LateResolveTypes.begin()->first;
2340 if (DID.Type == ValID::NameVal) {
2341 error("Reference to an undefined type: '"+DID.getName() + "'");
2343 error("Reference to an undefined type: #" + itostr(DID.Num));
2349 // ConstPool - Constants with optional names assigned to them.
2351 : ConstPool OptAssign TYPE TypesV {
2352 // Eagerly resolve types. This is not an optimization, this is a
2353 // requirement that is due to the fact that we could have this:
2355 // %list = type { %list * }
2356 // %list = type { %list * } ; repeated type decl
2358 // If types are not resolved eagerly, then the two types will not be
2359 // determined to be the same type!
2361 const Type* Ty = $4.T->get();
2362 ResolveTypeTo($2, Ty);
2364 if (!setTypeName(Ty, $2) && !$2) {
2365 // If this is a named type that is not a redefinition, add it to the slot
2367 CurModule.Types.push_back(Ty);
2371 | ConstPool FunctionProto { // Function prototypes can be in const pool
2373 | ConstPool MODULE ASM_TOK AsmBlock { // Asm blocks can be in the const pool
2375 | ConstPool OptAssign OptLinkage GlobalType ConstVal {
2377 error("Global value initializer is not a constant");
2378 CurGV = ParseGlobalVariable($2, $3, $4, $5.C->getType(), $5.C);
2379 } GlobalVarAttributes {
2382 | ConstPool OptAssign EXTERNAL GlobalType Types {
2383 const Type *Ty = $5.T->get();
2384 CurGV = ParseGlobalVariable($2, GlobalValue::ExternalLinkage, $4, Ty, 0);
2386 } GlobalVarAttributes {
2389 | ConstPool OptAssign DLLIMPORT GlobalType Types {
2390 const Type *Ty = $5.T->get();
2391 CurGV = ParseGlobalVariable($2, GlobalValue::DLLImportLinkage, $4, Ty, 0);
2393 } GlobalVarAttributes {
2396 | ConstPool OptAssign EXTERN_WEAK GlobalType Types {
2397 const Type *Ty = $5.T->get();
2399 ParseGlobalVariable($2, GlobalValue::ExternalWeakLinkage, $4, Ty, 0);
2401 } GlobalVarAttributes {
2404 | ConstPool TARGET TargetDefinition {
2406 | ConstPool DEPLIBS '=' LibrariesDefinition {
2408 | /* empty: end of list */ {
2414 const std::string &AsmSoFar = CurModule.CurrentModule->getModuleInlineAsm();
2415 char *EndStr = UnEscapeLexed($1, true);
2416 std::string NewAsm($1, EndStr);
2419 if (AsmSoFar.empty())
2420 CurModule.CurrentModule->setModuleInlineAsm(NewAsm);
2422 CurModule.CurrentModule->setModuleInlineAsm(AsmSoFar+"\n"+NewAsm);
2427 : BIG { $$ = Module::BigEndian; }
2428 | LITTLE { $$ = Module::LittleEndian; }
2432 : ENDIAN '=' BigOrLittle {
2433 CurModule.setEndianness($3);
2435 | POINTERSIZE '=' EUINT64VAL {
2437 CurModule.setPointerSize(Module::Pointer32);
2439 CurModule.setPointerSize(Module::Pointer64);
2441 error("Invalid pointer size: '" + utostr($3) + "'");
2443 | TRIPLE '=' STRINGCONSTANT {
2444 CurModule.CurrentModule->setTargetTriple($3);
2447 | DATALAYOUT '=' STRINGCONSTANT {
2448 CurModule.CurrentModule->setDataLayout($3);
2458 : LibList ',' STRINGCONSTANT {
2459 CurModule.CurrentModule->addLibrary($3);
2463 CurModule.CurrentModule->addLibrary($1);
2466 | /* empty: end of list */ { }
2469 //===----------------------------------------------------------------------===//
2470 // Rules to match Function Headers
2471 //===----------------------------------------------------------------------===//
2474 : VAR_ID | STRINGCONSTANT
2479 | /*empty*/ { $$ = 0; }
2484 if ($1.T->get() == Type::VoidTy)
2485 error("void typed arguments are invalid");
2486 $$ = new std::pair<PATypeInfo, char*>($1, $2);
2491 : ArgListH ',' ArgVal {
2497 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2504 : ArgListH { $$ = $1; }
2505 | ArgListH ',' DOTDOTDOT {
2508 VoidTI.T = new PATypeHolder(Type::VoidTy);
2509 VoidTI.S = Signless;
2510 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2513 $$ = new std::vector<std::pair<PATypeInfo,char*> >();
2515 VoidTI.T = new PATypeHolder(Type::VoidTy);
2516 VoidTI.S = Signless;
2517 $$->push_back(std::pair<PATypeInfo, char*>(VoidTI, 0));
2519 | /* empty */ { $$ = 0; }
2523 : OptCallingConv TypesV Name '(' ArgList ')' OptSection OptAlign {
2525 std::string FunctionName($3);
2526 free($3); // Free strdup'd memory!
2528 const Type* RetTy = $2.T->get();
2530 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
2531 error("LLVM functions cannot return aggregate types");
2533 std::vector<const Type*> ParamTypeList;
2535 // In LLVM 2.0 the signatures of three varargs intrinsics changed to take
2536 // i8*. We check here for those names and override the parameter list
2537 // types to ensure the prototype is correct.
2538 if (FunctionName == "llvm.va_start" || FunctionName == "llvm.va_end") {
2539 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2540 } else if (FunctionName == "llvm.va_copy") {
2541 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2542 ParamTypeList.push_back(PointerType::get(Type::Int8Ty));
2543 } else if ($5) { // If there are arguments...
2544 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2545 I = $5->begin(), E = $5->end(); I != E; ++I) {
2546 const Type *Ty = I->first.T->get();
2547 ParamTypeList.push_back(Ty);
2552 ParamTypeList.size() && ParamTypeList.back() == Type::VoidTy;
2553 if (isVarArg) ParamTypeList.pop_back();
2555 // Convert the CSRet calling convention into the corresponding parameter
2557 FunctionType::ParamAttrsList ParamAttrs;
2558 if ($1 == OldCallingConv::CSRet) {
2559 ParamAttrs.push_back(FunctionType::NoAttributeSet); // result
2560 ParamAttrs.push_back(FunctionType::StructRetAttribute); // first arg
2563 const FunctionType *FT = FunctionType::get(RetTy, ParamTypeList, isVarArg,
2565 const PointerType *PFT = PointerType::get(FT);
2569 if (!FunctionName.empty()) {
2570 ID = ValID::create((char*)FunctionName.c_str());
2572 ID = ValID::create((int)CurModule.Values[PFT].size());
2576 // See if this function was forward referenced. If so, recycle the object.
2577 if (GlobalValue *FWRef = CurModule.GetForwardRefForGlobal(PFT, ID)) {
2578 // Move the function to the end of the list, from whereever it was
2579 // previously inserted.
2580 Fn = cast<Function>(FWRef);
2581 CurModule.CurrentModule->getFunctionList().remove(Fn);
2582 CurModule.CurrentModule->getFunctionList().push_back(Fn);
2583 } else if (!FunctionName.empty() && // Merge with an earlier prototype?
2584 (Fn = CurModule.CurrentModule->getFunction(FunctionName, FT))) {
2585 // If this is the case, either we need to be a forward decl, or it needs
2587 if (!CurFun.isDeclare && !Fn->isExternal())
2588 error("Redefinition of function '" + FunctionName + "'");
2590 // Make sure to strip off any argument names so we can't get conflicts.
2591 if (Fn->isExternal())
2592 for (Function::arg_iterator AI = Fn->arg_begin(), AE = Fn->arg_end();
2595 } else { // Not already defined?
2596 Fn = new Function(FT, GlobalValue::ExternalLinkage, FunctionName,
2597 CurModule.CurrentModule);
2599 InsertValue(Fn, CurModule.Values);
2602 CurFun.FunctionStart(Fn);
2604 if (CurFun.isDeclare) {
2605 // If we have declaration, always overwrite linkage. This will allow us
2606 // to correctly handle cases, when pointer to function is passed as
2607 // argument to another function.
2608 Fn->setLinkage(CurFun.Linkage);
2610 Fn->setCallingConv(upgradeCallingConv($1));
2611 Fn->setAlignment($8);
2617 // Add all of the arguments we parsed to the function...
2618 if ($5) { // Is null if empty...
2619 if (isVarArg) { // Nuke the last entry
2620 assert($5->back().first.T->get() == Type::VoidTy &&
2621 $5->back().second == 0 && "Not a varargs marker");
2622 delete $5->back().first.T;
2623 $5->pop_back(); // Delete the last entry
2625 Function::arg_iterator ArgIt = Fn->arg_begin();
2626 for (std::vector<std::pair<PATypeInfo,char*> >::iterator
2627 I = $5->begin(), E = $5->end(); I != E; ++I, ++ArgIt) {
2628 delete I->first.T; // Delete the typeholder...
2629 setValueName(ArgIt, I->second); // Insert arg into symtab...
2632 delete $5; // We're now done with the argument list
2638 : BEGINTOK | '{' // Allow BEGIN or '{' to start a function
2642 : OptLinkage FunctionHeaderH BEGIN {
2643 $$ = CurFun.CurrentFunction;
2645 // Make sure that we keep track of the linkage type even if there was a
2646 // previous "declare".
2652 : ENDTOK | '}' // Allow end of '}' to end a function
2656 : BasicBlockList END {
2662 | DLLIMPORT { CurFun.Linkage = GlobalValue::DLLImportLinkage; }
2663 | EXTERN_WEAK { CurFun.Linkage = GlobalValue::ExternalWeakLinkage; }
2667 : DECLARE { CurFun.isDeclare = true; } FnDeclareLinkage FunctionHeaderH {
2668 $$ = CurFun.CurrentFunction;
2669 CurFun.FunctionDone();
2674 //===----------------------------------------------------------------------===//
2675 // Rules to match Basic Blocks
2676 //===----------------------------------------------------------------------===//
2679 : /* empty */ { $$ = false; }
2680 | SIDEEFFECT { $$ = true; }
2684 // A reference to a direct constant
2685 : ESINT64VAL { $$ = ValID::create($1); }
2686 | EUINT64VAL { $$ = ValID::create($1); }
2687 | FPVAL { $$ = ValID::create($1); }
2688 | TRUETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, true)); }
2689 | FALSETOK { $$ = ValID::create(ConstantInt::get(Type::Int1Ty, false)); }
2690 | NULL_TOK { $$ = ValID::createNull(); }
2691 | UNDEF { $$ = ValID::createUndef(); }
2692 | ZEROINITIALIZER { $$ = ValID::createZeroInit(); }
2693 | '<' ConstVector '>' { // Nonempty unsized packed vector
2694 const Type *ETy = (*$2)[0].C->getType();
2695 int NumElements = $2->size();
2696 PackedType* pt = PackedType::get(ETy, NumElements);
2697 PATypeHolder* PTy = new PATypeHolder(
2698 HandleUpRefs(PackedType::get(ETy, NumElements)));
2700 // Verify all elements are correct type!
2701 std::vector<Constant*> Elems;
2702 for (unsigned i = 0; i < $2->size(); i++) {
2703 Constant *C = (*$2)[i].C;
2704 const Type *CTy = C->getType();
2706 error("Element #" + utostr(i) + " is not of type '" +
2707 ETy->getDescription() +"' as required!\nIt is of type '" +
2708 CTy->getDescription() + "'");
2711 $$ = ValID::create(ConstantPacked::get(pt, Elems));
2712 delete PTy; delete $2;
2715 $$ = ValID::create($1.C);
2717 | ASM_TOK OptSideEffect STRINGCONSTANT ',' STRINGCONSTANT {
2718 char *End = UnEscapeLexed($3, true);
2719 std::string AsmStr = std::string($3, End);
2720 End = UnEscapeLexed($5, true);
2721 std::string Constraints = std::string($5, End);
2722 $$ = ValID::createInlineAsm(AsmStr, Constraints, $2);
2728 // SymbolicValueRef - Reference to one of two ways of symbolically refering to
2732 : INTVAL { $$ = ValID::create($1); }
2733 | Name { $$ = ValID::create($1); }
2736 // ValueRef - A reference to a definition... either constant or symbolic
2738 : SymbolicValueRef | ConstValueRef
2742 // ResolvedVal - a <type> <value> pair. This is used only in cases where the
2743 // type immediately preceeds the value reference, and allows complex constant
2744 // pool references (for things like: 'ret [2 x int] [ int 12, int 42]')
2747 const Type *Ty = $1.T->get();
2749 $$.V = getVal(Ty, $2);
2755 : BasicBlockList BasicBlock {
2758 | FunctionHeader BasicBlock { // Do not allow functions with 0 basic blocks
2763 // Basic blocks are terminated by branching instructions:
2764 // br, br/cc, switch, ret
2767 : InstructionList OptAssign BBTerminatorInst {
2768 setValueName($3, $2);
2770 $1->getInstList().push_back($3);
2777 : InstructionList Inst {
2779 $1->getInstList().push_back($2.I);
2783 $$ = CurBB = getBBVal(ValID::create((int)CurFun.NextBBNum++), true);
2784 // Make sure to move the basic block to the correct location in the
2785 // function, instead of leaving it inserted wherever it was first
2787 Function::BasicBlockListType &BBL =
2788 CurFun.CurrentFunction->getBasicBlockList();
2789 BBL.splice(BBL.end(), BBL, $$);
2792 $$ = CurBB = getBBVal(ValID::create($1), true);
2793 // Make sure to move the basic block to the correct location in the
2794 // function, instead of leaving it inserted wherever it was first
2796 Function::BasicBlockListType &BBL =
2797 CurFun.CurrentFunction->getBasicBlockList();
2798 BBL.splice(BBL.end(), BBL, $$);
2802 Unwind : UNWIND | EXCEPT;
2805 : RET ResolvedVal { // Return with a result...
2806 $$ = new ReturnInst($2.V);
2808 | RET VOID { // Return with no result...
2809 $$ = new ReturnInst();
2811 | BR LABEL ValueRef { // Unconditional Branch...
2812 BasicBlock* tmpBB = getBBVal($3);
2813 $$ = new BranchInst(tmpBB);
2814 } // Conditional Branch...
2815 | BR BOOL ValueRef ',' LABEL ValueRef ',' LABEL ValueRef {
2816 BasicBlock* tmpBBA = getBBVal($6);
2817 BasicBlock* tmpBBB = getBBVal($9);
2818 Value* tmpVal = getVal(Type::Int1Ty, $3);
2819 $$ = new BranchInst(tmpBBA, tmpBBB, tmpVal);
2821 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' JumpTable ']' {
2822 Value* tmpVal = getVal($2.T, $3);
2823 BasicBlock* tmpBB = getBBVal($6);
2824 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, $8->size());
2826 std::vector<std::pair<Constant*,BasicBlock*> >::iterator I = $8->begin(),
2828 for (; I != E; ++I) {
2829 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->first))
2830 S->addCase(CI, I->second);
2832 error("Switch case is constant, but not a simple integer");
2836 | SWITCH IntType ValueRef ',' LABEL ValueRef '[' ']' {
2837 Value* tmpVal = getVal($2.T, $3);
2838 BasicBlock* tmpBB = getBBVal($6);
2839 SwitchInst *S = new SwitchInst(tmpVal, tmpBB, 0);
2842 | INVOKE OptCallingConv TypesV ValueRef '(' ValueRefListE ')'
2843 TO LABEL ValueRef Unwind LABEL ValueRef {
2844 const PointerType *PFTy;
2845 const FunctionType *Ty;
2847 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
2848 !(Ty = dyn_cast<FunctionType>(PFTy->getElementType()))) {
2849 // Pull out the types of all of the arguments...
2850 std::vector<const Type*> ParamTypes;
2852 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
2854 ParamTypes.push_back((*I).V->getType());
2856 FunctionType::ParamAttrsList ParamAttrs;
2857 if ($2 == OldCallingConv::CSRet) {
2858 ParamAttrs.push_back(FunctionType::NoAttributeSet);
2859 ParamAttrs.push_back(FunctionType::StructRetAttribute);
2861 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
2862 if (isVarArg) ParamTypes.pop_back();
2863 Ty = FunctionType::get($3.T->get(), ParamTypes, isVarArg, ParamAttrs);
2864 PFTy = PointerType::get(Ty);
2866 Value *V = getVal(PFTy, $4); // Get the function we're calling...
2867 BasicBlock *Normal = getBBVal($10);
2868 BasicBlock *Except = getBBVal($13);
2870 // Create the call node...
2871 if (!$6) { // Has no arguments?
2872 $$ = new InvokeInst(V, Normal, Except, std::vector<Value*>());
2873 } else { // Has arguments?
2874 // Loop through FunctionType's arguments and ensure they are specified
2877 FunctionType::param_iterator I = Ty->param_begin();
2878 FunctionType::param_iterator E = Ty->param_end();
2879 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
2881 std::vector<Value*> Args;
2882 for (; ArgI != ArgE && I != E; ++ArgI, ++I) {
2883 if ((*ArgI).V->getType() != *I)
2884 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
2885 (*I)->getDescription() + "'");
2886 Args.push_back((*ArgI).V);
2889 if (I != E || (ArgI != ArgE && !Ty->isVarArg()))
2890 error("Invalid number of parameters detected");
2892 $$ = new InvokeInst(V, Normal, Except, Args);
2894 cast<InvokeInst>($$)->setCallingConv(upgradeCallingConv($2));
2899 $$ = new UnwindInst();
2902 $$ = new UnreachableInst();
2907 : JumpTable IntType ConstValueRef ',' LABEL ValueRef {
2909 Constant *V = cast<Constant>(getExistingValue($2.T, $3));
2912 error("May only switch on a constant pool value");
2914 BasicBlock* tmpBB = getBBVal($6);
2915 $$->push_back(std::make_pair(V, tmpBB));
2917 | IntType ConstValueRef ',' LABEL ValueRef {
2918 $$ = new std::vector<std::pair<Constant*, BasicBlock*> >();
2919 Constant *V = cast<Constant>(getExistingValue($1.T, $2));
2922 error("May only switch on a constant pool value");
2924 BasicBlock* tmpBB = getBBVal($5);
2925 $$->push_back(std::make_pair(V, tmpBB));
2930 : OptAssign InstVal {
2933 if (BitCastInst *BCI = dyn_cast<BitCastInst>($2.I))
2934 if (BCI->getSrcTy() == BCI->getDestTy() &&
2935 BCI->getOperand(0)->getName() == $1)
2936 // This is a useless bit cast causing a name redefinition. It is
2937 // a bit cast from a type to the same type of an operand with the
2938 // same name as the name we would give this instruction. Since this
2939 // instruction results in no code generation, it is safe to omit
2940 // the instruction. This situation can occur because of collapsed
2941 // type planes. For example:
2942 // %X = add int %Y, %Z
2943 // %X = cast int %Y to uint
2944 // After upgrade, this looks like:
2945 // %X = add i32 %Y, %Z
2946 // %X = bitcast i32 to i32
2947 // The bitcast is clearly useless so we omit it.
2953 setValueName($2.I, $1);
2959 PHIList : Types '[' ValueRef ',' ValueRef ']' { // Used for PHI nodes
2960 $$.P = new std::list<std::pair<Value*, BasicBlock*> >();
2962 Value* tmpVal = getVal($1.T->get(), $3);
2963 BasicBlock* tmpBB = getBBVal($5);
2964 $$.P->push_back(std::make_pair(tmpVal, tmpBB));
2967 | PHIList ',' '[' ValueRef ',' ValueRef ']' {
2969 Value* tmpVal = getVal($1.P->front().first->getType(), $4);
2970 BasicBlock* tmpBB = getBBVal($6);
2971 $1.P->push_back(std::make_pair(tmpVal, tmpBB));
2975 ValueRefList : ResolvedVal { // Used for call statements, and memory insts...
2976 $$ = new std::vector<ValueInfo>();
2979 | ValueRefList ',' ResolvedVal {
2984 // ValueRefListE - Just like ValueRefList, except that it may also be empty!
2987 | /*empty*/ { $$ = 0; }
3000 : ArithmeticOps Types ValueRef ',' ValueRef {
3001 const Type* Ty = $2.T->get();
3002 if (!Ty->isInteger() && !Ty->isFloatingPoint() && !isa<PackedType>(Ty))
3003 error("Arithmetic operator requires integer, FP, or packed operands");
3004 if (isa<PackedType>(Ty) &&
3005 ($1 == URemOp || $1 == SRemOp || $1 == FRemOp || $1 == RemOp))
3006 error("Remainder not supported on packed types");
3007 // Upgrade the opcode from obsolete versions before we do anything with it.
3008 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3009 Value* val1 = getVal(Ty, $3);
3010 Value* val2 = getVal(Ty, $5);
3011 $$.I = BinaryOperator::create(Opcode, val1, val2);
3013 error("binary operator returned null");
3017 | LogicalOps Types ValueRef ',' ValueRef {
3018 const Type *Ty = $2.T->get();
3019 if (!Ty->isInteger()) {
3020 if (!isa<PackedType>(Ty) ||
3021 !cast<PackedType>(Ty)->getElementType()->isInteger())
3022 error("Logical operator requires integral operands");
3024 Instruction::BinaryOps Opcode = getBinaryOp($1, Ty, $2.S);
3025 Value* tmpVal1 = getVal(Ty, $3);
3026 Value* tmpVal2 = getVal(Ty, $5);
3027 $$.I = BinaryOperator::create(Opcode, tmpVal1, tmpVal2);
3029 error("binary operator returned null");
3033 | SetCondOps Types ValueRef ',' ValueRef {
3034 const Type* Ty = $2.T->get();
3035 if(isa<PackedType>(Ty))
3036 error("PackedTypes currently not supported in setcc instructions");
3037 unsigned short pred;
3038 Instruction::OtherOps Opcode = getCompareOp($1, pred, Ty, $2.S);
3039 Value* tmpVal1 = getVal(Ty, $3);
3040 Value* tmpVal2 = getVal(Ty, $5);
3041 $$.I = CmpInst::create(Opcode, pred, tmpVal1, tmpVal2);
3043 error("binary operator returned null");
3047 | ICMP IPredicates Types ValueRef ',' ValueRef {
3048 const Type *Ty = $3.T->get();
3049 if (isa<PackedType>(Ty))
3050 error("PackedTypes currently not supported in icmp instructions");
3051 else if (!Ty->isInteger() && !isa<PointerType>(Ty))
3052 error("icmp requires integer or pointer typed operands");
3053 Value* tmpVal1 = getVal(Ty, $4);
3054 Value* tmpVal2 = getVal(Ty, $6);
3055 $$.I = new ICmpInst($2, tmpVal1, tmpVal2);
3059 | FCMP FPredicates Types ValueRef ',' ValueRef {
3060 const Type *Ty = $3.T->get();
3061 if (isa<PackedType>(Ty))
3062 error("PackedTypes currently not supported in fcmp instructions");
3063 else if (!Ty->isFloatingPoint())
3064 error("fcmp instruction requires floating point operands");
3065 Value* tmpVal1 = getVal(Ty, $4);
3066 Value* tmpVal2 = getVal(Ty, $6);
3067 $$.I = new FCmpInst($2, tmpVal1, tmpVal2);
3072 warning("Use of obsolete 'not' instruction: Replacing with 'xor");
3073 const Type *Ty = $2.V->getType();
3074 Value *Ones = ConstantInt::getAllOnesValue(Ty);
3076 error("Expected integral type for not instruction");
3077 $$.I = BinaryOperator::create(Instruction::Xor, $2.V, Ones);
3079 error("Could not create a xor instruction");
3082 | ShiftOps ResolvedVal ',' ResolvedVal {
3083 if (!$4.V->getType()->isInteger() ||
3084 cast<IntegerType>($4.V->getType())->getBitWidth() != 8)
3085 error("Shift amount must be int8");
3086 if (!$2.V->getType()->isInteger())
3087 error("Shift constant expression requires integer operand");
3088 $$.I = new ShiftInst(getOtherOp($1, $2.S), $2.V, $4.V);
3091 | CastOps ResolvedVal TO Types {
3092 const Type *DstTy = $4.T->get();
3093 if (!DstTy->isFirstClassType())
3094 error("cast instruction to a non-primitive type: '" +
3095 DstTy->getDescription() + "'");
3096 $$.I = cast<Instruction>(getCast($1, $2.V, $2.S, DstTy, $4.S, true));
3100 | SELECT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3101 if (!$2.V->getType()->isInteger() ||
3102 cast<IntegerType>($2.V->getType())->getBitWidth() != 1)
3103 error("select condition must be bool");
3104 if ($4.V->getType() != $6.V->getType())
3105 error("select value types should match");
3106 $$.I = new SelectInst($2.V, $4.V, $6.V);
3109 | VAARG ResolvedVal ',' Types {
3110 const Type *Ty = $4.T->get();
3112 $$.I = new VAArgInst($2.V, Ty);
3116 | VAARG_old ResolvedVal ',' Types {
3117 const Type* ArgTy = $2.V->getType();
3118 const Type* DstTy = $4.T->get();
3119 ObsoleteVarArgs = true;
3120 Function* NF = cast<Function>(CurModule.CurrentModule->
3121 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3124 //foo = alloca 1 of t
3128 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
3129 CurBB->getInstList().push_back(foo);
3130 CallInst* bar = new CallInst(NF, $2.V);
3131 CurBB->getInstList().push_back(bar);
3132 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3133 $$.I = new VAArgInst(foo, DstTy);
3137 | VANEXT_old ResolvedVal ',' Types {
3138 const Type* ArgTy = $2.V->getType();
3139 const Type* DstTy = $4.T->get();
3140 ObsoleteVarArgs = true;
3141 Function* NF = cast<Function>(CurModule.CurrentModule->
3142 getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy, (Type *)0));
3144 //b = vanext a, t ->
3145 //foo = alloca 1 of t
3148 //tmp = vaarg foo, t
3150 AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
3151 CurBB->getInstList().push_back(foo);
3152 CallInst* bar = new CallInst(NF, $2.V);
3153 CurBB->getInstList().push_back(bar);
3154 CurBB->getInstList().push_back(new StoreInst(bar, foo));
3155 Instruction* tmp = new VAArgInst(foo, DstTy);
3156 CurBB->getInstList().push_back(tmp);
3157 $$.I = new LoadInst(foo);
3161 | EXTRACTELEMENT ResolvedVal ',' ResolvedVal {
3162 if (!ExtractElementInst::isValidOperands($2.V, $4.V))
3163 error("Invalid extractelement operands");
3164 $$.I = new ExtractElementInst($2.V, $4.V);
3167 | INSERTELEMENT ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3168 if (!InsertElementInst::isValidOperands($2.V, $4.V, $6.V))
3169 error("Invalid insertelement operands");
3170 $$.I = new InsertElementInst($2.V, $4.V, $6.V);
3173 | SHUFFLEVECTOR ResolvedVal ',' ResolvedVal ',' ResolvedVal {
3174 if (!ShuffleVectorInst::isValidOperands($2.V, $4.V, $6.V))
3175 error("Invalid shufflevector operands");
3176 $$.I = new ShuffleVectorInst($2.V, $4.V, $6.V);
3180 const Type *Ty = $2.P->front().first->getType();
3181 if (!Ty->isFirstClassType())
3182 error("PHI node operands must be of first class type");
3183 PHINode *PHI = new PHINode(Ty);
3184 PHI->reserveOperandSpace($2.P->size());
3185 while ($2.P->begin() != $2.P->end()) {
3186 if ($2.P->front().first->getType() != Ty)
3187 error("All elements of a PHI node must be of the same type");
3188 PHI->addIncoming($2.P->front().first, $2.P->front().second);
3193 delete $2.P; // Free the list...
3195 | OptTailCall OptCallingConv TypesV ValueRef '(' ValueRefListE ')' {
3197 // Handle the short call syntax
3198 const PointerType *PFTy;
3199 const FunctionType *FTy;
3200 if (!(PFTy = dyn_cast<PointerType>($3.T->get())) ||
3201 !(FTy = dyn_cast<FunctionType>(PFTy->getElementType()))) {
3202 // Pull out the types of all of the arguments...
3203 std::vector<const Type*> ParamTypes;
3205 for (std::vector<ValueInfo>::iterator I = $6->begin(), E = $6->end();
3207 ParamTypes.push_back((*I).V->getType());
3210 FunctionType::ParamAttrsList ParamAttrs;
3211 if ($2 == OldCallingConv::CSRet) {
3212 ParamAttrs.push_back(FunctionType::NoAttributeSet);
3213 ParamAttrs.push_back(FunctionType::StructRetAttribute);
3215 bool isVarArg = ParamTypes.size() && ParamTypes.back() == Type::VoidTy;
3216 if (isVarArg) ParamTypes.pop_back();
3218 const Type *RetTy = $3.T->get();
3219 if (!RetTy->isFirstClassType() && RetTy != Type::VoidTy)
3220 error("Functions cannot return aggregate types");
3222 FTy = FunctionType::get(RetTy, ParamTypes, isVarArg, ParamAttrs);
3223 PFTy = PointerType::get(FTy);
3226 // First upgrade any intrinsic calls.
3227 std::vector<Value*> Args;
3229 for (unsigned i = 0, e = $6->size(); i < e; ++i)
3230 Args.push_back((*$6)[i].V);
3231 Instruction *Inst = upgradeIntrinsicCall(FTy, $4, Args);
3233 // If we got an upgraded intrinsic
3238 // Get the function we're calling
3239 Value *V = getVal(PFTy, $4);
3241 // Check the argument values match
3242 if (!$6) { // Has no arguments?
3243 // Make sure no arguments is a good thing!
3244 if (FTy->getNumParams() != 0)
3245 error("No arguments passed to a function that expects arguments");
3246 } else { // Has arguments?
3247 // Loop through FunctionType's arguments and ensure they are specified
3250 FunctionType::param_iterator I = FTy->param_begin();
3251 FunctionType::param_iterator E = FTy->param_end();
3252 std::vector<ValueInfo>::iterator ArgI = $6->begin(), ArgE = $6->end();
3254 for (; ArgI != ArgE && I != E; ++ArgI, ++I)
3255 if ((*ArgI).V->getType() != *I)
3256 error("Parameter " +(*ArgI).V->getName()+ " is not of type '" +
3257 (*I)->getDescription() + "'");
3259 if (I != E || (ArgI != ArgE && !FTy->isVarArg()))
3260 error("Invalid number of parameters detected");
3263 // Create the call instruction
3264 CallInst *CI = new CallInst(V, Args);
3265 CI->setTailCall($1);
3266 CI->setCallingConv(upgradeCallingConv($2));
3279 // IndexList - List of indices for GEP based instructions...
3281 : ',' ValueRefList { $$ = $2; }
3282 | /* empty */ { $$ = new std::vector<ValueInfo>(); }
3286 : VOLATILE { $$ = true; }
3287 | /* empty */ { $$ = false; }
3291 : MALLOC Types OptCAlign {
3292 const Type *Ty = $2.T->get();
3294 $$.I = new MallocInst(Ty, 0, $3);
3297 | MALLOC Types ',' UINT ValueRef OptCAlign {
3298 const Type *Ty = $2.T->get();
3300 $$.I = new MallocInst(Ty, getVal($4.T, $5), $6);
3303 | ALLOCA Types OptCAlign {
3304 const Type *Ty = $2.T->get();
3306 $$.I = new AllocaInst(Ty, 0, $3);
3309 | ALLOCA Types ',' UINT ValueRef OptCAlign {
3310 const Type *Ty = $2.T->get();
3312 $$.I = new AllocaInst(Ty, getVal($4.T, $5), $6);
3315 | FREE ResolvedVal {
3316 const Type *PTy = $2.V->getType();
3317 if (!isa<PointerType>(PTy))
3318 error("Trying to free nonpointer type '" + PTy->getDescription() + "'");
3319 $$.I = new FreeInst($2.V);
3322 | OptVolatile LOAD Types ValueRef {
3323 const Type* Ty = $3.T->get();
3325 if (!isa<PointerType>(Ty))
3326 error("Can't load from nonpointer type: " + Ty->getDescription());
3327 if (!cast<PointerType>(Ty)->getElementType()->isFirstClassType())
3328 error("Can't load from pointer of non-first-class type: " +
3329 Ty->getDescription());
3330 Value* tmpVal = getVal(Ty, $4);
3331 $$.I = new LoadInst(tmpVal, "", $1);
3334 | OptVolatile STORE ResolvedVal ',' Types ValueRef {
3335 const PointerType *PTy = dyn_cast<PointerType>($5.T->get());
3337 error("Can't store to a nonpointer type: " +
3338 $5.T->get()->getDescription());
3339 const Type *ElTy = PTy->getElementType();
3340 if (ElTy != $3.V->getType())
3341 error("Can't store '" + $3.V->getType()->getDescription() +
3342 "' into space of type '" + ElTy->getDescription() + "'");
3343 Value* tmpVal = getVal(PTy, $6);
3344 $$.I = new StoreInst($3.V, tmpVal, $1);
3348 | GETELEMENTPTR Types ValueRef IndexList {
3349 const Type* Ty = $2.T->get();
3350 if (!isa<PointerType>(Ty))
3351 error("getelementptr insn requires pointer operand");
3353 std::vector<Value*> VIndices;
3354 upgradeGEPIndices(Ty, $4, VIndices);
3356 Value* tmpVal = getVal(Ty, $3);
3357 $$.I = new GetElementPtrInst(tmpVal, VIndices);
3366 int yyerror(const char *ErrorMsg) {
3368 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3369 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3370 std::string errMsg = where + "error: " + std::string(ErrorMsg);
3371 if (yychar != YYEMPTY && yychar != 0)
3372 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3374 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3375 std::cout << "llvm-upgrade: parse failed.\n";
3379 void warning(const std::string& ErrorMsg) {
3381 = std::string((CurFilename == "-") ? std::string("<stdin>") : CurFilename)
3382 + ":" + llvm::utostr((unsigned) Upgradelineno-1) + ": ";
3383 std::string errMsg = where + "warning: " + std::string(ErrorMsg);
3384 if (yychar != YYEMPTY && yychar != 0)
3385 errMsg += " while reading token '" + std::string(Upgradetext, Upgradeleng) +
3387 std::cerr << "llvm-upgrade: " << errMsg << '\n';
3390 void error(const std::string& ErrorMsg, int LineNo) {
3391 if (LineNo == -1) LineNo = Upgradelineno;
3392 Upgradelineno = LineNo;
3393 yyerror(ErrorMsg.c_str());