1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Aggregate Expr nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CodeGenModule.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/StmtVisitor.h" 18 #include "llvm/Constants.h" 19 #include "llvm/Function.h" 20 #include "llvm/GlobalVariable.h" 21 #include "llvm/Support/Compiler.h" 22 #include "llvm/Intrinsics.h" 23 using namespace clang; 24 using namespace CodeGen; 25 26 //===----------------------------------------------------------------------===// 27 // Aggregate Expression Emitter 28 //===----------------------------------------------------------------------===// 29 30 namespace { 31 class VISIBILITY_HIDDEN AggExprEmitter : public StmtVisitor<AggExprEmitter> { 32 CodeGenFunction &CGF; 33 CGBuilderTy &Builder; 34 llvm::Value *DestPtr; 35 bool VolatileDest; 36 public: 37 AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool volatileDest) 38 : CGF(cgf), Builder(CGF.Builder), 39 DestPtr(destPtr), VolatileDest(volatileDest) { 40 } 41 42 //===--------------------------------------------------------------------===// 43 // Utilities 44 //===--------------------------------------------------------------------===// 45 46 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 47 /// represents a value lvalue, this method emits the address of the lvalue, 48 /// then loads the result into DestPtr. 49 void EmitAggLoadOfLValue(const Expr *E); 50 51 void EmitNonConstInit(InitListExpr *E); 52 53 //===--------------------------------------------------------------------===// 54 // Visitor Methods 55 //===--------------------------------------------------------------------===// 56 57 void VisitStmt(Stmt *S) { 58 CGF.ErrorUnsupported(S, "aggregate expression"); 59 } 60 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); } 61 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); } 62 63 // l-values. 64 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); } 65 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); } 66 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); } 67 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); } 68 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) 69 { EmitAggLoadOfLValue(E); } 70 71 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 72 EmitAggLoadOfLValue(E); 73 } 74 75 // Operators. 76 // case Expr::UnaryOperatorClass: 77 // case Expr::CastExprClass: 78 void VisitCStyleCastExpr(CStyleCastExpr *E); 79 void VisitImplicitCastExpr(ImplicitCastExpr *E); 80 void VisitCallExpr(const CallExpr *E); 81 void VisitStmtExpr(const StmtExpr *E); 82 void VisitBinaryOperator(const BinaryOperator *BO); 83 void VisitBinAssign(const BinaryOperator *E); 84 void VisitBinComma(const BinaryOperator *E); 85 86 void VisitObjCMessageExpr(ObjCMessageExpr *E); 87 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 88 EmitAggLoadOfLValue(E); 89 } 90 void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E); 91 void VisitObjCKVCRefExpr(ObjCKVCRefExpr *E); 92 93 void VisitConditionalOperator(const ConditionalOperator *CO); 94 void VisitInitListExpr(InitListExpr *E); 95 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) { 96 Visit(DAE->getExpr()); 97 } 98 void VisitVAArgExpr(VAArgExpr *E); 99 100 void EmitInitializationToLValue(Expr *E, LValue Address); 101 void EmitNullInitializationToLValue(LValue Address, QualType T); 102 // case Expr::ChooseExprClass: 103 104 }; 105 } // end anonymous namespace. 106 107 //===----------------------------------------------------------------------===// 108 // Utilities 109 //===----------------------------------------------------------------------===// 110 111 /// EmitAggLoadOfLValue - Given an expression with aggregate type that 112 /// represents a value lvalue, this method emits the address of the lvalue, 113 /// then loads the result into DestPtr. 114 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) { 115 LValue LV = CGF.EmitLValue(E); 116 assert(LV.isSimple() && "Can't have aggregate bitfield, vector, etc"); 117 llvm::Value *SrcPtr = LV.getAddress(); 118 119 // If the result is ignored, don't copy from the value. 120 if (DestPtr == 0) 121 // FIXME: If the source is volatile, we must read from it. 122 return; 123 124 CGF.EmitAggregateCopy(DestPtr, SrcPtr, E->getType()); 125 } 126 127 //===----------------------------------------------------------------------===// 128 // Visitor Methods 129 //===----------------------------------------------------------------------===// 130 131 void AggExprEmitter::VisitCStyleCastExpr(CStyleCastExpr *E) { 132 // GCC union extension 133 if (E->getType()->isUnionType()) { 134 RecordDecl *SD = E->getType()->getAsRecordType()->getDecl(); 135 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *SD->field_begin(), true, 0); 136 EmitInitializationToLValue(E->getSubExpr(), FieldLoc); 137 return; 138 } 139 140 Visit(E->getSubExpr()); 141 } 142 143 void AggExprEmitter::VisitImplicitCastExpr(ImplicitCastExpr *E) { 144 assert(CGF.getContext().typesAreCompatible( 145 E->getSubExpr()->getType().getUnqualifiedType(), 146 E->getType().getUnqualifiedType()) && 147 "Implicit cast types must be compatible"); 148 Visit(E->getSubExpr()); 149 } 150 151 void AggExprEmitter::VisitCallExpr(const CallExpr *E) { 152 RValue RV = CGF.EmitCallExpr(E); 153 assert(RV.isAggregate() && "Return value must be aggregate value!"); 154 155 // If the result is ignored, don't copy from the value. 156 if (DestPtr == 0) 157 // FIXME: If the source is volatile, we must read from it. 158 return; 159 160 CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 161 } 162 163 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) { 164 RValue RV = CGF.EmitObjCMessageExpr(E); 165 assert(RV.isAggregate() && "Return value must be aggregate value!"); 166 167 // If the result is ignored, don't copy from the value. 168 if (DestPtr == 0) 169 // FIXME: If the source is volatile, we must read from it. 170 return; 171 172 CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 173 } 174 175 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) { 176 RValue RV = CGF.EmitObjCPropertyGet(E); 177 assert(RV.isAggregate() && "Return value must be aggregate value!"); 178 179 // If the result is ignored, don't copy from the value. 180 if (DestPtr == 0) 181 // FIXME: If the source is volatile, we must read from it. 182 return; 183 184 CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 185 } 186 187 void AggExprEmitter::VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) { 188 RValue RV = CGF.EmitObjCPropertyGet(E); 189 assert(RV.isAggregate() && "Return value must be aggregate value!"); 190 191 // If the result is ignored, don't copy from the value. 192 if (DestPtr == 0) 193 // FIXME: If the source is volatile, we must read from it. 194 return; 195 196 CGF.EmitAggregateCopy(DestPtr, RV.getAggregateAddr(), E->getType()); 197 } 198 199 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) { 200 CGF.EmitAnyExpr(E->getLHS()); 201 CGF.EmitAggExpr(E->getRHS(), DestPtr, false); 202 } 203 204 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) { 205 CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest); 206 } 207 208 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) { 209 CGF.ErrorUnsupported(E, "aggregate binary expression"); 210 } 211 212 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) { 213 // For an assignment to work, the value on the right has 214 // to be compatible with the value on the left. 215 assert(CGF.getContext().typesAreCompatible( 216 E->getLHS()->getType().getUnqualifiedType(), 217 E->getRHS()->getType().getUnqualifiedType()) 218 && "Invalid assignment"); 219 LValue LHS = CGF.EmitLValue(E->getLHS()); 220 221 // We have to special case property setters, otherwise we must have 222 // a simple lvalue (no aggregates inside vectors, bitfields). 223 if (LHS.isPropertyRef()) { 224 // FIXME: Volatility? 225 llvm::Value *AggLoc = DestPtr; 226 if (!AggLoc) 227 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); 228 CGF.EmitAggExpr(E->getRHS(), AggLoc, false); 229 CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(), 230 RValue::getAggregate(AggLoc)); 231 } 232 else if (LHS.isKVCRef()) { 233 // FIXME: Volatility? 234 llvm::Value *AggLoc = DestPtr; 235 if (!AggLoc) 236 AggLoc = CGF.CreateTempAlloca(CGF.ConvertType(E->getRHS()->getType())); 237 CGF.EmitAggExpr(E->getRHS(), AggLoc, false); 238 CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(), 239 RValue::getAggregate(AggLoc)); 240 } else { 241 // Codegen the RHS so that it stores directly into the LHS. 242 CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), false /*FIXME: VOLATILE LHS*/); 243 244 if (DestPtr == 0) 245 return; 246 247 // If the result of the assignment is used, copy the RHS there also. 248 CGF.EmitAggregateCopy(DestPtr, LHS.getAddress(), E->getType()); 249 } 250 } 251 252 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) { 253 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true"); 254 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false"); 255 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end"); 256 257 llvm::Value *Cond = CGF.EvaluateExprAsBool(E->getCond()); 258 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock); 259 260 CGF.EmitBlock(LHSBlock); 261 262 // Handle the GNU extension for missing LHS. 263 assert(E->getLHS() && "Must have LHS for aggregate value"); 264 265 Visit(E->getLHS()); 266 CGF.EmitBranch(ContBlock); 267 268 CGF.EmitBlock(RHSBlock); 269 270 Visit(E->getRHS()); 271 CGF.EmitBranch(ContBlock); 272 273 CGF.EmitBlock(ContBlock); 274 } 275 276 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) { 277 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr()); 278 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType()); 279 280 if (!ArgPtr) { 281 CGF.ErrorUnsupported(VE, "aggregate va_arg expression"); 282 return; 283 } 284 285 if (DestPtr) 286 // FIXME: volatility 287 CGF.EmitAggregateCopy(DestPtr, ArgPtr, VE->getType()); 288 } 289 290 void AggExprEmitter::EmitNonConstInit(InitListExpr *E) { 291 const llvm::PointerType *APType = 292 cast<llvm::PointerType>(DestPtr->getType()); 293 const llvm::Type *DestType = APType->getElementType(); 294 295 if (E->hadArrayRangeDesignator()) { 296 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 297 } 298 299 if (const llvm::ArrayType *AType = dyn_cast<llvm::ArrayType>(DestType)) { 300 unsigned NumInitElements = E->getNumInits(); 301 302 unsigned i; 303 for (i = 0; i != NumInitElements; ++i) { 304 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 305 Expr *Init = E->getInit(i); 306 if (isa<InitListExpr>(Init)) 307 CGF.EmitAggExpr(Init, NextVal, VolatileDest); 308 else 309 // FIXME: volatility 310 Builder.CreateStore(CGF.EmitScalarExpr(Init), NextVal); 311 } 312 313 // Emit remaining default initializers 314 unsigned NumArrayElements = AType->getNumElements(); 315 QualType QType = E->getInit(0)->getType(); 316 const llvm::Type *EType = AType->getElementType(); 317 for (/*Do not initialize i*/; i < NumArrayElements; ++i) { 318 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 319 if (EType->isSingleValueType()) 320 // FIXME: volatility 321 Builder.CreateStore(llvm::Constant::getNullValue(EType), NextVal); 322 else 323 CGF.EmitAggregateClear(NextVal, QType); 324 } 325 } else 326 assert(false && "Invalid initializer"); 327 } 328 329 void AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) { 330 // FIXME: Are initializers affected by volatile? 331 if (isa<ImplicitValueInitExpr>(E)) { 332 EmitNullInitializationToLValue(LV, E->getType()); 333 } else if (E->getType()->isComplexType()) { 334 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false); 335 } else if (CGF.hasAggregateLLVMType(E->getType())) { 336 CGF.EmitAnyExpr(E, LV.getAddress(), false); 337 } else { 338 CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, E->getType()); 339 } 340 } 341 342 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) { 343 if (!CGF.hasAggregateLLVMType(T)) { 344 // For non-aggregates, we can store zero 345 llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T)); 346 CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T); 347 } else { 348 // Otherwise, just memset the whole thing to zero. This is legal 349 // because in LLVM, all default initializers are guaranteed to have a 350 // bit pattern of all zeros. 351 // There's a potential optimization opportunity in combining 352 // memsets; that would be easy for arrays, but relatively 353 // difficult for structures with the current code. 354 const llvm::Type *SizeTy = llvm::Type::Int64Ty; 355 llvm::Value *MemSet = CGF.CGM.getIntrinsic(llvm::Intrinsic::memset, 356 &SizeTy, 1); 357 uint64_t Size = CGF.getContext().getTypeSize(T); 358 359 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 360 llvm::Value* DestPtr = Builder.CreateBitCast(LV.getAddress(), BP, "tmp"); 361 Builder.CreateCall4(MemSet, DestPtr, 362 llvm::ConstantInt::get(llvm::Type::Int8Ty, 0), 363 llvm::ConstantInt::get(SizeTy, Size/8), 364 llvm::ConstantInt::get(llvm::Type::Int32Ty, 0)); 365 } 366 } 367 368 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) { 369 #if 0 370 // FIXME: Disabled while we figure out what to do about 371 // test/CodeGen/bitfield.c 372 // 373 // If we can, prefer a copy from a global; this is a lot less 374 // code for long globals, and it's easier for the current optimizers 375 // to analyze. 376 // FIXME: Should we really be doing this? Should we try to avoid 377 // cases where we emit a global with a lot of zeros? Should 378 // we try to avoid short globals? 379 if (E->isConstantInitializer(CGF.getContext(), 0)) { 380 llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, &CGF); 381 llvm::GlobalVariable* GV = 382 new llvm::GlobalVariable(C->getType(), true, 383 llvm::GlobalValue::InternalLinkage, 384 C, "", &CGF.CGM.getModule(), 0); 385 CGF.EmitAggregateCopy(DestPtr, GV, E->getType()); 386 return; 387 } 388 #endif 389 if (E->hadArrayRangeDesignator()) { 390 CGF.ErrorUnsupported(E, "GNU array range designator extension"); 391 } 392 393 // Handle initialization of an array. 394 if (E->getType()->isArrayType()) { 395 const llvm::PointerType *APType = 396 cast<llvm::PointerType>(DestPtr->getType()); 397 const llvm::ArrayType *AType = 398 cast<llvm::ArrayType>(APType->getElementType()); 399 400 uint64_t NumInitElements = E->getNumInits(); 401 402 if (E->getNumInits() > 0) { 403 QualType T1 = E->getType(); 404 QualType T2 = E->getInit(0)->getType(); 405 if (CGF.getContext().getCanonicalType(T1).getUnqualifiedType() == 406 CGF.getContext().getCanonicalType(T2).getUnqualifiedType()) { 407 EmitAggLoadOfLValue(E->getInit(0)); 408 return; 409 } 410 } 411 412 uint64_t NumArrayElements = AType->getNumElements(); 413 QualType ElementType = CGF.getContext().getCanonicalType(E->getType()); 414 ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType(); 415 416 unsigned CVRqualifier = ElementType.getCVRQualifiers(); 417 418 for (uint64_t i = 0; i != NumArrayElements; ++i) { 419 llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array"); 420 if (i < NumInitElements) 421 EmitInitializationToLValue(E->getInit(i), 422 LValue::MakeAddr(NextVal, CVRqualifier)); 423 else 424 EmitNullInitializationToLValue(LValue::MakeAddr(NextVal, CVRqualifier), 425 ElementType); 426 } 427 return; 428 } 429 430 assert(E->getType()->isRecordType() && "Only support structs/unions here!"); 431 432 // Do struct initialization; this code just sets each individual member 433 // to the approprate value. This makes bitfield support automatic; 434 // the disadvantage is that the generated code is more difficult for 435 // the optimizer, especially with bitfields. 436 unsigned NumInitElements = E->getNumInits(); 437 RecordDecl *SD = E->getType()->getAsRecordType()->getDecl(); 438 unsigned CurInitVal = 0; 439 440 if (E->getType()->isUnionType()) { 441 // Only initialize one field of a union. The field itself is 442 // specified by the initializer list. 443 if (!E->getInitializedFieldInUnion()) { 444 // Empty union; we have nothing to do. 445 446 #ifndef NDEBUG 447 // Make sure that it's really an empty and not a failure of 448 // semantic analysis. 449 for (RecordDecl::field_iterator Field = SD->field_begin(), 450 FieldEnd = SD->field_end(); 451 Field != FieldEnd; ++Field) 452 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed"); 453 #endif 454 return; 455 } 456 457 // FIXME: volatility 458 FieldDecl *Field = E->getInitializedFieldInUnion(); 459 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, Field, true, 0); 460 461 if (NumInitElements) { 462 // Store the initializer into the field 463 EmitInitializationToLValue(E->getInit(0), FieldLoc); 464 } else { 465 // Default-initialize to null 466 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 467 } 468 469 return; 470 } 471 472 // Here we iterate over the fields; this makes it simpler to both 473 // default-initialize fields and skip over unnamed fields. 474 for (RecordDecl::field_iterator Field = SD->field_begin(), 475 FieldEnd = SD->field_end(); 476 Field != FieldEnd; ++Field) { 477 // We're done once we hit the flexible array member 478 if (Field->getType()->isIncompleteArrayType()) 479 break; 480 481 if (Field->isUnnamedBitfield()) 482 continue; 483 484 // FIXME: volatility 485 LValue FieldLoc = CGF.EmitLValueForField(DestPtr, *Field, false, 0); 486 if (CurInitVal < NumInitElements) { 487 // Store the initializer into the field 488 EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc); 489 } else { 490 // We're out of initalizers; default-initialize to null 491 EmitNullInitializationToLValue(FieldLoc, Field->getType()); 492 } 493 } 494 } 495 496 //===----------------------------------------------------------------------===// 497 // Entry Points into this File 498 //===----------------------------------------------------------------------===// 499 500 /// EmitAggExpr - Emit the computation of the specified expression of 501 /// aggregate type. The result is computed into DestPtr. Note that if 502 /// DestPtr is null, the value of the aggregate expression is not needed. 503 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr, 504 bool VolatileDest) { 505 assert(E && hasAggregateLLVMType(E->getType()) && 506 "Invalid aggregate expression to emit"); 507 508 AggExprEmitter(*this, DestPtr, VolatileDest).Visit(const_cast<Expr*>(E)); 509 } 510 511 void CodeGenFunction::EmitAggregateClear(llvm::Value *DestPtr, QualType Ty) { 512 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 513 514 EmitMemSetToZero(DestPtr, Ty); 515 } 516 517 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr, 518 llvm::Value *SrcPtr, QualType Ty) { 519 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex"); 520 521 // Aggregate assignment turns into llvm.memmove. 522 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 523 if (DestPtr->getType() != BP) 524 DestPtr = Builder.CreateBitCast(DestPtr, BP, "tmp"); 525 if (SrcPtr->getType() != BP) 526 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 527 528 // Get size and alignment info for this aggregate. 529 std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty); 530 531 // FIXME: Handle variable sized types. 532 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth); 533 534 Builder.CreateCall4(CGM.getMemMoveFn(), 535 DestPtr, SrcPtr, 536 // TypeInfo.first describes size in bits. 537 llvm::ConstantInt::get(IntPtr, TypeInfo.first/8), 538 llvm::ConstantInt::get(llvm::Type::Int32Ty, 539 TypeInfo.second/8)); 540 } 541